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
|
|---|---|---|---|---|---|---|---|---|---|---|
Glu
|
import torch
import torch.nn as nn
class Glu(nn.Module):
def __init__(self, dim):
super(Glu, self).__init__()
self.dim = dim
def forward(self, x):
x_in, x_gate = x.chunk(2, dim=self.dim)
return x_in * x_gate.sigmoid()
def get_inputs():
return [torch.rand([4, 4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_sigmoid_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 % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (2 + x0 + 4 * x1), xmask)
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 2), (128, 32, 8, 2, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(512)](arg0_1, buf0, 512, XBLOCK
=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class GluNew(nn.Module):
def __init__(self, dim):
super(GluNew, self).__init__()
self.dim = dim
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
debasish-mihup/EfficientConformer
|
Glu
| false
| 10,335
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
WeightNet
|
import torch
import torch.nn as nn
class WeightNet(nn.Module):
"""WeightNet in Temporal interlace module.
The WeightNet consists of two parts: one convolution layer
and a sigmoid function. Following the convolution layer, the sigmoid
function and rescale module can scale our output to the range (0, 2).
Here we set the initial bias of the convolution layer to 0, and the
final initial output will be 1.0.
Args:
in_channels (int): Channel num of input features.
groups (int): Number of groups for fc layer outputs.
"""
def __init__(self, in_channels, groups):
super().__init__()
self.sigmoid = nn.Sigmoid()
self.groups = groups
self.conv = nn.Conv1d(in_channels, groups, 3, padding=1)
self.init_weights()
def init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
self.conv.bias.data[...] = 0
def forward(self, x):
"""Defines the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
n, _, t = x.shape
x = self.conv(x)
x = x.view(n, self.groups, t)
x = x.permute(0, 2, 1)
x = 2 * self.sigmoid(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_mul_sigmoid_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tmp5 = 2.0
tmp6 = tmp4 * tmp5
tl.store(in_out_ptr0 + x0, tmp3, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4, 3), (12, 3, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
padding=(1,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 4), (4, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_mul_sigmoid_0[grid(16)](buf1,
primals_3, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_1, primals_2, buf1
class WeightNetNew(nn.Module):
"""WeightNet in Temporal interlace module.
The WeightNet consists of two parts: one convolution layer
and a sigmoid function. Following the convolution layer, the sigmoid
function and rescale module can scale our output to the range (0, 2).
Here we set the initial bias of the convolution layer to 0, and the
final initial output will be 1.0.
Args:
in_channels (int): Channel num of input features.
groups (int): Number of groups for fc layer outputs.
"""
def __init__(self, in_channels, groups):
super().__init__()
self.sigmoid = nn.Sigmoid()
self.groups = groups
self.conv = nn.Conv1d(in_channels, groups, 3, padding=1)
self.init_weights()
def init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
self.conv.bias.data[...] = 0
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]
|
giahaowjx/mmaction2
|
WeightNet
| false
| 10,336
|
[
"Apache-2.0"
] | 0
|
4f95e9b91354acdcae768ce94e01d3821bba0154
|
https://github.com/giahaowjx/mmaction2/tree/4f95e9b91354acdcae768ce94e01d3821bba0154
|
UpscaleBlock
|
import math
import torch
import torch.jit
import torch.nn as nn
import torch.nn.init as init
import torch.onnx
def _initialize_orthogonal(conv):
prelu_gain = math.sqrt(2)
init.orthogonal(conv.weight, gain=prelu_gain)
if conv.bias is not None:
conv.bias.data.zero_()
class UpscaleBlock(nn.Module):
def __init__(self, n_filters):
super(UpscaleBlock, self).__init__()
self.upscaling_conv = nn.Conv2d(n_filters, 4 * n_filters,
kernel_size=3, padding=1)
self.upscaling_shuffler = nn.PixelShuffle(2)
self.upscaling = nn.PReLU(n_filters)
_initialize_orthogonal(self.upscaling_conv)
def forward(self, x):
return self.upscaling(self.upscaling_shuffler(self.upscaling_conv(x)))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_filters': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
import torch.jit
import torch.nn as nn
import torch.nn.init as init
import torch.onnx
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused__prelu_kernel_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8 % 8
x4 = xindex // 64
x2 = xindex // 64 % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (4 * (x1 // 2) + 16 * (x0 % 2) + 32 * (x1 % 2) +
64 * x4 + x0 // 2), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp4 = tmp3 * tmp0
tmp5 = tl.where(tmp2, tmp0, tmp4)
tl.store(out_ptr0 + x5, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (16, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (16,), (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, 16, 4, 4), (256, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(1024)](buf1, primals_2, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32)
triton_poi_fused__prelu_kernel_1[grid(1024)](buf1, primals_4, buf2,
1024, XBLOCK=128, num_warps=4, num_stages=1)
return buf2, primals_1, primals_3, primals_4, buf1
def _initialize_orthogonal(conv):
prelu_gain = math.sqrt(2)
init.orthogonal(conv.weight, gain=prelu_gain)
if conv.bias is not None:
conv.bias.data.zero_()
class UpscaleBlockNew(nn.Module):
def __init__(self, n_filters):
super(UpscaleBlockNew, self).__init__()
self.upscaling_conv = nn.Conv2d(n_filters, 4 * n_filters,
kernel_size=3, padding=1)
self.upscaling_shuffler = nn.PixelShuffle(2)
self.upscaling = nn.PReLU(n_filters)
_initialize_orthogonal(self.upscaling_conv)
def forward(self, input_0):
primals_1 = self.upscaling_conv.weight
primals_2 = self.upscaling_conv.bias
primals_4 = self.upscaling.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jamesr66a/onnx-fb-universe
|
UpscaleBlock
| false
| 10,337
|
[
"MIT"
] | 0
|
3c0d1ea06d90c3788c47c0d32d160499afabe2fb
|
https://github.com/jamesr66a/onnx-fb-universe/tree/3c0d1ea06d90c3788c47c0d32d160499afabe2fb
|
MultiHeadAttention
|
from torch.nn import Module
import torch
import numpy as np
from torch import nn
class ScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h):
"""
: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.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
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.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.bool(), -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
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):
super(MultiHeadAttention, self).__init__()
self.identity_map_reordering = identity_map_reordering
if attention_module is not None:
if attention_module_kwargs is not None:
self.attention = attention_module(d_model=d_model, d_k=d_k,
d_v=d_v, h=h, **attention_module_kwargs)
else:
self.attention = attention_module(d_model=d_model, d_k=d_k,
d_v=d_v, h=h)
else:
self.attention = ScaledDotProductAttention(d_model=d_model, d_k
=d_k, d_v=d_v, h=h)
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
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, 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=128,
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):
"""
: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.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
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.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.bool(), -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
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):
super(MultiHeadAttentionNew, self).__init__()
self.identity_map_reordering = identity_map_reordering
if attention_module is not None:
if attention_module_kwargs is not None:
self.attention = attention_module(d_model=d_model, d_k=d_k,
d_v=d_v, h=h, **attention_module_kwargs)
else:
self.attention = attention_module(d_model=d_model, d_k=d_k,
d_v=d_v, h=h)
else:
self.attention = ScaledDotProductAttention(d_model=d_model, d_k
=d_k, d_v=d_v, h=h)
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]
|
jmhessel/meshed-memory-transformer
|
MultiHeadAttention
| false
| 10,338
|
[
"BSD-3-Clause"
] | 0
|
b502da2522f2e25d602fba547ed6ebf7968857a9
|
https://github.com/jmhessel/meshed-memory-transformer/tree/b502da2522f2e25d602fba547ed6ebf7968857a9
|
BMNLoss
|
import torch
import torch.nn.functional as F
import torch.nn as nn
def binary_logistic_regression_loss(reg_score, label, threshold=0.5,
ratio_range=(1.05, 21), eps=1e-05):
"""Binary Logistic Regression Loss."""
label = label.view(-1)
reg_score = reg_score.contiguous().view(-1)
pmask = (label > threshold).float()
num_positive = max(torch.sum(pmask), 1)
num_entries = len(label)
ratio = num_entries / num_positive
ratio = min(max(ratio, ratio_range[0]), ratio_range[1])
coef_0 = 0.5 * ratio / (ratio - 1)
coef_1 = 0.5 * ratio
loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask
) * torch.log(1.0 - reg_score + eps)
loss = -torch.mean(loss)
return loss
class BMNLoss(nn.Module):
"""BMN Loss.
From paper https://arxiv.org/abs/1907.09702,
code https://github.com/JJBOY/BMN-Boundary-Matching-Network.
It will calculate loss for BMN Model. This loss is a weighted sum of
1) temporal evaluation loss based on confidence score of start and
end positions.
2) proposal evaluation regression loss based on confidence scores of
candidate proposals.
3) proposal evaluation classification loss based on classification
results of candidate proposals.
"""
@staticmethod
def tem_loss(pred_start, pred_end, gt_start, gt_end):
"""Calculate Temporal Evaluation Module Loss.
This function calculate the binary_logistic_regression_loss for start
and end respectively and returns the sum of their losses.
Args:
pred_start (torch.Tensor): Predicted start score by BMN model.
pred_end (torch.Tensor): Predicted end score by BMN model.
gt_start (torch.Tensor): Groundtruth confidence score for start.
gt_end (torch.Tensor): Groundtruth confidence score for end.
Returns:
torch.Tensor: Returned binary logistic loss.
"""
loss_start = binary_logistic_regression_loss(pred_start, gt_start)
loss_end = binary_logistic_regression_loss(pred_end, gt_end)
loss = loss_start + loss_end
return loss
@staticmethod
def pem_reg_loss(pred_score, gt_iou_map, mask,
high_temporal_iou_threshold=0.7, low_temporal_iou_threshold=0.3):
"""Calculate Proposal Evaluation Module Regression Loss.
Args:
pred_score (torch.Tensor): Predicted temporal_iou score by BMN.
gt_iou_map (torch.Tensor): Groundtruth temporal_iou score.
mask (torch.Tensor): Boundary-Matching mask.
high_temporal_iou_threshold (float): Higher threshold of
temporal_iou. Default: 0.7.
low_temporal_iou_threshold (float): Higher threshold of
temporal_iou. Default: 0.3.
Returns:
torch.Tensor: Proposal evaluation regression loss.
"""
u_hmask = (gt_iou_map > high_temporal_iou_threshold).float()
u_mmask = ((gt_iou_map <= high_temporal_iou_threshold) & (
gt_iou_map > low_temporal_iou_threshold)).float()
u_lmask = ((gt_iou_map <= low_temporal_iou_threshold) & (gt_iou_map >
0.0)).float()
u_lmask = u_lmask * mask
num_h = torch.sum(u_hmask)
num_m = torch.sum(u_mmask)
num_l = torch.sum(u_lmask)
r_m = num_h / num_m
u_smmask = torch.rand_like(gt_iou_map)
u_smmask = u_mmask * u_smmask
u_smmask = (u_smmask > 1.0 - r_m).float()
r_l = num_h / num_l
u_slmask = torch.rand_like(gt_iou_map)
u_slmask = u_lmask * u_slmask
u_slmask = (u_slmask > 1.0 - r_l).float()
weights = u_hmask + u_smmask + u_slmask
loss = F.mse_loss(pred_score * weights, gt_iou_map * weights)
loss = 0.5 * torch.sum(loss * torch.ones_like(weights)) / torch.sum(
weights)
return loss
@staticmethod
def pem_cls_loss(pred_score, gt_iou_map, mask, threshold=0.9,
ratio_range=(1.05, 21), eps=1e-05):
"""Calculate Proposal Evaluation Module Classification Loss.
Args:
pred_score (torch.Tensor): Predicted temporal_iou score by BMN.
gt_iou_map (torch.Tensor): Groundtruth temporal_iou score.
mask (torch.Tensor): Boundary-Matching mask.
threshold (float): Threshold of temporal_iou for positive
instances. Default: 0.9.
ratio_range (tuple): Lower bound and upper bound for ratio.
Default: (1.05, 21)
eps (float): Epsilon for small value. Default: 1e-5
Returns:
torch.Tensor: Proposal evaluation classification loss.
"""
pmask = (gt_iou_map > threshold).float()
nmask = (gt_iou_map <= threshold).float()
nmask = nmask * mask
num_positive = max(torch.sum(pmask), 1)
num_entries = num_positive + torch.sum(nmask)
ratio = num_entries / num_positive
ratio = torch.clamp(ratio, ratio_range[0], ratio_range[1])
coef_0 = 0.5 * ratio / (ratio - 1)
coef_1 = 0.5 * ratio
loss_pos = coef_1 * torch.log(pred_score + eps) * pmask
loss_neg = coef_0 * torch.log(1.0 - pred_score + eps) * nmask
loss = -1 * torch.sum(loss_pos + loss_neg) / num_entries
return loss
def forward(self, pred_bm, pred_start, pred_end, gt_iou_map, gt_start,
gt_end, bm_mask, weight_tem=1.0, weight_pem_reg=10.0,
weight_pem_cls=1.0):
"""Calculate Boundary Matching Network Loss.
Args:
pred_bm (torch.Tensor): Predicted confidence score for boundary
matching map.
pred_start (torch.Tensor): Predicted confidence score for start.
pred_end (torch.Tensor): Predicted confidence score for end.
gt_iou_map (torch.Tensor): Groundtruth score for boundary matching
map.
gt_start (torch.Tensor): Groundtruth temporal_iou score for start.
gt_end (torch.Tensor): Groundtruth temporal_iou score for end.
bm_mask (torch.Tensor): Boundary-Matching mask.
weight_tem (float): Weight for tem loss. Default: 1.0.
weight_pem_reg (float): Weight for pem regression loss.
Default: 10.0.
weight_pem_cls (float): Weight for pem classification loss.
Default: 1.0.
Returns:
tuple([torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]):
(loss, tem_loss, pem_reg_loss, pem_cls_loss). Loss is the bmn
loss, tem_loss is the temporal evaluation loss, pem_reg_loss is
the proposal evaluation regression loss, pem_cls_loss is the
proposal evaluation classification loss.
"""
pred_bm_reg = pred_bm[:, 0].contiguous()
pred_bm_cls = pred_bm[:, 1].contiguous()
gt_iou_map = gt_iou_map * bm_mask
pem_reg_loss = self.pem_reg_loss(pred_bm_reg, gt_iou_map, bm_mask)
pem_cls_loss = self.pem_cls_loss(pred_bm_cls, gt_iou_map, bm_mask)
tem_loss = self.tem_loss(pred_start, pred_end, gt_start, gt_end)
loss = (weight_tem * tem_loss + weight_pem_reg * pem_reg_loss +
weight_pem_cls * pem_cls_loss)
return loss, tem_loss, pem_reg_loss, pem_cls_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]), 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 import device
import triton
import triton.language as tl
from 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 as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused__to_copy_add_bitwise_and_clamp_clone_div_gt_le_log_mean_mse_loss_mul_neg_ones_like_reciprocal_rsub_sub_sum_0(
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, out_ptr12, 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
r1 = rindex % 16
r2 = rindex // 16 % 4
tmp0 = tl.load(in_ptr0 + r0, None)
tmp19 = tl.load(in_ptr1 + r0, None)
tmp36 = tl.load(in_ptr2 + r0, None)
tmp37 = tl.load(in_ptr3 + r0, None)
tmp62 = tl.load(in_ptr4 + r0, None)
tmp69 = tl.load(in_out_ptr0 + r0, None)
tmp76 = tl.load(in_ptr5 + (r1 + 64 * r2), None, eviction_policy=
'evict_last')
tmp110 = tl.load(in_ptr5 + (16 + r1 + 64 * r2), None, eviction_policy=
'evict_last')
tmp126 = tl.load(in_ptr6 + r0, None)
tmp139 = tl.load(in_ptr7 + r0, None)
tmp1 = 0.5
tmp2 = tmp0 > tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = 1.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tl.full([1], 1, tl.int32)
tmp10 = tmp9 / tmp8
tmp11 = 256.0
tmp12 = tmp10 * tmp11
tmp13 = 1.05
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = 21.0
tmp16 = triton_helpers.minimum(tmp14, tmp15)
tmp17 = tmp16 * tmp1
tmp18 = tmp17 * tmp3
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = tl_math.log(tmp21)
tmp23 = tmp18 * tmp22
tmp24 = tmp16 - tmp7
tmp25 = tmp17 / tmp24
tmp26 = tmp7 - tmp3
tmp27 = tmp25 * tmp26
tmp28 = tmp7 - tmp19
tmp29 = tmp28 + tmp20
tmp30 = tl_math.log(tmp29)
tmp31 = tmp27 * tmp30
tmp32 = tmp23 + tmp31
tmp33 = tl.broadcast_to(tmp32, [RBLOCK])
tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0))
tmp38 = tmp36 * tmp37
tmp39 = 0.7
tmp40 = tmp38 > tmp39
tmp41 = tmp40.to(tl.float32)
tmp42 = tl.broadcast_to(tmp41, [RBLOCK])
tmp44 = triton_helpers.promote_to_tensor(tl.sum(tmp42, 0))
tmp45 = tmp38 <= tmp39
tmp46 = 0.3
tmp47 = tmp38 > tmp46
tmp48 = tmp45 & tmp47
tmp49 = tmp48.to(tl.float32)
tmp50 = tl.broadcast_to(tmp49, [RBLOCK])
tmp52 = triton_helpers.promote_to_tensor(tl.sum(tmp50, 0))
tmp53 = tmp38 <= tmp46
tmp54 = 0.0
tmp55 = tmp38 > tmp54
tmp56 = tmp53 & tmp55
tmp57 = tmp56.to(tl.float32)
tmp58 = tmp57 * tmp37
tmp59 = tl.broadcast_to(tmp58, [RBLOCK])
tmp61 = triton_helpers.promote_to_tensor(tl.sum(tmp59, 0))
tmp63 = tmp49 * tmp62
tmp64 = tmp44 / tmp52
tmp65 = tmp7 - tmp64
tmp66 = tmp63 > tmp65
tmp67 = tmp66.to(tl.float32)
tmp68 = tmp41 + tmp67
tmp70 = tmp58 * tmp69
tmp71 = tmp44 / tmp61
tmp72 = tmp7 - tmp71
tmp73 = tmp70 > tmp72
tmp74 = tmp73.to(tl.float32)
tmp75 = tmp68 + tmp74
tmp77 = tmp76 * tmp75
tmp78 = tmp38 * tmp75
tmp79 = tmp77 - tmp78
tmp80 = tmp79 * tmp79
tmp81 = tl.broadcast_to(tmp80, [RBLOCK])
tmp83 = triton_helpers.promote_to_tensor(tl.sum(tmp81, 0))
tmp84 = 0.9
tmp85 = tmp38 > tmp84
tmp86 = tmp85.to(tl.float32)
tmp87 = tl.broadcast_to(tmp86, [RBLOCK])
tmp89 = triton_helpers.promote_to_tensor(tl.sum(tmp87, 0))
tmp90 = tmp38 <= tmp84
tmp91 = tmp90.to(tl.float32)
tmp92 = tmp91 * tmp37
tmp93 = tl.broadcast_to(tmp92, [RBLOCK])
tmp95 = triton_helpers.promote_to_tensor(tl.sum(tmp93, 0))
tmp96 = tl.broadcast_to(tmp75, [RBLOCK])
tmp98 = triton_helpers.promote_to_tensor(tl.sum(tmp96, 0))
tmp99 = tmp83 / tmp11
tmp100 = tmp99 * tmp7
tmp101 = tl.broadcast_to(tmp100, [RBLOCK])
tmp103 = triton_helpers.promote_to_tensor(tl.sum(tmp101, 0))
tmp104 = triton_helpers.maximum(tmp89, tmp7)
tmp105 = tmp104 + tmp95
tmp106 = tmp105 / tmp104
tmp107 = triton_helpers.maximum(tmp106, tmp13)
tmp108 = triton_helpers.minimum(tmp107, tmp15)
tmp109 = tmp108 * tmp1
tmp111 = tmp110 + tmp20
tmp112 = tl_math.log(tmp111)
tmp113 = tmp109 * tmp112
tmp114 = tmp113 * tmp86
tmp115 = tmp108 - tmp7
tmp116 = tmp109 / tmp115
tmp117 = tmp7 - tmp110
tmp118 = tmp117 + tmp20
tmp119 = tl_math.log(tmp118)
tmp120 = tmp116 * tmp119
tmp121 = tmp120 * tmp92
tmp122 = tmp114 + tmp121
tmp123 = tl.broadcast_to(tmp122, [RBLOCK])
tmp125 = triton_helpers.promote_to_tensor(tl.sum(tmp123, 0))
tmp127 = tmp126 > tmp1
tmp128 = tmp127.to(tl.float32)
tmp129 = tl.broadcast_to(tmp128, [RBLOCK])
tmp131 = triton_helpers.promote_to_tensor(tl.sum(tmp129, 0))
tmp132 = triton_helpers.maximum(tmp131, tmp7)
tmp133 = tmp9 / tmp132
tmp134 = tmp133 * tmp11
tmp135 = triton_helpers.maximum(tmp134, tmp13)
tmp136 = triton_helpers.minimum(tmp135, tmp15)
tmp137 = tmp136 * tmp1
tmp138 = tmp137 * tmp128
tmp140 = tmp139 + tmp20
tmp141 = tl_math.log(tmp140)
tmp142 = tmp138 * tmp141
tmp143 = tmp136 - tmp7
tmp144 = tmp137 / tmp143
tmp145 = tmp7 - tmp128
tmp146 = tmp144 * tmp145
tmp147 = tmp7 - tmp139
tmp148 = tmp147 + tmp20
tmp149 = tl_math.log(tmp148)
tmp150 = tmp146 * tmp149
tmp151 = tmp142 + tmp150
tmp152 = tl.broadcast_to(tmp151, [RBLOCK])
tmp154 = triton_helpers.promote_to_tensor(tl.sum(tmp152, 0))
tmp155 = tmp35 / tmp11
tmp156 = -tmp155
tmp157 = tmp154 / tmp11
tmp158 = -tmp157
tmp159 = tmp156 + tmp158
tmp160 = tmp103 * tmp1
tmp161 = tmp160 / tmp98
tmp162 = -1.0
tmp163 = tmp125 * tmp162
tmp164 = tmp163 / tmp105
tmp165 = tmp159 * tmp7
tmp166 = 10.0
tmp167 = tmp161 * tmp166
tmp168 = tmp165 + tmp167
tmp169 = tmp164 * tmp7
tmp170 = tmp168 + tmp169
tl.debug_barrier()
tl.store(in_out_ptr2 + tl.full([1], 0, tl.int32), tmp159, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([1], 0, tl.int32), tmp161, None)
tl.debug_barrier()
tl.store(in_out_ptr3 + tl.full([1], 0, tl.int32), tmp164, None)
tl.store(out_ptr12 + tl.full([1], 0, tl.int32), tmp170, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1, arg6_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg4_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg5_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg6_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf11 = torch.ops.aten.rand.default([4, 4, 4, 4], dtype=torch.
float32, device=device(type='cuda', index=0), pin_memory=False)
buf12 = buf11
del buf11
buf7 = torch.ops.aten.rand.default([4, 4, 4, 4], dtype=torch.
float32, device=device(type='cuda', index=0), pin_memory=False)
buf8 = buf7
del buf7
buf2 = empty_strided_cuda((), (), torch.float32)
buf14 = buf12
del buf12
buf15 = empty_strided_cuda((), (), torch.float32)
buf16 = buf15
del buf15
buf22 = empty_strided_cuda((), (), torch.float32)
buf6 = buf2
del buf2
buf18 = buf16
del buf16
buf23 = buf22
del buf22
buf24 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused__to_copy_add_bitwise_and_clamp_clone_div_gt_le_log_mean_mse_loss_mul_neg_ones_like_reciprocal_rsub_sub_sum_0[
grid(1)](buf14, buf18, buf6, buf23, arg4_1, arg3_1, arg1_1,
arg2_1, buf8, arg0_1, arg6_1, arg5_1, buf24, 1, 256, num_warps=
2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
del arg4_1
del arg5_1
del arg6_1
del buf14
del buf8
return buf24, buf6, buf18, buf23
def binary_logistic_regression_loss(reg_score, label, threshold=0.5,
ratio_range=(1.05, 21), eps=1e-05):
"""Binary Logistic Regression Loss."""
label = label.view(-1)
reg_score = reg_score.contiguous().view(-1)
pmask = (label > threshold).float()
num_positive = max(torch.sum(pmask), 1)
num_entries = len(label)
ratio = num_entries / num_positive
ratio = min(max(ratio, ratio_range[0]), ratio_range[1])
coef_0 = 0.5 * ratio / (ratio - 1)
coef_1 = 0.5 * ratio
loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask
) * torch.log(1.0 - reg_score + eps)
loss = -torch.mean(loss)
return loss
class BMNLossNew(nn.Module):
"""BMN Loss.
From paper https://arxiv.org/abs/1907.09702,
code https://github.com/JJBOY/BMN-Boundary-Matching-Network.
It will calculate loss for BMN Model. This loss is a weighted sum of
1) temporal evaluation loss based on confidence score of start and
end positions.
2) proposal evaluation regression loss based on confidence scores of
candidate proposals.
3) proposal evaluation classification loss based on classification
results of candidate proposals.
"""
@staticmethod
def tem_loss(pred_start, pred_end, gt_start, gt_end):
"""Calculate Temporal Evaluation Module Loss.
This function calculate the binary_logistic_regression_loss for start
and end respectively and returns the sum of their losses.
Args:
pred_start (torch.Tensor): Predicted start score by BMN model.
pred_end (torch.Tensor): Predicted end score by BMN model.
gt_start (torch.Tensor): Groundtruth confidence score for start.
gt_end (torch.Tensor): Groundtruth confidence score for end.
Returns:
torch.Tensor: Returned binary logistic loss.
"""
loss_start = binary_logistic_regression_loss(pred_start, gt_start)
loss_end = binary_logistic_regression_loss(pred_end, gt_end)
loss = loss_start + loss_end
return loss
@staticmethod
def pem_reg_loss(pred_score, gt_iou_map, mask,
high_temporal_iou_threshold=0.7, low_temporal_iou_threshold=0.3):
"""Calculate Proposal Evaluation Module Regression Loss.
Args:
pred_score (torch.Tensor): Predicted temporal_iou score by BMN.
gt_iou_map (torch.Tensor): Groundtruth temporal_iou score.
mask (torch.Tensor): Boundary-Matching mask.
high_temporal_iou_threshold (float): Higher threshold of
temporal_iou. Default: 0.7.
low_temporal_iou_threshold (float): Higher threshold of
temporal_iou. Default: 0.3.
Returns:
torch.Tensor: Proposal evaluation regression loss.
"""
u_hmask = (gt_iou_map > high_temporal_iou_threshold).float()
u_mmask = ((gt_iou_map <= high_temporal_iou_threshold) & (
gt_iou_map > low_temporal_iou_threshold)).float()
u_lmask = ((gt_iou_map <= low_temporal_iou_threshold) & (gt_iou_map >
0.0)).float()
u_lmask = u_lmask * mask
num_h = torch.sum(u_hmask)
num_m = torch.sum(u_mmask)
num_l = torch.sum(u_lmask)
r_m = num_h / num_m
u_smmask = torch.rand_like(gt_iou_map)
u_smmask = u_mmask * u_smmask
u_smmask = (u_smmask > 1.0 - r_m).float()
r_l = num_h / num_l
u_slmask = torch.rand_like(gt_iou_map)
u_slmask = u_lmask * u_slmask
u_slmask = (u_slmask > 1.0 - r_l).float()
weights = u_hmask + u_smmask + u_slmask
loss = F.mse_loss(pred_score * weights, gt_iou_map * weights)
loss = 0.5 * torch.sum(loss * torch.ones_like(weights)) / torch.sum(
weights)
return loss
@staticmethod
def pem_cls_loss(pred_score, gt_iou_map, mask, threshold=0.9,
ratio_range=(1.05, 21), eps=1e-05):
"""Calculate Proposal Evaluation Module Classification Loss.
Args:
pred_score (torch.Tensor): Predicted temporal_iou score by BMN.
gt_iou_map (torch.Tensor): Groundtruth temporal_iou score.
mask (torch.Tensor): Boundary-Matching mask.
threshold (float): Threshold of temporal_iou for positive
instances. Default: 0.9.
ratio_range (tuple): Lower bound and upper bound for ratio.
Default: (1.05, 21)
eps (float): Epsilon for small value. Default: 1e-5
Returns:
torch.Tensor: Proposal evaluation classification loss.
"""
pmask = (gt_iou_map > threshold).float()
nmask = (gt_iou_map <= threshold).float()
nmask = nmask * mask
num_positive = max(torch.sum(pmask), 1)
num_entries = num_positive + torch.sum(nmask)
ratio = num_entries / num_positive
ratio = torch.clamp(ratio, ratio_range[0], ratio_range[1])
coef_0 = 0.5 * ratio / (ratio - 1)
coef_1 = 0.5 * ratio
loss_pos = coef_1 * torch.log(pred_score + eps) * pmask
loss_neg = coef_0 * torch.log(1.0 - pred_score + eps) * nmask
loss = -1 * torch.sum(loss_pos + loss_neg) / num_entries
return loss
def forward(self, input_0, input_1, input_2, input_3, input_4, input_5,
input_6):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
arg4_1 = input_4
arg5_1 = input_5
arg6_1 = input_6
output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1, arg6_1])
return output[0], output[1], output[2], output[3]
|
giahaowjx/mmaction2
|
BMNLoss
| false
| 10,339
|
[
"Apache-2.0"
] | 0
|
4f95e9b91354acdcae768ce94e01d3821bba0154
|
https://github.com/giahaowjx/mmaction2/tree/4f95e9b91354acdcae768ce94e01d3821bba0154
|
ResidualAttentionBlock
|
import torch
from torch import nn
import torch.utils.checkpoint
from collections import OrderedDict
class LayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(LayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class QuickGELU(nn.Module):
def forward(self, x: 'torch.Tensor'):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', attn_mask:
'torch.Tensor'=None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: 'torch.Tensor'):
self.attn_mask = self.attn_mask if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask
)[0]
def forward(self, x: 'torch.Tensor'):
x = x + self.attention(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def get_inputs():
return [torch.rand([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 libdevice, math as tl_math
from torch import nn
import torch.utils.checkpoint
from collections import OrderedDict
assert_size_stride = torch._C._dynamo.guards.assert_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_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
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1e-12
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_mul_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__safe_softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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__safe_softmax_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 // 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_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mean_pow_sub_7(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_sqrt_sub_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = 1e-12
tmp8 = tmp6 + tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = tmp5 / tmp9
tmp11 = tmp0 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.702
tmp2 = tmp0 * tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = tmp0 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_out_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (16, 4), (4, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (4, 16), (16, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_sub_0[grid(16)](primals_1, buf0, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_1[grid(16)](primals_2,
buf0, primals_3, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
del primals_3
buf2 = buf0
del buf0
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 16), out=buf3)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8),
buf1, reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha=
1, beta=1, out=buf4)
buf5 = reinterpret_tensor(buf2, (1, 4, 4, 1), (16, 1, 4, 16), 0)
del buf2
triton_poi_fused_mul_2[grid(16)](buf5, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf6 = reinterpret_tensor(buf3, (1, 4, 1, 4), (16, 1, 16, 4), 0)
del buf3
triton_poi_fused_mul_3[grid(16)](buf6, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf5, (4, 4, 1), (1, 4, 0), 0
), reinterpret_tensor(buf6, (4, 1, 4), (1, 0, 4), 0), out=buf7)
buf8 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_4[grid(64)](buf7, buf8, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_5[grid(64)](buf7, buf8, buf9, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (4, 4, 1), (1, 4, 0), 0), out=buf10)
buf11 = empty_strided_cuda((4, 1, 4, 1), (4, 1, 1, 4), torch.float32)
triton_poi_fused_clone_6[grid(4, 4)](buf10, buf11, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 4), (4, 1), 0)
del buf10
extern_kernels.addmm(primals_7, reinterpret_tensor(buf11, (4, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf12)
del primals_7
buf13 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf14 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused_add_mean_pow_sub_7[grid(4)](primals_1, buf12,
buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_sqrt_sub_8[grid(16)](primals_8,
primals_1, buf12, buf13, buf14, primals_9, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf13
del buf14
del primals_9
buf16 = reinterpret_tensor(buf8, (4, 16), (16, 1), 0)
del buf8
extern_kernels.addmm(primals_11, buf15, reinterpret_tensor(
primals_10, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf16)
del primals_11
buf17 = reinterpret_tensor(buf7, (4, 16), (16, 1), 0)
del buf7
triton_poi_fused_mul_sigmoid_9[grid(64)](buf16, buf17, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf17, reinterpret_tensor(primals_12, (16, 4), (1,
16), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_add_10[grid(16)](buf19, primals_1, buf12,
primals_13, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_13
return (buf19, primals_1, primals_8, buf1, buf9, reinterpret_tensor(
buf11, (4, 4), (4, 1), 0), buf12, buf15, buf16, buf17, primals_12,
primals_10, primals_6, reinterpret_tensor(buf4, (4, 1, 4), (1, 1, 4
), 0), reinterpret_tensor(buf5, (4, 1, 4), (1, 4, 4), 0),
reinterpret_tensor(buf6, (4, 4, 1), (1, 4, 16), 0),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 0))
class LayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(LayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class QuickGELU(nn.Module):
def forward(self, x: 'torch.Tensor'):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlockNew(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', attn_mask:
'torch.Tensor'=None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: 'torch.Tensor'):
self.attn_mask = self.attn_mask if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask
)[0]
def forward(self, input_0):
primals_4 = self.attn.in_proj_weight
primals_5 = self.attn.in_proj_bias
primals_1 = self.attn.out_proj.weight
primals_2 = self.attn.out_proj.bias
primals_3 = self.ln_1.weight
primals_7 = self.ln_1.bias
primals_10 = self.mlp.c_fc.weight
primals_11 = self.mlp.c_fc.bias
primals_12 = self.mlp.c_proj.weight
primals_8 = self.mlp.c_proj.bias
primals_9 = self.ln_2.weight
primals_13 = self.ln_2.bias
primals_6 = 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]
|
jiazheng-xing/Swin_Multimodal
|
ResidualAttentionBlock
| false
| 10,340
|
[
"MIT"
] | 0
|
7bc41977fe7d8d4f0091852c63a6a32a0fada0fb
|
https://github.com/jiazheng-xing/Swin_Multimodal/tree/7bc41977fe7d8d4f0091852c63a6a32a0fada0fb
|
VideoAttText
|
import torch
from torch import nn
import torch.utils.checkpoint
from collections import OrderedDict
class LayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(LayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class QuickGELU(nn.Module):
def forward(self, x: 'torch.Tensor'):
return x * torch.sigmoid(1.702 * x)
class VideoAttText(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', drop_out: 'float',
attn_mask: 'torch.Tensor'=None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: 'torch.Tensor', y: 'torch.Tensor'):
self.attn_mask = self.attn_mask if self.attn_mask is not None else None
return self.attn(x, y, y, need_weights=False, attn_mask=self.attn_mask
)[0]
def forward(self, x: 'torch.Tensor', y: 'torch.Tensor'):
x = x + self.attention(self.ln_1(x), self.ln_1(y))
x = x + self.mlp(self.ln_2(x))
return x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'n_head': 4, 'drop_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import nn
import torch.utils.checkpoint
from collections import OrderedDict
assert_size_stride = torch._C._dynamo.guards.assert_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_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
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_1(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr3 + x2, xmask)
tmp23 = tl.load(in_ptr3 + 4 * x1, xmask, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr3 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp28 = tl.load(in_ptr3 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr3 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1e-12
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tmp24 = tmp23 * tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp29 = tmp28 * tmp28
tmp30 = tmp27 + tmp29
tmp32 = tmp31 * tmp31
tmp33 = tmp30 + tmp32
tmp34 = tmp33 / tmp13
tmp35 = tmp34 + tmp15
tmp36 = libdevice.sqrt(tmp35)
tmp37 = tmp22 / tmp36
tmp38 = tmp0 * tmp37
tmp39 = tmp38 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
tl.store(out_ptr1 + x2, tmp39, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_mul_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__safe_softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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__safe_softmax_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 // 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_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mean_pow_sub_7(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_sqrt_sub_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = 1e-12
tmp8 = tmp6 + tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = tmp5 / tmp9
tmp11 = tmp0 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.702
tmp2 = tmp0 * tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = tmp0 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_out_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (12, 4), (4, 1))
assert_size_stride(primals_6, (12,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (16, 4), (4, 1))
assert_size_stride(primals_12, (16,), (1,))
assert_size_stride(primals_13, (4, 16), (16, 1))
assert_size_stride(primals_14, (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_mean_sub_0[grid(16)](primals_1, buf0, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mean_sub_0[grid(16)](primals_4, buf1, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_1[grid(16)](primals_2,
buf0, primals_3, buf1, buf2, buf4, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_3
buf3 = buf1
del buf1
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4
), 0), out=buf3)
buf5 = buf0
del buf0
extern_kernels.mm(buf4, reinterpret_tensor(primals_5, (4, 4), (1, 4
), 16), out=buf5)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_6, (4,), (1,), 8),
buf4, reinterpret_tensor(primals_5, (4, 4), (1, 4), 32), alpha=
1, beta=1, out=buf6)
buf7 = reinterpret_tensor(buf3, (1, 4, 4, 1), (16, 1, 4, 16), 0)
del buf3
triton_poi_fused_mul_2[grid(16)](buf7, primals_6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (1, 4, 1, 4), (16, 1, 16, 4), 0)
del buf5
triton_poi_fused_mul_3[grid(16)](buf8, primals_6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_6
buf9 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf7, (4, 4, 1), (1, 4, 0), 0
), reinterpret_tensor(buf8, (4, 1, 4), (1, 0, 4), 0), out=buf9)
buf10 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_4[grid(64)](buf9, buf10, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_5[grid(64)](buf9, buf10, buf11, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf6, (4, 4, 1), (1, 4, 0), 0), out=buf12)
buf13 = empty_strided_cuda((4, 1, 4, 1), (4, 1, 1, 4), torch.float32)
triton_poi_fused_clone_6[grid(4, 4)](buf12, buf13, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf14 = reinterpret_tensor(buf12, (4, 4), (4, 1), 0)
del buf12
extern_kernels.addmm(primals_8, reinterpret_tensor(buf13, (4, 4), (
4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf14)
del primals_8
buf15 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf16 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused_add_mean_pow_sub_7[grid(4)](primals_1, buf14,
buf15, buf16, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_sqrt_sub_8[grid(16)](primals_9,
primals_1, buf14, buf15, buf16, primals_10, buf17, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del buf15
del buf16
del primals_10
buf18 = reinterpret_tensor(buf9, (4, 16), (16, 1), 0)
del buf9
extern_kernels.addmm(primals_12, buf17, reinterpret_tensor(
primals_11, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf18)
del primals_12
buf19 = reinterpret_tensor(buf10, (4, 16), (16, 1), 0)
del buf10
triton_poi_fused_mul_sigmoid_9[grid(64)](buf18, buf19, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf19, reinterpret_tensor(primals_13, (16, 4), (1,
16), 0), out=buf20)
buf21 = buf20
del buf20
triton_poi_fused_add_10[grid(16)](buf21, primals_1, buf14,
primals_14, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_14
return (buf21, primals_1, primals_4, primals_9, buf2, buf4, buf11,
reinterpret_tensor(buf13, (4, 4), (4, 1), 0), buf14, buf17, buf18,
buf19, primals_13, primals_11, primals_7, reinterpret_tensor(buf6,
(4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf7, (4, 1, 4), (1, 4,
4), 0), reinterpret_tensor(buf8, (4, 4, 1), (1, 4, 16), 0),
reinterpret_tensor(primals_5, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_5, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_5, (4, 4), (4, 1), 0))
class LayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(LayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class QuickGELU(nn.Module):
def forward(self, x: 'torch.Tensor'):
return x * torch.sigmoid(1.702 * x)
class VideoAttTextNew(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', drop_out: 'float',
attn_mask: 'torch.Tensor'=None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: 'torch.Tensor', y: 'torch.Tensor'):
self.attn_mask = self.attn_mask if self.attn_mask is not None else None
return self.attn(x, y, y, need_weights=False, attn_mask=self.attn_mask
)[0]
def forward(self, input_0, input_1):
primals_5 = self.attn.in_proj_weight
primals_6 = self.attn.in_proj_bias
primals_1 = self.attn.out_proj.weight
primals_2 = self.attn.out_proj.bias
primals_3 = self.ln_1.weight
primals_8 = self.ln_1.bias
primals_11 = self.mlp.c_fc.weight
primals_12 = self.mlp.c_fc.bias
primals_13 = self.mlp.c_proj.weight
primals_9 = self.mlp.c_proj.bias
primals_10 = self.ln_2.weight
primals_14 = self.ln_2.bias
primals_4 = input_0
primals_7 = 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])
return output[0]
|
jiazheng-xing/Swin_Multimodal
|
VideoAttText
| false
| 10,341
|
[
"MIT"
] | 0
|
7bc41977fe7d8d4f0091852c63a6a32a0fada0fb
|
https://github.com/jiazheng-xing/Swin_Multimodal/tree/7bc41977fe7d8d4f0091852c63a6a32a0fada0fb
|
Word2Vec
|
import torch
from torch import nn
import torch.functional as F
import torch.nn.functional as F
class Word2Vec(torch.nn.Module):
def __init__(self, vocab_size, embedding_size=300):
super(Word2Vec, self).__init__()
self.E = nn.Linear(vocab_size, embedding_size, bias=False)
self.W = nn.Linear(embedding_size, vocab_size)
def forward(self, one_hot):
z_e = self.E(one_hot)
z_w = self.W(z_e)
return F.log_softmax(z_w, dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'vocab_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_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')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (300, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 300), (300, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 300), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, buf0, reinterpret_tensor(primals_3,
(300, 4), (1, 300), 0), alpha=1, beta=1, out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](buf1, buf2, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused__log_softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf2
return buf3, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), buf0, buf3, primals_3
class Word2VecNew(torch.nn.Module):
def __init__(self, vocab_size, embedding_size=300):
super(Word2VecNew, self).__init__()
self.E = nn.Linear(vocab_size, embedding_size, bias=False)
self.W = nn.Linear(embedding_size, vocab_size)
def forward(self, input_0):
primals_1 = self.E.weight
primals_3 = self.W.weight
primals_4 = self.W.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
kfaRabi/NNTI-WS2021-NLP-Project
|
Word2Vec
| false
| 10,342
|
[
"MIT"
] | 0
|
9b0d28e64e3abc373e88265e47a4be4503d59a93
|
https://github.com/kfaRabi/NNTI-WS2021-NLP-Project/tree/9b0d28e64e3abc373e88265e47a4be4503d59a93
|
GroupedMultiHeadAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class GroupedMultiHeadAttention(MultiHeadAttention):
"""Grouped Mutli-Head Attention Layer
Grouped multi-head attention reduces attention complexity from O(T2·D) to O(T2·D/G)
by grouping neighbouring time elements along the feature dimension before applying
scaled dot-product attention.
Args:
dim_model: model feature dimension
num_heads: number of attention heads
group_size: attention group size
"""
def __init__(self, dim_model, num_heads, group_size):
super(GroupedMultiHeadAttention, self).__init__(dim_model, num_heads)
self.group_size = group_size
self.dim_head = self.group_size * dim_model // self.num_heads
def forward(self, Q, K, V, mask=None):
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q, K, V, mask, padding = self.pad(Q, K, V, mask, chunk_size=self.
group_size)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
mask = mask[:, :, ::self.group_size, ::self.group_size]
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = O[:, :O.size(1) - padding]
O = self.output_layer(O)
return O, att_w.detach()
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'dim_model': 4, 'num_heads': 4, 'group_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 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__softmax_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tmp2 - tmp2
tmp4 = 0.5
tmp5 = tmp3 * tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp6 / tmp6
tl.store(in_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) = 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), (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_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_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, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 1, 4), (4, 4, 1),
0), reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 1), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf3
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((16, 1, 4), (4, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 1, 1), (1, 1, 1),
0), reinterpret_tensor(buf2, (16, 1, 4), (4, 4, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf5, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf6)
del primals_11
return reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0
), buf4, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), buf4, reinterpret_tensor(buf5, (16, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 16), 0
), reinterpret_tensor(buf0, (16, 4, 1), (4, 1, 16), 0
), reinterpret_tensor(buf1, (16, 1, 4), (4, 16, 1), 0)
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class GroupedMultiHeadAttentionNew(MultiHeadAttention):
"""Grouped Mutli-Head Attention Layer
Grouped multi-head attention reduces attention complexity from O(T2·D) to O(T2·D/G)
by grouping neighbouring time elements along the feature dimension before applying
scaled dot-product attention.
Args:
dim_model: model feature dimension
num_heads: number of attention heads
group_size: attention group size
"""
def __init__(self, dim_model, num_heads, group_size):
super(GroupedMultiHeadAttentionNew, self).__init__(dim_model, num_heads
)
self.group_size = group_size
self.dim_head = self.group_size * dim_model // self.num_heads
def forward(self, input_0, input_1, input_2):
primals_2 = self.query_layer.weight
primals_3 = self.query_layer.bias
primals_4 = self.key_layer.weight
primals_5 = self.key_layer.bias
primals_7 = self.value_layer.weight
primals_8 = self.value_layer.bias
primals_10 = self.output_layer.weight
primals_11 = self.output_layer.bias
primals_1 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1]
|
debasish-mihup/EfficientConformer
|
GroupedMultiHeadAttention
| false
| 10,343
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
Conv1d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv1d(nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding='same', dilation=1, groups=1, bias=True):
super(Conv1d, self).__init__(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=0,
dilation=dilation, groups=groups, bias=bias, padding_mode='zeros')
assert padding in ['valid', 'same', 'causal']
if padding == 'valid':
self.pre_padding = None
elif padding == 'same':
self.pre_padding = nn.ConstantPad1d(padding=((kernel_size - 1) //
2, (kernel_size - 1) // 2), value=0)
elif padding == 'causal':
self.pre_padding = nn.ConstantPad1d(padding=(kernel_size - 1, 0
), value=0)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
if self.pre_padding is not None:
input = self.pre_padding(input)
return F.conv1d(input, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 24
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6
x2 = xindex
tmp0 = -1 + x0
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1), tmp5 & xmask, other=0.0)
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 = 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 6), (6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(24)](primals_2, buf0, 24,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_2
buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (1, 4, 6
), (0, 6, 1), 0), primals_1, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf1, (1, 4, 3), (12, 3, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(12)](buf2, primals_3, 12,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return reinterpret_tensor(buf2, (4, 3), (3, 1), 0
), primals_1, reinterpret_tensor(buf0, (1, 4, 6), (24, 6, 1), 0)
class Conv1dNew(nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding='same', dilation=1, groups=1, bias=True):
super(Conv1dNew, self).__init__(in_channels=in_channels,
out_channels=out_channels, kernel_size=kernel_size, stride=
stride, padding=0, dilation=dilation, groups=groups, bias=bias,
padding_mode='zeros')
assert padding in ['valid', 'same', 'causal']
if padding == 'valid':
self.pre_padding = None
elif padding == 'same':
self.pre_padding = nn.ConstantPad1d(padding=((kernel_size - 1) //
2, (kernel_size - 1) // 2), value=0)
elif padding == 'causal':
self.pre_padding = nn.ConstantPad1d(padding=(kernel_size - 1, 0
), value=0)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
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]
|
debasish-mihup/EfficientConformer
|
Conv1d
| false
| 10,344
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
InnerProductLayer
|
import torch
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
class InnerProductLayer(nn.Module):
"""InnerProduct Layer used in PNN that compute the element-wise
product or inner product between feature vectors.
Input shape
- a list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.
Output shape
- 3D tensor with shape: ``(batch_size, N*(N-1)/2 ,1)`` if use reduce_sum. or 3D tensor with shape:
``(batch_size, N*(N-1)/2, embedding_size )`` if not use reduce_sum.
Arguments
- **reduce_sum**: bool. Whether return inner product or element-wise product
References
- [Qu Y, Cai H, Ren K, et al. Product-based neural networks for user response prediction[C]//
Data Mining (ICDM), 2016 IEEE 16th International Conference on. IEEE, 2016: 1149-1154.]
(https://arxiv.org/pdf/1611.00144.pdf)"""
def __init__(self, reduce_sum=True, device='cpu'):
super(InnerProductLayer, self).__init__()
self.reduce_sum = reduce_sum
self
def forward(self, inputs):
embed_list = inputs
row = []
col = []
num_inputs = len(embed_list)
for i in range(num_inputs - 1):
for j in range(i + 1, num_inputs):
row.append(i)
col.append(j)
p = torch.cat([embed_list[idx] for idx in row], dim=1)
q = torch.cat([embed_list[idx] for idx in col], dim=1)
inner_product = p * q
if self.reduce_sum:
inner_product = torch.sum(inner_product, dim=2, keepdim=True)
return inner_product
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
from sklearn.metrics import *
import torch.onnx
import torch as torch
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 = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 24
x0 = xindex % 4
x2 = xindex // 96
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (x0 + 4 * (-4 + x1) + 16 * x2), tmp9 & xmask,
other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (x0 + 4 * (-8 + x1) + 16 * x2), tmp14 & xmask,
other=0.0)
tmp16 = tmp0 >= tmp12
tmp17 = tl.full([1], 16, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr0 + (64 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 &
xmask, other=0.0)
tmp21 = tmp0 >= tmp17
tmp22 = tl.full([1], 20, tl.int64)
tmp23 = tmp0 < tmp22
tmp24 = tmp21 & tmp23
tmp25 = tl.load(in_ptr0 + (64 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 &
xmask, other=0.0)
tmp26 = tmp0 >= tmp22
tl.full([1], 24, tl.int64)
tmp29 = tl.load(in_ptr0 + (128 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 &
xmask, other=0.0)
tmp30 = tl.where(tmp24, tmp25, 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, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 24
x0 = xindex % 4
x2 = xindex // 96
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 + (64 + x0 + 4 * x1 + 16 * 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_ptr0 + (128 + x0 + 4 * (-4 + x1) + 16 * x2), tmp9 &
xmask, other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (192 + x0 + 4 * (-8 + x1) + 16 * x2), tmp14 &
xmask, other=0.0)
tmp16 = tmp0 >= tmp12
tmp17 = tl.full([1], 16, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr0 + (128 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 &
xmask, other=0.0)
tmp21 = tmp0 >= tmp17
tmp22 = tl.full([1], 20, tl.int64)
tmp23 = tmp0 < tmp22
tmp24 = tmp21 & tmp23
tmp25 = tl.load(in_ptr0 + (192 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 &
xmask, other=0.0)
tmp26 = tmp0 >= tmp22
tl.full([1], 24, tl.int64)
tmp29 = tl.load(in_ptr0 + (192 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 &
xmask, other=0.0)
tmp30 = tl.where(tmp24, tmp25, 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, xmask)
@triton.jit
def triton_poi_fused_mul_sum_2(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
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
tl.store(out_ptr0 + x0, tmp14, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(384)](arg0_1, buf0, 384, XBLOCK=256,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.float32)
triton_poi_fused_cat_1[grid(384)](arg0_1, buf1, 384, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 24, 1), (24, 1, 1), torch.float32)
triton_poi_fused_mul_sum_2[grid(96)](buf0, buf1, buf2, 96, XBLOCK=
128, num_warps=4, num_stages=1)
del buf0
del buf1
return buf2,
class InnerProductLayerNew(nn.Module):
"""InnerProduct Layer used in PNN that compute the element-wise
product or inner product between feature vectors.
Input shape
- a list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.
Output shape
- 3D tensor with shape: ``(batch_size, N*(N-1)/2 ,1)`` if use reduce_sum. or 3D tensor with shape:
``(batch_size, N*(N-1)/2, embedding_size )`` if not use reduce_sum.
Arguments
- **reduce_sum**: bool. Whether return inner product or element-wise product
References
- [Qu Y, Cai H, Ren K, et al. Product-based neural networks for user response prediction[C]//
Data Mining (ICDM), 2016 IEEE 16th International Conference on. IEEE, 2016: 1149-1154.]
(https://arxiv.org/pdf/1611.00144.pdf)"""
def __init__(self, reduce_sum=True, device='cpu'):
super(InnerProductLayerNew, self).__init__()
self.reduce_sum = reduce_sum
self
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
InnerProductLayer
| false
| 10,345
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
SequenceBias
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from torch.nn.parameter import Parameter
class SequenceBias(nn.Module):
""" Adds one bias element to the end of the sequence
Args:
embed_dim: Embedding dimension
Shape:
- Input: (L, N, E), where
L - sequence length, N - batch size, E - embedding dimension
- Output: (L+1, N, E), where
L - sequence length, N - batch size, E - embedding dimension
Attributes:
bias: the learnable bias of the module of shape (E),
where E - embedding dimension
Examples::
>>> m = SequenceBias(16)
>>> input = torch.randn(20, 4, 16)
>>> output = m(input)
>>> print(output.size())
torch.Size([21, 4, 16])
"""
def __init__(self, embed_dim):
super(SequenceBias, self).__init__()
self.bias = Parameter(torch.empty(embed_dim))
self._reset_parameters()
def _reset_parameters(self):
nn.init.normal_(self.bias)
def forward(self, x):
_, bsz, _ = x.shape
return torch.cat([x, self.bias.repeat(1, bsz, 1)])
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embed_dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(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
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x4 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x3 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp9 = tl.load(in_ptr1 + x0, tmp6 & xmask, eviction_policy='evict_last',
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x4, tmp10, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((5, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(80)](primals_1, primals_2, buf0, 80,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0,
class SequenceBiasNew(nn.Module):
""" Adds one bias element to the end of the sequence
Args:
embed_dim: Embedding dimension
Shape:
- Input: (L, N, E), where
L - sequence length, N - batch size, E - embedding dimension
- Output: (L+1, N, E), where
L - sequence length, N - batch size, E - embedding dimension
Attributes:
bias: the learnable bias of the module of shape (E),
where E - embedding dimension
Examples::
>>> m = SequenceBias(16)
>>> input = torch.randn(20, 4, 16)
>>> output = m(input)
>>> print(output.size())
torch.Size([21, 4, 16])
"""
def __init__(self, embed_dim):
super(SequenceBiasNew, self).__init__()
self.bias = Parameter(torch.empty(embed_dim))
self._reset_parameters()
def _reset_parameters(self):
nn.init.normal_(self.bias)
def forward(self, input_0):
primals_2 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jyhong836/pytorch-dp
|
SequenceBias
| false
| 10,346
|
[
"Apache-2.0"
] | 0
|
e050b98d630d4db50cacc4fff82575daf345f012
|
https://github.com/jyhong836/pytorch-dp/tree/e050b98d630d4db50cacc4fff82575daf345f012
|
AGRUCell
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import *
import torch.onnx
import torch as torch
class AGRUCell(nn.Module):
""" Attention based GRU (AGRU)
Reference:
- Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018.
"""
def __init__(self, input_size, hidden_size, bias=True):
super(AGRUCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size)
)
self.register_parameter('weight_ih', self.weight_ih)
self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size,
hidden_size))
self.register_parameter('weight_hh', self.weight_hh)
if bias:
self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size))
self.register_parameter('bias_ih', self.bias_ih)
self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size))
self.register_parameter('bias_hh', self.bias_hh)
for tensor in [self.bias_ih, self.bias_hh]:
nn.init.zeros_(tensor)
else:
self.register_parameter('bias_ih', None)
self.register_parameter('bias_hh', None)
def forward(self, inputs, hx, att_score):
gi = F.linear(inputs, self.weight_ih, self.bias_ih)
gh = F.linear(hx, self.weight_hh, self.bias_hh)
i_r, _, i_n = gi.chunk(3, 1)
h_r, _, h_n = gh.chunk(3, 1)
reset_gate = torch.sigmoid(i_r + h_r)
new_state = torch.tanh(i_n + reset_gate * h_n)
att_score = att_score.view(-1, 1)
hy = (1.0 - att_score) * hx + att_score * new_state
return hy
def get_inputs():
return [torch.rand([16, 4]), torch.rand([16, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
assert_size_stride = torch._C._dynamo.guards.assert_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_rsub_sigmoid_tanh_tanh_backward_0(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 12 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 12 * x1), xmask)
tmp6 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr4 + x2, xmask)
tmp11 = tl.load(in_ptr0 + (8 + x0 + 12 * x1), xmask)
tmp12 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr2 + (8 + x0 + 12 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tmp7 = 1.0
tmp8 = tmp7 - tmp6
tmp10 = tmp8 * tmp9
tmp13 = tmp11 + tmp12
tmp15 = tmp5 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = libdevice.tanh(tmp16)
tmp18 = tmp6 * tmp17
tmp19 = tmp10 + tmp18
tmp20 = tmp17 * tmp17
tmp21 = tmp7 - tmp20
tl.store(out_ptr0 + x2, tmp5, xmask)
tl.store(out_ptr1 + x2, tmp19, xmask)
tl.store(out_ptr2 + x2, tmp21, 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, (12, 4), (4, 1))
assert_size_stride(primals_2, (12,), (1,))
assert_size_stride(primals_3, (16, 4), (4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (16, 4), (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((16, 12), (12, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 12),
(1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 12), (12, 1), torch.float32)
extern_kernels.addmm(primals_5, primals_6, reinterpret_tensor(
primals_4, (4, 12), (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)
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_rsub_sigmoid_tanh_tanh_backward_0[grid(64)](
buf0, primals_2, buf1, primals_7, primals_6, buf2, buf3, buf4,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf0
del primals_2
return buf3, primals_3, primals_6, primals_7, reinterpret_tensor(buf1,
(16, 4), (12, 1), 8), buf2, buf4
class AGRUCellNew(nn.Module):
""" Attention based GRU (AGRU)
Reference:
- Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018.
"""
def __init__(self, input_size, hidden_size, bias=True):
super(AGRUCellNew, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size)
)
self.register_parameter('weight_ih', self.weight_ih)
self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size,
hidden_size))
self.register_parameter('weight_hh', self.weight_hh)
if bias:
self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size))
self.register_parameter('bias_ih', self.bias_ih)
self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size))
self.register_parameter('bias_hh', self.bias_hh)
for tensor in [self.bias_ih, self.bias_hh]:
nn.init.zeros_(tensor)
else:
self.register_parameter('bias_ih', None)
self.register_parameter('bias_hh', None)
def forward(self, input_0, input_1, input_2):
primals_1 = self.weight_ih
primals_4 = self.weight_hh
primals_2 = self.bias_ih
primals_5 = self.bias_hh
primals_3 = input_0
primals_6 = input_1
primals_7 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
AGRUCell
| false
| 10,347
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
NoiseInjection
|
import torch
from torch import nn
class NoiseInjection(nn.Module):
def __init__(self, channel):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
def forward(self, image, noise):
return image + self.weight * noise
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channel': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x3, xmask)
tmp3 = tmp1 * tmp2
tmp4 = tmp0 + tmp3
tl.store(out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_3, primals_1,
primals_2, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_3
return buf0, primals_2
class NoiseInjectionNew(nn.Module):
def __init__(self, channel):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jeromepl/style-based-gan-pytorch
|
NoiseInjection
| false
| 10,348
|
[
"MIT"
] | 0
|
97c13e54316dc57a7cb44c0cb910c29aaed11738
|
https://github.com/jeromepl/style-based-gan-pytorch/tree/97c13e54316dc57a7cb44c0cb910c29aaed11738
|
MultiHeadLinearAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class MultiHeadLinearAttention(MultiHeadAttention):
"""Multi-Head Linear Attention
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Efficient Attention: Attention with Linear Complexities, Shen et al.
https://arxiv.org/abs/1812.01243
Efficient conformer-based speech recognition with linear attention, Li et al.
https://arxiv.org/abs/2104.06865
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadLinearAttention, self).__init__(dim_model, num_heads)
def forward(self, Q, K, V):
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
KV = (K / K.shape[-1] ** (1.0 / 4.0)).softmax(dim=-2).transpose(2, 3
).matmul(V)
O = (Q / Q.shape[-1] ** (1.0 / 4.0)).softmax(dim=-1).matmul(KV)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, KV.detach()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_model': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__softmax_div_0(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 4
x1 = xindex // 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.where(xmask, tmp5, float('-inf'))
tmp8 = triton_helpers.max2(tmp7, 1)[:, None]
tmp9 = tmp4 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.where(xmask, tmp11, 0)
tmp14 = tl.sum(tmp13, 1)[:, None]
tmp15 = tmp10 / tmp14
tl.store(out_ptr2 + (r2 + 16 * x3), tmp15, xmask)
@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 = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 64 * y1), xmask & ymask)
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 16 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_div_2(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
y3 = yindex
y0 = yindex % 16
y1 = yindex // 16
tmp0 = tl.load(in_ptr0 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp5 = tmp4 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp6 / tmp6
tl.store(out_ptr0 + (y0 + 16 * x2 + 64 * y1), tmp7, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(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, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4, 4, 4), (64, 16, 4, 1))
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((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (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_9, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf5 = empty_strided_cuda((4, 4, 16, 1), (64, 16, 1, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__softmax_div_0[grid(16)](buf1, primals_5, buf5, 16,
16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_5
buf6 = reinterpret_tensor(buf1, (4, 4, 16, 1), (64, 16, 1, 1), 0)
del buf1
triton_poi_fused_clone_1[grid(16, 16)](buf2, primals_8, buf6, 16,
16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del primals_8
buf7 = empty_strided_cuda((16, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 1, 16), (16, 16, 1
), 0), reinterpret_tensor(buf6, (16, 16, 1), (16, 1, 0), 0),
out=buf7)
buf8 = reinterpret_tensor(buf2, (4, 4, 16, 1), (64, 16, 1, 1), 0)
del buf2
triton_poi_fused__softmax_div_2[grid(64, 4)](buf0, primals_3, buf8,
64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf9 = reinterpret_tensor(buf0, (16, 16, 1), (16, 1, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 16, 1), (16, 1, 1),
0), buf7, out=buf9)
buf10 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(64, 4)](buf9, buf10, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf11 = reinterpret_tensor(buf9, (64, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf10, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 16, 4), (64, 4, 1), 0)
del buf11
triton_poi_fused_add_4[grid(256)](buf12, primals_11, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_11
return buf12, reinterpret_tensor(buf7, (4, 4, 1, 1), (4, 1, 1, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (64, 4), (4, 1), 0
), buf5, buf8, reinterpret_tensor(buf10, (64, 4), (4, 1), 0
), primals_10, buf7, reinterpret_tensor(buf6, (16, 1, 16), (16, 1,
1), 0)
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class MultiHeadLinearAttentionNew(MultiHeadAttention):
"""Multi-Head Linear Attention
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Efficient Attention: Attention with Linear Complexities, Shen et al.
https://arxiv.org/abs/1812.01243
Efficient conformer-based speech recognition with linear attention, Li et al.
https://arxiv.org/abs/2104.06865
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadLinearAttentionNew, self).__init__(dim_model, num_heads)
def forward(self, input_0, input_1, input_2):
primals_2 = self.query_layer.weight
primals_3 = self.query_layer.bias
primals_4 = self.key_layer.weight
primals_5 = self.key_layer.bias
primals_7 = self.value_layer.weight
primals_8 = self.value_layer.bias
primals_10 = self.output_layer.weight
primals_11 = self.output_layer.bias
primals_1 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1]
|
debasish-mihup/EfficientConformer
|
MultiHeadLinearAttention
| false
| 10,349
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
AdaptiveInstanceNorm
|
import torch
from torch import nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveInstanceNorm(nn.Module):
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.style = EqualLinear(style_dim, in_channel * 2)
self.style.linear.bias.data[:in_channel] = 1
self.style.linear.bias.data[in_channel:] = 0
def forward(self, input, style):
style = self.style(style).unsqueeze(2).unsqueeze(3)
gamma, beta = style.chunk(2, 1)
out = self.norm(input)
out = gamma * out + beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_mul_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp22 = tl.load(in_ptr1 + (x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr1 + (4 + x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr2 + (4 + x2), xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 16.0
tmp18 = tmp16 / tmp17
tmp19 = 1e-05
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tmp24 = tmp22 + tmp23
tmp25 = tmp0 - tmp10
tmp26 = tmp25 * tmp21
tmp27 = tmp24 * tmp26
tmp30 = tmp28 + tmp29
tmp31 = tmp27 + tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(out_ptr1 + (r1 + 16 * x0), tmp31, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (8, 4), (4, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((8, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(32)](primals_1, buf0, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(buf0, (4, 8), (1, 4
), 0), out=buf1)
buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf3 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf5 = reinterpret_tensor(buf3, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused__native_batch_norm_legit_add_mul_1[grid(16)](buf5,
primals_4, buf1, primals_2, buf2, buf6, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del buf1
del primals_2
return buf6, buf0, primals_3, primals_4, buf2, buf5
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveInstanceNormNew(nn.Module):
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.style = EqualLinear(style_dim, in_channel * 2)
self.style.linear.bias.data[:in_channel] = 1
self.style.linear.bias.data[in_channel:] = 0
def forward(self, input_0, input_1):
primals_2 = self.style.linear.bias
primals_1 = self.style.linear.weight_orig
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jeromepl/style-based-gan-pytorch
|
AdaptiveInstanceNorm
| false
| 10,350
|
[
"MIT"
] | 0
|
97c13e54316dc57a7cb44c0cb910c29aaed11738
|
https://github.com/jeromepl/style-based-gan-pytorch/tree/97c13e54316dc57a7cb44c0cb910c29aaed11738
|
ATT
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ATT(nn.Module):
def __init__(self, din):
super(ATT, self).__init__()
self.fc1 = nn.Linear(din, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, 1)
def forward(self, x):
y = F.relu(self.fc1(x))
y = F.relu(self.fc2(y))
y = F.sigmoid(self.fc3(y))
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'din': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (1, 64), (64, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf7, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf3,
primals_5, buf6, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_6, (64, 1), (1, 64), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf4
triton_poi_fused_sigmoid_1[grid(64)](buf5, primals_7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_7
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(
buf3, (64, 64), (64, 1), 0), buf5, primals_6, buf6, primals_4, buf7
class ATTNew(nn.Module):
def __init__(self, din):
super(ATTNew, self).__init__()
self.fc1 = nn.Linear(din, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, 1)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jungwoohan72/DGN_pytorch
|
ATT
| false
| 10,351
|
[
"MIT"
] | 0
|
65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
https://github.com/jungwoohan72/DGN_pytorch/tree/65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
LocalMultiHeadAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class LocalMultiHeadAttention(MultiHeadAttention):
"""Local Multi-Head Attention Layer
Local multi-head attention restricts the attended positions to a local neighborhood
around the query position. This is achieved by segmenting the hidden sequence into
non overlapping blocks of size K and performing scaled dot-product attention in
parallel for each of these blocks.
Args:
dim_model: model feature dimension
num_heads: number of attention heads
kernel_size: attention kernel size / window
References:
Image Transformer, Parmar et al.
https://arxiv.org/abs/1802.05751
"""
def __init__(self, dim_model, num_heads, kernel_size):
super(LocalMultiHeadAttention, self).__init__(dim_model, num_heads)
self.kernel_size = kernel_size
def forward(self, Q, K, V, mask=None):
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q, K, V, mask, padding = self.pad(Q, K, V, mask, chunk_size=self.
kernel_size)
Q = Q.reshape(batch_size, -1, self.kernel_size, self.num_heads,
self.dim_head).transpose(2, 3)
K = K.reshape(batch_size, -1, self.kernel_size, self.num_heads,
self.dim_head).transpose(2, 3)
V = V.reshape(batch_size, -1, self.kernel_size, self.num_heads,
self.dim_head).transpose(2, 3)
att_scores = Q.matmul(K.transpose(3, 4)) / K.shape[-1] ** 0.5
if mask is not None:
masks = []
for m in range(mask.size(-1) // self.kernel_size):
masks.append(mask[:, :, m * self.kernel_size:(m + 1) * self
.kernel_size, m * self.kernel_size:(m + 1) * self.
kernel_size])
mask = torch.stack(masks, dim=1)
att_scores = att_scores.float() - mask.float() * 1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(2, 3).reshape(batch_size, -1, self.dim_model)
O = O[:, :O.size(1) - padding]
O = self.output_layer(O)
return O, att_w.detach()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4,
4, 4, 4])]
def get_init_inputs():
return [[], {'dim_model': 4, 'num_heads': 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 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_clone_0(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 % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, 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
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x1 + 4 * x0 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x4, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, 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, 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), (16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4, 4, 4), (64, 16, 4, 1))
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((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((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((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (64, 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, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](buf0, primals_3, buf3, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1, 4), (64, 16, 4, 4, 1), 0)
del buf0
triton_poi_fused_clone_1[grid(256)](buf1, primals_5, buf4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_5
buf5 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (64, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (64, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused__softmax_2[grid(1024)](buf5, buf6, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0
)
del buf5
triton_poi_fused__softmax_3[grid(1024)](buf6, buf7, 1024, XBLOCK=
128, num_warps=4, num_stages=1)
del buf6
buf8 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
triton_poi_fused_clone_0[grid(64, 4)](buf2, primals_8, buf8, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (64, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (64, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1),
torch.float32)
triton_poi_fused_clone_4[grid(64, 4)](buf9, buf10, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf11 = reinterpret_tensor(buf9, (64, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_11, reinterpret_tensor(buf10, (64, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_11
return reinterpret_tensor(buf11, (4, 16, 4), (64, 4, 1), 0
), buf7, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (64, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (64, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf8, (64, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (64, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (64, 4, 1), (4, 1, 4), 0)
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in_features=in_features, out_features=
out_features, bias=bias)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
return F.linear(input, weight, self.bias)
class MultiHeadAttention(nn.Module):
"""Mutli-Head Attention Layer
Args:
dim_model: model feature dimension
num_heads: number of attention heads
References:
Attention Is All You Need, Vaswani et al.
https://arxiv.org/abs/1706.03762
"""
def __init__(self, dim_model, num_heads):
super(MultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.dim_model = dim_model
self.dim_head = dim_model // num_heads
self.query_layer = Linear(self.dim_model, self.dim_model)
self.key_layer = Linear(self.dim_model, self.dim_model)
self.value_layer = Linear(self.dim_model, self.dim_model)
self.output_layer = Linear(self.dim_model, self.dim_model)
def forward(self, Q, K, V, mask=None):
"""Scaled Dot-Product Multi-Head Attention
Args:
Q: Query of shape (B, T, D)
K: Key of shape (B, T, D)
V: Value of shape (B, T, D)
mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
Return:
O: Attention output of shape (B, T, D)
att_w: Attention weights of shape (B, H, T, T)
"""
batch_size = Q.size(0)
Q = self.query_layer(Q)
K = self.key_layer(K)
V = self.value_layer(V)
Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
1, 2)
att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
if mask is not None:
att_scores += mask * -1000000000.0
att_w = att_scores.softmax(dim=-1)
O = att_w.matmul(V)
O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
O = self.output_layer(O)
return O, att_w.detach()
def pad(self, Q, K, V, mask, chunk_size):
overflow_Q = Q.size(1) % chunk_size
overflow_KV = K.size(1) % chunk_size
padding_Q = chunk_size - overflow_Q if overflow_Q else 0
padding_KV = chunk_size - overflow_KV if overflow_KV else 0
batch_size, seq_len_KV, _ = K.size()
Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
K = F.pad(K, (0, 0, 0, padding_KV), value=0)
V = F.pad(V, (0, 0, 0, padding_KV), value=0)
if mask is not None:
if mask.size(2) == 1:
mask = F.pad(mask, pad=(0, padding_KV), value=1)
else:
mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
elif padding_KV:
mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
padding_KV), value=1)
return Q, K, V, mask, padding_Q
class LocalMultiHeadAttentionNew(MultiHeadAttention):
"""Local Multi-Head Attention Layer
Local multi-head attention restricts the attended positions to a local neighborhood
around the query position. This is achieved by segmenting the hidden sequence into
non overlapping blocks of size K and performing scaled dot-product attention in
parallel for each of these blocks.
Args:
dim_model: model feature dimension
num_heads: number of attention heads
kernel_size: attention kernel size / window
References:
Image Transformer, Parmar et al.
https://arxiv.org/abs/1802.05751
"""
def __init__(self, dim_model, num_heads, kernel_size):
super(LocalMultiHeadAttentionNew, self).__init__(dim_model, num_heads)
self.kernel_size = kernel_size
def forward(self, input_0, input_1, input_2):
primals_2 = self.query_layer.weight
primals_3 = self.query_layer.bias
primals_4 = self.key_layer.weight
primals_5 = self.key_layer.bias
primals_7 = self.value_layer.weight
primals_8 = self.value_layer.bias
primals_10 = self.output_layer.weight
primals_11 = self.output_layer.bias
primals_1 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1]
|
debasish-mihup/EfficientConformer
|
LocalMultiHeadAttention
| false
| 10,352
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
MLPTanH
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.onnx
import torch.optim
import torch.utils.data.distributed
class MLPTanH(nn.Module):
def __init__(self, input_dim, hidden_dim, vocab_size):
super(MLPTanH, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.layers = nn.Sequential()
linear = nn.Linear(input_dim, hidden_dim)
self.layers.add_module('fc_0', linear)
self.layers.add_module('Tanh_0', nn.Tanh())
self.layers.add_module('fc_1', nn.Linear(hidden_dim, vocab_size))
def forward(self, x):
return self.layers(x.view(x.size(0), -1))
def set_decoder_weights(self, embedding_weights):
self.layers.fc_1.weight = embedding_weights
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'hidden_dim': 4, 'vocab_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.onnx
import torch.optim
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
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,), (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), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(16)](buf1, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del primals_5
return buf2, primals_1, buf1, primals_4
class MLPTanHNew(nn.Module):
def __init__(self, input_dim, hidden_dim, vocab_size):
super(MLPTanHNew, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.layers = nn.Sequential()
linear = nn.Linear(input_dim, hidden_dim)
self.layers.add_module('fc_0', linear)
self.layers.add_module('Tanh_0', nn.Tanh())
self.layers.add_module('fc_1', nn.Linear(hidden_dim, vocab_size))
def set_decoder_weights(self, embedding_weights):
self.layers.fc_1.weight = embedding_weights
def forward(self, input_0):
primals_1 = self.layers.fc_0.weight
primals_3 = self.layers.fc_0.bias
primals_2 = self.layers.fc_1.weight
primals_5 = self.layers.fc_1.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
kiathwe97/examples
|
MLPTanH
| false
| 10,353
|
[
"BSD-3-Clause"
] | 0
|
b4a8792023db8c50c7e9fb186bd982edd0dce3ce
|
https://github.com/kiathwe97/examples/tree/b4a8792023db8c50c7e9fb186bd982edd0dce3ce
|
Critic
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, num_inputs, num_actions):
super(Critic, self).__init__()
self.fc1 = nn.Linear(num_inputs, 100)
self.state_value = nn.Linear(100, 1)
def forward(self, x):
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
value = self.state_value(x)
return value
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 100
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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (100, 4), (4, 1))
assert_size_stride(primals_3, (100,), (1,))
assert_size_stride(primals_4, (1, 100), (100, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 100), (100, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 100),
(1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(400)](buf1, primals_3, 400, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(100, 1), (1, 100), 0), alpha=1, beta=1, out=buf3)
del primals_5
return buf3, primals_1, buf1, primals_4
class CriticNew(nn.Module):
def __init__(self, num_inputs, num_actions):
super(CriticNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, 100)
self.state_value = nn.Linear(100, 1)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.state_value.weight
primals_5 = self.state_value.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
kama1kant/rl-autonomous-driving
|
Critic
| false
| 10,354
|
[
"MIT"
] | 0
|
8f8687ff81892874a32c6a556c6be2e686012731
|
https://github.com/kama1kant/rl-autonomous-driving/tree/8f8687ff81892874a32c6a556c6be2e686012731
|
CustomGruCell
|
import torch
import numpy as np
from torch import nn
class CustomGruCell(nn.Module):
"""
A forward only GRU cell.
Input should be: (sequence length x batch size x input_size).
The output is the output of the final forward call.
It's not clear if it would be possible to use the output from each cell in a Plan
because of the assumptions of 2D tensors in backprop.
"""
def __init__(self, input_size, hidden_size, bias=True):
super(CustomGruCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc_ir = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hr = nn.Linear(hidden_size, hidden_size, bias=bias)
self.fc_iz = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hz = nn.Linear(hidden_size, hidden_size, bias=bias)
self.fc_in = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hn = nn.Linear(hidden_size, hidden_size, bias=bias)
self.init_parameters()
def init_parameters(self):
std = 1.0 / np.sqrt(self.hidden_size)
for w in self.parameters():
w.data.uniform_(-std, std)
def forward(self, x, h):
i_r = self.fc_ir(x)
h_r = self.fc_hr(h)
i_z = self.fc_iz(x)
h_z = self.fc_hz(h)
i_n = self.fc_in(x)
h_n = self.fc_hn(h)
resetgate = (i_r + h_r).sigmoid()
inputgate = (i_z + h_z).sigmoid()
newgate = (i_n + resetgate * h_n).tanh()
hy = newgate + inputgate * (h - newgate)
return hy
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mul_sigmoid_sub_tanh_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7,
in_ptr8, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_out_ptr1 + x2, xmask)
tmp9 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, xmask)
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr6 + x2, xmask)
tmp17 = tl.load(in_ptr7 + x2, xmask)
tmp21 = tl.load(in_ptr8 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp18 = tmp7 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = libdevice.tanh(tmp19)
tmp22 = tmp21 - tmp20
tmp23 = tmp15 * tmp22
tmp24 = tmp20 + tmp23
tl.store(in_out_ptr0 + x2, tmp7, xmask)
tl.store(in_out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr0 + x2, tmp24, 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, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf3)
del primals_9
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_12, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_11, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf4)
del primals_11
del primals_12
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_14, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0), reinterpret_tensor(primals_13, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf5)
del primals_13
del primals_14
buf6 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf7 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_sigmoid_sub_tanh_0[grid(256)](buf6, buf7,
primals_2, buf1, primals_5, primals_8, buf3, primals_10, buf4,
buf5, primals_6, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del buf3
del primals_10
del primals_2
del primals_5
del primals_8
return buf8, primals_6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf4, buf5, buf6, buf7
class CustomGruCellNew(nn.Module):
"""
A forward only GRU cell.
Input should be: (sequence length x batch size x input_size).
The output is the output of the final forward call.
It's not clear if it would be possible to use the output from each cell in a Plan
because of the assumptions of 2D tensors in backprop.
"""
def __init__(self, input_size, hidden_size, bias=True):
super(CustomGruCellNew, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc_ir = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hr = nn.Linear(hidden_size, hidden_size, bias=bias)
self.fc_iz = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hz = nn.Linear(hidden_size, hidden_size, bias=bias)
self.fc_in = nn.Linear(input_size, hidden_size, bias=bias)
self.fc_hn = nn.Linear(hidden_size, hidden_size, bias=bias)
self.init_parameters()
def init_parameters(self):
std = 1.0 / np.sqrt(self.hidden_size)
for w in self.parameters():
w.data.uniform_(-std, std)
def forward(self, input_0, input_1):
primals_1 = self.fc_ir.weight
primals_2 = self.fc_ir.bias
primals_4 = self.fc_hr.weight
primals_5 = self.fc_hr.bias
primals_7 = self.fc_iz.weight
primals_8 = self.fc_iz.bias
primals_9 = self.fc_hz.weight
primals_10 = self.fc_hz.bias
primals_11 = self.fc_in.weight
primals_12 = self.fc_in.bias
primals_13 = self.fc_hn.weight
primals_14 = self.fc_hn.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14])
return output[0]
|
kouohhashi/PySyft
|
CustomGruCell
| false
| 10,355
|
[
"Apache-2.0"
] | 0
|
7415961b459f1d25f762467b346b7b94c1d6943f
|
https://github.com/kouohhashi/PySyft/tree/7415961b459f1d25f762467b346b7b94c1d6943f
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, num_inputs, num_actions):
super(Actor, self).__init__()
self.fc1 = nn.Linear(num_inputs, 100)
self.action_head = nn.Linear(100, num_actions)
def forward(self, x):
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
action_prob = F.softmax(self.action_head(x), dim=1)
return action_prob
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
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 = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 100
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__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (100, 4), (4, 1))
assert_size_stride(primals_3, (100,), (1,))
assert_size_stride(primals_4, (4, 100), (100, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 100), (100, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 100),
(1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(400)](buf1, primals_3, 400, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(100, 4), (1, 100), 0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused__softmax_2[grid(16)](buf3, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf3
return buf4, primals_1, buf1, buf4, primals_4
class ActorNew(nn.Module):
def __init__(self, num_inputs, num_actions):
super(ActorNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, 100)
self.action_head = nn.Linear(100, num_actions)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.action_head.weight
primals_5 = self.action_head.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
kama1kant/rl-autonomous-driving
|
Actor
| false
| 10,356
|
[
"MIT"
] | 0
|
8f8687ff81892874a32c6a556c6be2e686012731
|
https://github.com/kama1kant/rl-autonomous-driving/tree/8f8687ff81892874a32c6a556c6be2e686012731
|
AttModel
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class AttModel(nn.Module):
def __init__(self, n_node, din, hidden_dim, dout):
super(AttModel, self).__init__()
self.fcv = nn.Linear(din, hidden_dim)
self.fck = nn.Linear(din, hidden_dim)
self.fcq = nn.Linear(din, hidden_dim)
self.fcout = nn.Linear(hidden_dim, dout)
def forward(self, x, mask):
v = F.relu(self.fcv(x))
q = F.relu(self.fcq(x))
k = F.relu(self.fck(x)).permute(0, 2, 1)
att = F.softmax(torch.mul(torch.bmm(q, k), mask) -
9000000000000000.0 * (1 - mask), dim=2)
out = torch.bmm(att, v)
out = F.relu(self.fcout(out))
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_node': 4, 'din': 4, 'hidden_dim': 4, 'dout': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_rsub_sub_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp23 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = 9000000000000000.0
tmp6 = tmp4 * tmp5
tmp7 = tmp2 - tmp6
tmp10 = tmp8 * tmp9
tmp11 = tmp3 - tmp9
tmp12 = tmp11 * tmp5
tmp13 = tmp10 - tmp12
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp17 = tmp15 * tmp16
tmp18 = tmp3 - tmp16
tmp19 = tmp18 * tmp5
tmp20 = tmp17 - tmp19
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp24 = tmp22 * tmp23
tmp25 = tmp3 - 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 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp39, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_rsub_sub_3(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x2, xmask)
tmp8 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = 9000000000000000.0
tmp6 = tmp4 * tmp5
tmp7 = tmp2 - tmp6
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tl.store(in_out_ptr0 + x2, 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) = 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), (16, 4, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (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 = reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(64)](buf1, primals_2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
del primals_4
buf3 = reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
del buf2
triton_poi_fused_relu_0[grid(64)](buf3, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf4 = 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=buf4)
del primals_6
buf5 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf5,
primals_7, buf14, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf5, (4, 4, 4), (16, 1,
4), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused__softmax_mul_rsub_sub_2[grid(16)](buf6, primals_8,
buf7, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf9 = buf6
del buf6
triton_poi_fused__softmax_mul_rsub_sub_3[grid(64)](buf9, primals_8,
buf7, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf7
del buf8
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf9, buf1, out=buf10)
buf11 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf12,
primals_10, buf13, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
return buf12, primals_8, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf1, buf3, buf9, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), buf13, primals_9, buf5, buf14
class AttModelNew(nn.Module):
def __init__(self, n_node, din, hidden_dim, dout):
super(AttModelNew, self).__init__()
self.fcv = nn.Linear(din, hidden_dim)
self.fck = nn.Linear(din, hidden_dim)
self.fcq = nn.Linear(din, hidden_dim)
self.fcout = nn.Linear(hidden_dim, dout)
def forward(self, input_0, input_1):
primals_1 = self.fcv.weight
primals_2 = self.fcv.bias
primals_4 = self.fck.weight
primals_5 = self.fck.bias
primals_6 = self.fcq.weight
primals_7 = self.fcq.bias
primals_9 = self.fcout.weight
primals_10 = self.fcout.bias
primals_3 = 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])
return output[0]
|
jungwoohan72/DGN_pytorch
|
AttModel
| false
| 10,357
|
[
"MIT"
] | 0
|
65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
https://github.com/jungwoohan72/DGN_pytorch/tree/65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
Downsample
|
import torch
import torch.nn as nn
import torch.nn.parallel
class Downsample(nn.Module):
"""
Image to Patch Embedding, downsampling between stage1 and stage2
"""
def __init__(self, in_embed_dim, out_embed_dim, patch_size):
super().__init__()
self.proj = nn.Conv2d(in_embed_dim, out_embed_dim, kernel_size=
patch_size, stride=patch_size)
def forward(self, x):
x = x.permute(0, 3, 1, 2)
x = self.proj(x)
x = x.permute(0, 2, 3, 1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_embed_dim': 4, 'out_embed_dim': 4, 'patch_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
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_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 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, 1, 16, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 16)](primals_2, buf0, 16,
16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(reinterpret_tensor(primals_1, (4,
4, 4, 4), (64, 1, 16, 4), 0), buf0, stride=(4, 4), padding=(0,
0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 1, 1), (4, 1, 4, 4))
del buf0
buf2 = reinterpret_tensor(buf1, (4, 4, 1, 1), (4, 1, 16, 16), 0)
del buf1
triton_poi_fused_convolution_1[grid(16)](buf2, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return reinterpret_tensor(buf2, (4, 1, 1, 4), (4, 4, 4, 1), 0
), primals_2, reinterpret_tensor(primals_1, (4, 4, 4, 4), (64, 1,
16, 4), 0)
class DownsampleNew(nn.Module):
"""
Image to Patch Embedding, downsampling between stage1 and stage2
"""
def __init__(self, in_embed_dim, out_embed_dim, patch_size):
super().__init__()
self.proj = nn.Conv2d(in_embed_dim, out_embed_dim, kernel_size=
patch_size, stride=patch_size)
def forward(self, input_0):
primals_1 = self.proj.weight
primals_3 = self.proj.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
javierrodenas/clearml_javi
|
Downsample
| false
| 10,358
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
BiInteractionPooling
|
import torch
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
class BiInteractionPooling(nn.Module):
"""Bi-Interaction Layer used in Neural FM,compress the
pairwise element-wise product of features into one single vector.
Input shape
- A 3D tensor with shape:``(batch_size,field_size,embedding_size)``.
Output shape
- 3D tensor with shape: ``(batch_size,1,embedding_size)``.
References
- [He X, Chua T S. Neural factorization machines for sparse predictive analytics[C]//Proceedings of the 40th International ACM SIGIR conference on Research and Development in Information Retrieval. ACM, 2017: 355-364.](http://arxiv.org/abs/1708.05027)
"""
def __init__(self):
super(BiInteractionPooling, self).__init__()
def forward(self, inputs):
concated_embeds_value = inputs
square_of_sum = torch.pow(torch.sum(concated_embeds_value, dim=1,
keepdim=True), 2)
sum_of_square = torch.sum(concated_embeds_value *
concated_embeds_value, dim=1, keepdim=True)
cross_term = 0.5 * (square_of_sum - sum_of_square)
return cross_term
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
from sklearn.metrics import *
import torch.onnx
import torch as torch
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_pow_sub_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp0 * tmp0
tmp9 = tmp1 * tmp1
tmp10 = tmp8 + tmp9
tmp11 = tmp3 * tmp3
tmp12 = tmp10 + tmp11
tmp13 = tmp5 * tmp5
tmp14 = tmp12 + tmp13
tmp15 = tmp7 - tmp14
tmp16 = 0.5
tmp17 = tmp15 * 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)
buf0 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_pow_sub_sum_0[grid(64)](arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
return buf0,
class BiInteractionPoolingNew(nn.Module):
"""Bi-Interaction Layer used in Neural FM,compress the
pairwise element-wise product of features into one single vector.
Input shape
- A 3D tensor with shape:``(batch_size,field_size,embedding_size)``.
Output shape
- 3D tensor with shape: ``(batch_size,1,embedding_size)``.
References
- [He X, Chua T S. Neural factorization machines for sparse predictive analytics[C]//Proceedings of the 40th International ACM SIGIR conference on Research and Development in Information Retrieval. ACM, 2017: 355-364.](http://arxiv.org/abs/1708.05027)
"""
def __init__(self):
super(BiInteractionPoolingNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
BiInteractionPooling
| false
| 10,359
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
SoftTargetCrossEntropy
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
class SoftTargetCrossEntropy(nn.Module):
"""
The native CE loss with soft target
input: x is output of model, target is ground truth
return: loss
"""
def __init__(self, weights):
super(SoftTargetCrossEntropy, self).__init__()
self.weights = weights
def forward(self, x, target):
N_rep = x.shape[0]
N = target.shape[0]
if not N == N_rep:
target = target.repeat(N_rep // N, 1)
loss = torch.sum(-target * F.log_softmax(x, dim=-1) * self.weights,
dim=-1)
return loss.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'weights': 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
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_mean_mul_neg_sum_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp1 = -tmp0
tmp3 = tl_math.exp(tmp2)
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp3 + tmp5
tmp8 = tl_math.exp(tmp7)
tmp9 = tmp6 + tmp8
tmp11 = tl_math.exp(tmp10)
tmp12 = tmp9 + tmp11
tmp13 = tl_math.log(tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tmp1 * tmp14
tmp16 = 4.0
tmp17 = tmp15 * tmp16
tmp19 = -tmp18
tmp20 = tmp4 - tmp13
tmp21 = tmp19 * tmp20
tmp22 = tmp21 * tmp16
tmp23 = tmp17 + tmp22
tmp25 = -tmp24
tmp26 = tmp7 - tmp13
tmp27 = tmp25 * tmp26
tmp28 = tmp27 * tmp16
tmp29 = tmp23 + tmp28
tmp31 = -tmp30
tmp32 = tmp10 - tmp13
tmp33 = tmp31 * tmp32
tmp34 = tmp33 * tmp16
tmp35 = tmp29 + tmp34
tmp36 = tl.broadcast_to(tmp35, [XBLOCK, RBLOCK])
tmp38 = tl.sum(tmp36, 1)[:, None]
tmp39 = 64.0
tmp40 = tmp38 / tmp39
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp40, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused__log_softmax_mean_mul_neg_sum_1[grid(1)](buf3,
arg1_1, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf0
return buf3,
class SoftTargetCrossEntropyNew(nn.Module):
"""
The native CE loss with soft target
input: x is output of model, target is ground truth
return: loss
"""
def __init__(self, weights):
super(SoftTargetCrossEntropyNew, self).__init__()
self.weights = weights
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
javierrodenas/clearml_javi
|
SoftTargetCrossEntropy
| false
| 10,360
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
SqueezeAndExcitationModule
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Swish(nn.Module):
def __init__(self):
super(Swish, self).__init__()
def forward(self, x):
return x * x.sigmoid()
class Conv1d(nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding='same', dilation=1, groups=1, bias=True):
super(Conv1d, self).__init__(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=0,
dilation=dilation, groups=groups, bias=bias, padding_mode='zeros')
assert padding in ['valid', 'same', 'causal']
if padding == 'valid':
self.pre_padding = None
elif padding == 'same':
self.pre_padding = nn.ConstantPad1d(padding=((kernel_size - 1) //
2, (kernel_size - 1) // 2), value=0)
elif padding == 'causal':
self.pre_padding = nn.ConstantPad1d(padding=(kernel_size - 1, 0
), value=0)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
if self.pre_padding is not None:
input = self.pre_padding(input)
return F.conv1d(input, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
class SqueezeAndExcitationModule(nn.Module):
"""Squeeze And Excitation Module
Args:
input_dim: input feature dimension
reduction_ratio: bottleneck reduction ratio
inner_act: bottleneck inner activation function
Input: (batch_size, in_dim, in_length)
Output: (batch_size, out_dim, out_length)
"""
def __init__(self, input_dim, reduction_ratio, inner_act='relu'):
super(SqueezeAndExcitationModule, self).__init__()
assert input_dim % reduction_ratio == 0
self.conv1 = Conv1d(input_dim, input_dim // reduction_ratio,
kernel_size=1)
self.conv2 = Conv1d(input_dim // reduction_ratio, input_dim,
kernel_size=1)
assert inner_act in ['relu', 'swish']
if inner_act == 'relu':
self.inner_act = nn.ReLU()
elif inner_act == 'swish':
self.inner_act = Swish()
def forward(self, x):
scale = x.mean(dim=-1, keepdim=True)
scale = self.conv1(scale)
scale = self.inner_act(scale)
scale = self.conv2(scale)
scale = scale.sigmoid()
x = x * scale
return x
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'reduction_ratio': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mean_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_out_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr0 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = 0.0
tmp8 = tmp6 <= tmp7
tl.store(in_out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp6, None)
tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp8, None)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (1, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_0[grid(4)](primals_1, buf0, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (1, 4, 1
), (0, 1, 0), 0), primals_2, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf1, (1, 1, 1), (1, 1, 1))
buf2 = reinterpret_tensor(buf1, (1, 1), (1, 1), 0)
del buf1
buf6 = empty_strided_cuda((1, 1), (1, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(1)](buf2, primals_3,
buf6, 1, XBLOCK=1, num_warps=1, num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(reinterpret_tensor(buf2, (1, 1, 1
), (0, 0, 0), 0), primals_4, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf3, (1, 4, 1), (4, 1, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_2[grid(4)](buf4, primals_5, 4, XBLOCK=
4, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(16)](primals_1, buf4, buf5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
return buf5, primals_1, primals_2, primals_4, reinterpret_tensor(buf0,
(1, 4, 1), (4, 1, 1), 0), reinterpret_tensor(buf2, (1, 1, 1), (1, 1,
1), 0), buf4, buf6
class Swish(nn.Module):
def __init__(self):
super(Swish, self).__init__()
def forward(self, x):
return x * x.sigmoid()
class Conv1d(nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding='same', dilation=1, groups=1, bias=True):
super(Conv1d, self).__init__(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=0,
dilation=dilation, groups=groups, bias=bias, padding_mode='zeros')
assert padding in ['valid', 'same', 'causal']
if padding == 'valid':
self.pre_padding = None
elif padding == 'same':
self.pre_padding = nn.ConstantPad1d(padding=((kernel_size - 1) //
2, (kernel_size - 1) // 2), value=0)
elif padding == 'causal':
self.pre_padding = nn.ConstantPad1d(padding=(kernel_size - 1, 0
), value=0)
self.noise = None
self.vn_std = None
def init_vn(self, vn_std):
self.vn_std = vn_std
def sample_synaptic_noise(self, distributed):
self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
), device=self.weight.device, dtype=self.weight.dtype)
if distributed:
torch.distributed.broadcast(self.noise, 0)
def forward(self, input):
weight = self.weight
if self.noise is not None and self.training:
weight = weight + self.vn_std * self.noise
if self.pre_padding is not None:
input = self.pre_padding(input)
return F.conv1d(input, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
class SqueezeAndExcitationModuleNew(nn.Module):
"""Squeeze And Excitation Module
Args:
input_dim: input feature dimension
reduction_ratio: bottleneck reduction ratio
inner_act: bottleneck inner activation function
Input: (batch_size, in_dim, in_length)
Output: (batch_size, out_dim, out_length)
"""
def __init__(self, input_dim, reduction_ratio, inner_act='relu'):
super(SqueezeAndExcitationModuleNew, self).__init__()
assert input_dim % reduction_ratio == 0
self.conv1 = Conv1d(input_dim, input_dim // reduction_ratio,
kernel_size=1)
self.conv2 = Conv1d(input_dim // reduction_ratio, input_dim,
kernel_size=1)
assert inner_act in ['relu', 'swish']
if inner_act == 'relu':
self.inner_act = nn.ReLU()
elif inner_act == 'swish':
self.inner_act = Swish()
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]
|
debasish-mihup/EfficientConformer
|
SqueezeAndExcitationModule
| false
| 10,361
|
[
"Apache-2.0"
] | 0
|
bddd927cebcde044a999aaa7766fa6d44dc20576
|
https://github.com/debasish-mihup/EfficientConformer/tree/bddd927cebcde044a999aaa7766fa6d44dc20576
|
DGN
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self, din=32, hidden_dim=128):
super(Encoder, self).__init__()
self.fc = nn.Linear(din, hidden_dim)
def forward(self, x):
embedding = F.relu(self.fc(x))
return embedding
class AttModel(nn.Module):
def __init__(self, n_node, din, hidden_dim, dout):
super(AttModel, self).__init__()
self.fcv = nn.Linear(din, hidden_dim)
self.fck = nn.Linear(din, hidden_dim)
self.fcq = nn.Linear(din, hidden_dim)
self.fcout = nn.Linear(hidden_dim, dout)
def forward(self, x, mask):
v = F.relu(self.fcv(x))
q = F.relu(self.fcq(x))
k = F.relu(self.fck(x)).permute(0, 2, 1)
att = F.softmax(torch.mul(torch.bmm(q, k), mask) -
9000000000000000.0 * (1 - mask), dim=2)
out = torch.bmm(att, v)
out = F.relu(self.fcout(out))
return out
class Q_Net(nn.Module):
def __init__(self, hidden_dim, dout):
super(Q_Net, self).__init__()
self.fc = nn.Linear(hidden_dim, dout)
def forward(self, x):
q = self.fc(x)
return q
class DGN(nn.Module):
def __init__(self, n_agent, num_inputs, hidden_dim, num_actions):
super(DGN, self).__init__()
self.encoder = Encoder(num_inputs, hidden_dim)
self.att_1 = AttModel(n_agent, hidden_dim, hidden_dim, hidden_dim)
self.att_2 = AttModel(n_agent, hidden_dim, hidden_dim, hidden_dim)
self.q_net = Q_Net(hidden_dim, num_actions)
def forward(self, x, mask):
h1 = self.encoder(x)
h2 = self.att_1(h1, mask)
h3 = self.att_2(h2, mask)
q = self.q_net(h3)
return q
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_agent': 4, 'num_inputs': 4, 'hidden_dim': 4,
'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 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__softmax_mul_rsub_sub_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp23 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = 9000000000000000.0
tmp6 = tmp4 * tmp5
tmp7 = tmp2 - tmp6
tmp10 = tmp8 * tmp9
tmp11 = tmp3 - tmp9
tmp12 = tmp11 * tmp5
tmp13 = tmp10 - tmp12
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp17 = tmp15 * tmp16
tmp18 = tmp3 - tmp16
tmp19 = tmp18 * tmp5
tmp20 = tmp17 - tmp19
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp24 = tmp22 * tmp23
tmp25 = tmp3 - 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 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp39, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_rsub_sub_3(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x2, xmask)
tmp8 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = 9000000000000000.0
tmp6 = tmp4 * tmp5
tmp7 = tmp2 - tmp6
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tl.store(in_out_ptr0 + x2, 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, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4, 4), (4, 1))
assert_size_stride(primals_16, (4,), (1,))
assert_size_stride(primals_17, (4, 4), (4, 1))
assert_size_stride(primals_18, (4,), (1,))
assert_size_stride(primals_19, (4, 4), (4, 1))
assert_size_stride(primals_20, (4,), (1,))
assert_size_stride(primals_21, (4, 4), (4, 1))
assert_size_stride(primals_22, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0)
del buf0
buf33 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf1,
primals_2, buf33, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
del buf2
triton_poi_fused_relu_1[grid(64)](buf3, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
triton_poi_fused_relu_1[grid(64)](buf5, primals_7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf6)
buf7 = reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0)
del buf6
buf32 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf7,
primals_9, buf32, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf5, reinterpret_tensor(buf7, (4, 4, 4), (16, 1,
4), 0), out=buf8)
buf9 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused__softmax_mul_rsub_sub_2[grid(16)](buf8, primals_10,
buf9, buf10, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf11 = buf8
del buf8
triton_poi_fused__softmax_mul_rsub_sub_3[grid(64)](buf11,
primals_10, buf9, buf10, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf11, buf3, out=buf12)
buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf13)
buf14 = reinterpret_tensor(buf13, (4, 4, 4), (16, 4, 1), 0)
del buf13
buf31 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf14,
primals_12, buf31, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf14, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf15)
buf16 = reinterpret_tensor(buf15, (4, 4, 4), (16, 4, 1), 0)
del buf15
triton_poi_fused_relu_1[grid(64)](buf16, primals_14, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_14
buf17 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf14, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_15, (4, 4), (1, 4), 0), out=buf17)
buf18 = reinterpret_tensor(buf17, (4, 4, 4), (16, 4, 1), 0)
del buf17
triton_poi_fused_relu_1[grid(64)](buf18, primals_16, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_16
buf19 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf14, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_17, (4, 4), (1, 4), 0), out=buf19)
buf20 = reinterpret_tensor(buf19, (4, 4, 4), (16, 4, 1), 0)
del buf19
buf30 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf20,
primals_18, buf30, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_18
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf18, reinterpret_tensor(buf20, (4, 4, 4), (16,
1, 4), 0), out=buf21)
buf22 = buf9
del buf9
buf23 = buf10
del buf10
triton_poi_fused__softmax_mul_rsub_sub_2[grid(16)](buf21,
primals_10, buf22, buf23, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf24 = buf21
del buf21
triton_poi_fused__softmax_mul_rsub_sub_3[grid(64)](buf24,
primals_10, buf22, buf23, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf22
del buf23
buf25 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf24, buf16, out=buf25)
buf26 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf25, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_19, (4, 4), (1, 4), 0), out=buf26)
buf27 = reinterpret_tensor(buf26, (4, 4, 4), (16, 4, 1), 0)
del buf26
buf29 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf27,
primals_20, buf29, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_20
buf28 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_22, reinterpret_tensor(buf27, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_21, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf28)
del primals_22
return (reinterpret_tensor(buf28, (4, 4, 4), (16, 4, 1), 0), primals_10,
reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(buf1, (16, 4), (4, 1), 0), buf3, buf5, buf11,
reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(
buf14, (16, 4), (4, 1), 0), buf16, buf18, buf24, reinterpret_tensor
(buf25, (16, 4), (4, 1), 0), reinterpret_tensor(buf27, (16, 4), (4,
1), 0), primals_21, buf29, primals_19, buf20, buf30, primals_17,
primals_15, primals_13, buf31, primals_11, buf7, buf32, primals_8,
primals_6, primals_4, buf33)
class Encoder(nn.Module):
def __init__(self, din=32, hidden_dim=128):
super(Encoder, self).__init__()
self.fc = nn.Linear(din, hidden_dim)
def forward(self, x):
embedding = F.relu(self.fc(x))
return embedding
class AttModel(nn.Module):
def __init__(self, n_node, din, hidden_dim, dout):
super(AttModel, self).__init__()
self.fcv = nn.Linear(din, hidden_dim)
self.fck = nn.Linear(din, hidden_dim)
self.fcq = nn.Linear(din, hidden_dim)
self.fcout = nn.Linear(hidden_dim, dout)
def forward(self, x, mask):
v = F.relu(self.fcv(x))
q = F.relu(self.fcq(x))
k = F.relu(self.fck(x)).permute(0, 2, 1)
att = F.softmax(torch.mul(torch.bmm(q, k), mask) -
9000000000000000.0 * (1 - mask), dim=2)
out = torch.bmm(att, v)
out = F.relu(self.fcout(out))
return out
class Q_Net(nn.Module):
def __init__(self, hidden_dim, dout):
super(Q_Net, self).__init__()
self.fc = nn.Linear(hidden_dim, dout)
def forward(self, x):
q = self.fc(x)
return q
class DGNNew(nn.Module):
def __init__(self, n_agent, num_inputs, hidden_dim, num_actions):
super(DGNNew, self).__init__()
self.encoder = Encoder(num_inputs, hidden_dim)
self.att_1 = AttModel(n_agent, hidden_dim, hidden_dim, hidden_dim)
self.att_2 = AttModel(n_agent, hidden_dim, hidden_dim, hidden_dim)
self.q_net = Q_Net(hidden_dim, num_actions)
def forward(self, input_0, input_1):
primals_1 = self.encoder.fc.weight
primals_2 = self.encoder.fc.bias
primals_4 = self.att_1.fcv.weight
primals_5 = self.att_1.fcv.bias
primals_6 = self.att_1.fck.weight
primals_7 = self.att_1.fck.bias
primals_8 = self.att_1.fcq.weight
primals_9 = self.att_1.fcq.bias
primals_11 = self.att_1.fcout.weight
primals_12 = self.att_1.fcout.bias
primals_13 = self.att_2.fcv.weight
primals_14 = self.att_2.fcv.bias
primals_15 = self.att_2.fck.weight
primals_16 = self.att_2.fck.bias
primals_17 = self.att_2.fcq.weight
primals_18 = self.att_2.fcq.bias
primals_19 = self.att_2.fcout.weight
primals_20 = self.att_2.fcout.bias
primals_21 = self.q_net.fc.weight
primals_22 = self.q_net.fc.bias
primals_3 = input_0
primals_10 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22])
return output[0]
|
jungwoohan72/DGN_pytorch
|
DGN
| false
| 10,362
|
[
"MIT"
] | 0
|
65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
https://github.com/jungwoohan72/DGN_pytorch/tree/65fe7ab4df661d97725f2a72a1fdb49df1b2ea44
|
CircleLoss
|
import torch
from torch import Tensor
from torch import nn
class CircleLoss(nn.Module):
def __init__(self, m: 'float', gamma: 'float') ->None:
super(CircleLoss, self).__init__()
self.m = m
self.gamma = gamma
self.soft_plus = nn.Softplus()
def forward(self, sp: 'Tensor', sn: 'Tensor') ->Tensor:
ap = torch.clamp_min(-sp.detach() + 1 + self.m, min=0.0)
an = torch.clamp_min(sn.detach() + self.m, min=0.0)
delta_p = 1 - self.m
delta_n = self.m
logit_p = -ap * (sp - delta_p) * self.gamma
logit_n = an * (sn - delta_n) * self.gamma
loss = self.soft_plus(torch.logsumexp(logit_n, dim=0) + torch.
logsumexp(logit_p, dim=0))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'m': 4, 'gamma': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_clamp_min_logsumexp_mul_neg_softplus_sub_0(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
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp8 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp15 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp22 = tl.load(in_ptr0 + (192 + x0), xmask)
tmp44 = tl.load(in_ptr1 + x0, xmask)
tmp55 = tl.load(in_ptr1 + (64 + x0), xmask)
tmp65 = tl.load(in_ptr1 + (128 + x0), xmask)
tmp75 = tl.load(in_ptr1 + (192 + x0), xmask)
tmp1 = 4.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = tmp0 - tmp1
tmp6 = tmp4 * tmp5
tmp7 = tmp6 * tmp1
tmp9 = tmp8 + tmp1
tmp10 = triton_helpers.maximum(tmp9, tmp3)
tmp11 = tmp8 - tmp1
tmp12 = tmp10 * tmp11
tmp13 = tmp12 * tmp1
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp16 = tmp15 + tmp1
tmp17 = triton_helpers.maximum(tmp16, tmp3)
tmp18 = tmp15 - tmp1
tmp19 = tmp17 * tmp18
tmp20 = tmp19 * tmp1
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp23 = tmp22 + tmp1
tmp24 = triton_helpers.maximum(tmp23, tmp3)
tmp25 = tmp22 - tmp1
tmp26 = tmp24 * tmp25
tmp27 = tmp26 * tmp1
tmp28 = triton_helpers.maximum(tmp21, tmp27)
tmp29 = tl_math.abs(tmp28)
tmp30 = float('inf')
tmp31 = tmp29 == tmp30
tmp32 = tl.where(tmp31, tmp3, tmp28)
tmp33 = tmp7 - tmp32
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp13 - tmp32
tmp36 = tl_math.exp(tmp35)
tmp37 = tmp34 + tmp36
tmp38 = tmp20 - tmp32
tmp39 = tl_math.exp(tmp38)
tmp40 = tmp37 + tmp39
tmp41 = tmp27 - tmp32
tmp42 = tl_math.exp(tmp41)
tmp43 = tmp40 + tmp42
tmp45 = -tmp44
tmp46 = 1.0
tmp47 = tmp45 + tmp46
tmp48 = tmp47 + tmp1
tmp49 = triton_helpers.maximum(tmp48, tmp3)
tmp50 = -tmp49
tmp51 = -3.0
tmp52 = tmp44 - tmp51
tmp53 = tmp50 * tmp52
tmp54 = tmp53 * tmp1
tmp56 = -tmp55
tmp57 = tmp56 + tmp46
tmp58 = tmp57 + tmp1
tmp59 = triton_helpers.maximum(tmp58, tmp3)
tmp60 = -tmp59
tmp61 = tmp55 - tmp51
tmp62 = tmp60 * tmp61
tmp63 = tmp62 * tmp1
tmp64 = triton_helpers.maximum(tmp54, tmp63)
tmp66 = -tmp65
tmp67 = tmp66 + tmp46
tmp68 = tmp67 + tmp1
tmp69 = triton_helpers.maximum(tmp68, tmp3)
tmp70 = -tmp69
tmp71 = tmp65 - tmp51
tmp72 = tmp70 * tmp71
tmp73 = tmp72 * tmp1
tmp74 = triton_helpers.maximum(tmp64, tmp73)
tmp76 = -tmp75
tmp77 = tmp76 + tmp46
tmp78 = tmp77 + tmp1
tmp79 = triton_helpers.maximum(tmp78, tmp3)
tmp80 = -tmp79
tmp81 = tmp75 - tmp51
tmp82 = tmp80 * tmp81
tmp83 = tmp82 * tmp1
tmp84 = triton_helpers.maximum(tmp74, tmp83)
tmp85 = tl_math.abs(tmp84)
tmp86 = tmp85 == tmp30
tmp87 = tl.where(tmp86, tmp3, tmp84)
tmp88 = tmp54 - tmp87
tmp89 = tl_math.exp(tmp88)
tmp90 = tmp63 - tmp87
tmp91 = tl_math.exp(tmp90)
tmp92 = tmp89 + tmp91
tmp93 = tmp73 - tmp87
tmp94 = tl_math.exp(tmp93)
tmp95 = tmp92 + tmp94
tmp96 = tmp83 - tmp87
tmp97 = tl_math.exp(tmp96)
tmp98 = tmp95 + tmp97
tmp99 = tl_math.log(tmp43)
tmp100 = tmp99 + tmp32
tmp101 = tl_math.log(tmp98)
tmp102 = tmp101 + tmp87
tmp103 = tmp100 + tmp102
tmp104 = tmp103 * tmp46
tmp105 = 20.0
tmp106 = tmp104 > tmp105
tmp107 = tl_math.exp(tmp104)
tmp108 = libdevice.log1p(tmp107)
tmp109 = tmp108 * tmp46
tmp110 = tl.where(tmp106, tmp103, tmp109)
tl.store(in_out_ptr0 + x0, tmp110, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf5 = buf2
del buf2
get_raw_stream(0)
triton_poi_fused_add_clamp_min_logsumexp_mul_neg_softplus_sub_0[grid
(64)](buf5, arg1_1, arg0_1, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del arg0_1
del arg1_1
return buf5,
class CircleLossNew(nn.Module):
def __init__(self, m: 'float', gamma: 'float') ->None:
super(CircleLossNew, self).__init__()
self.m = m
self.gamma = gamma
self.soft_plus = nn.Softplus()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
kagawa123/Person_reID_baseline_pytorch
|
CircleLoss
| false
| 10,363
|
[
"MIT"
] | 0
|
a503af2fa329406e97c5347bf3b13629ad0ffd10
|
https://github.com/kagawa123/Person_reID_baseline_pytorch/tree/a503af2fa329406e97c5347bf3b13629ad0ffd10
|
PatchEmbed
|
import torch
import torch.nn as nn
import torch.nn.parallel
class PatchEmbed(nn.Module):
"""
Image to Patch Embedding.
Different with ViT use 1 conv layer, we use 4 conv layers to do patch embedding
"""
def __init__(self, img_size=224, stem_conv=False, stem_stride=1,
patch_size=8, in_chans=3, hidden_dim=64, embed_dim=384):
super().__init__()
assert patch_size in [4, 8, 16]
self.stem_conv = stem_conv
if stem_conv:
self.conv = nn.Sequential(nn.Conv2d(in_chans, hidden_dim,
kernel_size=7, stride=stem_stride, padding=3, bias=False),
nn.BatchNorm2d(hidden_dim), nn.ReLU(inplace=True), nn.
Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1,
padding=1, bias=False), nn.BatchNorm2d(hidden_dim), nn.ReLU
(inplace=True), nn.Conv2d(hidden_dim, hidden_dim,
kernel_size=3, stride=1, padding=1, bias=False), nn.
BatchNorm2d(hidden_dim), nn.ReLU(inplace=True))
self.proj = nn.Conv2d(hidden_dim, embed_dim, kernel_size=patch_size //
stem_stride, stride=patch_size // stem_stride)
self.num_patches = img_size // patch_size * (img_size // patch_size)
def forward(self, x):
if self.stem_conv:
x = self.conv(x)
x = self.proj(x)
return x
def get_inputs():
return [torch.rand([4, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 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
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 64 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 64 * x2 + 4096 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 64 * x2 + 262144 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 1536
xnumel = 64
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 384
y1 = yindex // 384
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 384 * x2 + 24576 * 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 + 64 * y3), tmp2, xmask & ymask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (384, 64, 8, 8), (4096, 64, 8, 1))
assert_size_stride(primals_2, (384,), (1,))
assert_size_stride(primals_3, (4, 64, 64, 64), (262144, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((384, 64, 8, 8), (4096, 1, 512, 64),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(24576, 64)](primals_1, buf0, 24576, 64,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 64, 64, 64), (262144, 1, 4096, 64),
torch.float32)
triton_poi_fused_1[grid(256, 4096)](primals_3, buf1, 256, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(buf1, buf0, stride=(8, 8),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 384, 8, 8), (24576, 1, 3072, 384))
buf3 = empty_strided_cuda((4, 384, 8, 8), (24576, 64, 8, 1), torch.
float32)
triton_poi_fused_convolution_2[grid(1536, 64)](buf2, primals_2,
buf3, 1536, 64, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del buf2
del primals_2
return buf3, buf0, buf1
class PatchEmbedNew(nn.Module):
"""
Image to Patch Embedding.
Different with ViT use 1 conv layer, we use 4 conv layers to do patch embedding
"""
def __init__(self, img_size=224, stem_conv=False, stem_stride=1,
patch_size=8, in_chans=3, hidden_dim=64, embed_dim=384):
super().__init__()
assert patch_size in [4, 8, 16]
self.stem_conv = stem_conv
if stem_conv:
self.conv = nn.Sequential(nn.Conv2d(in_chans, hidden_dim,
kernel_size=7, stride=stem_stride, padding=3, bias=False),
nn.BatchNorm2d(hidden_dim), nn.ReLU(inplace=True), nn.
Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1,
padding=1, bias=False), nn.BatchNorm2d(hidden_dim), nn.ReLU
(inplace=True), nn.Conv2d(hidden_dim, hidden_dim,
kernel_size=3, stride=1, padding=1, bias=False), nn.
BatchNorm2d(hidden_dim), nn.ReLU(inplace=True))
self.proj = nn.Conv2d(hidden_dim, embed_dim, kernel_size=patch_size //
stem_stride, stride=patch_size // stem_stride)
self.num_patches = img_size // patch_size * (img_size // patch_size)
def forward(self, input_0):
primals_1 = self.proj.weight
primals_2 = self.proj.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
javierrodenas/clearml_javi
|
PatchEmbed
| false
| 10,364
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
C3D
|
import logging
import torch
import torch.nn as nn
class C3D(nn.Module):
def __init__(self, pretrained=None, modality='RGB'):
super(C3D, self).__init__()
self.pretrained = pretrained
self.modality = modality
inplace = True
assert modality in ['RGB']
self.conv1a = nn.Conv3d(3, 64, kernel_size=(3, 3, 3), stride=(1, 1,
1), padding=(1, 1, 1), bias=True)
self.relu1a = nn.ReLU(inplace)
self.pool1 = nn.MaxPool3d((1, 2, 2), stride=(1, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv2a = nn.Conv3d(64, 128, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu2a = nn.ReLU(inplace)
self.pool2 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv3a = nn.Conv3d(128, 256, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu3a = nn.ReLU(inplace)
self.conv3b = nn.Conv3d(256, 256, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu3b = nn.ReLU(inplace)
self.pool3 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv4a = nn.Conv3d(256, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu4a = nn.ReLU(inplace)
self.conv4b = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu4b = nn.ReLU(inplace)
self.pool4 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv5a = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu5a = nn.ReLU(inplace)
self.conv5b = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu5b = nn.ReLU(inplace)
self.pool5 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.fc6 = nn.Linear(8192, 4096)
self.relu6 = nn.ReLU(inplace)
self.drop6 = nn.Dropout(p=0.5)
self.fc7 = nn.Linear(4096, 4096)
self.relu7 = nn.ReLU(inplace)
def init_weights(self):
if isinstance(self.pretrained, str):
logger = logging.getLogger()
load_checkpoint(self, self.pretrained, strict=False, logger=logger)
elif self.pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv3d):
normal_init(m, std=0.01, bias=1)
elif isinstance(m, nn.Linear):
normal_init(m, std=0.005, bias=1)
def forward(self, input):
conv1a = self.conv1a(input)
conv1a = self.relu1a(conv1a)
pool1 = self.pool1(conv1a)
conv2a = self.conv2a(pool1)
conv2a = self.relu2a(conv2a)
pool2 = self.pool2(conv2a)
conv3a = self.conv3a(pool2)
conv3a = self.relu3a(conv3a)
conv3b = self.conv3b(conv3a)
conv3b = self.relu3b(conv3b)
pool3 = self.pool3(conv3b)
conv4a = self.conv4a(pool3)
conv4a = self.relu4a(conv4a)
conv4b = self.conv4b(conv4a)
conv4b = self.relu4b(conv4b)
pool4 = self.pool4(conv4b)
conv5a = self.conv5a(pool4)
conv5a = self.relu5a(conv5a)
conv5b = self.conv5b(conv5a)
conv5b = self.relu5b(conv5b)
pool5 = self.pool5(conv5b)
pool5 = pool5.flatten(start_dim=1)
fc6 = self.fc6(pool5)
fc6 = self.relu6(fc6)
fc6 = self.drop6(fc6)
fc7 = self.fc7(fc6)
fc7 = self.relu7(fc7)
fc7 = fc7.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
return fc7
def train(self, mode=True):
super(C3D, self).train(mode)
def get_inputs():
return [torch.rand([4, 3, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import logging
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 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_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 // 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_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 // 8192 % 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_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 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_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 // 128 % 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_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 4096
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_6(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 4096
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21) = args
args.clear()
assert_size_stride(primals_1, (64, 3, 3, 3, 3), (81, 27, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64, 64), (786432, 262144, 4096,
64, 1))
assert_size_stride(primals_4, (128, 64, 3, 3, 3), (1728, 27, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (256, 128, 3, 3, 3), (3456, 27, 9, 3, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (256, 256, 3, 3, 3), (6912, 27, 9, 3, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (512, 256, 3, 3, 3), (6912, 27, 9, 3, 1))
assert_size_stride(primals_11, (512,), (1,))
assert_size_stride(primals_12, (512, 512, 3, 3, 3), (13824, 27, 9, 3, 1))
assert_size_stride(primals_13, (512,), (1,))
assert_size_stride(primals_14, (512, 512, 3, 3, 3), (13824, 27, 9, 3, 1))
assert_size_stride(primals_15, (512,), (1,))
assert_size_stride(primals_16, (512, 512, 3, 3, 3), (13824, 27, 9, 3, 1))
assert_size_stride(primals_17, (512,), (1,))
assert_size_stride(primals_18, (4096, 8192), (8192, 1))
assert_size_stride(primals_19, (4096,), (1,))
assert_size_stride(primals_20, (4096, 4096), (4096, 1))
assert_size_stride(primals_21, (4096,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, 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, (4, 64, 64, 64, 64), (16777216, 262144,
4096, 64, 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 = torch.ops.aten.max_pool3d_with_indices.default(buf1, [1, 2,
2], [1, 2, 2], [0, 0, 0], [1, 1, 1], True)
buf3 = buf2[0]
buf4 = buf2[1]
del buf2
buf5 = extern_kernels.convolution(buf3, 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(buf5, (4, 128, 64, 32, 32), (8388608, 65536,
1024, 32, 1))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_1[grid(33554432)](buf6, primals_5,
33554432, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf7 = torch.ops.aten.max_pool3d_with_indices.default(buf6, [2, 2,
2], [2, 2, 2], [0, 0, 0], [1, 1, 1], True)
buf8 = buf7[0]
buf9 = buf7[1]
del buf7
buf10 = extern_kernels.convolution(buf8, primals_6, 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(buf10, (4, 256, 32, 16, 16), (2097152, 8192, 256,
16, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_2[grid(8388608)](buf11, primals_7,
8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf12 = extern_kernels.convolution(buf11, primals_8, 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(buf12, (4, 256, 32, 16, 16), (2097152, 8192, 256,
16, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_2[grid(8388608)](buf13, primals_9,
8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_9
buf14 = torch.ops.aten.max_pool3d_with_indices.default(buf13, [2, 2,
2], [2, 2, 2], [0, 0, 0], [1, 1, 1], True)
buf15 = buf14[0]
buf16 = buf14[1]
del buf14
buf17 = extern_kernels.convolution(buf15, primals_10, 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(buf17, (4, 512, 16, 8, 8), (524288, 1024, 64, 8, 1))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_3[grid(2097152)](buf18,
primals_11, 2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_11
buf19 = extern_kernels.convolution(buf18, primals_12, 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(buf19, (4, 512, 16, 8, 8), (524288, 1024, 64, 8, 1))
buf20 = buf19
del buf19
triton_poi_fused_convolution_relu_3[grid(2097152)](buf20,
primals_13, 2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_13
buf21 = torch.ops.aten.max_pool3d_with_indices.default(buf20, [2, 2,
2], [2, 2, 2], [0, 0, 0], [1, 1, 1], True)
buf22 = buf21[0]
buf23 = buf21[1]
del buf21
buf24 = extern_kernels.convolution(buf22, primals_14, 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(buf24, (4, 512, 8, 4, 4), (65536, 128, 16, 4, 1))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_4[grid(262144)](buf25, primals_15,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_15
buf26 = extern_kernels.convolution(buf25, primals_16, 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(buf26, (4, 512, 8, 4, 4), (65536, 128, 16, 4, 1))
buf27 = buf26
del buf26
triton_poi_fused_convolution_relu_4[grid(262144)](buf27, primals_17,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_17
buf28 = torch.ops.aten.max_pool3d_with_indices.default(buf27, [2, 2,
2], [2, 2, 2], [0, 0, 0], [1, 1, 1], True)
buf29 = buf28[0]
buf30 = buf28[1]
del buf28
buf31 = empty_strided_cuda((4, 4096), (4096, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf29, (4, 8192), (8192, 1), 0
), reinterpret_tensor(primals_18, (8192, 4096), (1, 8192), 0),
out=buf31)
buf32 = buf31
del buf31
triton_poi_fused_relu_5[grid(16384)](buf32, primals_19, 16384,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_19
buf33 = empty_strided_cuda((4, 4096), (4096, 1), torch.float32)
extern_kernels.mm(buf32, reinterpret_tensor(primals_20, (4096, 4096
), (1, 4096), 0), out=buf33)
buf34 = empty_strided_cuda((4, 4096), (4096, 1), torch.bool)
buf35 = empty_strided_cuda((4, 4096), (4096, 1), torch.float32)
triton_poi_fused_relu_threshold_backward_6[grid(16384)](buf33,
primals_21, buf34, buf35, 16384, XBLOCK=128, num_warps=4,
num_stages=1)
del buf33
del primals_21
return (reinterpret_tensor(buf35, (4, 4096, 1, 1, 1), (4096, 1, 1, 1, 1
), 0), primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, primals_16, buf1, buf3, buf4,
buf6, buf8, buf9, buf11, buf13, buf15, buf16, buf18, buf20, buf22,
buf23, buf25, buf27, buf30, reinterpret_tensor(buf29, (4, 8192), (
8192, 1), 0), buf32, buf34, primals_20, primals_18)
class C3DNew(nn.Module):
def __init__(self, pretrained=None, modality='RGB'):
super(C3DNew, self).__init__()
self.pretrained = pretrained
self.modality = modality
inplace = True
assert modality in ['RGB']
self.conv1a = nn.Conv3d(3, 64, kernel_size=(3, 3, 3), stride=(1, 1,
1), padding=(1, 1, 1), bias=True)
self.relu1a = nn.ReLU(inplace)
self.pool1 = nn.MaxPool3d((1, 2, 2), stride=(1, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv2a = nn.Conv3d(64, 128, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu2a = nn.ReLU(inplace)
self.pool2 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv3a = nn.Conv3d(128, 256, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu3a = nn.ReLU(inplace)
self.conv3b = nn.Conv3d(256, 256, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu3b = nn.ReLU(inplace)
self.pool3 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv4a = nn.Conv3d(256, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu4a = nn.ReLU(inplace)
self.conv4b = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu4b = nn.ReLU(inplace)
self.pool4 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.conv5a = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu5a = nn.ReLU(inplace)
self.conv5b = nn.Conv3d(512, 512, kernel_size=(3, 3, 3), stride=(1,
1, 1), padding=(1, 1, 1), bias=True)
self.relu5b = nn.ReLU(inplace)
self.pool5 = nn.MaxPool3d((2, 2, 2), stride=(2, 2, 2), dilation=(1,
1, 1), ceil_mode=True)
self.fc6 = nn.Linear(8192, 4096)
self.relu6 = nn.ReLU(inplace)
self.drop6 = nn.Dropout(p=0.5)
self.fc7 = nn.Linear(4096, 4096)
self.relu7 = nn.ReLU(inplace)
def init_weights(self):
if isinstance(self.pretrained, str):
logger = logging.getLogger()
load_checkpoint(self, self.pretrained, strict=False, logger=logger)
elif self.pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv3d):
normal_init(m, std=0.01, bias=1)
elif isinstance(m, nn.Linear):
normal_init(m, std=0.005, bias=1)
def train(self, mode=True):
super(C3DNew, self).train(mode)
def forward(self, input_0):
primals_1 = self.conv1a.weight
primals_2 = self.conv1a.bias
primals_4 = self.conv2a.weight
primals_5 = self.conv2a.bias
primals_6 = self.conv3a.weight
primals_7 = self.conv3a.bias
primals_8 = self.conv3b.weight
primals_9 = self.conv3b.bias
primals_10 = self.conv4a.weight
primals_11 = self.conv4a.bias
primals_12 = self.conv4b.weight
primals_13 = self.conv4b.bias
primals_14 = self.conv5a.weight
primals_15 = self.conv5a.bias
primals_16 = self.conv5b.weight
primals_17 = self.conv5b.bias
primals_18 = self.fc6.weight
primals_19 = self.fc6.bias
primals_20 = self.fc7.weight
primals_21 = self.fc7.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])
return output[0]
|
hushunda/mmaction
|
C3D
| false
| 10,365
|
[
"Apache-2.0"
] | 0
|
b599273ddb80fd74ecf51ef5fa0c81639ea723c5
|
https://github.com/hushunda/mmaction/tree/b599273ddb80fd74ecf51ef5fa0c81639ea723c5
|
MeanStd
|
import torch
import torch.nn as nn
class MeanStd(nn.Module):
def __init__(self):
super(MeanStd, self).__init__()
def forward(self, x):
x = x.view(x.size(0), x.size(1), -1)
mean_x = torch.mean(x, dim=2)
var_x = torch.mean(x ** 2, dim=2) - mean_x * mean_x
return torch.cat([mean_x, var_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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_mul_pow_sub_0(in_ptr0, out_ptr2, out_ptr3, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = 16.0
tmp11 = tmp9 / tmp10
tmp12 = tmp5 / tmp10
tmp13 = tmp11 * tmp11
tmp14 = tmp12 - tmp13
tl.store(out_ptr2 + (x2 + 8 * x3), tmp11, xmask)
tl.store(out_ptr3 + (x2 + 8 * x3), tmp14, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf4 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
buf2 = reinterpret_tensor(buf4, (4, 4), (8, 1), 0)
buf3 = reinterpret_tensor(buf4, (4, 4), (8, 1), 4)
get_raw_stream(0)
triton_per_fused_mean_mul_pow_sub_0[grid(16)](arg0_1, buf2, buf3,
16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf4,
class MeanStdNew(nn.Module):
def __init__(self):
super(MeanStdNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jwen307/pytorch_GAN_zoo
|
MeanStd
| false
| 10,366
|
[
"BSD-3-Clause"
] | 0
|
b1e538a2f03fda42bd7a12872238b770ea5e0f23
|
https://github.com/jwen307/pytorch_GAN_zoo/tree/b1e538a2f03fda42bd7a12872238b770ea5e0f23
|
InnerProductNetwork
|
import torch
import torch.utils.data
class InnerProductNetwork(torch.nn.Module):
def forward(self, x):
"""
:param x: Float tensor of size ``(batch_size, num_fields, embed_dim)``
"""
num_fields = x.shape[1]
row, col = list(), list()
for i in range(num_fields - 1):
for j in range(i + 1, num_fields):
row.append(i), col.append(j)
return torch.sum(x[:, row] * x[:, col], dim=2)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_index_mul_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 96
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 6
x0 = xindex % 4
x2 = xindex // 24
x3 = xindex
tmp0 = x1
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = tl.full([1], 0, tl.int64)
tmp8 = tl.where(tmp6, tmp7, tmp7)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tl.full([1], 4, tl.int64)
tmp11 = tmp0 < tmp10
tmp12 = tl.full([1], 5, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tl.where(tmp13, tmp3, tmp5)
tmp15 = tl.where(tmp11, tmp3, tmp14)
tmp16 = tl.where(tmp2, tmp9, tmp15)
tmp17 = tl.load(in_ptr0 + (x0 + 16 * tmp16 + 64 * x2), xmask)
tmp18 = tl.where(tmp6, tmp5, tmp1)
tmp19 = tl.where(tmp4, tmp3, tmp18)
tmp20 = tl.where(tmp13, tmp1, tmp1)
tmp21 = tl.where(tmp11, tmp5, tmp20)
tmp22 = tl.where(tmp2, tmp19, tmp21)
tmp23 = tl.load(in_ptr0 + (x0 + 16 * tmp22 + 64 * x2), xmask)
tmp24 = tmp17 * tmp23
tmp25 = tl.load(in_ptr0 + (4 + x0 + 16 * tmp16 + 64 * x2), xmask)
tmp26 = tl.load(in_ptr0 + (4 + x0 + 16 * tmp22 + 64 * x2), xmask)
tmp27 = tmp25 * tmp26
tmp28 = tmp24 + tmp27
tmp29 = tl.load(in_ptr0 + (8 + x0 + 16 * tmp16 + 64 * x2), xmask)
tmp30 = tl.load(in_ptr0 + (8 + x0 + 16 * tmp22 + 64 * x2), xmask)
tmp31 = tmp29 * tmp30
tmp32 = tmp28 + tmp31
tmp33 = tl.load(in_ptr0 + (12 + x0 + 16 * tmp16 + 64 * x2), xmask)
tmp34 = tl.load(in_ptr0 + (12 + x0 + 16 * tmp22 + 64 * x2), xmask)
tmp35 = tmp33 * tmp34
tmp36 = tmp32 + tmp35
tl.store(out_ptr0 + x3, tmp36, 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, 6, 4), (24, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_index_mul_sum_0[grid(96)](arg0_1, buf0, 96, XBLOCK
=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class InnerProductNetworkNew(torch.nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jqsl2012/pytorch-fm
|
InnerProductNetwork
| false
| 10,367
|
[
"MIT"
] | 0
|
de6240d0a17750303bbc97dba676b667c3a27829
|
https://github.com/jqsl2012/pytorch-fm/tree/de6240d0a17750303bbc97dba676b667c3a27829
|
ConvNet
|
import torch
import torch.nn as nn
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=
5, padding=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size
=3, padding=1)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=16, kernel_size
=3, padding=1)
self.relu = nn.ReLU()
self.pooling = nn.MaxPool2d(kernel_size=2)
self.linear = nn.Linear(in_features=1296, out_features=3)
def forward(self, x):
x = self.pooling(self.relu(self.conv1(x)))
x = self.pooling(self.relu(self.conv2(x)))
x = self.pooling(self.relu(self.conv2(x)))
x = self.pooling(self.relu(self.conv3(x)))
x = self.linear(x.view(-1, 1296))
return x
def get_inputs():
return [torch.rand([4, 3, 144, 144])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 20736 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 72
x1 = xindex // 72
x4 = xindex
x3 = xindex // 5184
x5 = xindex % 5184
tmp0 = tl.load(in_ptr0 + (2 * x0 + 288 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 288 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (144 + 2 * x0 + 288 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (145 + 2 * x0 + 288 * 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 + x4, tmp6, None)
tl.store(out_ptr1 + (x5 + 5248 * x3), tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 5184 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_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 % 36
x3 = xindex // 36
x2 = xindex // 1296
x4 = xindex % 1296
tmp0 = tl.load(in_ptr0 + (2 * x0 + 144 * x3), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 144 * x3), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (72 + 2 * x0 + 144 * x3), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (73 + 2 * x0 + 144 * x3), 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 + (x4 + 1312 * x2), tmp6, None)
tl.store(out_ptr1 + (x4 + 1408 * x2), tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1296 % 32
x0 = xindex % 1296
x4 = xindex // 1296
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)
tl.store(out_ptr0 + (x0 + 1312 * x4), tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_5(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 41472
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 18
x1 = xindex // 18 % 18
x2 = xindex // 324
x3 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 72 * x1 + 1312 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 72 * x1 + 1312 * x2), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (36 + 2 * x0 + 72 * x1 + 1312 * x2), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (37 + 2 * x0 + 72 * x1 + 1312 * x2), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 20736
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 324 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_7(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 5184
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 9
x3 = xindex // 9
x2 = xindex // 1296
x4 = xindex % 1296
tmp0 = tl.load(in_ptr0 + (2 * x0 + 36 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 36 * x3), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (18 + 2 * x0 + 36 * x3), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (19 + 2 * x0 + 36 * x3), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + (x4 + 1408 * x2), tmp15, xmask)
tl.store(out_ptr1 + (x4 + 1312 * x2), tmp16, 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, (32, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 144, 144), (62208, 20736, 144, 1))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (16, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (3, 1296), (1296, 1))
assert_size_stride(primals_9, (3,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 144, 144), (663552, 20736, 144, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(2654208)](buf1, primals_2,
2654208, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 32, 72, 72), (165888, 5184, 72, 1),
torch.float32)
buf3 = empty_strided_cuda((4, 32, 72, 72), (167936, 5248, 72, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(663552)](buf1, buf2,
buf3, 663552, XBLOCK=512, num_warps=8, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 72, 72), (165888, 5184, 72, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(663552)](buf5, primals_5,
663552, XBLOCK=1024, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((4, 32, 36, 36), (41984, 1312, 36, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 32, 36, 36), (45056, 1408, 36, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(165888)](buf5, buf6,
buf7, 165888, XBLOCK=512, num_warps=8, num_stages=1)
buf8 = extern_kernels.convolution(buf6, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 32, 36, 36), (41472, 1296, 36, 1))
buf9 = empty_strided_cuda((4, 32, 36, 36), (41984, 1312, 36, 1),
torch.float32)
triton_poi_fused_convolution_relu_4[grid(165888)](buf8, primals_5,
buf9, 165888, XBLOCK=1024, num_warps=4, num_stages=1)
del buf8
del primals_5
buf10 = empty_strided_cuda((4, 32, 18, 18), (10368, 324, 18, 1),
torch.float32)
buf11 = empty_strided_cuda((4, 32, 18, 18), (10368, 324, 18, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_5[grid(41472)](buf9, buf10,
buf11, 41472, XBLOCK=256, num_warps=4, num_stages=1)
buf12 = extern_kernels.convolution(buf10, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 16, 18, 18), (5184, 324, 18, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_6[grid(20736)](buf13, primals_7,
20736, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf14 = empty_strided_cuda((4, 16, 9, 9), (1408, 81, 9, 1), torch.int8)
buf15 = empty_strided_cuda((4, 16, 9, 9), (1312, 81, 9, 1), torch.
float32)
triton_poi_fused_max_pool2d_with_indices_7[grid(5184)](buf13, buf14,
buf15, 5184, XBLOCK=128, num_warps=4, num_stages=1)
buf16 = empty_strided_cuda((4, 3), (3, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf15, (4, 1296),
(1312, 1), 0), reinterpret_tensor(primals_8, (1296, 3), (1,
1296), 0), alpha=1, beta=1, out=buf16)
del primals_9
return (buf16, primals_1, primals_3, primals_4, primals_6, buf1, buf2,
buf3, buf5, buf6, buf7, buf9, buf10, buf11, buf13, buf14,
reinterpret_tensor(buf15, (4, 1296), (1312, 1), 0), primals_8)
class ConvNetNew(nn.Module):
def __init__(self):
super(ConvNetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=
5, padding=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size
=3, padding=1)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=16, kernel_size
=3, padding=1)
self.relu = nn.ReLU()
self.pooling = nn.MaxPool2d(kernel_size=2)
self.linear = nn.Linear(in_features=1296, out_features=3)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.linear.weight
primals_9 = self.linear.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]
|
krishsethi19/dffml
|
ConvNet
| false
| 10,368
|
[
"MIT"
] | 0
|
2dd0a9c4a125a9739d27228128bbd381a8e0fef4
|
https://github.com/krishsethi19/dffml/tree/2dd0a9c4a125a9739d27228128bbd381a8e0fef4
|
learned_similarity_8
|
import torch
import torch.nn as nn
class learned_similarity_8(nn.Module):
def __init__(self, in_size=1024):
super(learned_similarity_8, self).__init__()
self.lin = nn.Linear(1, 1)
self.lin2 = nn.Linear(1, 1)
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, xi, xj):
out = torch.reshape(torch.dist(xi, xj, 2), (1, 1))
out = self.lin2(out)
out = self.tanh(out)
out = self.lin(out)
out = self.sigmoid(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_dist_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = libdevice.sqrt(tmp6)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp7, None)
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_out_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr0 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = libdevice.tanh(tmp4)
tl.store(in_out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None)
@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_out_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr0 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(in_out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, 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, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 1), (1, 1))
assert_size_stride(primals_4, (1,), (1,))
assert_size_stride(primals_5, (1, 1), (1, 1))
assert_size_stride(primals_6, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((1, 1), (1, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_dist_0[grid(1)](buf1, primals_2, primals_1, buf2,
1, 256, num_warps=2, num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((1, 1), (1, 1), torch.float32)
extern_kernels.mm(buf2, primals_3, out=buf3)
del primals_3
buf4 = buf3
del buf3
triton_poi_fused_tanh_1[grid(1)](buf4, primals_4, 1, XBLOCK=1,
num_warps=1, num_stages=1)
del primals_4
buf5 = buf2
del buf2
extern_kernels.mm(buf4, primals_5, out=buf5)
buf6 = buf5
del buf5
triton_poi_fused_sigmoid_2[grid(1)](buf6, primals_6, 1, XBLOCK=1,
num_warps=1, num_stages=1)
del primals_6
return buf6, reinterpret_tensor(buf1, (1, 1), (1, 1), 0
), buf4, primals_5, buf6
class learned_similarity_8New(nn.Module):
def __init__(self, in_size=1024):
super(learned_similarity_8New, self).__init__()
self.lin = nn.Linear(1, 1)
self.lin2 = nn.Linear(1, 1)
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, input_0, input_1):
primals_3 = self.lin.weight
primals_4 = self.lin.bias
primals_5 = self.lin2.weight
primals_6 = self.lin2.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
laurinwagner/grouploss_plus
|
learned_similarity_8
| false
| 10,369
|
[
"MIT"
] | 0
|
add9e3e7b4fcfccf0393124aeb6e1f35a442ed88
|
https://github.com/laurinwagner/grouploss_plus/tree/add9e3e7b4fcfccf0393124aeb6e1f35a442ed88
|
OutlookAttention
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
class OutlookAttention(nn.Module):
"""
Implementation of outlook attention
--dim: hidden dim
--num_heads: number of heads
--kernel_size: kernel size in each window for outlook attention
return: token features after outlook attention
"""
def __init__(self, dim, num_heads, kernel_size=3, padding=1, stride=1,
qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
head_dim = dim // num_heads
self.num_heads = num_heads
self.kernel_size = kernel_size
self.padding = padding
self.stride = stride
self.scale = qk_scale or head_dim ** -0.5
self.v = nn.Linear(dim, dim, bias=qkv_bias)
self.attn = nn.Linear(dim, kernel_size ** 4 * num_heads)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.unfold = nn.Unfold(kernel_size=kernel_size, padding=padding,
stride=stride)
self.pool = nn.AvgPool2d(kernel_size=stride, stride=stride,
ceil_mode=True)
def forward(self, x):
B, H, W, C = x.shape
v = self.v(x).permute(0, 3, 1, 2)
h, w = math.ceil(H / self.stride), math.ceil(W / self.stride)
v = self.unfold(v).reshape(B, self.num_heads, C // self.num_heads,
self.kernel_size * self.kernel_size, h * w).permute(0, 1, 4, 3, 2)
attn = self.pool(x.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
attn = self.attn(attn).reshape(B, h * w, self.num_heads, self.
kernel_size * self.kernel_size, self.kernel_size * self.kernel_size
).permute(0, 2, 1, 3, 4)
attn = attn * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).permute(0, 1, 4, 3, 2).reshape(B, C * self.
kernel_size * self.kernel_size, h * w)
x = F.fold(x, output_size=(H, W), kernel_size=self.kernel_size,
padding=self.padding, stride=self.stride)
x = self.proj(x.permute(0, 2, 3, 1))
x = self.proj_drop(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_im2col_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 12
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = x0 + x1
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused__softmax_mul_2(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 2304
rnumel = 9
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r2 = rindex
x7 = xindex
x0 = xindex % 36
x3 = xindex % 9
x4 = xindex // 9 % 4
x5 = xindex // 36 % 16
x6 = xindex // 576
tmp0 = tl.load(in_ptr0 + (r2 + 9 * x7), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r2 + 9 * x0), rmask & xmask, eviction_policy=
'evict_last', other=0.0)
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.where(rmask & xmask, tmp5, float('-inf'))
tmp8 = triton_helpers.max2(tmp7, 1)[:, None]
tmp9 = tmp4 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.where(rmask & xmask, tmp11, 0)
tmp14 = tl.sum(tmp13, 1)[:, None]
tmp15 = tmp10 / tmp14
tl.store(out_ptr2 + (r2 + 9 * x3 + 81 * x5 + 1312 * x4 + 5248 * x6),
tmp15, rmask & xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 2304
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 9
x1 = xindex // 9 % 16
x2 = xindex // 144 % 4
x3 = xindex // 576
x5 = xindex
tmp0 = tl.load(in_ptr0 + (4 * (x0 // 3) + x1 // 4), xmask,
eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (4 * (x0 % 3) + x1 % 4), xmask,
eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 6, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 6) | ~xmask,
'index out of bounds: 0 <= tmp4 < 6')
tmp7 = tmp6 + tmp1
tmp8 = tmp6 < 0
tmp9 = tl.where(tmp8, tmp7, tmp6)
tl.device_assert((0 <= tmp9) & (tmp9 < 6) | ~xmask,
'index out of bounds: 0 <= tmp9 < 6')
tmp11 = -1 + tmp4
tmp12 = tl.full([1], 0, tl.int64)
tmp13 = tmp11 >= tmp12
tmp14 = tl.full([1], 4, tl.int64)
tmp15 = tmp11 < tmp14
tmp16 = -1 + tmp9
tmp17 = tmp16 >= tmp12
tmp18 = tmp16 < tmp14
tmp19 = tmp13 & tmp15
tmp20 = tmp19 & tmp17
tmp21 = tmp20 & tmp18
tmp22 = tl.load(in_ptr1 + (-20 + x2 + 4 * tmp9 + 16 * tmp4 + 64 * x3),
tmp21 & xmask, eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + x5, tmp22, xmask)
@triton.jit
def triton_poi_fused_bmm_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 20736
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 81
x1 = xindex // 81
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 81 * (x1 % 16) + 1312 * (x1 // 16)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_col2im_5(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = 0.0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_col2im_6(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 576
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
y5 = yindex // 3 % 12
x4 = xindex
y0 = yindex % 3
y1 = yindex // 3 % 4
y2 = yindex // 12 % 3
y3 = yindex // 36
tmp0 = tl.load(in_ptr0 + y5, ymask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (x4 + 4 * y0), xmask & ymask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr1 + (y0 + 3 * y2 + 9 * x4 + 36 * y1 + 144 * y3 +
144 * ((y0 + 3 * y2) // 9)), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.full([XBLOCK, YBLOCK], 6, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 6) | ~ymask,
'index out of bounds: 0 <= tmp4 < 6')
tmp7 = tmp6 + tmp1
tmp8 = tmp6 < 0
tmp9 = tl.where(tmp8, tmp7, tmp6)
tl.device_assert((0 <= tmp9) & (tmp9 < 6) | ~(xmask & ymask),
'index out of bounds: 0 <= tmp9 < 6')
tl.atomic_add(out_ptr0 + tl.broadcast_to(tmp9 + 6 * tmp4 + 36 * y3, [
XBLOCK, YBLOCK]), tmp11, xmask & ymask, sem='relaxed')
@triton.jit
def triton_poi_fused_clone_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
y1 = yindex // 4 % 4
y0 = yindex % 4
x3 = xindex
y2 = yindex // 16
y5 = yindex
tmp0 = 1 + y1
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1, 1], 6, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = 1 + y0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (7 + y0 + 6 * y1 + 36 * x3 + 144 * y2), tmp10 &
xmask & ymask, eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x3 + 4 * y5), tmp11, xmask & ymask)
@triton.jit
def triton_poi_fused_add_8(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, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (324, 4), (4, 1))
assert_size_stride(primals_4, (324,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((3, 4), (4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused_im2col_0[grid(12)](buf1, 12, XBLOCK=16, num_warps=
1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_avg_pool2d_1[grid(256)](primals_1, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((64, 324), (324, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 324), (1, 4), 0), out=buf3)
del primals_3
buf6 = empty_strided_cuda((4, 4, 16, 9, 9), (5248, 1312, 81, 9, 1),
torch.float32)
triton_per_fused__softmax_mul_2[grid(2304)](buf3, primals_4, buf6,
2304, 9, XBLOCK=8, num_warps=2, num_stages=1)
del primals_4
buf7 = empty_strided_cuda((4, 4, 16, 9, 1), (576, 144, 9, 1, 1),
torch.float32)
triton_poi_fused_clone_3[grid(2304)](buf1, buf0, buf7, 2304, XBLOCK
=128, num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf3, (256, 9, 9), (81, 9, 1), 0)
del buf3
triton_poi_fused_bmm_4[grid(20736)](buf6, buf8, 20736, XBLOCK=256,
num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((256, 9, 1), (9, 1, 1), torch.float32)
extern_kernels.bmm(buf8, reinterpret_tensor(buf7, (256, 9, 1), (9,
1, 0), 0), out=buf9)
del buf8
buf10 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32
)
triton_poi_fused_col2im_5[grid(576)](buf10, 576, XBLOCK=256,
num_warps=4, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32
)
triton_poi_fused_col2im_5[grid(576)](buf11, 576, XBLOCK=256,
num_warps=4, num_stages=1)
triton_poi_fused_col2im_6[grid(576, 4)](buf1, buf9, buf11, 576, 4,
XBLOCK=1, YBLOCK=256, num_warps=4, num_stages=1)
del buf9
buf13 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_clone_7[grid(64, 4)](buf11, buf13, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
del buf11
buf14 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf13, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf14)
buf15 = reinterpret_tensor(buf14, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf14
triton_poi_fused_add_8[grid(256)](buf15, primals_6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_6
return buf15, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1, reinterpret_tensor(buf2, (64, 4), (4, 1), 0
), buf6, buf10, reinterpret_tensor(buf13, (64, 4), (4, 1), 0
), primals_5, reinterpret_tensor(buf7, (256, 1, 9), (9, 1, 1), 0)
class OutlookAttentionNew(nn.Module):
"""
Implementation of outlook attention
--dim: hidden dim
--num_heads: number of heads
--kernel_size: kernel size in each window for outlook attention
return: token features after outlook attention
"""
def __init__(self, dim, num_heads, kernel_size=3, padding=1, stride=1,
qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
head_dim = dim // num_heads
self.num_heads = num_heads
self.kernel_size = kernel_size
self.padding = padding
self.stride = stride
self.scale = qk_scale or head_dim ** -0.5
self.v = nn.Linear(dim, dim, bias=qkv_bias)
self.attn = nn.Linear(dim, kernel_size ** 4 * num_heads)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.unfold = nn.Unfold(kernel_size=kernel_size, padding=padding,
stride=stride)
self.pool = nn.AvgPool2d(kernel_size=stride, stride=stride,
ceil_mode=True)
def forward(self, input_0):
primals_2 = self.v.weight
primals_3 = self.attn.weight
primals_4 = self.attn.bias
primals_5 = self.proj.weight
primals_6 = self.proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
javierrodenas/clearml_javi
|
OutlookAttention
| false
| 10,370
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
AdaIN
|
import math
import torch
import torch.nn as nn
from numpy import prod
def getLayerNormalizationFactor(x, gain, fromTF):
"""
Get He's constant for the given layer
https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf
"""
size = x.weight.size()
fan_in = prod(size[1:])
if not fromTF:
return math.sqrt(2.0 / fan_in)
else:
return gain / math.sqrt(fan_in)
class ConstrainedLayer(nn.Module):
"""
A handy refactor that allows the user to:
- initialize one layer's bias to zero
- apply He's initialization at runtime
"""
def __init__(self, module, equalized=True, lrMul=1.0, initBiasToZero=
True, gain=math.sqrt(2.0), fromTF=False):
"""
equalized (bool): if true, the layer's weight should evolve within
the range (-1, 1)
initBiasToZero (bool): if true, bias will be initialized to zero
"""
super(ConstrainedLayer, self).__init__()
self.module = module
self.equalized = equalized
self.fromTF = fromTF
if initBiasToZero:
self.module.bias.data.fill_(0)
if self.equalized:
self.module.weight.data.normal_(0, 1)
self.module.weight.data /= lrMul
self.weight = getLayerNormalizationFactor(self.module, gain,
self.fromTF) * lrMul
def forward(self, x):
if not self.fromTF:
x = self.module(x)
if self.equalized:
x *= self.weight
else:
size = self.module.weight.size()
if len(size) <= 2:
x = self.module(x)
if self.equalized:
x -= self.module.bias.data
x *= self.weight
x += self.module.bias.data
else:
x = self.module(x)
if self.equalized:
x -= self.module.bias.view(-1, 1, 1)
x *= self.weight
x += self.module.bias.view(-1, 1, 1)
return x
class EqualizedLinear(ConstrainedLayer):
def __init__(self, nChannelsPrevious, nChannels, bias=True, **kwargs):
"""
A nn.Linear module with specific constraints
Args:
nChannelsPrevious (int): number of channels in the previous layer
nChannels (int): number of channels of the current layer
bias (bool): with bias ?
"""
ConstrainedLayer.__init__(self, nn.Linear(nChannelsPrevious,
nChannels, bias=bias), **kwargs)
class AdaIN(nn.Module):
def __init__(self, dimIn, dimOut, epsilon=1e-08):
super(AdaIN, self).__init__()
self.epsilon = epsilon
self.styleModulator = EqualizedLinear(dimIn, 2 * dimOut, equalized=
True, initBiasToZero=True)
self.dimOut = dimOut
def forward(self, x, y):
batchSize, nChannel, _width, _height = x.size()
tmpX = x.view(batchSize, nChannel, -1)
mux = tmpX.mean(dim=2).view(batchSize, nChannel, 1, 1)
varx = torch.clamp((tmpX * tmpX).mean(dim=2).view(batchSize,
nChannel, 1, 1) - mux * mux, min=0)
varx = torch.rsqrt(varx + self.epsilon)
x = (x - mux) * varx
styleY = self.styleModulator(y)
yA = styleY[:, :self.dimOut].view(batchSize, self.dimOut, 1, 1)
yB = styleY[:, self.dimOut:].view(batchSize, self.dimOut, 1, 1)
return yA * x + yB
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'dimIn': 4, 'dimOut': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.nn as nn
from numpy import prod
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_clamp_mean_mul_rsqrt_sub_0(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp20 = tl.load(in_ptr1 + (x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr1 + (4 + x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr2 + (4 + x2), xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = tmp0 * tmp0
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = 16.0
tmp11 = tmp4 / tmp10
tmp12 = tmp9 / tmp10
tmp13 = tmp11 * tmp11
tmp14 = tmp12 - tmp13
tmp15 = 0.0
tmp16 = triton_helpers.maximum(tmp14, tmp15)
tmp17 = 1e-08
tmp18 = tmp16 + tmp17
tmp19 = libdevice.rsqrt(tmp18)
tmp22 = tmp20 + tmp21
tmp23 = 0.7071067811865476
tmp24 = tmp22 * tmp23
tmp25 = tmp0 - tmp11
tmp26 = tmp25 * tmp19
tmp27 = tmp24 * tmp26
tmp30 = tmp28 + tmp29
tmp31 = tmp30 * tmp23
tmp32 = tmp27 + tmp31
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp11, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp19, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp32, 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, (8, 4), (4, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf4 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_4, reinterpret_tensor(primals_2, (4, 8),
(1, 4), 0), out=buf4)
del primals_2
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf1 = buf0
del buf0
buf3 = reinterpret_tensor(buf2, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_clamp_mean_mul_rsqrt_sub_0[grid(16)](buf1,
buf3, primals_1, buf4, primals_3, buf5, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del buf4
del primals_3
return buf5, primals_1, primals_4, reinterpret_tensor(buf1, (4, 4, 1, 1
), (4, 1, 1, 1), 0), buf3
def getLayerNormalizationFactor(x, gain, fromTF):
"""
Get He's constant for the given layer
https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf
"""
size = x.weight.size()
fan_in = prod(size[1:])
if not fromTF:
return math.sqrt(2.0 / fan_in)
else:
return gain / math.sqrt(fan_in)
class ConstrainedLayer(nn.Module):
"""
A handy refactor that allows the user to:
- initialize one layer's bias to zero
- apply He's initialization at runtime
"""
def __init__(self, module, equalized=True, lrMul=1.0, initBiasToZero=
True, gain=math.sqrt(2.0), fromTF=False):
"""
equalized (bool): if true, the layer's weight should evolve within
the range (-1, 1)
initBiasToZero (bool): if true, bias will be initialized to zero
"""
super(ConstrainedLayer, self).__init__()
self.module = module
self.equalized = equalized
self.fromTF = fromTF
if initBiasToZero:
self.module.bias.data.fill_(0)
if self.equalized:
self.module.weight.data.normal_(0, 1)
self.module.weight.data /= lrMul
self.weight = getLayerNormalizationFactor(self.module, gain,
self.fromTF) * lrMul
def forward(self, x):
if not self.fromTF:
x = self.module(x)
if self.equalized:
x *= self.weight
else:
size = self.module.weight.size()
if len(size) <= 2:
x = self.module(x)
if self.equalized:
x -= self.module.bias.data
x *= self.weight
x += self.module.bias.data
else:
x = self.module(x)
if self.equalized:
x -= self.module.bias.view(-1, 1, 1)
x *= self.weight
x += self.module.bias.view(-1, 1, 1)
return x
class EqualizedLinear(ConstrainedLayer):
def __init__(self, nChannelsPrevious, nChannels, bias=True, **kwargs):
"""
A nn.Linear module with specific constraints
Args:
nChannelsPrevious (int): number of channels in the previous layer
nChannels (int): number of channels of the current layer
bias (bool): with bias ?
"""
ConstrainedLayer.__init__(self, nn.Linear(nChannelsPrevious,
nChannels, bias=bias), **kwargs)
class AdaINNew(nn.Module):
def __init__(self, dimIn, dimOut, epsilon=1e-08):
super(AdaINNew, self).__init__()
self.epsilon = epsilon
self.styleModulator = EqualizedLinear(dimIn, 2 * dimOut, equalized=
True, initBiasToZero=True)
self.dimOut = dimOut
def forward(self, input_0, input_1):
primals_2 = self.styleModulator.module.weight
primals_3 = self.styleModulator.module.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jwen307/pytorch_GAN_zoo
|
AdaIN
| false
| 10,371
|
[
"BSD-3-Clause"
] | 0
|
b1e538a2f03fda42bd7a12872238b770ea5e0f23
|
https://github.com/jwen307/pytorch_GAN_zoo/tree/b1e538a2f03fda42bd7a12872238b770ea5e0f23
|
Model
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 60, kernel_size=5)
self.conv2 = nn.Conv2d(60, 60, kernel_size=5)
self.conv3 = nn.Conv2d(60, 30, kernel_size=3)
self.conv4 = nn.Conv2d(30, 30, kernel_size=3)
self.lin1 = nn.Linear(4 * 4 * 30, 500)
self.lin2 = nn.Linear(500, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = F.max_pool2d(x, 2)
x = F.dropout(x, p=0.5, training=self.training)
x = x.view(-1, 4 * 4 * 30)
x = F.relu(self.lin1(x))
x = F.dropout(x, p=0.5, training=self.training)
x = self.lin2(x)
return F.log_softmax(x, dim=1)
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 864000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3600 % 60
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 752640
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3136 % 60
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 188160
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 28
x1 = xindex // 28
x4 = xindex
x3 = xindex // 47040
x5 = xindex % 47040
tmp0 = tl.load(in_ptr0 + (2 * x0 + 112 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 112 * x1), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (56 + 2 * x0 + 112 * x1), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (57 + 2 * x0 + 112 * x1), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x4, tmp6, xmask)
tl.store(out_ptr1 + (x5 + 47104 * x3), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 81120
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 676 % 30
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_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 69120
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 576 % 30
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_5(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 17280
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x3 = xindex // 12
x2 = xindex // 4320
x4 = xindex % 4320
x5 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 48 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 48 * x3), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (24 + 2 * x0 + 48 * x3), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (25 + 2 * x0 + 48 * x3), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + (x4 + 4352 * x2), tmp15, xmask)
tl.store(out_ptr1 + x5, tmp16, xmask)
@triton.jit
def triton_poi_fused_relu_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 18000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 500
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__log_softmax_7(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 36
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (60, 1, 5, 5), (25, 25, 5, 1))
assert_size_stride(primals_2, (60,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (60, 60, 5, 5), (1500, 25, 5, 1))
assert_size_stride(primals_5, (60,), (1,))
assert_size_stride(primals_6, (30, 60, 3, 3), (540, 9, 3, 1))
assert_size_stride(primals_7, (30,), (1,))
assert_size_stride(primals_8, (30, 30, 3, 3), (270, 9, 3, 1))
assert_size_stride(primals_9, (30,), (1,))
assert_size_stride(primals_10, (500, 480), (480, 1))
assert_size_stride(primals_11, (500,), (1,))
assert_size_stride(primals_12, (10, 500), (500, 1))
assert_size_stride(primals_13, (10,), (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, 60, 60, 60), (216000, 3600, 60, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(864000)](buf1, primals_2,
864000, XBLOCK=1024, 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, 60, 56, 56), (188160, 3136, 56, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(752640)](buf3, primals_5,
752640, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 60, 28, 28), (47040, 784, 28, 1),
torch.float32)
buf5 = empty_strided_cuda((4, 60, 28, 28), (47104, 784, 28, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_2[grid(188160)](buf3, buf4,
buf5, 188160, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = extern_kernels.convolution(buf4, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 30, 26, 26), (20280, 676, 26, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_3[grid(81120)](buf7, primals_7,
81120, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 30, 24, 24), (17280, 576, 24, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(69120)](buf9, primals_9,
69120, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf10 = empty_strided_cuda((4, 30, 12, 12), (4352, 144, 12, 1),
torch.int8)
buf11 = empty_strided_cuda((4, 30, 12, 12), (4320, 144, 12, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_5[grid(17280)](buf9, buf10,
buf11, 17280, XBLOCK=128, num_warps=4, num_stages=1)
buf12 = empty_strided_cuda((36, 500), (500, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf11, (36, 480), (480, 1), 0),
reinterpret_tensor(primals_10, (480, 500), (1, 480), 0), out=buf12)
buf13 = buf12
del buf12
triton_poi_fused_relu_6[grid(18000)](buf13, primals_11, 18000,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf14 = empty_strided_cuda((36, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_13, buf13, reinterpret_tensor(
primals_12, (500, 10), (1, 500), 0), alpha=1, beta=1, out=buf14)
del primals_13
buf17 = empty_strided_cuda((36, 10), (10, 1), torch.float32)
triton_per_fused__log_softmax_7[grid(36)](buf14, buf17, 36, 10,
XBLOCK=32, num_warps=4, num_stages=1)
del buf14
return (buf17, primals_1, primals_3, primals_4, primals_6, primals_8,
buf1, buf3, buf4, buf5, buf7, buf9, buf10, reinterpret_tensor(buf11,
(36, 480), (480, 1), 0), buf13, buf17, primals_12, primals_10)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.conv1 = nn.Conv2d(1, 60, kernel_size=5)
self.conv2 = nn.Conv2d(60, 60, kernel_size=5)
self.conv3 = nn.Conv2d(60, 30, kernel_size=3)
self.conv4 = nn.Conv2d(30, 30, kernel_size=3)
self.lin1 = nn.Linear(4 * 4 * 30, 500)
self.lin2 = nn.Linear(500, 10)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.lin1.weight
primals_11 = self.lin1.bias
primals_12 = self.lin2.weight
primals_13 = self.lin2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
kproshakov/SudokuCV
|
Model
| false
| 10,372
|
[
"MIT"
] | 0
|
8c29f4f1ac32513e7bd7d194d1fefb249c5d7921
|
https://github.com/kproshakov/SudokuCV/tree/8c29f4f1ac32513e7bd7d194d1fefb249c5d7921
|
LNN
|
import math
import torch
from torch.nn import functional as F
import torch.utils.data
class LNN(torch.nn.Module):
"""
A pytorch implementation of LNN layer
Input shape
- A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.
Output shape
- 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``.
Arguments
- **in_features** : Embedding of feature.
- **num_fields**: int.The field size of feature.
- **LNN_dim**: int.The number of Logarithmic neuron.
- **bias**: bool.Whether or not use bias in LNN.
"""
def __init__(self, num_fields, embed_dim, LNN_dim, bias=False):
super(LNN, self).__init__()
self.num_fields = num_fields
self.embed_dim = embed_dim
self.LNN_dim = LNN_dim
self.lnn_output_dim = LNN_dim * embed_dim
self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields))
if bias:
self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, x):
"""
:param x: Long tensor of size ``(batch_size, num_fields, embedding_size)``
"""
embed_x_abs = torch.abs(x)
embed_x_afn = torch.add(embed_x_abs, 1e-07)
embed_x_log = torch.log1p(embed_x_afn)
lnn_out = torch.matmul(self.weight, embed_x_log)
if self.bias is not None:
lnn_out += self.bias
lnn_exp = torch.expm1(lnn_out)
output = F.relu(lnn_exp).contiguous().view(-1, self.lnn_output_dim)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_fields': 4, 'embed_dim': 4, 'LNN_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl_math.abs(tmp0)
tmp2 = 1e-07
tmp3 = tmp1 + tmp2
tmp4 = libdevice.log1p(tmp3)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_expm1_relu_threshold_backward_1(in_ptr0,
out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = libdevice.expm1(tmp0)
tmp2 = tl.full([1, 1], 0, tl.int32)
tmp3 = triton_helpers.maximum(tmp2, tmp1)
tmp4 = 0.0
tmp5 = tmp3 <= tmp4
tl.store(out_ptr0 + (x2 + 4 * y3), tmp3, xmask & ymask)
tl.store(out_ptr1 + (x2 + 4 * y3), tmp5, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_clone_expm1_relu_threshold_backward_1[grid(64, 4)](
buf1, buf2, buf3, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4,
num_stages=1)
return reinterpret_tensor(buf2, (16, 16), (16, 1), 0), reinterpret_tensor(
buf0, (64, 4), (4, 1), 0), buf1, buf3
class LNNNew(torch.nn.Module):
"""
A pytorch implementation of LNN layer
Input shape
- A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.
Output shape
- 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``.
Arguments
- **in_features** : Embedding of feature.
- **num_fields**: int.The field size of feature.
- **LNN_dim**: int.The number of Logarithmic neuron.
- **bias**: bool.Whether or not use bias in LNN.
"""
def __init__(self, num_fields, embed_dim, LNN_dim, bias=False):
super(LNNNew, self).__init__()
self.num_fields = num_fields
self.embed_dim = embed_dim
self.LNN_dim = LNN_dim
self.lnn_output_dim = LNN_dim * embed_dim
self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields))
if bias:
self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jqsl2012/pytorch-fm
|
LNN
| false
| 10,373
|
[
"MIT"
] | 0
|
de6240d0a17750303bbc97dba676b667c3a27829
|
https://github.com/jqsl2012/pytorch-fm/tree/de6240d0a17750303bbc97dba676b667c3a27829
|
ClassBlock
|
import torch
import torch.nn as nn
import torch.nn.parallel
class Mlp(nn.Module):
"""Implementation of MLP"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class ClassAttention(nn.Module):
"""
Class attention layer from CaiT, see details in CaiT
Class attention is the post stage in our VOLO, which is optional.
"""
def __init__(self, dim, num_heads=8, head_dim=None, qkv_bias=False,
qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
if head_dim is not None:
self.head_dim = head_dim
else:
head_dim = dim // num_heads
self.head_dim = head_dim
self.scale = qk_scale or head_dim ** -0.5
self.kv = nn.Linear(dim, self.head_dim * self.num_heads * 2, bias=
qkv_bias)
self.q = nn.Linear(dim, self.head_dim * self.num_heads, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(self.head_dim * self.num_heads, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, _C = x.shape
kv = self.kv(x).reshape(B, N, 2, self.num_heads, self.head_dim
).permute(2, 0, 3, 1, 4)
k, v = kv[0], kv[1]
q = self.q(x[:, :1, :]).reshape(B, self.num_heads, 1, self.head_dim)
attn = q * self.scale @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
cls_embed = (attn @ v).transpose(1, 2).reshape(B, 1, self.head_dim *
self.num_heads)
cls_embed = self.proj(cls_embed)
cls_embed = self.proj_drop(cls_embed)
return cls_embed
class ClassBlock(nn.Module):
"""
Class attention block from CaiT, see details in CaiT
We use two-layers class attention in our VOLO, which is optional.
"""
def __init__(self, dim, num_heads, head_dim=None, mlp_ratio=4.0,
qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=
0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = ClassAttention(dim, num_heads=num_heads, head_dim=
head_dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=
attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
def forward(self, x):
cls_embed = x[:, :1]
cls_embed = cls_embed + self.drop_path(self.attn(self.norm1(x)))
cls_embed = cls_embed + self.drop_path(self.mlp(self.norm2(cls_embed)))
return torch.cat([cls_embed, x[:, 1:]], dim=1)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 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__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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_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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (4 + 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_add_native_layer_norm_7(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 16 * 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 + 16 * 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 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1e-05
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_gelu_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865476
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_10(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
x1 = xindex // 4 % 4
x0 = xindex % 4
x2 = xindex // 16
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + (x0 + 4 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.load(in_ptr2 + (x0 + 4 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp9 = tl.load(in_ptr3 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp10 = tmp8 + tmp9
tmp11 = tmp7 + tmp10
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp17 = tl.load(in_ptr0 + (4 + x0 + 4 * (-1 + x1) + 16 * x2), tmp14 &
xmask, other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (8, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (16, 4), (4, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (4, 16), (16, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_1, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](primals_1, buf0,
buf1, primals_2, primals_3, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_2
del primals_3
buf3 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 8), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
del buf1
extern_kernels.mm(reinterpret_tensor(buf2, (4, 4), (16, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 1, 1), (4, 1, 16, 16), 0)
del buf4
triton_poi_fused_mul_2[grid(16)](buf5, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf6 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf3, buf6, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((16, 1, 4), (4, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 1, 1), (1, 0, 0),
0), reinterpret_tensor(buf6, (16, 1, 4), (4, 0, 1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 64, 1), torch.float32)
triton_poi_fused__softmax_4[grid(64)](buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf7
triton_poi_fused__softmax_5[grid(64)](buf8, buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf10 = reinterpret_tensor(buf8, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf8
triton_poi_fused_clone_6[grid(16, 4)](buf3, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf3
buf11 = reinterpret_tensor(buf0, (16, 1, 1), (1, 1, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf9, (16, 1, 4), (4, 4, 1),
0), reinterpret_tensor(buf10, (16, 4, 1), (4, 1, 0), 0), out=buf11)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf11, (4, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf12)
del primals_7
buf13 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf14 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
triton_poi_fused_add_native_layer_norm_7[grid(4)](primals_1, buf12,
buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_8[grid(16)](primals_1, buf12,
buf13, buf14, primals_8, primals_9, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf13
del buf14
del primals_9
buf16 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf15, (4, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 16), (1, 4), 0),
alpha=1, beta=1, out=buf16)
del primals_11
buf17 = empty_strided_cuda((4, 1, 16), (16, 16, 1), torch.float32)
triton_poi_fused_gelu_9[grid(64)](buf16, buf17, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf17, (4, 16), (16, 1), 0),
reinterpret_tensor(primals_12, (16, 4), (1, 16), 0), out=buf18)
buf19 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_cat_10[grid(64)](primals_1, buf12, buf18,
primals_13, buf19, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf18
del primals_13
return buf19, primals_1, primals_8, reinterpret_tensor(buf2, (16, 4), (
4, 1), 0), reinterpret_tensor(buf2, (4, 4), (16, 1), 0
), buf9, reinterpret_tensor(buf11, (4, 4), (4, 1), 0
), buf12, reinterpret_tensor(buf15, (4, 4), (4, 1), 0
), buf16, reinterpret_tensor(buf17, (4, 16), (16, 1), 0
), primals_12, primals_10, primals_6, reinterpret_tensor(buf10, (16,
1, 4), (4, 1, 1), 0), reinterpret_tensor(buf5, (16, 1, 1), (1, 1, 1), 0
), reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 4), 0
), primals_5, primals_4
class Mlp(nn.Module):
"""Implementation of MLP"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class ClassAttention(nn.Module):
"""
Class attention layer from CaiT, see details in CaiT
Class attention is the post stage in our VOLO, which is optional.
"""
def __init__(self, dim, num_heads=8, head_dim=None, qkv_bias=False,
qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
if head_dim is not None:
self.head_dim = head_dim
else:
head_dim = dim // num_heads
self.head_dim = head_dim
self.scale = qk_scale or head_dim ** -0.5
self.kv = nn.Linear(dim, self.head_dim * self.num_heads * 2, bias=
qkv_bias)
self.q = nn.Linear(dim, self.head_dim * self.num_heads, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(self.head_dim * self.num_heads, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, _C = x.shape
kv = self.kv(x).reshape(B, N, 2, self.num_heads, self.head_dim
).permute(2, 0, 3, 1, 4)
k, v = kv[0], kv[1]
q = self.q(x[:, :1, :]).reshape(B, self.num_heads, 1, self.head_dim)
attn = q * self.scale @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
cls_embed = (attn @ v).transpose(1, 2).reshape(B, 1, self.head_dim *
self.num_heads)
cls_embed = self.proj(cls_embed)
cls_embed = self.proj_drop(cls_embed)
return cls_embed
class ClassBlockNew(nn.Module):
"""
Class attention block from CaiT, see details in CaiT
We use two-layers class attention in our VOLO, which is optional.
"""
def __init__(self, dim, num_heads, head_dim=None, mlp_ratio=4.0,
qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=
0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = ClassAttention(dim, num_heads=num_heads, head_dim=
head_dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=
attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
def forward(self, input_0):
primals_2 = self.norm1.weight
primals_3 = self.norm1.bias
primals_4 = self.attn.kv.weight
primals_5 = self.attn.q.weight
primals_6 = self.attn.proj.weight
primals_7 = self.attn.proj.bias
primals_8 = self.norm2.weight
primals_9 = self.norm2.bias
primals_10 = self.mlp.fc1.weight
primals_11 = self.mlp.fc1.bias
primals_12 = self.mlp.fc2.weight
primals_13 = self.mlp.fc2.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]
|
javierrodenas/clearml_javi
|
ClassBlock
| false
| 10,374
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
Conv2D
|
import torch
import torch.utils.data
from torch import nn
class Conv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, dilation_h
=1, dilation_w=1, causal=True):
super(Conv2D, self).__init__()
self.causal = causal
self.dilation_h, self.dilation_w = dilation_h, dilation_w
if self.causal:
self.padding_h = dilation_h * (kernel_size - 1)
else:
self.padding_h = dilation_h * (kernel_size - 1) // 2
self.padding_w = dilation_w * (kernel_size - 1) // 2
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size,
dilation=(dilation_h, dilation_w), padding=(self.padding_h,
self.padding_w))
self.conv = nn.utils.weight_norm(self.conv)
nn.init.kaiming_normal_(self.conv.weight)
def forward(self, tensor):
out = self.conv(tensor)
if self.causal and self.padding_h != 0:
out = out[:, :, :-self.padding_h, :]
return out
def reverse_fast(self, tensor):
self.conv.padding = 0, self.padding_w
out = self.conv(tensor)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__weight_norm_interface_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
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)
tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(rmask & xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = libdevice.sqrt(tmp5)
tmp8 = tmp7 / tmp6
tmp9 = tmp0 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr0 + (r1 + 36 * x0), tmp9, rmask & xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 24 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 1, 1), (1, 1, 1, 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, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf0
buf2 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__weight_norm_interface_0[grid(4)](buf1, primals_2,
primals_1, buf2, 4, 36, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = extern_kernels.convolution(primals_4, buf2, stride=(1, 1),
padding=(2, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 6, 4), (96, 24, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_1[grid(384)](buf4, primals_3, 384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
return reinterpret_tensor(buf4, (4, 4, 4, 4), (96, 24, 4, 1), 0
), buf2, primals_1, primals_2, primals_4, buf1, buf2
class Conv2DNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, dilation_h
=1, dilation_w=1, causal=True):
super(Conv2DNew, self).__init__()
self.causal = causal
self.dilation_h, self.dilation_w = dilation_h, dilation_w
if self.causal:
self.padding_h = dilation_h * (kernel_size - 1)
else:
self.padding_h = dilation_h * (kernel_size - 1) // 2
self.padding_w = dilation_w * (kernel_size - 1) // 2
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size,
dilation=(dilation_h, dilation_w), padding=(self.padding_h,
self.padding_w))
self.conv = nn.utils.weight_norm(self.conv)
nn.init.kaiming_normal_(self.conv.weight)
def reverse_fast(self, tensor):
self.conv.padding = 0, self.padding_w
out = self.conv(tensor)
return out
def forward(self, input_0):
primals_3 = self.conv.bias
primals_1 = self.conv.weight_g
primals_2 = self.conv.weight_v
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
leoauri/WaveFlow
|
Conv2D
| false
| 10,375
|
[
"BSD-3-Clause"
] | 0
|
a34843f06a8b70acf8d4a3ffa5c2e8d5a07a7d66
|
https://github.com/leoauri/WaveFlow/tree/a34843f06a8b70acf8d4a3ffa5c2e8d5a07a7d66
|
LatentAtten
|
import math
import torch
import torch.nn as nn
class LatentAtten(nn.Module):
"""
Attention on latent representation
"""
def __init__(self, h_dim, key_dim=None) ->None:
super(LatentAtten, self).__init__()
if key_dim is None:
key_dim = h_dim
self.key_dim = key_dim
self.key_layer = nn.Linear(h_dim, key_dim)
self.query_layer = nn.Linear(h_dim, key_dim)
def forward(self, h_M, h_R):
key = self.key_layer(h_M)
query = self.query_layer(h_R)
atten = key @ query.transpose(0, 1) / math.sqrt(self.key_dim)
atten = torch.softmax(atten, 1)
return atten
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'h_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex % 16
x0 = xindex % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x4 + 16 * x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x5, tmp2, xmask)
@triton.jit
def triton_poi_fused__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)
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_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf1, primals_5, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_2[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf4
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), buf5, reinterpret_tensor(buf0, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf2, (16, 4, 4), (16, 1, 4), 0)
class LatentAttenNew(nn.Module):
"""
Attention on latent representation
"""
def __init__(self, h_dim, key_dim=None) ->None:
super(LatentAttenNew, self).__init__()
if key_dim is None:
key_dim = h_dim
self.key_dim = key_dim
self.key_layer = nn.Linear(h_dim, key_dim)
self.query_layer = nn.Linear(h_dim, key_dim)
def forward(self, input_0, input_1):
primals_1 = self.key_layer.weight
primals_2 = self.key_layer.bias
primals_4 = self.query_layer.weight
primals_5 = self.query_layer.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]
|
kage08/CAMul
|
LatentAtten
| false
| 10,376
|
[
"MIT"
] | 0
|
79f8a27f472943229fb087bae8e405e38e5e0b47
|
https://github.com/kage08/CAMul/tree/79f8a27f472943229fb087bae8e405e38e5e0b47
|
SpatialPyramidPooling
|
import torch
import torch.nn as nn
class SpatialPyramidPooling(nn.Module):
def __init__(self, pool_sizes=[5, 9, 13]):
super(SpatialPyramidPooling, self).__init__()
self.maxpools = nn.ModuleList([nn.MaxPool2d(pool_size, 1, pool_size //
2) for pool_size in pool_sizes])
def forward(self, x):
features = [maxpool(x) for maxpool in self.maxpools[::-1]]
features = torch.cat(features + [x], dim=1)
return features
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_max_pool2d_with_indices_0(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 4
x0 = xindex % 4
x7 = xindex
x3 = xindex // 64
x4 = xindex % 64
tmp116 = tl.load(in_ptr0 + x7, xmask)
tmp0 = -2 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -2 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-10 + x7), tmp10 & xmask, other=float('-inf'))
tmp12 = -1 + x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-9 + x7), tmp16 & xmask, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-8 + x7), tmp23 & xmask, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = 1 + x0
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp5 & tmp29
tmp31 = tl.load(in_ptr0 + (-7 + x7), tmp30 & xmask, other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = 2 + x0
tmp34 = tmp33 >= tmp1
tmp35 = tmp33 < tmp3
tmp36 = tmp34 & tmp35
tmp37 = tmp5 & tmp36
tmp38 = tl.load(in_ptr0 + (-6 + x7), tmp37 & xmask, other=float('-inf'))
tmp39 = triton_helpers.maximum(tmp38, tmp32)
tmp40 = -1 + x1
tmp41 = tmp40 >= tmp1
tmp42 = tmp40 < tmp3
tmp43 = tmp41 & tmp42
tmp44 = tmp43 & tmp9
tmp45 = tl.load(in_ptr0 + (-6 + x7), tmp44 & xmask, other=float('-inf'))
tmp46 = triton_helpers.maximum(tmp45, tmp39)
tmp47 = tmp43 & tmp15
tmp48 = tl.load(in_ptr0 + (-5 + x7), tmp47 & xmask, other=float('-inf'))
tmp49 = triton_helpers.maximum(tmp48, tmp46)
tmp50 = tmp43 & tmp22
tmp51 = tl.load(in_ptr0 + (-4 + x7), tmp50 & xmask, other=float('-inf'))
tmp52 = triton_helpers.maximum(tmp51, tmp49)
tmp53 = tmp43 & tmp29
tmp54 = tl.load(in_ptr0 + (-3 + x7), tmp53 & xmask, other=float('-inf'))
tmp55 = triton_helpers.maximum(tmp54, tmp52)
tmp56 = tmp43 & tmp36
tmp57 = tl.load(in_ptr0 + (-2 + x7), tmp56 & xmask, other=float('-inf'))
tmp58 = triton_helpers.maximum(tmp57, tmp55)
tmp59 = x1
tmp60 = tmp59 >= tmp1
tmp61 = tmp59 < tmp3
tmp62 = tmp60 & tmp61
tmp63 = tmp62 & tmp9
tmp64 = tl.load(in_ptr0 + (-2 + x7), tmp63 & xmask, other=float('-inf'))
tmp65 = triton_helpers.maximum(tmp64, tmp58)
tmp66 = tmp62 & tmp15
tmp67 = tl.load(in_ptr0 + (-1 + x7), tmp66 & xmask, other=float('-inf'))
tmp68 = triton_helpers.maximum(tmp67, tmp65)
tmp69 = tmp62 & tmp22
tmp70 = tl.load(in_ptr0 + x7, tmp69 & xmask, other=float('-inf'))
tmp71 = triton_helpers.maximum(tmp70, tmp68)
tmp72 = tmp62 & tmp29
tmp73 = tl.load(in_ptr0 + (1 + x7), tmp72 & xmask, other=float('-inf'))
tmp74 = triton_helpers.maximum(tmp73, tmp71)
tmp75 = tmp62 & tmp36
tmp76 = tl.load(in_ptr0 + (2 + x7), tmp75 & xmask, other=float('-inf'))
tmp77 = triton_helpers.maximum(tmp76, tmp74)
tmp78 = 1 + x1
tmp79 = tmp78 >= tmp1
tmp80 = tmp78 < tmp3
tmp81 = tmp79 & tmp80
tmp82 = tmp81 & tmp9
tmp83 = tl.load(in_ptr0 + (2 + x7), tmp82 & xmask, other=float('-inf'))
tmp84 = triton_helpers.maximum(tmp83, tmp77)
tmp85 = tmp81 & tmp15
tmp86 = tl.load(in_ptr0 + (3 + x7), tmp85 & xmask, other=float('-inf'))
tmp87 = triton_helpers.maximum(tmp86, tmp84)
tmp88 = tmp81 & tmp22
tmp89 = tl.load(in_ptr0 + (4 + x7), tmp88 & xmask, other=float('-inf'))
tmp90 = triton_helpers.maximum(tmp89, tmp87)
tmp91 = tmp81 & tmp29
tmp92 = tl.load(in_ptr0 + (5 + x7), tmp91 & xmask, other=float('-inf'))
tmp93 = triton_helpers.maximum(tmp92, tmp90)
tmp94 = tmp81 & tmp36
tmp95 = tl.load(in_ptr0 + (6 + x7), tmp94 & xmask, other=float('-inf'))
tmp96 = triton_helpers.maximum(tmp95, tmp93)
tmp97 = 2 + x1
tmp98 = tmp97 >= tmp1
tmp99 = tmp97 < tmp3
tmp100 = tmp98 & tmp99
tmp101 = tmp100 & tmp9
tmp102 = tl.load(in_ptr0 + (6 + x7), tmp101 & xmask, other=float('-inf'))
tmp103 = triton_helpers.maximum(tmp102, tmp96)
tmp104 = tmp100 & tmp15
tmp105 = tl.load(in_ptr0 + (7 + x7), tmp104 & xmask, other=float('-inf'))
tmp106 = triton_helpers.maximum(tmp105, tmp103)
tmp107 = tmp100 & tmp22
tmp108 = tl.load(in_ptr0 + (8 + x7), tmp107 & xmask, other=float('-inf'))
tmp109 = triton_helpers.maximum(tmp108, tmp106)
tmp110 = tmp100 & tmp29
tmp111 = tl.load(in_ptr0 + (9 + x7), tmp110 & xmask, other=float('-inf'))
tmp112 = triton_helpers.maximum(tmp111, tmp109)
tmp113 = tmp100 & tmp36
tmp114 = tl.load(in_ptr0 + (10 + x7), tmp113 & xmask, other=float('-inf'))
tmp115 = triton_helpers.maximum(tmp114, tmp112)
tl.store(out_ptr0 + (x4 + 256 * x3), tmp115, xmask)
tl.store(out_ptr1 + (x4 + 256 * x3), tmp116, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tl.store(out_ptr0 + (x0 + 256 * x1), tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten.max_pool2d_with_indices.default(arg0_1, [13,
13], [1, 1], [6, 6])
buf1 = buf0[0]
del buf0
buf3 = torch.ops.aten.max_pool2d_with_indices.default(arg0_1, [9, 9
], [1, 1], [4, 4])
buf4 = buf3[0]
del buf3
buf10 = empty_strided_cuda((4, 16, 4, 4), (256, 16, 4, 1), torch.
float32)
buf6 = reinterpret_tensor(buf10, (4, 4, 4, 4), (256, 16, 4, 1), 128)
buf9 = reinterpret_tensor(buf10, (4, 4, 4, 4), (256, 16, 4, 1), 192)
get_raw_stream(0)
triton_poi_fused_cat_max_pool2d_with_indices_0[grid(256)](arg0_1,
buf6, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
buf7 = reinterpret_tensor(buf10, (4, 4, 4, 4), (256, 16, 4, 1), 0)
triton_poi_fused_cat_1[grid(256)](buf1, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
buf8 = reinterpret_tensor(buf10, (4, 4, 4, 4), (256, 16, 4, 1), 64)
triton_poi_fused_cat_1[grid(256)](buf4, buf8, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf4
return buf10,
class SpatialPyramidPoolingNew(nn.Module):
def __init__(self, pool_sizes=[5, 9, 13]):
super(SpatialPyramidPoolingNew, self).__init__()
self.maxpools = nn.ModuleList([nn.MaxPool2d(pool_size, 1, pool_size //
2) for pool_size in pool_sizes])
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
janewen134/fyp
|
SpatialPyramidPooling
| false
| 10,377
|
[
"Apache-2.0"
] | 0
|
8fb93ac22d21d5d862035ba794fe9d264add2e63
|
https://github.com/janewen134/fyp/tree/8fb93ac22d21d5d862035ba794fe9d264add2e63
|
Affine
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch import optim as optim
class Affine(nn.Module):
def __init__(self, dim):
super().__init__()
self.alpha = nn.Parameter(torch.ones((1, 1, dim)))
self.beta = nn.Parameter(torch.zeros((1, 1, dim)))
def forward(self, x):
return torch.addcmul(self.beta, self.alpha, x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_addcmul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x2, xmask)
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp5 = tmp3 * tmp4
tmp6 = tmp0 + tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 4), (4, 4, 1))
assert_size_stride(primals_2, (1, 1, 4), (4, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_addcmul_0[grid(256)](primals_1, primals_2,
primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0, primals_3
class AffineNew(nn.Module):
def __init__(self, dim):
super().__init__()
self.alpha = nn.Parameter(torch.ones((1, 1, dim)))
self.beta = nn.Parameter(torch.zeros((1, 1, dim)))
def forward(self, input_0):
primals_1 = self.alpha
primals_2 = self.beta
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
liangmuxue/pytorch-image-models
|
Affine
| false
| 10,378
|
[
"Apache-2.0"
] | 0
|
84da7fdbedda76b1cb513ae128c612ab885e5e3f
|
https://github.com/liangmuxue/pytorch-image-models/tree/84da7fdbedda76b1cb513ae128c612ab885e5e3f
|
EqualLinear
|
import torch
from torch import nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf0, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinearNew(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input_0):
primals_2 = self.linear.bias
primals_1 = self.linear.weight_orig
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jeromepl/style-based-gan-pytorch
|
EqualLinear
| false
| 10,379
|
[
"MIT"
] | 0
|
97c13e54316dc57a7cb44c0cb910c29aaed11738
|
https://github.com/jeromepl/style-based-gan-pytorch/tree/97c13e54316dc57a7cb44c0cb910c29aaed11738
|
SentinelMBSI
|
import torch
from typing import *
class SentinelMBSI(torch.nn.Module):
def __init__(self, band_count):
super(SentinelMBSI, self).__init__()
self.no_weights = True
def forward(self, x):
self.red = x[:, 3:4, :, :]
self.green = x[:, 2:3, :, :]
return 2 * (self.red - self.green) / (self.red + self.green - 2 * (
1 << 16))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'band_count': 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 *
assert_size_stride = torch._C._dynamo.guards.assert_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_mul_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp2 = tmp0 - tmp1
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tmp5 = tmp0 + tmp1
tmp6 = 131072.0
tmp7 = tmp5 - tmp6
tmp8 = tmp4 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mul_sub_0[grid(64)](arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
return buf0, reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 16, 4, 1), 32
), reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 16, 4, 1), 48)
class SentinelMBSINew(torch.nn.Module):
def __init__(self, band_count):
super(SentinelMBSINew, self).__init__()
self.no_weights = True
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
geotrellis/deeplab-nlcd
|
SentinelMBSI
| false
| 10,380
|
[
"MIT"
] | 0
|
9444299597e1d1bc34ee187f2092890449c188be
|
https://github.com/geotrellis/deeplab-nlcd/tree/9444299597e1d1bc34ee187f2092890449c188be
|
CNN
|
import torch
from torch import nn
import torch.nn.functional as F
class CNN(torch.nn.Module):
"""Basic CNN architecture."""
def __init__(self, in_channels=1):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, 8, 1)
self.conv2 = nn.Conv2d(64, 128, 6, 2)
self.conv3 = nn.Conv2d(128, 128, 5, 1)
self.fc1 = nn.Linear(128 * 4 * 4, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x = x.view(-1, 128 * 4 * 4)
x = self.fc1(x)
x = self.fc2(x)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 36
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 + 36 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 64 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 25
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 + 25 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 128 * x2 + 3200 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 256
xnumel = 3249
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 3249 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (y0 + 64 * x2 + 207936 * y1), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_4(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 512
xnumel = 484
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 % 128
y1 = yindex // 128
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 128 * x2 + 61952 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x2 + 484 * y3), tmp4, xmask & ymask)
tl.store(out_ptr1 + (y0 + 128 * x2 + 61952 * y1), tmp6, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (64, 1, 8, 8), (64, 64, 8, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (128, 64, 6, 6), (2304, 36, 6, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (128, 128, 5, 5), (3200, 25, 5, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (128, 2048), (2048, 1))
assert_size_stride(primals_9, (128,), (1,))
assert_size_stride(primals_10, (10, 128), (128, 1))
assert_size_stride(primals_11, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((128, 64, 6, 6), (2304, 1, 384, 64),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(8192, 36)](primals_4, buf0, 8192, 36,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_4
buf1 = empty_strided_cuda((128, 128, 5, 5), (3200, 1, 640, 128),
torch.float32)
triton_poi_fused_1[grid(16384, 25)](primals_6, buf1, 16384, 25,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_6
buf2 = 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(buf2, (4, 64, 57, 57), (207936, 3249, 57, 1))
buf3 = empty_strided_cuda((4, 64, 57, 57), (207936, 1, 3648, 64),
torch.float32)
triton_poi_fused_convolution_relu_2[grid(256, 3249)](buf2,
primals_2, buf3, 256, 3249, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf2
del primals_2
buf4 = extern_kernels.convolution(buf3, buf0, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 128, 26, 26), (86528, 1, 3328, 128))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_3[grid(346112)](buf5, primals_5,
346112, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf6 = extern_kernels.convolution(buf5, buf1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 128, 22, 22), (61952, 1, 2816, 128))
buf7 = empty_strided_cuda((4, 128, 22, 22), (61952, 484, 22, 1),
torch.float32)
buf10 = empty_strided_cuda((4, 128, 22, 22), (61952, 1, 2816, 128),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_4[grid(512, 484)](
buf6, primals_7, buf7, buf10, 512, 484, XBLOCK=32, YBLOCK=32,
num_warps=4, num_stages=1)
del buf6
del primals_7
buf8 = empty_strided_cuda((121, 128), (128, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf7, (121, 2048
), (2048, 1), 0), reinterpret_tensor(primals_8, (2048, 128), (1,
2048), 0), alpha=1, beta=1, out=buf8)
del primals_9
buf9 = empty_strided_cuda((121, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_11, buf8, reinterpret_tensor(
primals_10, (128, 10), (1, 128), 0), alpha=1, beta=1, out=buf9)
del primals_11
return (buf9, primals_1, primals_3, buf0, buf1, buf3, buf5,
reinterpret_tensor(buf7, (121, 2048), (2048, 1), 0), buf8,
primals_10, primals_8, buf10)
class CNNNew(torch.nn.Module):
"""Basic CNN architecture."""
def __init__(self, in_channels=1):
super(CNNNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, 8, 1)
self.conv2 = nn.Conv2d(64, 128, 6, 2)
self.conv3 = nn.Conv2d(128, 128, 5, 1)
self.fc1 = nn.Linear(128 * 4 * 4, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
kylematoba/cleverhans
|
CNN
| false
| 10,381
|
[
"MIT"
] | 0
|
acfd87e065ec5aabff1295ffbffafaf54057cb6c
|
https://github.com/kylematoba/cleverhans/tree/acfd87e065ec5aabff1295ffbffafaf54057cb6c
|
Flip
|
import torch
import torch.nn as nn
class Flip(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
xf = torch.flip(x, [2])
y1 = xf[:, :, 0::2, :]
y2 = xf[:, :, 1::2, :]
y = torch.cat((y1, y2), dim=2)
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 4
x0 = xindex % 4
x2 = xindex // 16
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (12 + x0 + -8 * x1 + 16 * x2), tmp4 & xmask,
other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp9 = tl.load(in_ptr0 + (8 + x0 + -8 * (-2 + x1) + 16 * x2), tmp6 &
xmask, other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class FlipNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
liorkad3/ncnn
|
Flip
| false
| 10,382
|
[
"BSD-3-Clause"
] | 0
|
bcabffdf1ddc3739dc1051accba53a7f0a43863d
|
https://github.com/liorkad3/ncnn/tree/bcabffdf1ddc3739dc1051accba53a7f0a43863d
|
StyleResidual
|
import torch
from torch import nn
import torch.utils.data
import torch.optim
class StyleResidual(nn.Module):
"""Styling."""
def __init__(self, d_channel: 'int', d_style: 'int', kernel_size: 'int'=1):
super().__init__()
self.rs = nn.Conv1d(in_channels=d_style, out_channels=d_channel,
kernel_size=kernel_size, stride=1, padding=kernel_size // 2)
def forward(self, x: 'torch.Tensor', s: 'torch.Tensor') ->torch.Tensor:
"""`x`: [B,C,T], `s`: [B,S,T] => [B,C,T]."""
return x + self.rs(s)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_channel': 4, 'd_style': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.utils.data
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4), (16, 4, 1), 0), primals_1, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 4), (16, 4, 1))
buf1 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(16)](buf1, primals_4, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
del primals_4
return buf1, primals_1, reinterpret_tensor(primals_3, (1, 4, 4), (16, 4,
1), 0)
class StyleResidualNew(nn.Module):
"""Styling."""
def __init__(self, d_channel: 'int', d_style: 'int', kernel_size: 'int'=1):
super().__init__()
self.rs = nn.Conv1d(in_channels=d_style, out_channels=d_channel,
kernel_size=kernel_size, stride=1, padding=kernel_size // 2)
def forward(self, input_0, input_1):
primals_1 = self.rs.weight
primals_2 = self.rs.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jinsongpan/NeMo
|
StyleResidual
| false
| 10,383
|
[
"Apache-2.0"
] | 0
|
27f5f2dc6ecf7e0fd4225eedb2500cee6284e7d7
|
https://github.com/jinsongpan/NeMo/tree/27f5f2dc6ecf7e0fd4225eedb2500cee6284e7d7
|
Relation
|
import torch
import torch.utils.data
import torch.nn as nn
from torch.nn import functional as F
class Relation(nn.Module):
def __init__(self, C, H, out_size):
super(Relation, self).__init__()
self.out_size = out_size
self.M = torch.nn.Parameter(torch.randn(H, H, out_size))
self.W = torch.nn.Parameter(torch.randn(C * out_size, C))
self.b = torch.nn.Parameter(torch.randn(C))
def forward(self, class_vector, query_encoder):
mid_pro = []
for slice in range(self.out_size):
slice_inter = torch.mm(torch.mm(class_vector, self.M[:, :,
slice]), query_encoder.transpose(1, 0))
mid_pro.append(slice_inter)
mid_pro = torch.cat(mid_pro, dim=0)
V = F.relu(mid_pro.transpose(0, 1))
probs = torch.sigmoid(torch.mm(V, self.W) + self.b)
return probs
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'C': 4, 'H': 4, 'out_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mm_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_mm_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 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_mm_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_mm_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_sigmoid_5(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.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (16, 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), torch.float32)
get_raw_stream(0)
triton_poi_fused_mm_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_2, buf0, out=buf1)
buf12 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
buf2 = reinterpret_tensor(buf12, (4, 4), (4, 1), 0)
extern_kernels.mm(buf1, reinterpret_tensor(primals_3, (4, 4), (1, 4
), 0), out=buf2)
buf3 = buf1
del buf1
triton_poi_fused_mm_1[grid(16)](primals_1, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = buf0
del buf0
extern_kernels.mm(primals_2, buf3, out=buf4)
buf5 = reinterpret_tensor(buf12, (4, 4), (4, 1), 16)
extern_kernels.mm(buf4, reinterpret_tensor(primals_3, (4, 4), (1, 4
), 0), out=buf5)
buf6 = buf4
del buf4
triton_poi_fused_mm_2[grid(16)](primals_1, buf6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf7 = buf3
del buf3
extern_kernels.mm(primals_2, buf6, out=buf7)
buf8 = reinterpret_tensor(buf12, (4, 4), (4, 1), 32)
extern_kernels.mm(buf7, reinterpret_tensor(primals_3, (4, 4), (1, 4
), 0), out=buf8)
buf9 = buf7
del buf7
triton_poi_fused_mm_3[grid(16)](primals_1, buf9, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
buf10 = buf6
del buf6
extern_kernels.mm(primals_2, buf9, out=buf10)
del buf9
buf11 = reinterpret_tensor(buf12, (4, 4), (4, 1), 48)
extern_kernels.mm(buf10, reinterpret_tensor(primals_3, (4, 4), (1,
4), 0), out=buf11)
buf13 = empty_strided_cuda((4, 16), (1, 4), torch.float32)
triton_poi_fused_relu_4[grid(64)](buf12, buf13, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf11
del buf12
del buf2
del buf5
del buf8
buf14 = buf10
del buf10
extern_kernels.mm(buf13, primals_4, out=buf14)
buf15 = buf14
del buf14
triton_poi_fused_add_sigmoid_5[grid(16)](buf15, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf15, primals_4, buf13, buf15, primals_3, reinterpret_tensor(
primals_2, (4, 4), (1, 4), 0)
class RelationNew(nn.Module):
def __init__(self, C, H, out_size):
super(RelationNew, self).__init__()
self.out_size = out_size
self.M = torch.nn.Parameter(torch.randn(H, H, out_size))
self.W = torch.nn.Parameter(torch.randn(C * out_size, C))
self.b = torch.nn.Parameter(torch.randn(C))
def forward(self, input_0, input_1):
primals_1 = self.M
primals_4 = self.W
primals_5 = self.b
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
liangshb/few-shot-text-classification
|
Relation
| false
| 10,384
|
[
"Apache-2.0"
] | 0
|
3bb2b3e87215ccf0fb6d5b0d436774557ac9ddd0
|
https://github.com/liangshb/few-shot-text-classification/tree/3bb2b3e87215ccf0fb6d5b0d436774557ac9ddd0
|
MultAttention
|
import torch
import torch.nn as nn
class MultAttention(nn.Module):
"""
Multiplicative attention similar to Vaswani et al.
"""
def __init__(self, key_dim: 'int', val_dim: 'int', out_dim: 'int'):
super(MultAttention, self).__init__()
self.key_encoder = nn.Linear(key_dim, out_dim)
self.val_encoder = nn.Linear(val_dim, out_dim)
self.query_encoder = nn.Linear(key_dim, out_dim)
def forward(self, vals, keys_):
"""
# Inputs:
:param vals: Values of shape [batch x val_dim]
:param keys: Keys of shape [batch x graphs x key_dim]
"""
keys = self.key_encoder(keys_)
queries = self.query_encoder(keys_)
vals = self.val_encoder(vals)
vals = vals.unsqueeze(1)
weights = torch.matmul(keys, vals.transpose(1, 2))
weights = torch.softmax(weights, 1)
summed_queries = (queries * weights).sum(1)
return summed_queries, weights
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'key_dim': 4, 'val_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 256
x0 = xindex % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x0, 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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 64
x4 = xindex % 16
x0 = xindex % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x4 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x5, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 64
x2 = xindex // 256
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 64
x2 = xindex // 256
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_sum_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x0 + 256 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (64 + x0 + 256 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (128 + x0 + 256 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + (192 + x0 + 256 * x1), xmask)
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x2, tmp14, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_8, (64, 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, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(1024)](buf0, primals_2, buf3, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_2
buf4 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_clone_1[grid(1024)](buf2, primals_7, buf4, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf5 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (64, 4, 4), (16, 4, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused__softmax_2[grid(1024)](buf5, buf6, 1024, XBLOCK=
128, num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0
)
del buf5
triton_poi_fused__softmax_3[grid(1024)](buf6, buf7, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_mul_sum_4[grid(256)](buf1, buf7, buf8, 256, XBLOCK
=128, num_warps=4, num_stages=1)
return buf8, buf7, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, reinterpret_tensor(primals_8, (64, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf3, (64, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (64, 4, 4), (16, 1, 4), 0)
class MultAttentionNew(nn.Module):
"""
Multiplicative attention similar to Vaswani et al.
"""
def __init__(self, key_dim: 'int', val_dim: 'int', out_dim: 'int'):
super(MultAttentionNew, self).__init__()
self.key_encoder = nn.Linear(key_dim, out_dim)
self.val_encoder = nn.Linear(val_dim, out_dim)
self.query_encoder = nn.Linear(key_dim, out_dim)
def forward(self, input_0, input_1):
primals_1 = self.key_encoder.weight
primals_2 = self.key_encoder.bias
primals_4 = self.val_encoder.weight
primals_5 = self.val_encoder.bias
primals_6 = self.query_encoder.weight
primals_7 = self.query_encoder.bias
primals_3 = input_0
primals_8 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
kage08/CAMul
|
MultAttention
| false
| 10,385
|
[
"MIT"
] | 0
|
79f8a27f472943229fb087bae8e405e38e5e0b47
|
https://github.com/kage08/CAMul/tree/79f8a27f472943229fb087bae8e405e38e5e0b47
|
FusedLeakyReLU
|
import torch
from torch import nn
from torch.nn.functional import leaky_relu
class FusedLeakyReLU(nn.Module):
def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
super().__init__()
self.bias = nn.Parameter(torch.zeros(channel))
self.negative_slope = negative_slope
self.scale = scale
def forward(self, x):
return self.scale * leaky_relu(x + self.bias.reshape((1, -1, 1, 1))
[:, :x.shape[1]], self.negative_slope, inplace=True)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channel': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_leaky_relu_leaky_relu_backward_mul_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)
tmp8 = 1.4142135623730951
tmp9 = tmp7 * tmp8
tmp10 = tmp7 > tmp3
tl.store(out_ptr0 + x3, tmp9, xmask)
tl.store(out_ptr1 + x3, tmp10, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_leaky_relu_leaky_relu_backward_mul_0[grid(256)](
primals_2, primals_1, buf0, buf1, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_1
del primals_2
return buf0, buf1
class FusedLeakyReLUNew(nn.Module):
def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
super().__init__()
self.bias = nn.Parameter(torch.zeros(channel))
self.negative_slope = negative_slope
self.scale = scale
def forward(self, input_0):
primals_1 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jchetboun/anycost-gan
|
FusedLeakyReLU
| false
| 10,386
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
MixedCycleLoss
|
import torch
from torch import nn
import torch.nn.functional as F
class MixedCycleLoss(nn.Module):
def __init__(self, reduction: 'str'='none') ->None:
super(MixedCycleLoss, self).__init__()
self.reduction = reduction
def forward(self, input_2d, input_3d, target_2d, target_3d, w_cycle=1,
w_3d=1):
loss_cycle = F.mse_loss(input_2d, target_2d, reduction=self.reduction)
loss_3d = F.mse_loss(input_3d, target_3d, reduction=self.reduction)
mixed_loss = w_cycle * loss_cycle + w_3d * loss_3d
return mixed_loss, loss_cycle, loss_3d
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 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_mse_loss_mul_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask)
tmp5 = tl.load(in_ptr3 + x0, xmask)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = 1.0
tmp9 = tmp3 * tmp8
tmp10 = tmp7 * tmp8
tmp11 = tmp9 + tmp10
tl.store(out_ptr0 + x0, tmp3, xmask)
tl.store(out_ptr1 + x0, tmp7, xmask)
tl.store(out_ptr2 + x0, tmp11, xmask)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mse_loss_mul_0[grid(256)](arg1_1, arg0_1,
arg3_1, arg2_1, buf0, buf1, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
return buf2, buf0, buf1
class MixedCycleLossNew(nn.Module):
def __init__(self, reduction: 'str'='none') ->None:
super(MixedCycleLossNew, self).__init__()
self.reduction = reduction
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0], output[1], output[2]
|
koustav123/SemGCN
|
MixedCycleLoss
| false
| 10,387
|
[
"Apache-2.0"
] | 0
|
e74014378933c19027865499080629b36ac6a5c9
|
https://github.com/koustav123/SemGCN/tree/e74014378933c19027865499080629b36ac6a5c9
|
EqualLinear
|
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
from torch import nn
from torch.nn.functional import leaky_relu
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_2, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, reinterpret_tensor(primals_3, (64, 4), (
4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1,
beta=1, out=buf2)
del buf0
del buf1
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
class EqualLinearNew(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jchetboun/anycost-gan
|
EqualLinear
| false
| 10,388
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
EqualConv2d
|
import math
import torch
from torch import nn
from torch.nn import functional as F
class EqualConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, stride=1,
padding=0, bias=True):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_channel, in_channel,
kernel_size, kernel_size))
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.stride = stride
self.padding = padding
if bias:
self.bias = nn.Parameter(torch.zeros(out_channel))
else:
self.bias = None
def forward(self, x):
in_channel = x.shape[1]
weight = self.weight
if hasattr(self, 'first_k_oup') and self.first_k_oup is not None:
weight = weight[:self.first_k_oup]
weight = weight[:, :in_channel].contiguous()
out = F.conv2d(x, weight * self.scale, bias=self.bias, stride=self.
stride, padding=self.padding)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]}, {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_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.125
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 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_mul_0[grid(256)](primals_2, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
buf1 = extern_kernels.convolution(primals_1, buf0, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 1, 1), (4, 1, 1, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(16)](buf2, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_1, buf0
class EqualConv2dNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, stride=1,
padding=0, bias=True):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_channel, in_channel,
kernel_size, kernel_size))
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.stride = stride
self.padding = padding
if bias:
self.bias = nn.Parameter(torch.zeros(out_channel))
else:
self.bias = None
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]}, {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
)
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]
|
jchetboun/anycost-gan
|
EqualConv2d
| false
| 10,389
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
GeM
|
import torch
import torch.nn as nn
class GeM(nn.Module):
def __init__(self, dim=1, p=0.0, eps=1e-06):
super(GeM, self).__init__()
self.p = nn.Parameter(torch.ones(()) * p, requires_grad=True)
self.eps = eps
self.dim = dim
def forward(self, x):
return self.gem(x, p=self.p, eps=self.eps)
def gem(self, x, p=3, eps=1e-06):
x_max = x.max(dim=-1, keepdim=False)[0]
x_avg = x.mean(dim=-1, keepdim=False)
w = torch.sigmoid(self.p)
x = w * x_max + (1 - w) * x_avg
return x
def __repr__(self):
return self.__class__.__name__ + '(' + 'p=' + '{:.2f}'.format(self.p
) + ', ' + 'eps=' + str(self.eps) + ')'
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_max_mean_mul_rsub_sigmoid_0(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
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')
tmp12 = tl.load(in_ptr1 + 0)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK])
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = tmp0 + tmp1
tmp8 = tmp7 + tmp3
tmp9 = tmp8 + tmp5
tmp10 = 4.0
tmp11 = tmp9 / tmp10
tmp14 = tl.sigmoid(tmp13)
tmp15 = tmp14 * tmp6
tmp16 = 1.0
tmp17 = tmp16 - tmp14
tmp18 = tmp17 * tmp11
tmp19 = tmp15 + tmp18
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
tl.store(out_ptr2 + x0, tmp19, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (), ())
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_max_mean_mul_rsub_sigmoid_0[grid(64)](primals_2,
primals_1, buf0, buf1, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_2
return buf2, primals_1, buf0, buf1
class GeMNew(nn.Module):
def __init__(self, dim=1, p=0.0, eps=1e-06):
super(GeMNew, self).__init__()
self.p = nn.Parameter(torch.ones(()) * p, requires_grad=True)
self.eps = eps
self.dim = dim
def gem(self, x, p=3, eps=1e-06):
x_max = x.max(dim=-1, keepdim=False)[0]
x_avg = x.mean(dim=-1, keepdim=False)
w = torch.sigmoid(self.p)
x = w * x_max + (1 - w) * x_avg
return x
def __repr__(self):
return self.__class__.__name__ + '(' + 'p=' + '{:.2f}'.format(self.p
) + ', ' + 'eps=' + str(self.eps) + ')'
def forward(self, input_0):
primals_1 = self.p
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
layumi/dgcnn
|
GeM
| false
| 10,390
|
[
"MIT"
] | 0
|
a7b58796ffe549f2d8bdb06a84f62aba03e1d3a1
|
https://github.com/layumi/dgcnn/tree/a7b58796ffe549f2d8bdb06a84f62aba03e1d3a1
|
BertOutput
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.utils.data
import torch.utils.data.distributed
import torch.utils.checkpoint
import torch.utils.tensorboard
class BertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(intermediate_size=4, hidden_size=4,
layer_norm_eps=1, hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.utils.data
import torch.utils.data.distributed
import torch.utils.checkpoint
import torch.utils.tensorboard
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1.0
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_2, primals_4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](buf1, buf2, buf3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_2[grid(256)](buf1, buf2, buf3,
primals_5, primals_6, buf4, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_6
return buf4, primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1
class BertOutputNew(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.dense.weight
primals_2 = self.dense.bias
primals_5 = self.LayerNorm.weight
primals_6 = self.LayerNorm.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
ali-senguel/fairo-explore
|
BertOutput
| false
| 10,391
|
[
"MIT"
] | 0
|
893481da270eed1e6d504c71e483d685ca9218d1
|
https://github.com/ali-senguel/fairo-explore/tree/893481da270eed1e6d504c71e483d685ca9218d1
|
AttentionConv
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
class AttentionConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, groups=1, bias=False):
super(AttentionConv, self).__init__()
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.groups = groups
assert self.out_channels % self.groups == 0, 'out_channels should be divided by groups. (example: out_channels: 40, groups: 4)'
self.rel_h = nn.Parameter(torch.randn(out_channels // 2, 1, 1,
kernel_size, 1), requires_grad=True)
self.rel_w = nn.Parameter(torch.randn(out_channels // 2, 1, 1, 1,
kernel_size), requires_grad=True)
self.key_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1,
bias=bias)
self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size=
1, bias=bias)
self.value_conv = nn.Conv2d(in_channels, out_channels, kernel_size=
1, bias=bias)
self.reset_parameters()
def forward(self, x):
batch, _channels, height, width = x.size()
padded_x = F.pad(x, [self.padding, self.padding, self.padding, self
.padding])
q_out = self.query_conv(x)
k_out = self.key_conv(padded_x)
v_out = self.value_conv(padded_x)
k_out = k_out.unfold(2, self.kernel_size, self.stride).unfold(3,
self.kernel_size, self.stride)
v_out = v_out.unfold(2, self.kernel_size, self.stride).unfold(3,
self.kernel_size, self.stride)
v_out_h, v_out_w = v_out.split(self.out_channels // 2, dim=1)
v_out = torch.cat((v_out_h + self.rel_h, v_out_w + self.rel_w), dim=1)
k_out = k_out.contiguous().view(batch, self.groups, self.
out_channels // self.groups, height, width, -1)
v_out = v_out.contiguous().view(batch, self.groups, self.
out_channels // self.groups, height, width, -1)
q_out = q_out.view(batch, self.groups, self.out_channels // self.
groups, height, width, 1)
out = q_out * k_out
out = F.softmax(out, dim=-1)
out = torch.einsum('bnchwk,bnchwk -> bnchw', out, v_out).view(batch,
-1, height, width)
return out
def reset_parameters(self):
init.kaiming_normal_(self.key_conv.weight, mode='fan_out',
nonlinearity='relu')
init.kaiming_normal_(self.value_conv.weight, mode='fan_out',
nonlinearity='relu')
init.kaiming_normal_(self.query_conv.weight, mode='fan_out',
nonlinearity='relu')
init.normal_(self.rel_h, 0, 1)
init.normal_(self.rel_w, 0, 1)
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.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.init as init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_mul_unfold_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
x3 = xindex // 16 % 4
x4 = xindex // 64
x5 = xindex % 16
x2 = xindex // 4 % 4
x1 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp20 = tl.load(in_ptr3 + x0, xmask)
tmp1 = x3
tl.full([1], 0, tl.int64)
tmp4 = tl.full([1], 2, tl.int64)
tmp5 = tmp1 < tmp4
tmp6 = tl.load(in_ptr0 + (x5 + 16 * x3 + 64 * x4), tmp5 & xmask, other=0.0)
tmp7 = tl.load(in_ptr1 + (x2 + 4 * x3), tmp5 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp5, tmp8, tmp9)
tmp11 = tmp1 >= tmp4
tl.full([1], 4, tl.int64)
tmp14 = tl.load(in_ptr0 + (32 + x5 + 16 * (-2 + x3) + 64 * x4), tmp11 &
xmask, other=0.0)
tmp15 = tl.load(in_ptr2 + (x1 + 4 * (-2 + x3)), 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(tmp5, tmp10, tmp18)
tmp21 = 0.0
tmp22 = tmp0 >= tmp21
tmp23 = 1.0
tmp24 = -1.0
tmp25 = tl.where(tmp22, tmp23, tmp24)
tmp26 = tmp20 * tmp25
tmp27 = tmp26 - tmp26
tmp28 = tmp25 * tmp0
tmp29 = tmp27 * tmp28
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp30 / tmp30
tmp32 = tmp31 * tmp19
tl.store(in_out_ptr0 + x0, tmp0, xmask)
tl.store(out_ptr0 + x0, tmp19, xmask)
tl.store(out_ptr1 + x0, tmp32, 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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (2, 1, 1, 4, 1), (4, 4, 4, 1, 1))
assert_size_stride(primals_6, (2, 1, 1, 1, 4), (4, 4, 4, 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, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = extern_kernels.convolution(primals_1, 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 = 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, 4, 4, 4), (64, 16, 4, 1))
buf3 = reinterpret_tensor(buf1, (4, 4, 1, 1, 4, 4), (64, 16, 16, 4,
4, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 1, 1, 4, 4), (64, 16, 16, 16, 4, 1
), torch.float32)
buf5 = empty_strided_cuda((4, 1, 4, 4, 4, 1), (64, 64, 16, 4, 1, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_mul_unfold_0[grid(256)](buf3, buf2, primals_5,
primals_6, buf0, buf4, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del primals_5
del primals_6
return reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, primals_2, primals_3, primals_4, buf0, buf3, buf4
class AttentionConvNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, groups=1, bias=False):
super(AttentionConvNew, self).__init__()
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.groups = groups
assert self.out_channels % self.groups == 0, 'out_channels should be divided by groups. (example: out_channels: 40, groups: 4)'
self.rel_h = nn.Parameter(torch.randn(out_channels // 2, 1, 1,
kernel_size, 1), requires_grad=True)
self.rel_w = nn.Parameter(torch.randn(out_channels // 2, 1, 1, 1,
kernel_size), requires_grad=True)
self.key_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1,
bias=bias)
self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size=
1, bias=bias)
self.value_conv = nn.Conv2d(in_channels, out_channels, kernel_size=
1, bias=bias)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_normal_(self.key_conv.weight, mode='fan_out',
nonlinearity='relu')
init.kaiming_normal_(self.value_conv.weight, mode='fan_out',
nonlinearity='relu')
init.kaiming_normal_(self.query_conv.weight, mode='fan_out',
nonlinearity='relu')
init.normal_(self.rel_h, 0, 1)
init.normal_(self.rel_w, 0, 1)
def forward(self, input_0):
primals_5 = self.rel_h
primals_6 = self.rel_w
primals_2 = self.key_conv.weight
primals_3 = self.query_conv.weight
primals_4 = self.value_conv.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
khy0809/Stand-Alone-Self-Attention
|
AttentionConv
| false
| 10,392
|
[
"MIT"
] | 0
|
019718c8983faac24d69bd9b37eaf33cd28e1c4a
|
https://github.com/khy0809/Stand-Alone-Self-Attention/tree/019718c8983faac24d69bd9b37eaf33cd28e1c4a
|
Transformer
|
import torch
import torch.nn as nn
import torch.nn.parallel
class Mlp(nn.Module):
"""Implementation of MLP"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
"""Implementation of self-attention"""
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None,
attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, H, W, C = x.shape
qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, C // self.
num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, H, W, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Transformer(nn.Module):
"""
Implementation of Transformer,
Transformer is the second stage in our VOLO
"""
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False,
qk_scale=None, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU,
norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
qk_scale=qk_scale, attn_drop=attn_drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 192 * y1), xmask & ymask)
tl.store(out_ptr0 + (x2 + 16 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (4 + y0 + 12 * x2 + 192 * y1), xmask & ymask)
tl.store(out_ptr0 + (x2 + 16 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_per_fused__softmax_4(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 256
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, float('-inf'))
tmp6 = triton_helpers.max2(tmp5, 1)[:, None]
tmp7 = tmp2 - tmp6
tmp8 = tmp7 * tmp1
tmp9 = tl_math.exp(tmp8)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tmp14 = tmp9 / tmp13
tl.store(out_ptr2 + (r1 + 16 * x0), tmp14, xmask)
@triton.jit
def triton_poi_fused_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (8 + y0 + 12 * x2 + 192 * y1), xmask & ymask)
tl.store(out_ptr0 + (x2 + 16 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + 1)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr2 + 2)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr2 + 3)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = tmp0 + tmp4
tmp10 = tmp7 + tmp9
tmp11 = tmp6 + tmp10
tmp12 = tmp5 + tmp11
tmp17 = tmp14 + tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp12 + tmp18
tmp24 = tmp21 + tmp23
tmp25 = tmp20 + tmp24
tmp26 = tmp19 + tmp25
tmp27 = 4.0
tmp28 = tmp26 / tmp27
tmp29 = tmp5 - tmp28
tmp30 = tmp29 * tmp29
tmp31 = tmp11 - tmp28
tmp32 = tmp31 * tmp31
tmp33 = tmp30 + tmp32
tmp34 = tmp18 - tmp28
tmp35 = tmp34 * tmp34
tmp36 = tmp33 + tmp35
tmp37 = tmp25 - tmp28
tmp38 = tmp37 * tmp37
tmp39 = tmp36 + tmp38
tmp40 = tmp39 / tmp27
tl.store(out_ptr0 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp40, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp6 = tmp4 - tmp5
tmp8 = 1e-05
tmp9 = tmp7 + tmp8
tmp10 = libdevice.rsqrt(tmp9)
tmp11 = tmp6 * tmp10
tmp13 = tmp11 * tmp12
tmp15 = tmp13 + tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused_gelu_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865476
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3,
xnumel, XBLOCK: tl.constexpr):
xnumel = 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 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_out_ptr0 + x2, xmask)
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp7 = tmp5 + tmp6
tmp8 = tmp4 + tmp7
tl.store(in_out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (16, 4), (4, 1))
assert_size_stride(primals_10, (16,), (1,))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 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 primals_1
del primals_2
buf3 = empty_strided_cuda((64, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 12), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 16, 1), (64, 16, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(16, 16)](buf3, buf4, 16, 16, XBLOCK=
16, YBLOCK=16, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 1, 16), (64, 16, 16, 1), torch.float32
)
triton_poi_fused_clone_3[grid(16, 16)](buf3, buf5, 16, 16, XBLOCK=
16, YBLOCK=16, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((16, 16, 16), (256, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 16, 1), (16, 1, 0),
0), reinterpret_tensor(buf5, (16, 1, 16), (16, 0, 1), 0), out=buf6)
buf9 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch
.float32)
triton_per_fused__softmax_4[grid(256)](buf6, buf9, 256, 16, XBLOCK=
8, num_warps=2, num_stages=1)
del buf6
buf10 = empty_strided_cuda((4, 4, 16, 1), (64, 16, 1, 1), torch.float32
)
triton_poi_fused_clone_5[grid(16, 16)](buf3, buf10, 16, 16, XBLOCK=
16, YBLOCK=16, num_warps=4, num_stages=1)
del buf3
buf11 = empty_strided_cuda((16, 16, 1), (16, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf9, (16, 16, 16), (256, 16,
1), 0), reinterpret_tensor(buf10, (16, 16, 1), (16, 1, 0), 0),
out=buf11)
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_6[grid(64, 4)](buf11, buf12, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf13 = reinterpret_tensor(buf11, (64, 4), (4, 1), 0)
del buf11
extern_kernels.mm(reinterpret_tensor(buf12, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf13)
buf14 = buf1
del buf1
buf15 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_7[grid(64)](primals_3, buf13,
primals_6, buf14, buf15, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf16 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_8[grid(256)](primals_3,
buf13, primals_6, buf14, buf15, primals_7, primals_8, buf16,
256, XBLOCK=128, num_warps=4, num_stages=1)
del buf14
del buf15
del primals_8
buf17 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_10, reinterpret_tensor(buf16, (64, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 16), (1, 4), 0),
alpha=1, beta=1, out=buf17)
del primals_10
buf18 = empty_strided_cuda((4, 4, 4, 16), (256, 64, 16, 1), torch.
float32)
triton_poi_fused_gelu_9[grid(1024)](buf17, buf18, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
buf19 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf18, (64, 16), (16, 1), 0),
reinterpret_tensor(primals_11, (16, 4), (1, 16), 0), out=buf19)
buf20 = reinterpret_tensor(buf19, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf19
triton_poi_fused_add_10[grid(256)](buf20, primals_3, buf13,
primals_6, primals_12, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_12
return buf20, primals_3, primals_6, primals_7, reinterpret_tensor(buf2,
(64, 4), (4, 1), 0), buf9, reinterpret_tensor(buf12, (64, 4), (4, 1), 0
), buf13, reinterpret_tensor(buf16, (64, 4), (4, 1), 0
), buf17, reinterpret_tensor(buf18, (64, 16), (16, 1), 0
), primals_11, primals_9, primals_5, reinterpret_tensor(buf10, (16,
1, 16), (16, 1, 1), 0), reinterpret_tensor(buf4, (16, 1, 16), (16,
1, 1), 0), reinterpret_tensor(buf5, (16, 16, 1), (16, 1, 16), 0
), primals_4
class Mlp(nn.Module):
"""Implementation of MLP"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
"""Implementation of self-attention"""
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None,
attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, H, W, C = x.shape
qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, C // self.
num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, H, W, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class TransformerNew(nn.Module):
"""
Implementation of Transformer,
Transformer is the second stage in our VOLO
"""
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False,
qk_scale=None, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU,
norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
qk_scale=qk_scale, attn_drop=attn_drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer)
def forward(self, input_0):
primals_1 = self.norm1.weight
primals_2 = self.norm1.bias
primals_4 = self.attn.qkv.weight
primals_5 = self.attn.proj.weight
primals_6 = self.attn.proj.bias
primals_7 = self.norm2.weight
primals_8 = self.norm2.bias
primals_9 = self.mlp.fc1.weight
primals_10 = self.mlp.fc1.bias
primals_11 = self.mlp.fc2.weight
primals_12 = self.mlp.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
javierrodenas/clearml_javi
|
Transformer
| false
| 10,393
|
[
"Apache-2.0"
] | 0
|
b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
https://github.com/javierrodenas/clearml_javi/tree/b6326104fe6a6f522223c2ac3d87468990a9e6f2
|
MSEWithLogitsLoss
|
import torch
from torch import nn
from torch.nn import MSELoss
class MSEWithLogitsLoss(MSELoss):
"""
This loss combines a `Sigmoid` layer and the `MSELoss` in one single class.
"""
def __init__(self):
super(MSEWithLogitsLoss, self).__init__()
self.sigmoid = nn.Sigmoid()
def forward(self, input, target):
return super().forward(self.sigmoid(input), target)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
from torch.nn import MSELoss
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_mse_loss_sigmoid_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 - tmp2
tmp4 = tmp3 * tmp3
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = 256.0
tmp9 = tmp7 / tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mse_loss_sigmoid_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 MSEWithLogitsLossNew(MSELoss):
"""
This loss combines a `Sigmoid` layer and the `MSELoss` in one single class.
"""
def __init__(self):
super(MSEWithLogitsLossNew, self).__init__()
self.sigmoid = nn.Sigmoid()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
joowlim/pytorch-3dunet
|
MSEWithLogitsLoss
| false
| 10,394
|
[
"MIT"
] | 0
|
d08049f60b619627521efd0fb171247e1536b262
|
https://github.com/joowlim/pytorch-3dunet/tree/d08049f60b619627521efd0fb171247e1536b262
|
ToRGB
|
from torch.autograd import Function
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, x, style):
batch, in_channel, height, width = x.shape
style = self.modulation(style)
style = style.view(batch, 1, -1, 1, 1)
first_k_oup = self.first_k_oup if hasattr(self, 'first_k_oup'
) and self.first_k_oup is not None else self.weight.shape[1]
assert first_k_oup <= self.weight.shape[1]
weight = self.weight
weight = weight[:, :first_k_oup, :in_channel].contiguous()
weight = self.scale * weight * style[:, :, :in_channel]
if self.demodulate:
weight = weight * torch.rsqrt(weight.pow(2).sum([2, 3, 4],
keepdim=True) + self.eps)
if self.upsample:
x = x.view(1, batch * in_channel, height, width)
weight = weight.transpose(1, 2)
weight = weight.reshape(weight.shape[0] * weight.shape[1],
weight.shape[2], weight.shape[3], weight.shape[4])
out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups
=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
out = self.blur(out)
else:
x = x.contiguous().view(1, batch * in_channel, height, width)
weight = weight.view(weight.shape[0] * weight.shape[1], weight.
shape[2], weight.shape[3], weight.shape[4])
out = F.conv2d(x, weight, padding=self.padding, groups=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
return out
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, x):
out = upfirdn2d(x, self.kernel, up=self.factor, down=1, pad=self.pad)
return out
class ToRGB(nn.Module):
def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=(1,
3, 3, 1)):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate
=False)
self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
def forward(self, x, style, skip=None):
out = self.conv(x, style)
out = out + self.bias
if skip is not None:
skip = self.upsample(skip)
out = out + skip
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import math
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 12
x0 = xindex % 4
x2 = xindex // 12
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x4, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 3
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (1, 3, 4, 1, 1), (12, 4, 1, 1, 1))
assert_size_stride(primals_6, (1, 3, 1, 1), (3, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, reinterpret_tensor(primals_4, (64, 4), (
4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1,
beta=1, out=buf2)
del buf0
del buf1
buf3 = empty_strided_cuda((4, 3, 4, 1, 1), (12, 4, 1, 1, 1), torch.
float32)
triton_poi_fused_mul_2[grid(48)](primals_5, buf2, buf3, 48, XBLOCK=
64, num_warps=1, num_stages=1)
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (12, 4,
1, 1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf4, (1, 12, 4, 4), (192, 16, 4, 1))
buf5 = reinterpret_tensor(buf4, (4, 3, 4, 4), (48, 16, 4, 1), 0)
del buf4
triton_poi_fused_add_3[grid(192)](buf5, primals_6, 192, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_6
return buf5, primals_5, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 1, 4, 1, 1), (64, 64, 1, 1, 1), 0
), reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4, 1), 0
), reinterpret_tensor(buf3, (12, 4, 1, 1), (4, 1, 1, 1), 0)
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, x, style):
batch, in_channel, height, width = x.shape
style = self.modulation(style)
style = style.view(batch, 1, -1, 1, 1)
first_k_oup = self.first_k_oup if hasattr(self, 'first_k_oup'
) and self.first_k_oup is not None else self.weight.shape[1]
assert first_k_oup <= self.weight.shape[1]
weight = self.weight
weight = weight[:, :first_k_oup, :in_channel].contiguous()
weight = self.scale * weight * style[:, :, :in_channel]
if self.demodulate:
weight = weight * torch.rsqrt(weight.pow(2).sum([2, 3, 4],
keepdim=True) + self.eps)
if self.upsample:
x = x.view(1, batch * in_channel, height, width)
weight = weight.transpose(1, 2)
weight = weight.reshape(weight.shape[0] * weight.shape[1],
weight.shape[2], weight.shape[3], weight.shape[4])
out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups
=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
out = self.blur(out)
else:
x = x.contiguous().view(1, batch * in_channel, height, width)
weight = weight.view(weight.shape[0] * weight.shape[1], weight.
shape[2], weight.shape[3], weight.shape[4])
out = F.conv2d(x, weight, padding=self.padding, groups=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
return out
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, x):
out = upfirdn2d(x, self.kernel, up=self.factor, down=1, pad=self.pad)
return out
class ToRGBNew(nn.Module):
def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=(1,
3, 3, 1)):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate
=False)
self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
def forward(self, input_0, input_1):
primals_6 = self.bias
primals_5 = self.conv.weight
primals_2 = self.conv.modulation.weight
primals_3 = self.conv.modulation.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
jchetboun/anycost-gan
|
ToRGB
| false
| 10,395
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
ModulatedConv2d
|
from torch.autograd import Function
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, x, style):
batch, in_channel, height, width = x.shape
style = self.modulation(style)
style = style.view(batch, 1, -1, 1, 1)
first_k_oup = self.first_k_oup if hasattr(self, 'first_k_oup'
) and self.first_k_oup is not None else self.weight.shape[1]
assert first_k_oup <= self.weight.shape[1]
weight = self.weight
weight = weight[:, :first_k_oup, :in_channel].contiguous()
weight = self.scale * weight * style[:, :, :in_channel]
if self.demodulate:
weight = weight * torch.rsqrt(weight.pow(2).sum([2, 3, 4],
keepdim=True) + self.eps)
if self.upsample:
x = x.view(1, batch * in_channel, height, width)
weight = weight.transpose(1, 2)
weight = weight.reshape(weight.shape[0] * weight.shape[1],
weight.shape[2], weight.shape[3], weight.shape[4])
out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups
=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
out = self.blur(out)
else:
x = x.contiguous().view(1, batch * in_channel, height, width)
weight = weight.view(weight.shape[0] * weight.shape[1], weight.
shape[2], weight.shape[3], weight.shape[4])
out = F.conv2d(x, weight, padding=self.padding, groups=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel_size': 4,
'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch.autograd import Function
import math
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_rsqrt_sum_2(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
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)
r5 = rindex
x0 = xindex % 4
r3 = rindex // 16
x1 = xindex // 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (r5 + 64 * x0), xmask, eviction_policy=
'evict_last', other=0.0)
tmp3 = tl.load(in_ptr1 + (r3 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp1 = 0.125
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = 1e-08
tmp11 = tmp9 + tmp10
tmp12 = libdevice.rsqrt(tmp11)
tmp13 = tmp4 * tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + x4, tmp12, xmask)
tl.store(out_ptr0 + (r5 + 64 * x4), tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, reinterpret_tensor(primals_4, (64, 4), (
4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1,
beta=1, out=buf2)
del buf1
buf3 = reinterpret_tensor(buf0, (4, 4, 1, 1, 1), (4, 1, 16, 16, 16), 0)
del buf0
buf4 = reinterpret_tensor(buf3, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_per_fused_add_mul_pow_rsqrt_sum_2[grid(16)](buf4, primals_5,
buf2, buf5, 16, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf6 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf5, (16, 4,
4, 4), (64, 16, 4, 1), 0), stride=(1, 1), padding=(2, 2),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf6, (1, 16, 5, 5), (400, 25, 5, 1))
return reinterpret_tensor(buf6, (4, 4, 5, 5), (100, 25, 5, 1), 0
), primals_5, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 1, 4, 1, 1), (64, 64, 1, 1, 1), 0
), buf4, reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4,
1), 0), reinterpret_tensor(buf5, (16, 4, 4, 4), (64, 16, 4, 1), 0)
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2dNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input_0, input_1):
primals_5 = self.weight
primals_2 = self.modulation.weight
primals_3 = self.modulation.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jchetboun/anycost-gan
|
ModulatedConv2d
| false
| 10,396
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
MarginCosineProduct
|
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.utils.data
import torch.optim
def cosine_sim(x1, x2, dim=1, eps=1e-08):
ip = torch.mm(x1, x2.t())
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return ip / torch.ger(w1, w2).clamp(min=eps)
class MarginCosineProduct(nn.Module):
"""Implement of large margin cosine distance: :
Args:
in_features: size of each input sample
out_features: size of each output sample
s: norm of input feature
m: margin
"""
def __init__(self, in_features, out_features, s=30.0, m=0.4):
super(MarginCosineProduct, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.weight = Parameter(torch.Tensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
def forward(self, input, label):
cosine = cosine_sim(input, self.weight)
one_hot = torch.zeros_like(cosine)
one_hot.scatter_(1, label.view(-1, 1), 1.0)
output = self.s * (cosine - one_hot * self.m)
return output
def __repr__(self):
return self.__class__.__name__ + '(' + 'in_features=' + str(self.
in_features) + ', out_features=' + str(self.out_features
) + ', s=' + str(self.s) + ', m=' + str(self.m) + ')'
def get_inputs():
return [torch.rand([4, 4]), torch.ones([4], dtype=torch.int64)]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn import Parameter
import torch.utils.data
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clamp_div_linalg_vector_norm_mul_scatter_sub_0(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
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr3 + 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)
tmp14 = tmp13 * tmp13
tmp16 = tmp15 * tmp15
tmp17 = tmp14 + tmp16
tmp19 = tmp18 * tmp18
tmp20 = tmp17 + tmp19
tmp22 = tmp21 * tmp21
tmp23 = tmp20 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = tmp12 * tmp24
tmp26 = 1e-08
tmp27 = triton_helpers.maximum(tmp25, tmp26)
tmp28 = tmp0 / tmp27
tmp30 = x0
tmp31 = tmp29 == tmp30
tmp32 = 1.0
tmp33 = 0.0
tmp34 = tl.where(tmp31, tmp32, tmp33)
tmp35 = 0.4
tmp36 = tmp34 * tmp35
tmp37 = tmp28 - tmp36
tmp38 = 30.0
tmp39 = tmp37 * tmp38
tl.store(in_out_ptr0 + x2, tmp39, 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,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_2, reinterpret_tensor(primals_1, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_clamp_div_linalg_vector_norm_mul_scatter_sub_0[grid
(16)](buf2, buf0, primals_2, primals_1, primals_3, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_1, primals_2, buf0
def cosine_sim(x1, x2, dim=1, eps=1e-08):
ip = torch.mm(x1, x2.t())
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return ip / torch.ger(w1, w2).clamp(min=eps)
class MarginCosineProductNew(nn.Module):
"""Implement of large margin cosine distance: :
Args:
in_features: size of each input sample
out_features: size of each output sample
s: norm of input feature
m: margin
"""
def __init__(self, in_features, out_features, s=30.0, m=0.4):
super(MarginCosineProductNew, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.weight = Parameter(torch.Tensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
def __repr__(self):
return self.__class__.__name__ + '(' + 'in_features=' + str(self.
in_features) + ', out_features=' + str(self.out_features
) + ', s=' + str(self.s) + ', m=' + str(self.m) + ')'
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
lindsey98/CosFace_pytorch
|
MarginCosineProduct
| false
| 10,397
|
[
"MIT"
] | 0
|
39bddf763e06c7ccd21fbf45d0c7f1f4a9d8d24d
|
https://github.com/lindsey98/CosFace_pytorch/tree/39bddf763e06c7ccd21fbf45d0c7f1f4a9d8d24d
|
SplitDim
|
import torch
from torch import nn as nn
import torch.utils.data
class SplitDim(nn.Module):
def __init__(self, nonlin_col=1, nonlin_type=torch.nn.functional.
softplus, correction=True):
super(SplitDim, self).__init__()
self.nonlinearity = nonlin_type
self.col = nonlin_col
if correction:
self.var = torch.nn.Parameter(torch.zeros(1))
else:
self.register_buffer('var', torch.ones(1, requires_grad=False) *
-15.0)
self.correction = correction
def forward(self, input):
transformed_output = self.nonlinearity(input[:, self.col])
transformed_output = transformed_output + self.nonlinearity(self.var)
stack_list = [input[:, :self.col], transformed_output.view(-1, 1)]
if self.col + 1 < input.size(1):
stack_list.append(input[:, self.col + 1:])
output = torch.cat(stack_list, 1)
return output
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import 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_cat_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 % 4
x1 = xindex // 4
x2 = xindex
tmp16 = tl.load(in_ptr1 + 0)
tmp17 = tl.broadcast_to(tmp16, [XBLOCK])
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 = tmp0 >= tmp3
tmp7 = tl.full([1], 2, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), tmp9 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = 20.0
tmp12 = tmp10 > tmp11
tmp13 = tl_math.exp(tmp10)
tmp14 = libdevice.log1p(tmp13)
tmp15 = tl.where(tmp12, tmp10, tmp14)
tmp18 = tmp17 > tmp11
tmp19 = tl_math.exp(tmp17)
tmp20 = libdevice.log1p(tmp19)
tmp21 = tl.where(tmp18, tmp17, tmp20)
tmp22 = tmp15 + tmp21
tmp23 = tl.full(tmp22.shape, 0.0, tmp22.dtype)
tmp24 = tl.where(tmp9, tmp22, tmp23)
tmp25 = tmp0 >= tmp7
tl.full([1], 4, tl.int64)
tmp28 = tl.load(in_ptr0 + (2 + 4 * x1 + (-2 + x0)), tmp25 & xmask,
eviction_policy='evict_last', other=0.0)
tmp29 = tl.where(tmp9, tmp24, tmp28)
tmp30 = tl.where(tmp4, tmp5, tmp29)
tl.store(out_ptr0 + x2, tmp30, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(16)](primals_1, primals_2, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_1
return buf0, primals_2
class SplitDimNew(nn.Module):
def __init__(self, nonlin_col=1, nonlin_type=torch.nn.functional.
softplus, correction=True):
super(SplitDimNew, self).__init__()
self.nonlinearity = nonlin_type
self.col = nonlin_col
if correction:
self.var = torch.nn.Parameter(torch.zeros(1))
else:
self.register_buffer('var', torch.ones(1, requires_grad=False) *
-15.0)
self.correction = correction
def forward(self, input_0):
primals_2 = self.var
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
junmokane/rlkit_jm
|
SplitDim
| false
| 10,398
|
[
"MIT"
] | 0
|
34a1bcf47706d4c98e9ce3b7edfd96fee6f2dd70
|
https://github.com/junmokane/rlkit_jm/tree/34a1bcf47706d4c98e9ce3b7edfd96fee6f2dd70
|
StyledConv
|
from torch.autograd import Function
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class FusedLeakyReLU(nn.Module):
def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
super().__init__()
self.bias = nn.Parameter(torch.zeros(channel))
self.negative_slope = negative_slope
self.scale = scale
def forward(self, x):
return self.scale * leaky_relu(x + self.bias.reshape((1, -1, 1, 1))
[:, :x.shape[1]], self.negative_slope, inplace=True)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, x, style):
batch, in_channel, height, width = x.shape
style = self.modulation(style)
style = style.view(batch, 1, -1, 1, 1)
first_k_oup = self.first_k_oup if hasattr(self, 'first_k_oup'
) and self.first_k_oup is not None else self.weight.shape[1]
assert first_k_oup <= self.weight.shape[1]
weight = self.weight
weight = weight[:, :first_k_oup, :in_channel].contiguous()
weight = self.scale * weight * style[:, :, :in_channel]
if self.demodulate:
weight = weight * torch.rsqrt(weight.pow(2).sum([2, 3, 4],
keepdim=True) + self.eps)
if self.upsample:
x = x.view(1, batch * in_channel, height, width)
weight = weight.transpose(1, 2)
weight = weight.reshape(weight.shape[0] * weight.shape[1],
weight.shape[2], weight.shape[3], weight.shape[4])
out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups
=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
out = self.blur(out)
else:
x = x.contiguous().view(1, batch * in_channel, height, width)
weight = weight.view(weight.shape[0] * weight.shape[1], weight.
shape[2], weight.shape[3], weight.shape[4])
out = F.conv2d(x, weight, padding=self.padding, groups=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
return out
class NoiseInjection(nn.Module):
def __init__(self):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1))
def forward(self, image, noise=None):
if noise is None:
batch, _, height, width = image.shape
noise = image.new_empty(batch, 1, height, width).normal_()
return image + self.weight * noise
class StyledConv(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
upsample=False, blur_kernel=(1, 3, 3, 1), demodulate=True,
activation='lrelu'):
super().__init__()
self.conv = ModulatedConv2d(in_channel, out_channel, kernel_size,
style_dim, upsample=upsample, blur_kernel=blur_kernel,
demodulate=demodulate)
self.noise = NoiseInjection()
if activation == 'lrelu':
self.activate = FusedLeakyReLU(out_channel)
else:
raise NotImplementedError
def forward(self, x, style, noise=None):
out = self.conv(x, style)
out = self.noise(out, noise=noise)
out = self.activate(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel_size': 4,
'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch.autograd import Function
import math
from torch import nn
from torch.nn import functional as F
from torch.nn.functional import leaky_relu
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_rsqrt_sum_2(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
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)
r5 = rindex
x0 = xindex % 4
r3 = rindex // 16
x1 = xindex // 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (r5 + 64 * x0), xmask, eviction_policy=
'evict_last', other=0.0)
tmp3 = tl.load(in_ptr1 + (r3 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp1 = 0.125
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = 1e-08
tmp11 = tmp9 + tmp10
tmp12 = libdevice.rsqrt(tmp11)
tmp13 = tmp4 * tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + x4, tmp12, xmask)
tl.store(out_ptr0 + (r5 + 64 * x4), tmp13, xmask)
@triton.jit
def triton_poi_fused_add_leaky_relu_leaky_relu_backward_mul_3(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr
):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 25
x2 = xindex // 100
x1 = xindex // 25 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tl.load(in_ptr2 + (x0 + 25 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp4 = tmp2 * tmp3
tmp5 = tmp0 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 0.0
tmp9 = tmp7 > tmp8
tmp10 = 0.2
tmp11 = tmp7 * tmp10
tmp12 = tl.where(tmp9, tmp7, tmp11)
tmp13 = 1.4142135623730951
tmp14 = tmp12 * tmp13
tmp15 = tmp12 > tmp8
tl.store(out_ptr0 + x3, tmp14, xmask)
tl.store(out_ptr1 + x3, tmp15, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
assert_size_stride(primals_6, (1,), (1,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, reinterpret_tensor(primals_4, (64, 4), (
4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1,
beta=1, out=buf2)
del buf1
buf3 = reinterpret_tensor(buf0, (4, 4, 1, 1, 1), (4, 1, 16, 16, 16), 0)
del buf0
buf4 = reinterpret_tensor(buf3, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_per_fused_add_mul_pow_rsqrt_sum_2[grid(16)](buf4, primals_5,
buf2, buf5, 16, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf6 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf5, (16, 4,
4, 4), (64, 16, 4, 1), 0), stride=(1, 1), padding=(2, 2),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf6, (1, 16, 5, 5), (400, 25, 5, 1))
buf7 = empty_strided_cuda((4, 1, 5, 5), (25, 25, 5, 1), torch.float32)
buf8 = torch.ops.aten.normal_functional.default(buf7)
del buf7
buf9 = buf8
del buf8
buf10 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32
)
buf11 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.bool)
triton_poi_fused_add_leaky_relu_leaky_relu_backward_mul_3[grid(400)](
buf6, primals_6, buf9, primals_7, buf10, buf11, 400, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
del primals_6
del primals_7
return buf10, primals_5, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 1, 4, 1, 1), (64, 64, 1, 1, 1), 0
), buf4, reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4,
1), 0), reinterpret_tensor(buf5, (16, 4, 4, 4), (64, 16, 4, 1), 0
), buf9, buf11
def fused_leaky_relu(input_, bias, negative_slope=0.2, scale=2 ** 0.5):
return scale * leaky_relu(input_ + bias[:input_.shape[1]],
negative_slope, inplace=True)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
k = torch.flip(k, [0, 1])
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, ch, _in_h, _in_w = input.shape
kernel_h, kernel_w = kernel.shape
assert up_y == up_x and up_y in [1, 2]
if up_y == 2:
w = input.new_zeros(2, 2)
w[0, 0] = 1
out = F.conv_transpose2d(input, w.view(1, 1, 2, 2).repeat(ch, 1, 1,
1), groups=ch, stride=2)
else:
out = input
out = F.pad(out, [pad_x0, pad_x1, pad_y0, pad_y1])
out = F.conv2d(out, kernel.view(1, 1, kernel_h, kernel_w).repeat(ch, 1,
1, 1), groups=ch)
return out[:, :, ::down_y, ::down_x]
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0],
pad[1], pad[0], pad[1])
else:
out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0
], pad[1], pad[0], pad[1]))
return out
class FusedLeakyReLU(nn.Module):
def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
super().__init__()
self.bias = nn.Parameter(torch.zeros(channel))
self.negative_slope = negative_slope
self.scale = scale
def forward(self, x):
return self.scale * leaky_relu(x + self.bias.reshape((1, -1, 1, 1))
[:, :x.shape[1]], self.negative_slope, inplace=True)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1.0,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, x):
if self.activation:
out = F.linear(x, self.weight * self.scale)
if self.activation == 'lrelu':
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
raise NotImplementedError
else:
out = F.linear(x, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size,
ctx.out_size)
return grad_input, None, None, None, None
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, x):
out = upfirdn2d(x, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=(1,
3, 3, 1)):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
assert not downsample, 'Downsample is not implemented yet!'
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
self.blur = Blur(blur_kernel, pad=((p + 1) // 2 + factor - 1, p //
2 + 1), upsample_factor=factor)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, x, style):
batch, in_channel, height, width = x.shape
style = self.modulation(style)
style = style.view(batch, 1, -1, 1, 1)
first_k_oup = self.first_k_oup if hasattr(self, 'first_k_oup'
) and self.first_k_oup is not None else self.weight.shape[1]
assert first_k_oup <= self.weight.shape[1]
weight = self.weight
weight = weight[:, :first_k_oup, :in_channel].contiguous()
weight = self.scale * weight * style[:, :, :in_channel]
if self.demodulate:
weight = weight * torch.rsqrt(weight.pow(2).sum([2, 3, 4],
keepdim=True) + self.eps)
if self.upsample:
x = x.view(1, batch * in_channel, height, width)
weight = weight.transpose(1, 2)
weight = weight.reshape(weight.shape[0] * weight.shape[1],
weight.shape[2], weight.shape[3], weight.shape[4])
out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups
=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
out = self.blur(out)
else:
x = x.contiguous().view(1, batch * in_channel, height, width)
weight = weight.view(weight.shape[0] * weight.shape[1], weight.
shape[2], weight.shape[3], weight.shape[4])
out = F.conv2d(x, weight, padding=self.padding, groups=batch)
out = out.view(batch, -1, out.shape[-2], out.shape[-1])
return out
class NoiseInjection(nn.Module):
def __init__(self):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1))
def forward(self, image, noise=None):
if noise is None:
batch, _, height, width = image.shape
noise = image.new_empty(batch, 1, height, width).normal_()
return image + self.weight * noise
class StyledConvNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
upsample=False, blur_kernel=(1, 3, 3, 1), demodulate=True,
activation='lrelu'):
super().__init__()
self.conv = ModulatedConv2d(in_channel, out_channel, kernel_size,
style_dim, upsample=upsample, blur_kernel=blur_kernel,
demodulate=demodulate)
self.noise = NoiseInjection()
if activation == 'lrelu':
self.activate = FusedLeakyReLU(out_channel)
else:
raise NotImplementedError
def forward(self, input_0, input_1):
primals_5 = self.conv.weight
primals_2 = self.conv.modulation.weight
primals_3 = self.conv.modulation.bias
primals_6 = self.noise.weight
primals_7 = self.activate.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jchetboun/anycost-gan
|
StyledConv
| false
| 10,399
|
[
"MIT"
] | 0
|
7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
https://github.com/jchetboun/anycost-gan/tree/7e0005e50b915e2dfeb90fe7a9846c5df38d7c06
|
DiceLoss
|
import torch
from torch import nn
from torch.autograd import Variable
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
C = tensor.size(1)
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
transposed = tensor.permute(axis_order)
return transposed.view(C, -1)
def compute_per_channel_dice(input, target, epsilon=1e-05, ignore_index=
None, weight=None):
assert input.size() == target.size(
), "'input' and 'target' must have the same shape"
if ignore_index is not None:
mask = target.clone().ne_(ignore_index)
mask.requires_grad = False
input = input * mask
target = target * mask
input = flatten(input)
target = flatten(target)
target = target.float()
intersect = (input * target).sum(-1)
if weight is not None:
intersect = weight * intersect
denominator = (input + target).sum(-1)
return 2.0 * intersect / denominator.clamp(min=epsilon)
class DiceLoss(nn.Module):
"""Computes Dice Loss, which just 1 - DiceCoefficient described above.
Additionally allows per-class weights to be provided.
"""
def __init__(self, epsilon=1e-05, weight=None, ignore_index=None,
sigmoid_normalization=True, skip_last_target=False):
super(DiceLoss, self).__init__()
self.epsilon = epsilon
self.register_buffer('weight', weight)
self.ignore_index = ignore_index
if sigmoid_normalization:
self.normalization = nn.Sigmoid()
else:
self.normalization = nn.Softmax(dim=1)
self.skip_last_target = skip_last_target
def forward(self, input, target):
input = self.normalization(input)
if self.weight is not None:
weight = Variable(self.weight, requires_grad=False)
else:
weight = None
if self.skip_last_target:
target = target[:, :-1, ...]
per_channel_dice = compute_per_channel_dice(input, target, epsilon=
self.epsilon, ignore_index=self.ignore_index, weight=weight)
return torch.mean(1.0 - per_channel_dice)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch 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_div_mean_mul_rsub_sum_0(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp4 = tl.load(in_ptr0 + (4 + r0), None)
tmp6 = tl.load(in_ptr1 + (4 + r0), None)
tmp9 = tl.load(in_ptr0 + (8 + r0), None)
tmp11 = tl.load(in_ptr1 + (8 + r0), None)
tmp14 = tl.load(in_ptr0 + (12 + r0), None)
tmp16 = tl.load(in_ptr1 + (12 + r0), None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp5 = tl.sigmoid(tmp4)
tmp7 = tmp5 * tmp6
tmp8 = tmp3 + tmp7
tmp10 = tl.sigmoid(tmp9)
tmp12 = tmp10 * tmp11
tmp13 = tmp8 + tmp12
tmp15 = tl.sigmoid(tmp14)
tmp17 = tmp15 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = 2.0
tmp20 = tmp18 * tmp19
tmp21 = tmp1 + tmp2
tmp22 = tmp5 + tmp6
tmp23 = tmp21 + tmp22
tmp24 = tmp10 + tmp11
tmp25 = tmp23 + tmp24
tmp26 = tmp15 + tmp16
tmp27 = tmp25 + tmp26
tmp28 = 1e-05
tmp29 = triton_helpers.maximum(tmp27, tmp28)
tmp30 = tmp20 / tmp29
tmp31 = 1.0
tmp32 = tmp31 - tmp30
tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK])
tmp35 = tl.sum(tmp33, 1)[:, None]
tmp36 = 4.0
tmp37 = tmp35 / tmp36
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp37, 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)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_clamp_div_mean_mul_rsub_sum_0[grid(1)](buf2,
arg0_1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
C = tensor.size(1)
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
transposed = tensor.permute(axis_order)
return transposed.view(C, -1)
def compute_per_channel_dice(input, target, epsilon=1e-05, ignore_index=
None, weight=None):
assert input.size() == target.size(
), "'input' and 'target' must have the same shape"
if ignore_index is not None:
mask = target.clone().ne_(ignore_index)
mask.requires_grad = False
input = input * mask
target = target * mask
input = flatten(input)
target = flatten(target)
target = target.float()
intersect = (input * target).sum(-1)
if weight is not None:
intersect = weight * intersect
denominator = (input + target).sum(-1)
return 2.0 * intersect / denominator.clamp(min=epsilon)
class DiceLossNew(nn.Module):
"""Computes Dice Loss, which just 1 - DiceCoefficient described above.
Additionally allows per-class weights to be provided.
"""
def __init__(self, epsilon=1e-05, weight=None, ignore_index=None,
sigmoid_normalization=True, skip_last_target=False):
super(DiceLossNew, self).__init__()
self.epsilon = epsilon
self.register_buffer('weight', weight)
self.ignore_index = ignore_index
if sigmoid_normalization:
self.normalization = nn.Sigmoid()
else:
self.normalization = nn.Softmax(dim=1)
self.skip_last_target = skip_last_target
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
joowlim/pytorch-3dunet
|
DiceLoss
| false
| 10,400
|
[
"MIT"
] | 0
|
d08049f60b619627521efd0fb171247e1536b262
|
https://github.com/joowlim/pytorch-3dunet/tree/d08049f60b619627521efd0fb171247e1536b262
|
InferenceNetLSTMCell
|
import torch
import torch.nn as nn
class InferenceNetLSTMCell(nn.Module):
def __init__(self, z_dim: 'int', input_dim: 'int', hidden_hat_dim:
'int', hidden_dim: 'int'):
super(InferenceNetLSTMCell, self).__init__()
self.w_hh = nn.Linear(hidden_hat_dim, z_dim)
self.w_hx = nn.Linear(hidden_hat_dim, z_dim)
self.w_hb = nn.Linear(hidden_hat_dim, z_dim)
self.W_hz = nn.Linear(z_dim, 4 * hidden_dim, bias=False)
self.W_xz = nn.Linear(z_dim, 4 * hidden_dim, bias=False)
self.b = nn.Linear(z_dim, 4 * hidden_dim)
self.Wh = nn.Linear(hidden_dim, 4 * hidden_dim)
self.Wx = nn.Linear(input_dim, 4 * hidden_dim)
self.dropout = nn.Dropout(p=0.1, inplace=True)
self.norm_h = nn.LayerNorm(hidden_dim)
self.norm_c = nn.LayerNorm(hidden_dim)
def forward(self, h_t, c, h_t_hat, inf_inputs):
z_h = self.w_hh(h_t_hat)
z_x = self.w_hx(h_t_hat)
z_bias = self.w_hb(h_t_hat)
d_z_h = self.W_hz(z_h)
d_z_x = self.W_xz(z_x)
b_z_b = self.b(z_bias)
ifgo = d_z_h * self.Wh(h_t) + d_z_x * self.Wx(inf_inputs) + b_z_b
i, f, g, o = torch.chunk(ifgo, 4, -1)
i = torch.sigmoid(i)
f = torch.sigmoid(f)
g = torch.sigmoid(g)
o = torch.sigmoid(o)
new_c = f * c + i * c
new_h = o * torch.tanh(new_c)
new_h = self.dropout(new_h)
new_h = self.norm_h(new_h)
new_c = self.norm_c(new_c)
return new_h, new_c
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'z_dim': 4, 'input_dim': 4, 'hidden_hat_dim': 4,
'hidden_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_sigmoid_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + (x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr4 + (x0 + 16 * x1), xmask)
tmp8 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp11 = tl.sigmoid(tmp10)
tl.store(out_ptr0 + x2, tmp11, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + (4 + x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr4 + (4 + x0 + 16 * x1), xmask)
tmp8 = tl.load(in_ptr5 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp11 = tl.sigmoid(tmp10)
tl.store(out_ptr0 + x2, tmp11, xmask)
@triton.jit
def triton_poi_fused_sigmoid_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (12 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + (12 + x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr4 + (12 + x0 + 16 * x1), xmask)
tmp8 = tl.load(in_ptr5 + (12 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp11 = tl.sigmoid(tmp10)
tl.store(out_ptr0 + x2, tmp11, xmask)
@triton.jit
def triton_poi_fused_add_mul_native_layer_norm_tanh_3(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, out_ptr1, out_ptr2, out_ptr3, 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')
tmp2 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp23 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp30 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp33 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp1 * tmp2
tmp5 = tmp4 * tmp2
tmp6 = tmp3 + tmp5
tmp7 = libdevice.tanh(tmp6)
tmp8 = tmp0 * tmp7
tmp12 = tmp10 * tmp11
tmp14 = tmp13 * tmp11
tmp15 = tmp12 + tmp14
tmp16 = libdevice.tanh(tmp15)
tmp17 = tmp9 * tmp16
tmp18 = tmp8 + tmp17
tmp22 = tmp20 * tmp21
tmp24 = tmp23 * tmp21
tmp25 = tmp22 + tmp24
tmp26 = libdevice.tanh(tmp25)
tmp27 = tmp19 * tmp26
tmp28 = tmp18 + tmp27
tmp32 = tmp30 * tmp31
tmp34 = tmp33 * tmp31
tmp35 = tmp32 + tmp34
tmp36 = libdevice.tanh(tmp35)
tmp37 = tmp29 * tmp36
tmp38 = tmp28 + tmp37
tmp39 = 4.0
tmp40 = tmp38 / tmp39
tmp41 = tmp8 - tmp40
tmp42 = tmp41 * tmp41
tmp43 = tmp17 - tmp40
tmp44 = tmp43 * tmp43
tmp45 = tmp42 + tmp44
tmp46 = tmp27 - tmp40
tmp47 = tmp46 * tmp46
tmp48 = tmp45 + tmp47
tmp49 = tmp37 - tmp40
tmp50 = tmp49 * tmp49
tmp51 = tmp48 + tmp50
tmp52 = tmp51 / tmp39
tmp53 = tmp6 + tmp15
tmp54 = tmp53 + tmp25
tmp55 = tmp54 + tmp35
tmp56 = tmp55 / tmp39
tmp57 = tmp6 - tmp56
tmp58 = tmp57 * tmp57
tmp59 = tmp15 - tmp56
tmp60 = tmp59 * tmp59
tmp61 = tmp58 + tmp60
tmp62 = tmp25 - tmp56
tmp63 = tmp62 * tmp62
tmp64 = tmp61 + tmp63
tmp65 = tmp35 - tmp56
tmp66 = tmp65 * tmp65
tmp67 = tmp64 + tmp66
tmp68 = tmp67 / tmp39
tl.store(out_ptr0 + x0, tmp40, xmask)
tl.store(out_ptr1 + x0, tmp52, xmask)
tl.store(out_ptr2 + x0, tmp56, xmask)
tl.store(out_ptr3 + x0, tmp68, xmask)
@triton.jit
def triton_poi_fused_add_mul_native_layer_norm_tanh_4(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9,
in_ptr10, in_ptr11, 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 // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x2, xmask)
tmp4 = tl.load(in_ptr3 + x2, xmask)
tmp9 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr10 + x0, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr11 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 * tmp2
tmp5 = tmp4 * tmp2
tmp6 = tmp3 + tmp5
tmp7 = libdevice.tanh(tmp6)
tmp8 = tmp0 * tmp7
tmp10 = tmp8 - tmp9
tmp12 = 1e-05
tmp13 = tmp11 + tmp12
tmp14 = libdevice.rsqrt(tmp13)
tmp15 = tmp10 * tmp14
tmp17 = tmp15 * tmp16
tmp19 = tmp17 + tmp18
tmp21 = tmp6 - tmp20
tmp23 = tmp22 + tmp12
tmp24 = libdevice.rsqrt(tmp23)
tmp25 = tmp21 * tmp24
tmp27 = tmp25 * tmp26
tmp29 = tmp27 + tmp28
tl.store(out_ptr0 + x2, tmp19, xmask)
tl.store(out_ptr1 + x2, tmp29, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (16, 4), (4, 1))
assert_size_stride(primals_9, (16, 4), (4, 1))
assert_size_stride(primals_10, (16, 4), (4, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (16, 4), (4, 1))
assert_size_stride(primals_13, (16,), (1,))
assert_size_stride(primals_14, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_15, (16, 4), (4, 1))
assert_size_stride(primals_16, (16,), (1,))
assert_size_stride(primals_17, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_18, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_19, (4,), (1,))
assert_size_stride(primals_20, (4,), (1,))
assert_size_stride(primals_21, (4,), (1,))
assert_size_stride(primals_22, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(primals_3, (64,
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((64, 16), (16, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_8, (4, 16), (1,
4), 0), out=buf3)
buf4 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_9, (4, 16), (1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_10, (4, 16), (1,
4), 0), out=buf5)
buf6 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(primals_14, (64,
4), (4, 1), 0), reinterpret_tensor(primals_12, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf6)
del primals_12
del primals_13
buf7 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_16, reinterpret_tensor(primals_17, (64,
4), (4, 1), 0), reinterpret_tensor(primals_15, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf7)
del primals_15
del primals_16
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sigmoid_0[grid(256)](buf3, buf6, buf4, buf7, buf5,
primals_11, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_1[grid(256)](buf3, buf6, buf4, buf7, buf5,
primals_11, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_2[grid(256)](buf3, buf6, buf4, buf7, buf5,
primals_11, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf5
del primals_11
buf11 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf12 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf14 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_mul_native_layer_norm_tanh_3[grid(64)](buf10,
buf9, primals_18, buf8, buf11, buf12, buf14, buf15, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf16 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_native_layer_norm_tanh_4[grid(256)](buf10,
buf9, primals_18, buf8, buf11, buf12, primals_19, primals_20,
buf14, buf15, primals_21, primals_22, buf13, buf16, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del buf11
del buf12
del buf14
del buf15
del primals_20
del primals_22
return (buf13, buf16, primals_18, primals_19, primals_21,
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0, buf3, buf1,
buf4, buf2, reinterpret_tensor(primals_14, (64, 4), (4, 1), 0),
buf6, reinterpret_tensor(primals_17, (64, 4), (4, 1), 0), buf7,
buf8, buf9, buf10, primals_10, primals_9, primals_8)
class InferenceNetLSTMCellNew(nn.Module):
def __init__(self, z_dim: 'int', input_dim: 'int', hidden_hat_dim:
'int', hidden_dim: 'int'):
super(InferenceNetLSTMCellNew, self).__init__()
self.w_hh = nn.Linear(hidden_hat_dim, z_dim)
self.w_hx = nn.Linear(hidden_hat_dim, z_dim)
self.w_hb = nn.Linear(hidden_hat_dim, z_dim)
self.W_hz = nn.Linear(z_dim, 4 * hidden_dim, bias=False)
self.W_xz = nn.Linear(z_dim, 4 * hidden_dim, bias=False)
self.b = nn.Linear(z_dim, 4 * hidden_dim)
self.Wh = nn.Linear(hidden_dim, 4 * hidden_dim)
self.Wx = nn.Linear(input_dim, 4 * hidden_dim)
self.dropout = nn.Dropout(p=0.1, inplace=True)
self.norm_h = nn.LayerNorm(hidden_dim)
self.norm_c = nn.LayerNorm(hidden_dim)
def forward(self, input_0, input_1, input_2, input_3):
primals_1 = self.w_hh.weight
primals_2 = self.w_hh.bias
primals_4 = self.w_hx.weight
primals_5 = self.w_hx.bias
primals_6 = self.w_hb.weight
primals_7 = self.w_hb.bias
primals_8 = self.W_hz.weight
primals_9 = self.W_xz.weight
primals_10 = self.b.weight
primals_11 = self.b.bias
primals_12 = self.Wh.weight
primals_13 = self.Wh.bias
primals_15 = self.Wx.weight
primals_16 = self.Wx.bias
primals_19 = self.norm_h.weight
primals_20 = self.norm_h.bias
primals_21 = self.norm_c.weight
primals_22 = self.norm_c.bias
primals_3 = input_0
primals_14 = input_1
primals_17 = input_2
primals_18 = 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])
return output[0], output[1]
|
kingofpigeon/hypernlp
|
InferenceNetLSTMCell
| false
| 10,401
|
[
"MIT"
] | 0
|
1270ae318e698775160a6299db35752823fda7c7
|
https://github.com/kingofpigeon/hypernlp/tree/1270ae318e698775160a6299db35752823fda7c7
|
MinMaxNorm
|
import torch
import torch.nn as nn
class MinMaxNorm(nn.Module):
def __init__(self, min, max, a=0, b=1):
super(MinMaxNorm, self).__init__()
self.min, self.max = min, max
self.a, self.b = a, b
def forward(self, x):
return self.a + (x - self.min) * (self.b - self.a) / (self.max -
self.min)
def inverse(self, x):
return self.min + (x - self.a) * (self.max - self.min) / (self.b -
self.a)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'min': 4, 'max': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mul_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 4.0
tmp2 = tmp0 - tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp5 = float('inf')
tmp6 = tmp4 * tmp5
tmp7 = 0.0
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mul_sub_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class MinMaxNormNew(nn.Module):
def __init__(self, min, max, a=0, b=1):
super(MinMaxNormNew, self).__init__()
self.min, self.max = min, max
self.a, self.b = a, b
def inverse(self, x):
return self.min + (x - self.a) * (self.max - self.min) / (self.b -
self.a)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
iclementine/speedyspeech
|
MinMaxNorm
| false
| 10,402
|
[
"BSD-3-Clause"
] | 0
|
db527587a3699b71082d61c9e9fad7ed795d1980
|
https://github.com/iclementine/speedyspeech/tree/db527587a3699b71082d61c9e9fad7ed795d1980
|
CCAMDec
|
from torch.nn import Module
import torch
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn.parameter import Parameter
class CCAMDec(Module):
"""
CCAM decoding module
"""
def __init__(self):
super(CCAMDec, self).__init__()
self.softmax = Softmax(dim=-1)
self.scale = Parameter(torch.zeros(1))
def forward(self, x, y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,H,W)
returns :
out : compact channel attention feature
attention map: K*C
"""
m_batchsize, C, width, height = x.size()
x_reshape = x.view(m_batchsize, C, -1)
B, K, _W, _H = y.size()
y_reshape = y.view(B, K, -1)
proj_query = x_reshape
proj_key = y_reshape.permute(0, 2, 1)
energy = torch.bmm(proj_query, proj_key)
energy_new = torch.max(energy, -1, keepdim=True)[0].expand_as(energy
) - energy
attention = self.softmax(energy_new)
proj_value = y.view(B, K, -1)
out = torch.bmm(attention, proj_value)
out = out.view(m_batchsize, C, width, height)
out = x + self.scale * out
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + x2, xmask)
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp8 = tmp6 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_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 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tl.load(in_ptr2 + x0, xmask)
tmp4 = tmp2 * tmp3
tmp5 = tmp0 + tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (4, 4, 16), (64,
16, 1), 0), reinterpret_tensor(primals_2, (4, 16, 4), (64, 1,
16), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sub_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = buf1
del buf1
triton_poi_fused__softmax_2[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf2
buf4 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(primals_2, (4, 4, 16),
(64, 16, 1), 0), out=buf4)
del buf3
del primals_2
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_3[grid(256)](primals_1, primals_3, buf4,
buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_3
return buf5, buf4
class CCAMDecNew(Module):
"""
CCAM decoding module
"""
def __init__(self):
super(CCAMDecNew, self).__init__()
self.softmax = Softmax(dim=-1)
self.scale = Parameter(torch.zeros(1))
def forward(self, input_0, input_1):
primals_3 = self.scale
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bfjei2825401/siamban
|
CCAMDec
| false
| 10,403
|
[
"Apache-2.0"
] | 0
|
c41d58742b146dfc8960053453227c6e9fec1bac
|
https://github.com/bfjei2825401/siamban/tree/c41d58742b146dfc8960053453227c6e9fec1bac
|
PAM_Module
|
from torch.nn import Module
import torch
from torch.nn import Conv2d
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn.parameter import Parameter
class PAM_Module(Module):
""" Position attention module"""
def __init__(self, in_dim):
super(PAM_Module, self).__init__()
self.channel_in = in_dim
out_channels = max(in_dim // 8, min(in_dim, 2))
self.query_conv = Conv2d(in_channels=in_dim, out_channels=
out_channels, kernel_size=1)
self.key_conv = Conv2d(in_channels=in_dim, out_channels=
out_channels, kernel_size=1)
self.value_conv = Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = Parameter(torch.zeros(1))
self.softmax = Softmax(dim=-1)
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
"""
m_batchsize, C, height, width = 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, height, width)
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.nn import Module
from torch.nn import Conv2d
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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=8,
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=256, 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=256, 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 PAM_ModuleNew(Module):
""" Position attention module"""
def __init__(self, in_dim):
super(PAM_ModuleNew, self).__init__()
self.channel_in = in_dim
out_channels = max(in_dim // 8, min(in_dim, 2))
self.query_conv = Conv2d(in_channels=in_dim, out_channels=
out_channels, kernel_size=1)
self.key_conv = Conv2d(in_channels=in_dim, out_channels=
out_channels, kernel_size=1)
self.value_conv = Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = Parameter(torch.zeros(1))
self.softmax = 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]
|
bfjei2825401/siamban
|
PAM_Module
| false
| 10,404
|
[
"Apache-2.0"
] | 0
|
c41d58742b146dfc8960053453227c6e9fec1bac
|
https://github.com/bfjei2825401/siamban/tree/c41d58742b146dfc8960053453227c6e9fec1bac
|
Encoder
|
import torch
from torch import nn
def conv3d(in_channels, out_channels, kernel_size, bias, padding=1):
return nn.Conv3d(in_channels, out_channels, kernel_size, padding=
padding, bias=bias)
def create_conv(in_channels, out_channels, kernel_size, order, num_groups,
padding=1):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
order (string): order of things, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
padding (int): add zero-padding to the input
Return:
list of tuple (name, module)
"""
assert 'c' in order, 'Conv layer MUST be present'
assert order[0
] not in 'rle', 'Non-linearity cannot be the first operation in the layer'
modules = []
for i, char in enumerate(order):
if char == 'r':
modules.append(('ReLU', nn.ReLU(inplace=True)))
elif char == 'l':
modules.append(('LeakyReLU', nn.LeakyReLU(negative_slope=0.1,
inplace=True)))
elif char == 'e':
modules.append(('ELU', nn.ELU(inplace=True)))
elif char == 'c':
bias = not ('g' in order or 'b' in order)
modules.append(('conv', conv3d(in_channels, out_channels,
kernel_size, bias, padding=padding)))
elif char == 'g':
is_before_conv = i < order.index('c')
assert not is_before_conv, 'GroupNorm MUST go after the Conv3d'
if out_channels < num_groups:
num_groups = out_channels
modules.append(('groupnorm', nn.GroupNorm(num_groups=num_groups,
num_channels=out_channels)))
elif char == 'b':
is_before_conv = i < order.index('c')
if is_before_conv:
modules.append(('batchnorm', nn.BatchNorm3d(in_channels)))
else:
modules.append(('batchnorm', nn.BatchNorm3d(out_channels)))
else:
raise ValueError(
f"Unsupported layer type '{char}'. MUST be one of ['b', 'g', 'r', 'l', 'e', 'c']"
)
return modules
class SingleConv(nn.Sequential):
"""
Basic convolutional module consisting of a Conv3d, non-linearity and optional batchnorm/groupnorm. The order
of operations can be specified via the `order` parameter
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'crg', num_groups=8, padding=1):
super(SingleConv, self).__init__()
for name, module in create_conv(in_channels, out_channels,
kernel_size, order, num_groups, padding=padding):
self.add_module(name, module)
class DoubleConv(nn.Sequential):
"""
A module consisting of two consecutive convolution layers (e.g. BatchNorm3d+ReLU+Conv3d).
We use (Conv3d+ReLU+GroupNorm3d) by default.
This can be changed however by providing the 'order' argument, e.g. in order
to change to Conv3d+BatchNorm3d+ELU use order='cbe'.
Use padded convolutions to make sure that the output (H_out, W_out) is the same
as (H_in, W_in), so that you don't have to crop in the decoder path.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
encoder (bool): if True we're in the encoder path, otherwise we're in the decoder
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, encoder, kernel_size=3,
order='crg', num_groups=8):
super(DoubleConv, self).__init__()
if encoder:
conv1_in_channels = in_channels
conv1_out_channels = out_channels // 2
if conv1_out_channels < in_channels:
conv1_out_channels = in_channels
conv2_in_channels, conv2_out_channels = (conv1_out_channels,
out_channels)
else:
conv1_in_channels, conv1_out_channels = in_channels, out_channels
conv2_in_channels, conv2_out_channels = out_channels, out_channels
self.add_module('SingleConv1', SingleConv(conv1_in_channels,
conv1_out_channels, kernel_size, order, num_groups))
self.add_module('SingleConv2', SingleConv(conv2_in_channels,
conv2_out_channels, kernel_size, order, num_groups))
class Encoder(nn.Module):
"""
A single module from the encoder path consisting of the optional max
pooling layer (one may specify the MaxPool kernel_size to be different
than the standard (2,2,2), e.g. if the volumetric data is anisotropic
(make sure to use complementary scale_factor in the decoder path) followed by
a DoubleConv module.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
conv_kernel_size (int): size of the convolving kernel
apply_pooling (bool): if True use MaxPool3d before DoubleConv
pool_kernel_size (tuple): the size of the window to take a max over
pool_type (str): pooling layer: 'max' or 'avg'
basic_module(nn.Module): either ResNetBlock or DoubleConv
conv_layer_order (string): determines the order of layers
in `DoubleConv` module. See `DoubleConv` for more info.
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, conv_kernel_size=3,
apply_pooling=True, pool_kernel_size=(2, 2, 2), pool_type='max',
basic_module=DoubleConv, conv_layer_order='crg', num_groups=8):
super(Encoder, self).__init__()
assert pool_type in ['max', 'avg']
if apply_pooling:
if pool_type == 'max':
self.pooling = nn.MaxPool3d(kernel_size=pool_kernel_size)
else:
self.pooling = nn.AvgPool3d(kernel_size=pool_kernel_size)
else:
self.pooling = None
self.basic_module = basic_module(in_channels, out_channels, encoder
=True, kernel_size=conv_kernel_size, order=conv_layer_order,
num_groups=num_groups)
def forward(self, x):
if self.pooling is not None:
x = self.pooling(x)
x = self.basic_module(x)
return x
def get_inputs():
return [torch.rand([4, 8, 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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_group_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp1, tmp3)
tmp5 = tmp2 + tmp4
tmp7 = triton_helpers.maximum(tmp1, tmp6)
tmp8 = tmp5 + tmp7
tmp10 = triton_helpers.maximum(tmp1, tmp9)
tmp11 = tmp8 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tmp4 - tmp13
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp19 = tmp7 - tmp13
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp10 - tmp13
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp24 / tmp12
tmp26 = 1e-05
tmp27 = tmp25 + tmp26
tmp28 = libdevice.rsqrt(tmp27)
tl.store(out_ptr0 + x0, tmp13, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_native_group_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex // 4
x1 = xindex // 4 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = tmp2 - tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 * tmp7
tmp10 = tmp8 + tmp9
tl.store(out_ptr0 + x3, 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, 8, 4, 4), (128, 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 = torch.ops.aten.max_pool3d_with_indices.default(primals_1, [2,
2, 2], [2, 2, 2])
del primals_1
buf1 = buf0[0]
del buf0
buf3 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 4,
2, 2), (64, 16, 4, 2, 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(buf3, (1, 4, 4, 2, 2), (64, 16, 4, 2, 1))
buf4 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf5 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_group_norm_0[grid(16)](buf3, buf4, buf5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_native_group_norm_1[grid(64)](buf3, buf4, buf5,
primals_3, primals_4, buf6, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_4
buf7 = extern_kernels.convolution(reinterpret_tensor(buf6, (1, 4, 4,
2, 2), (0, 16, 4, 2, 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, 2, 2), (64, 16, 4, 2, 1))
buf8 = buf5
del buf5
buf9 = buf4
del buf4
triton_poi_fused_native_group_norm_0[grid(16)](buf7, buf8, buf9, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf10 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_native_group_norm_1[grid(64)](buf7, buf8, buf9,
primals_6, primals_7, buf10, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf8
del buf9
del primals_7
return (buf10, primals_2, primals_3, primals_5, primals_6,
reinterpret_tensor(buf1, (1, 4, 4, 2, 2), (64, 16, 4, 2, 1), 0),
buf3, reinterpret_tensor(buf6, (1, 4, 4, 2, 2), (64, 16, 4, 2, 1),
0), buf7)
def conv3d(in_channels, out_channels, kernel_size, bias, padding=1):
return nn.Conv3d(in_channels, out_channels, kernel_size, padding=
padding, bias=bias)
def create_conv(in_channels, out_channels, kernel_size, order, num_groups,
padding=1):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
order (string): order of things, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
padding (int): add zero-padding to the input
Return:
list of tuple (name, module)
"""
assert 'c' in order, 'Conv layer MUST be present'
assert order[0
] not in 'rle', 'Non-linearity cannot be the first operation in the layer'
modules = []
for i, char in enumerate(order):
if char == 'r':
modules.append(('ReLU', nn.ReLU(inplace=True)))
elif char == 'l':
modules.append(('LeakyReLU', nn.LeakyReLU(negative_slope=0.1,
inplace=True)))
elif char == 'e':
modules.append(('ELU', nn.ELU(inplace=True)))
elif char == 'c':
bias = not ('g' in order or 'b' in order)
modules.append(('conv', conv3d(in_channels, out_channels,
kernel_size, bias, padding=padding)))
elif char == 'g':
is_before_conv = i < order.index('c')
assert not is_before_conv, 'GroupNorm MUST go after the Conv3d'
if out_channels < num_groups:
num_groups = out_channels
modules.append(('groupnorm', nn.GroupNorm(num_groups=num_groups,
num_channels=out_channels)))
elif char == 'b':
is_before_conv = i < order.index('c')
if is_before_conv:
modules.append(('batchnorm', nn.BatchNorm3d(in_channels)))
else:
modules.append(('batchnorm', nn.BatchNorm3d(out_channels)))
else:
raise ValueError(
f"Unsupported layer type '{char}'. MUST be one of ['b', 'g', 'r', 'l', 'e', 'c']"
)
return modules
class SingleConv(nn.Sequential):
"""
Basic convolutional module consisting of a Conv3d, non-linearity and optional batchnorm/groupnorm. The order
of operations can be specified via the `order` parameter
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'crg', num_groups=8, padding=1):
super(SingleConv, self).__init__()
for name, module in create_conv(in_channels, out_channels,
kernel_size, order, num_groups, padding=padding):
self.add_module(name, module)
class DoubleConv(nn.Sequential):
"""
A module consisting of two consecutive convolution layers (e.g. BatchNorm3d+ReLU+Conv3d).
We use (Conv3d+ReLU+GroupNorm3d) by default.
This can be changed however by providing the 'order' argument, e.g. in order
to change to Conv3d+BatchNorm3d+ELU use order='cbe'.
Use padded convolutions to make sure that the output (H_out, W_out) is the same
as (H_in, W_in), so that you don't have to crop in the decoder path.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
encoder (bool): if True we're in the encoder path, otherwise we're in the decoder
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, encoder, kernel_size=3,
order='crg', num_groups=8):
super(DoubleConv, self).__init__()
if encoder:
conv1_in_channels = in_channels
conv1_out_channels = out_channels // 2
if conv1_out_channels < in_channels:
conv1_out_channels = in_channels
conv2_in_channels, conv2_out_channels = (conv1_out_channels,
out_channels)
else:
conv1_in_channels, conv1_out_channels = in_channels, out_channels
conv2_in_channels, conv2_out_channels = out_channels, out_channels
self.add_module('SingleConv1', SingleConv(conv1_in_channels,
conv1_out_channels, kernel_size, order, num_groups))
self.add_module('SingleConv2', SingleConv(conv2_in_channels,
conv2_out_channels, kernel_size, order, num_groups))
class EncoderNew(nn.Module):
"""
A single module from the encoder path consisting of the optional max
pooling layer (one may specify the MaxPool kernel_size to be different
than the standard (2,2,2), e.g. if the volumetric data is anisotropic
(make sure to use complementary scale_factor in the decoder path) followed by
a DoubleConv module.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
conv_kernel_size (int): size of the convolving kernel
apply_pooling (bool): if True use MaxPool3d before DoubleConv
pool_kernel_size (tuple): the size of the window to take a max over
pool_type (str): pooling layer: 'max' or 'avg'
basic_module(nn.Module): either ResNetBlock or DoubleConv
conv_layer_order (string): determines the order of layers
in `DoubleConv` module. See `DoubleConv` for more info.
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, conv_kernel_size=3,
apply_pooling=True, pool_kernel_size=(2, 2, 2), pool_type='max',
basic_module=DoubleConv, conv_layer_order='crg', num_groups=8):
super(EncoderNew, self).__init__()
assert pool_type in ['max', 'avg']
if apply_pooling:
if pool_type == 'max':
self.pooling = nn.MaxPool3d(kernel_size=pool_kernel_size)
else:
self.pooling = nn.AvgPool3d(kernel_size=pool_kernel_size)
else:
self.pooling = None
self.basic_module = basic_module(in_channels, out_channels, encoder
=True, kernel_size=conv_kernel_size, order=conv_layer_order,
num_groups=num_groups)
def forward(self, input_0):
primals_2 = self.basic_module.SingleConv1.conv.weight
primals_3 = self.basic_module.SingleConv1.groupnorm.weight
primals_4 = self.basic_module.SingleConv1.groupnorm.bias
primals_5 = self.basic_module.SingleConv2.conv.weight
primals_6 = self.basic_module.SingleConv2.groupnorm.weight
primals_7 = self.basic_module.SingleConv2.groupnorm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
joowlim/pytorch-3dunet
|
Encoder
| false
| 10,405
|
[
"MIT"
] | 0
|
d08049f60b619627521efd0fb171247e1536b262
|
https://github.com/joowlim/pytorch-3dunet/tree/d08049f60b619627521efd0fb171247e1536b262
|
StandardNorm
|
import torch
import torch.nn as nn
class StandardNorm(nn.Module):
def __init__(self, mean, std):
super(StandardNorm, self).__init__()
self.mean = mean
self.std = std
def forward(self, x):
return (x - self.mean) / self.std
def inverse(self, x):
return x * self.std + self.mean
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'mean': 4, 'std': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_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 = 4.0
tmp2 = tmp0 - tmp1
tmp3 = 0.25
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class StandardNormNew(nn.Module):
def __init__(self, mean, std):
super(StandardNormNew, self).__init__()
self.mean = mean
self.std = std
def inverse(self, x):
return x * self.std + self.mean
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
iclementine/speedyspeech
|
StandardNorm
| false
| 10,406
|
[
"BSD-3-Clause"
] | 0
|
db527587a3699b71082d61c9e9fad7ed795d1980
|
https://github.com/iclementine/speedyspeech/tree/db527587a3699b71082d61c9e9fad7ed795d1980
|
EuclideanComparator_1
|
import torch
from dataclasses import dataclass
from collections import defaultdict
import torch.optim
from torch import nn
class Base(nn.Module):
registered = defaultdict(dict)
@dataclass
class Config:
pass
@property
def config(self):
return self._config
def __init__(self, *args, config: Config=None, **kwargs):
super().__init__(*args, **kwargs)
self._config = config
def __str__(self) ->str:
return self.__name__
@classmethod
def module(Child, Impl):
try:
Impl.name
except AttributeError:
msg = 'Class {Impl} has no attribute .name'
raise irtm.IRTMError(msg)
Base.registered[Child.__name__][Impl.name] = Impl
return Impl
@classmethod
def init(Child, *, name: str=None, **kwargs):
try:
if name is None:
name = 'noop'
A = Base.registered[Child.__name__][name]
except KeyError:
dicrep = yaml.dump(Base.registered, default_flow_style=False)
msg = (
f'could not find module "{name}"\n\navailable modules:\n{dicrep}'
)
raise irtm.IRTMError(msg)
config = A.Config(**kwargs)
log.info(f'! initializing {A.__name__} with {config}')
return A(config=config)
class Comparator(Base):
pass
@Comparator.module
class EuclideanComparator_1(Comparator):
name = 'euclidean 1'
def forward(self, X, Y):
return torch.dist(X, Y, p=2) / X.shape[0]
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from dataclasses import dataclass
from collections import defaultdict
import torch.optim
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_dist_div_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = libdevice.sqrt(tmp6)
tmp8 = 0.25
tmp9 = tmp7 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_dist_div_0[grid(1)](buf1, arg1_1, arg0_1, 1, 256,
num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class Base(nn.Module):
registered = defaultdict(dict)
@dataclass
class Config:
pass
@property
def config(self):
return self._config
def __init__(self, *args, config: Config=None, **kwargs):
super().__init__(*args, **kwargs)
self._config = config
def __str__(self) ->str:
return self.__name__
@classmethod
def module(Child, Impl):
try:
Impl.name
except AttributeError:
msg = 'Class {Impl} has no attribute .name'
raise irtm.IRTMError(msg)
Base.registered[Child.__name__][Impl.name] = Impl
return Impl
@classmethod
def init(Child, *, name: str=None, **kwargs):
try:
if name is None:
name = 'noop'
A = Base.registered[Child.__name__][name]
except KeyError:
dicrep = yaml.dump(Base.registered, default_flow_style=False)
msg = (
f'could not find module "{name}"\n\navailable modules:\n{dicrep}'
)
raise irtm.IRTMError(msg)
config = A.Config(**kwargs)
log.info(f'! initializing {A.__name__} with {config}')
return A(config=config)
class Comparator(Base):
pass
@Comparator.module
class EuclideanComparator_1New(Comparator):
name = 'euclidean 1'
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
lavis-nlp/irtm
|
EuclideanComparator_1
| false
| 10,407
|
[
"MIT"
] | 0
|
e6c96519918795cfaa0c09ef2d4164f451265518
|
https://github.com/lavis-nlp/irtm/tree/e6c96519918795cfaa0c09ef2d4164f451265518
|
AffineConstantFlow
|
import torch
from torch import Tensor
from torch import nn
class FlowBlock(nn.Module):
"""
Abstract base class for any flow blocks.
"""
def __init__(self, dimension):
super(FlowBlock, self).__init__()
self.dimension = dimension
def forward(self, x: 'Tensor') ->(Tensor, Tensor):
"""
When implemented, forward method will represent z = f(x) and log |det f'(x)/dx|
x: (*, dimension), z: (*, dimension) and log_det: (*, 1)
"""
raise NotImplementedError('Forward not implemented')
def inverse(self, z: 'Tensor') ->(Tensor, Tensor):
"""
When implemented, inverse method will represent x = f^-(z) and log |det f^-'(z)/dz|
z: (*, dimension), x: (*, dimension) and log_det: (*, 1)
"""
raise NotImplementedError('Inverse not implemented')
class AffineConstantFlow(FlowBlock):
"""
Scales + Shifts the flow by (learned) constants per dimension.
In NICE paper there is a Scaling layer which is a special case of this where t is None
"""
def __init__(self, dimension, scale=True, shift=True):
super().__init__(dimension)
zeros = torch.zeros(size=(1, dimension))
self.s = nn.Parameter(torch.randn(1, dimension, requires_grad=True)
) if scale else zeros
self.t = nn.Parameter(torch.randn(1, dimension, requires_grad=True)
) if shift else zeros
def forward(self, x) ->(Tensor, Tensor):
z = x * torch.exp(self.s) + self.t
log_det = torch.sum(self.s, dim=1)
return z, log_det.repeat(x.shape[0], 1)
def inverse(self, z) ->(Tensor, Tensor):
x = (z - self.t) * torch.exp(-self.s)
log_det = torch.sum(-self.s, dim=1)
return x, log_det.repeat(z.shape[0], 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dimension': 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
from torch import Tensor
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_exp_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')
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp3 = tmp0 * tmp2
tmp5 = tmp3 + tmp4
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_per_fused_repeat_sum_1(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 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.sum(tmp1, 1)[:, None]
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp3, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_exp_mul_0[grid(256)](primals_2, primals_1,
primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
triton_per_fused_repeat_sum_1[grid(1)](primals_1, buf2, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
return buf0, buf2, primals_1, primals_2
class FlowBlock(nn.Module):
"""
Abstract base class for any flow blocks.
"""
def __init__(self, dimension):
super(FlowBlock, self).__init__()
self.dimension = dimension
def forward(self, x: 'Tensor') ->(Tensor, Tensor):
"""
When implemented, forward method will represent z = f(x) and log |det f'(x)/dx|
x: (*, dimension), z: (*, dimension) and log_det: (*, 1)
"""
raise NotImplementedError('Forward not implemented')
def inverse(self, z: 'Tensor') ->(Tensor, Tensor):
"""
When implemented, inverse method will represent x = f^-(z) and log |det f^-'(z)/dz|
z: (*, dimension), x: (*, dimension) and log_det: (*, 1)
"""
raise NotImplementedError('Inverse not implemented')
class AffineConstantFlowNew(FlowBlock):
"""
Scales + Shifts the flow by (learned) constants per dimension.
In NICE paper there is a Scaling layer which is a special case of this where t is None
"""
def __init__(self, dimension, scale=True, shift=True):
super().__init__(dimension)
zeros = torch.zeros(size=(1, dimension))
self.s = nn.Parameter(torch.randn(1, dimension, requires_grad=True)
) if scale else zeros
self.t = nn.Parameter(torch.randn(1, dimension, requires_grad=True)
) if shift else zeros
def inverse(self, z) ->(Tensor, Tensor):
x = (z - self.t) * torch.exp(-self.s)
log_det = torch.sum(-self.s, dim=1)
return x, log_det.repeat(z.shape[0], 1)
def forward(self, input_0):
primals_1 = self.s
primals_3 = self.t
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
lleonart1984/generative_modeling
|
AffineConstantFlow
| false
| 10,408
|
[
"MIT"
] | 0
|
d47c53d34b9eb704b6e8b2c334262b53fe7f4f32
|
https://github.com/lleonart1984/generative_modeling/tree/d47c53d34b9eb704b6e8b2c334262b53fe7f4f32
|
MaxPoolingAggregator_1
|
import torch
from dataclasses import dataclass
from collections import defaultdict
import torch.optim
from torch import nn
class Base(nn.Module):
registered = defaultdict(dict)
@dataclass
class Config:
pass
@property
def config(self):
return self._config
def __init__(self, *args, config: Config=None, **kwargs):
super().__init__(*args, **kwargs)
self._config = config
def __str__(self) ->str:
return self.__name__
@classmethod
def module(Child, Impl):
try:
Impl.name
except AttributeError:
msg = 'Class {Impl} has no attribute .name'
raise irtm.IRTMError(msg)
Base.registered[Child.__name__][Impl.name] = Impl
return Impl
@classmethod
def init(Child, *, name: str=None, **kwargs):
try:
if name is None:
name = 'noop'
A = Base.registered[Child.__name__][name]
except KeyError:
dicrep = yaml.dump(Base.registered, default_flow_style=False)
msg = (
f'could not find module "{name}"\n\navailable modules:\n{dicrep}'
)
raise irtm.IRTMError(msg)
config = A.Config(**kwargs)
log.info(f'! initializing {A.__name__} with {config}')
return A(config=config)
class Aggregator(Base):
pass
@Aggregator.module
class MaxPoolingAggregator_1(Aggregator):
name = 'max 1'
def forward(self, X: 'torch.Tensor') ->torch.Tensor:
return X.max(axis=1).values
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from dataclasses import dataclass
from collections import defaultdict
import torch.optim
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class Base(nn.Module):
registered = defaultdict(dict)
@dataclass
class Config:
pass
@property
def config(self):
return self._config
def __init__(self, *args, config: Config=None, **kwargs):
super().__init__(*args, **kwargs)
self._config = config
def __str__(self) ->str:
return self.__name__
@classmethod
def module(Child, Impl):
try:
Impl.name
except AttributeError:
msg = 'Class {Impl} has no attribute .name'
raise irtm.IRTMError(msg)
Base.registered[Child.__name__][Impl.name] = Impl
return Impl
@classmethod
def init(Child, *, name: str=None, **kwargs):
try:
if name is None:
name = 'noop'
A = Base.registered[Child.__name__][name]
except KeyError:
dicrep = yaml.dump(Base.registered, default_flow_style=False)
msg = (
f'could not find module "{name}"\n\navailable modules:\n{dicrep}'
)
raise irtm.IRTMError(msg)
config = A.Config(**kwargs)
log.info(f'! initializing {A.__name__} with {config}')
return A(config=config)
class Aggregator(Base):
pass
@Aggregator.module
class MaxPoolingAggregator_1New(Aggregator):
name = 'max 1'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
lavis-nlp/irtm
|
MaxPoolingAggregator_1
| false
| 10,409
|
[
"MIT"
] | 0
|
e6c96519918795cfaa0c09ef2d4164f451265518
|
https://github.com/lavis-nlp/irtm/tree/e6c96519918795cfaa0c09ef2d4164f451265518
|
CPAMDec
|
from torch.nn import Module
import torch
from torch.nn import Conv2d
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn import Linear
from torch.nn.parameter import Parameter
class CPAMDec(Module):
"""
CPAM decoding module
"""
def __init__(self, in_channels):
super(CPAMDec, self).__init__()
self.softmax = Softmax(dim=-1)
self.scale = Parameter(torch.zeros(1))
self.conv_query = Conv2d(in_channels=in_channels, out_channels=
in_channels // 4, kernel_size=1)
self.conv_key = Linear(in_channels, in_channels // 4)
self.conv_value = Linear(in_channels, in_channels)
def forward(self, x, y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,M)
returns :
out : compact position attention feature
attention map: (H*W)*M
"""
m_batchsize, C, width, height = x.size()
m_batchsize, K, _M = y.size()
proj_query = self.conv_query(x).view(m_batchsize, -1, width * height
).permute(0, 2, 1)
proj_key = self.conv_key(y).view(m_batchsize, K, -1).permute(0, 2, 1)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.conv_value(y).permute(0, 2, 1)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, C, width, height)
out = self.scale * out + x
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
from torch.nn import Conv2d
from torch.nn import Parameter
from torch.nn import Softmax
from torch.nn import Linear
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_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, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (1,), (1,))
assert_size_stride(primals_5, (1, 4), (4, 1))
assert_size_stride(primals_6, (1,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_3, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 4, 4), (16, 16, 4, 1))
buf2 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_5
del primals_6
buf3 = reinterpret_tensor(buf0, (4, 1, 4, 4), (16, 1, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(64)](buf3, primals_4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_4
buf4 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (4, 16, 1), (16, 1, 0),
0), reinterpret_tensor(buf2, (4, 1, 4), (4, 1, 1), 0), out=buf4)
buf5 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf7)
del primals_7
del primals_8
buf8 = reinterpret_tensor(buf5, (4, 4, 16), (64, 16, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(buf7, (4, 4, 4), (16, 1, 4),
0), reinterpret_tensor(buf6, (4, 4, 16), (64, 1, 4), 0), out=buf8)
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_3[grid(256)](primals_9, buf8, primals_1,
buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
return buf9, primals_1, primals_3, primals_9, reinterpret_tensor(primals_2,
(16, 4), (4, 1), 0), buf6, buf8, reinterpret_tensor(buf7, (4, 4, 4),
(16, 4, 1), 0), reinterpret_tensor(buf3, (4, 1, 16), (16, 16, 1), 0
), reinterpret_tensor(buf2, (4, 4, 1), (4, 1, 1), 0)
class CPAMDecNew(Module):
"""
CPAM decoding module
"""
def __init__(self, in_channels):
super(CPAMDecNew, self).__init__()
self.softmax = Softmax(dim=-1)
self.scale = Parameter(torch.zeros(1))
self.conv_query = Conv2d(in_channels=in_channels, out_channels=
in_channels // 4, kernel_size=1)
self.conv_key = Linear(in_channels, in_channels // 4)
self.conv_value = Linear(in_channels, in_channels)
def forward(self, input_0, input_1):
primals_4 = self.scale
primals_3 = self.conv_query.weight
primals_6 = self.conv_query.bias
primals_5 = self.conv_key.weight
primals_9 = self.conv_key.bias
primals_7 = self.conv_value.weight
primals_8 = self.conv_value.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
bfjei2825401/siamban
|
CPAMDec
| false
| 10,410
|
[
"Apache-2.0"
] | 0
|
c41d58742b146dfc8960053453227c6e9fec1bac
|
https://github.com/bfjei2825401/siamban/tree/c41d58742b146dfc8960053453227c6e9fec1bac
|
LearnedPositionalEncoding
|
import torch
from torch import nn
class LayerNorm(nn.Module):
"""A layernorm module in the TF style (epsilon inside the square root)."""
def __init__(self, d_model, variance_epsilon=1e-12):
super().__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class LearnedPositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=100):
super(LearnedPositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
self.pos_embed = nn.Embedding(max_len, d_model)
self.layernorm = LayerNorm(d_model)
def forward(self, x):
seq_len = x.size(0)
pos = torch.arange(seq_len, dtype=torch.long, device=x.device)
pos = pos.unsqueeze(-1).expand(x.size()[:2])
x = x + self.pos_embed(pos)
return self.dropout(self.layernorm(x))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 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
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_arange_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_embedding_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
x2 = xindex // 16
x0 = xindex % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 100, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 100) | ~xmask,
'index out of bounds: 0 <= tmp4 < 100')
tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask)
tl.store(out_ptr0 + x4, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_mean_pow_sub_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
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x2), 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 * x2), 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 * x2), 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 + x2, tmp16, xmask)
tl.store(out_ptr1 + x2, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_sqrt_sub_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x3 = xindex
x4 = xindex % 64
x5 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr3 + x5, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr4 + x5, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 - tmp4
tmp7 = 1e-12
tmp8 = tmp6 + tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = tmp5 / tmp9
tmp11 = tmp0 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x3, tmp13, 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, (100, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.int64)
get_raw_stream(0)
triton_poi_fused_arange_0[grid(4)](buf0, 4, XBLOCK=4, num_warps=1,
num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_embedding_1[grid(64)](buf0, primals_2, buf1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_mean_pow_sub_2[grid(64)](primals_1, buf1, buf2,
buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_sqrt_sub_3[grid(256)](primals_3,
primals_1, buf1, buf2, buf3, primals_4, buf4, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf2
del buf3
del primals_4
return buf4, primals_1, primals_3, reinterpret_tensor(buf0, (4, 1), (1,
1), 0), buf1
class LayerNorm(nn.Module):
"""A layernorm module in the TF style (epsilon inside the square root)."""
def __init__(self, d_model, variance_epsilon=1e-12):
super().__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class LearnedPositionalEncodingNew(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=100):
super(LearnedPositionalEncodingNew, self).__init__()
self.dropout = nn.Dropout(p=dropout)
self.pos_embed = nn.Embedding(max_len, d_model)
self.layernorm = LayerNorm(d_model)
def forward(self, input_0):
primals_2 = self.pos_embed.weight
primals_3 = self.layernorm.gamma
primals_4 = self.layernorm.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
longnsl1998/vietocr
|
LearnedPositionalEncoding
| false
| 10,411
|
[
"Apache-2.0"
] | 0
|
686dd6c9d897e0401c20e7dcadb07a07c1dbc284
|
https://github.com/longnsl1998/vietocr/tree/686dd6c9d897e0401c20e7dcadb07a07c1dbc284
|
CrossNet
|
import torch
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
class CrossNet(nn.Module):
"""The Cross Network part of Deep&Cross Network model,
which leans both low and high degree cross feature.
Input shape
- 2D tensor with shape: ``(batch_size, units)``.
Output shape
- 2D tensor with shape: ``(batch_size, units)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **input_feature_num**: Positive integer, shape(Input tensor)[-1]
- **layer_num**: Positive integer, the cross layer number
- **parameterization**: string, ``"vector"`` or ``"matrix"`` , way to parameterize the cross network.
- **l2_reg**: float between 0 and 1. L2 regularizer strength applied to the kernel weights matrix
- **seed**: A Python integer to use as random seed.
References
- [Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12.](https://arxiv.org/abs/1708.05123)
- [Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Improved Deep & Cross Network for Feature Cross Learning in Web-scale Learning to Rank Systems[J]. 2020.](https://arxiv.org/abs/2008.13535)
"""
def __init__(self, in_features, layer_num=2, parameterization='vector',
seed=1024, device='cpu'):
super(CrossNet, self).__init__()
self.layer_num = layer_num
self.parameterization = parameterization
if self.parameterization == 'vector':
self.kernels = nn.Parameter(torch.Tensor(self.layer_num,
in_features, 1))
elif self.parameterization == 'matrix':
self.kernels = nn.Parameter(torch.Tensor(self.layer_num,
in_features, in_features))
else:
raise ValueError("parameterization should be 'vector' or 'matrix'")
self.bias = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1))
for i in range(self.kernels.shape[0]):
nn.init.xavier_normal_(self.kernels[i])
for i in range(self.bias.shape[0]):
nn.init.zeros_(self.bias[i])
self
def forward(self, inputs):
x_0 = inputs.unsqueeze(2)
x_l = x_0
for i in range(self.layer_num):
if self.parameterization == 'vector':
xl_w = torch.tensordot(x_l, self.kernels[i], dims=([1], [0]))
dot_ = torch.matmul(x_0, xl_w)
x_l = dot_ + self.bias[i] + x_l
elif self.parameterization == 'matrix':
xl_w = torch.matmul(self.kernels[i], x_l)
dot_ = xl_w + self.bias[i]
x_l = x_0 * dot_ + x_l
else:
raise ValueError(
"parameterization should be 'vector' or 'matrix'")
x_l = torch.squeeze(x_l, dim=2)
return x_l
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__unsafe_view_clone_0(in_ptr0, out_ptr0, 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
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (16 * x1 + 64 * (y0 // 16) + y0 % 16), xmask &
ymask, eviction_policy='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x4 = xindex // 256
x5 = xindex // 16 % 16
x2 = xindex // 16 % 4
x6 = xindex // 4 % 16
x7 = xindex
tmp0 = tl.load(in_ptr0 + (x5 + 16 * x0 + 64 * x4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x6 + 16 * x0 + 64 * x4), xmask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + x7, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_squeeze_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex // 4
x1 = xindex // 4 % 4
x3 = xindex // 64
x6 = xindex % 16
x7 = xindex
tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + (x6 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp2 + tmp7
tl.store(out_ptr0 + x7, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (2, 4, 1), (4, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__unsafe_view_clone_0[grid(64, 4)](primals_1, buf0,
64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_2, (4, 1), (1, 1
), 0), out=buf1)
buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_clone_1[grid(1024)](primals_1, buf2, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
triton_poi_fused_clone_2[grid(256)](buf1, buf3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf1
buf4 = empty_strided_cuda((64, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf3, (64, 4, 1), (4, 1, 0), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_clone_3[grid(1024)](buf4, primals_3, primals_1,
buf5, 1024, XBLOCK=256, num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf3, (256, 1), (1, 1), 0)
del buf3
extern_kernels.mm(reinterpret_tensor(buf5, (256, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 1), (1, 1), 4), out=buf6)
buf7 = empty_strided_cuda((64, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf6, (64, 4, 1), (4, 1, 1), 0), out=buf7)
del buf6
buf8 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_add_squeeze_4[grid(1024)](buf7, primals_3, buf4,
primals_1, buf8, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del buf4
del buf7
del primals_1
del primals_3
return buf8, reinterpret_tensor(buf2, (64, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf5, (4, 256), (1, 4), 0), reinterpret_tensor(
primals_2, (1, 4), (1, 1), 4), reinterpret_tensor(buf0, (4, 64), (1,
4), 0)
class CrossNetNew(nn.Module):
"""The Cross Network part of Deep&Cross Network model,
which leans both low and high degree cross feature.
Input shape
- 2D tensor with shape: ``(batch_size, units)``.
Output shape
- 2D tensor with shape: ``(batch_size, units)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **input_feature_num**: Positive integer, shape(Input tensor)[-1]
- **layer_num**: Positive integer, the cross layer number
- **parameterization**: string, ``"vector"`` or ``"matrix"`` , way to parameterize the cross network.
- **l2_reg**: float between 0 and 1. L2 regularizer strength applied to the kernel weights matrix
- **seed**: A Python integer to use as random seed.
References
- [Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12.](https://arxiv.org/abs/1708.05123)
- [Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Improved Deep & Cross Network for Feature Cross Learning in Web-scale Learning to Rank Systems[J]. 2020.](https://arxiv.org/abs/2008.13535)
"""
def __init__(self, in_features, layer_num=2, parameterization='vector',
seed=1024, device='cpu'):
super(CrossNetNew, self).__init__()
self.layer_num = layer_num
self.parameterization = parameterization
if self.parameterization == 'vector':
self.kernels = nn.Parameter(torch.Tensor(self.layer_num,
in_features, 1))
elif self.parameterization == 'matrix':
self.kernels = nn.Parameter(torch.Tensor(self.layer_num,
in_features, in_features))
else:
raise ValueError("parameterization should be 'vector' or 'matrix'")
self.bias = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1))
for i in range(self.kernels.shape[0]):
nn.init.xavier_normal_(self.kernels[i])
for i in range(self.bias.shape[0]):
nn.init.zeros_(self.bias[i])
self
def forward(self, input_0):
primals_2 = self.kernels
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
CrossNet
| false
| 10,412
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
ExtResNetBlock
|
import torch
from torch import nn
def conv3d(in_channels, out_channels, kernel_size, bias, padding=1):
return nn.Conv3d(in_channels, out_channels, kernel_size, padding=
padding, bias=bias)
def create_conv(in_channels, out_channels, kernel_size, order, num_groups,
padding=1):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
order (string): order of things, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
padding (int): add zero-padding to the input
Return:
list of tuple (name, module)
"""
assert 'c' in order, 'Conv layer MUST be present'
assert order[0
] not in 'rle', 'Non-linearity cannot be the first operation in the layer'
modules = []
for i, char in enumerate(order):
if char == 'r':
modules.append(('ReLU', nn.ReLU(inplace=True)))
elif char == 'l':
modules.append(('LeakyReLU', nn.LeakyReLU(negative_slope=0.1,
inplace=True)))
elif char == 'e':
modules.append(('ELU', nn.ELU(inplace=True)))
elif char == 'c':
bias = not ('g' in order or 'b' in order)
modules.append(('conv', conv3d(in_channels, out_channels,
kernel_size, bias, padding=padding)))
elif char == 'g':
is_before_conv = i < order.index('c')
assert not is_before_conv, 'GroupNorm MUST go after the Conv3d'
if out_channels < num_groups:
num_groups = out_channels
modules.append(('groupnorm', nn.GroupNorm(num_groups=num_groups,
num_channels=out_channels)))
elif char == 'b':
is_before_conv = i < order.index('c')
if is_before_conv:
modules.append(('batchnorm', nn.BatchNorm3d(in_channels)))
else:
modules.append(('batchnorm', nn.BatchNorm3d(out_channels)))
else:
raise ValueError(
f"Unsupported layer type '{char}'. MUST be one of ['b', 'g', 'r', 'l', 'e', 'c']"
)
return modules
class SingleConv(nn.Sequential):
"""
Basic convolutional module consisting of a Conv3d, non-linearity and optional batchnorm/groupnorm. The order
of operations can be specified via the `order` parameter
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'crg', num_groups=8, padding=1):
super(SingleConv, self).__init__()
for name, module in create_conv(in_channels, out_channels,
kernel_size, order, num_groups, padding=padding):
self.add_module(name, module)
class ExtResNetBlock(nn.Module):
"""
Basic UNet block consisting of a SingleConv followed by the residual block.
The SingleConv takes care of increasing/decreasing the number of channels and also ensures that the number
of output channels is compatible with the residual block that follows.
This block can be used instead of standard DoubleConv in the Encoder module.
Motivated by: https://arxiv.org/pdf/1706.00120.pdf
Notice we use ELU instead of ReLU (order='cge') and put non-linearity after the groupnorm.
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'cge', num_groups=8, **kwargs):
super(ExtResNetBlock, self).__init__()
self.conv1 = SingleConv(in_channels, out_channels, kernel_size=
kernel_size, order=order, num_groups=num_groups)
self.conv2 = SingleConv(out_channels, out_channels, kernel_size=
kernel_size, order=order, num_groups=num_groups)
n_order = order
for c in 'rel':
n_order = n_order.replace(c, '')
self.conv3 = SingleConv(out_channels, out_channels, kernel_size=
kernel_size, order=n_order, num_groups=num_groups)
if 'l' in order:
self.non_linearity = nn.LeakyReLU(negative_slope=0.1, inplace=True)
elif 'e' in order:
self.non_linearity = nn.ELU(inplace=True)
else:
self.non_linearity = nn.ReLU(inplace=True)
def forward(self, x):
out = self.conv1(x)
residual = out
out = self.conv2(out)
out = self.conv3(out)
out += residual
out = self.non_linearity(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_elu_native_group_norm_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, out_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 16.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 = 1.0
tmp31 = tmp27 * tmp30
tmp32 = libdevice.expm1(tmp31)
tmp33 = tmp32 * tmp30
tmp34 = tl.where(tmp29, tmp31, tmp33)
tl.store(in_out_ptr0 + (r1 + 16 * x0), tmp34, xmask)
tl.store(out_ptr2 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_per_fused_add_elu_native_group_norm_1(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr3 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 16.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp29 = tmp27 + tmp28
tmp30 = 0.0
tmp31 = tmp29 > tmp30
tmp32 = 1.0
tmp33 = tmp29 * tmp32
tmp34 = libdevice.expm1(tmp33)
tmp35 = tmp34 * tmp32
tmp36 = tl.where(tmp31, tmp33, tmp35)
tl.store(in_out_ptr0 + (r1 + 16 * x0), tmp36, xmask)
tl.store(out_ptr2 + x0, tmp22, 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, primals_8, primals_9, primals_10) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3, 3), (108, 27, 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, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_2, (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, 1, 1), (4, 1, 16, 16), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf6 = buf4
del buf4
buf5 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
get_raw_stream(0)
triton_per_fused_elu_native_group_norm_0[grid(16)](buf6, buf0,
primals_3, primals_4, buf1, buf5, 16, 16, XBLOCK=8, num_warps=2,
num_stages=1)
del primals_4
buf7 = extern_kernels.convolution(reinterpret_tensor(buf6, (1, 4, 4,
4, 4), (256, 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((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf13 = buf11
del buf11
buf12 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
triton_per_fused_elu_native_group_norm_0[grid(16)](buf13, buf7,
primals_6, primals_7, buf8, buf12, 16, 16, XBLOCK=8, num_warps=
2, num_stages=1)
del primals_7
buf14 = extern_kernels.convolution(reinterpret_tensor(buf13, (1, 4,
4, 4, 4), (256, 64, 16, 4, 1), 0), primals_8, 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(buf14, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf15 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf19 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf20 = buf19
del buf19
buf18 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
triton_per_fused_add_elu_native_group_norm_1[grid(16)](buf20, buf14,
primals_9, primals_10, buf6, buf15, buf18, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del primals_10
return (buf20, primals_1, primals_3, primals_5, primals_6, primals_8,
primals_9, reinterpret_tensor(primals_2, (1, 4, 4, 4, 4), (256, 64,
16, 4, 1), 0), buf0, reinterpret_tensor(buf1, (4, 4), (4, 1), 0),
reinterpret_tensor(buf5, (4, 4), (4, 1), 0), buf6, buf7,
reinterpret_tensor(buf8, (4, 4), (4, 1), 0), reinterpret_tensor(
buf12, (4, 4), (4, 1), 0), buf13, buf14, reinterpret_tensor(buf15,
(4, 4), (4, 1), 0), reinterpret_tensor(buf18, (4, 4), (4, 1), 0), buf20
)
def conv3d(in_channels, out_channels, kernel_size, bias, padding=1):
return nn.Conv3d(in_channels, out_channels, kernel_size, padding=
padding, bias=bias)
def create_conv(in_channels, out_channels, kernel_size, order, num_groups,
padding=1):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
order (string): order of things, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
padding (int): add zero-padding to the input
Return:
list of tuple (name, module)
"""
assert 'c' in order, 'Conv layer MUST be present'
assert order[0
] not in 'rle', 'Non-linearity cannot be the first operation in the layer'
modules = []
for i, char in enumerate(order):
if char == 'r':
modules.append(('ReLU', nn.ReLU(inplace=True)))
elif char == 'l':
modules.append(('LeakyReLU', nn.LeakyReLU(negative_slope=0.1,
inplace=True)))
elif char == 'e':
modules.append(('ELU', nn.ELU(inplace=True)))
elif char == 'c':
bias = not ('g' in order or 'b' in order)
modules.append(('conv', conv3d(in_channels, out_channels,
kernel_size, bias, padding=padding)))
elif char == 'g':
is_before_conv = i < order.index('c')
assert not is_before_conv, 'GroupNorm MUST go after the Conv3d'
if out_channels < num_groups:
num_groups = out_channels
modules.append(('groupnorm', nn.GroupNorm(num_groups=num_groups,
num_channels=out_channels)))
elif char == 'b':
is_before_conv = i < order.index('c')
if is_before_conv:
modules.append(('batchnorm', nn.BatchNorm3d(in_channels)))
else:
modules.append(('batchnorm', nn.BatchNorm3d(out_channels)))
else:
raise ValueError(
f"Unsupported layer type '{char}'. MUST be one of ['b', 'g', 'r', 'l', 'e', 'c']"
)
return modules
class SingleConv(nn.Sequential):
"""
Basic convolutional module consisting of a Conv3d, non-linearity and optional batchnorm/groupnorm. The order
of operations can be specified via the `order` parameter
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size (int): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'crg', num_groups=8, padding=1):
super(SingleConv, self).__init__()
for name, module in create_conv(in_channels, out_channels,
kernel_size, order, num_groups, padding=padding):
self.add_module(name, module)
class ExtResNetBlockNew(nn.Module):
"""
Basic UNet block consisting of a SingleConv followed by the residual block.
The SingleConv takes care of increasing/decreasing the number of channels and also ensures that the number
of output channels is compatible with the residual block that follows.
This block can be used instead of standard DoubleConv in the Encoder module.
Motivated by: https://arxiv.org/pdf/1706.00120.pdf
Notice we use ELU instead of ReLU (order='cge') and put non-linearity after the groupnorm.
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order=
'cge', num_groups=8, **kwargs):
super(ExtResNetBlockNew, self).__init__()
self.conv1 = SingleConv(in_channels, out_channels, kernel_size=
kernel_size, order=order, num_groups=num_groups)
self.conv2 = SingleConv(out_channels, out_channels, kernel_size=
kernel_size, order=order, num_groups=num_groups)
n_order = order
for c in 'rel':
n_order = n_order.replace(c, '')
self.conv3 = SingleConv(out_channels, out_channels, kernel_size=
kernel_size, order=n_order, num_groups=num_groups)
if 'l' in order:
self.non_linearity = nn.LeakyReLU(negative_slope=0.1, inplace=True)
elif 'e' in order:
self.non_linearity = nn.ELU(inplace=True)
else:
self.non_linearity = nn.ReLU(inplace=True)
def forward(self, input_0):
primals_1 = self.conv1.conv.weight
primals_3 = self.conv1.groupnorm.weight
primals_4 = self.conv1.groupnorm.bias
primals_5 = self.conv2.conv.weight
primals_6 = self.conv2.groupnorm.weight
primals_7 = self.conv2.groupnorm.bias
primals_8 = self.conv3.conv.weight
primals_9 = self.conv3.groupnorm.weight
primals_10 = self.conv3.groupnorm.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9, primals_10])
return output[0]
|
joowlim/pytorch-3dunet
|
ExtResNetBlock
| false
| 10,413
|
[
"MIT"
] | 0
|
d08049f60b619627521efd0fb171247e1536b262
|
https://github.com/joowlim/pytorch-3dunet/tree/d08049f60b619627521efd0fb171247e1536b262
|
QNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=296,
fc2_units=296):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, action_size)
def forward(self, state):
"""Build a network that maps state -> action values."""
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
return self.fc3(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 18944
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 296
x2 = xindex % 1184
x3 = xindex // 1184
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1280 * x3), tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (296, 4), (4, 1))
assert_size_stride(primals_2, (296,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (296, 296), (296, 1))
assert_size_stride(primals_5, (296,), (1,))
assert_size_stride(primals_6, (4, 296), (296, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 296), (296, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 296), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 296), (4736, 1184, 296, 1), 0
)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 296), (5120, 1280, 296, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(18944)](buf1,
primals_2, buf6, 18944, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 296), (296, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 296), (296, 1), 0),
reinterpret_tensor(primals_4, (296, 296), (1, 296), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 296), (4736, 1184, 296, 1), 0
)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 296), (5120, 1280, 296, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(18944)](buf3,
primals_5, buf5, 18944, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 296),
(296, 1), 0), reinterpret_tensor(primals_6, (296, 4), (1, 296),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 296), (296, 1), 0
), reinterpret_tensor(buf3, (64, 296), (296, 1), 0
), primals_6, buf5, primals_4, buf6
class QNetworkNew(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=296,
fc2_units=296):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(QNetworkNew, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, action_size)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
luiz-rocha94/navigation
|
QNetwork
| false
| 10,414
|
[
"MIT"
] | 0
|
fd5e00d8b9051e82dfe15793e53f8d1f86e8ecbe
|
https://github.com/luiz-rocha94/navigation/tree/fd5e00d8b9051e82dfe15793e53f8d1f86e8ecbe
|
Coskx
|
import torch
from torch import nn
class Coskx(nn.Module):
def __init__(self, k=50):
super(Coskx, self).__init__()
self.k = k
def forward(self, input):
return torch.cos(input * self.k)
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
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_cos_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 = 50.0
tmp2 = tmp0 * tmp1
tmp3 = tl_math.cos(tmp2)
tl.store(out_ptr0 + x0, tmp3, 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_cos_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class CoskxNew(nn.Module):
def __init__(self, k=50):
super(CoskxNew, self).__init__()
self.k = k
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiaj15/SAIL
|
Coskx
| false
| 10,415
|
[
"MIT"
] | 0
|
734be06a2b0ae70801f59c191b86332592da97cf
|
https://github.com/jiaj15/SAIL/tree/734be06a2b0ae70801f59c191b86332592da97cf
|
GroupNorm32
|
import torch
import torch.nn.functional as F
from torch import nn
class GroupNorm32(nn.GroupNorm):
def __init__(self, num_groups, num_channels, swish, eps=1e-05):
super().__init__(num_groups=num_groups, num_channels=num_channels,
eps=eps)
self.swish = swish
def forward(self, x):
y = super().forward(x.float())
if self.swish == 1.0:
y = F.silu(y)
elif self.swish:
y = y * F.sigmoid(y * float(self.swish))
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_groups': 1, 'num_channels': 4, 'swish': 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
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_mul_native_group_norm_sigmoid_0(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, 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
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, 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 = 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 = 4.0
tmp29 = tmp27 * tmp28
tmp30 = tl.sigmoid(tmp29)
tmp31 = tmp27 * tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(in_out_ptr1 + (r1 + 64 * x0), tmp31, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 1, 1, 1), torch.float32)
buf1 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf3 = reinterpret_tensor(buf1, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = buf4
del buf4
get_raw_stream(0)
triton_per_fused_mul_native_group_norm_sigmoid_0[grid(4)](buf3,
buf5, primals_1, primals_2, primals_3, buf0, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
return buf5, primals_1, primals_2, primals_3, buf0, buf3
class GroupNorm32New(nn.GroupNorm):
def __init__(self, num_groups, num_channels, swish, eps=1e-05):
super().__init__(num_groups=num_groups, num_channels=num_channels,
eps=eps)
self.swish = swish
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]
|
litevxx/glid-3
|
GroupNorm32
| false
| 10,416
|
[
"MIT"
] | 0
|
d7bd53e671d642b0cbc8af81197170b585c7e624
|
https://github.com/litevxx/glid-3/tree/d7bd53e671d642b0cbc8af81197170b585c7e624
|
Qnet
|
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
class Qnet(nn.Module):
def __init__(self):
super(Qnet, self).__init__()
self.fc1 = nn.Linear(4, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 2)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def get_action(self, obs, epsilon):
out = self.forward(obs)
coin = random.random()
if coin < epsilon:
return random.randint(0, 1)
else:
return out.argmax().item()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import random
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
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, (128, 4), (4, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 128), (128, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (2, 128), (128, 1))
assert_size_stride(primals_7, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 128), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1,
primals_2, buf6, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_4, (128, 128), (1, 128), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf3,
primals_5, buf5, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_6, (128, 2), (1, 128),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 2), (32, 8, 2, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 128), (128, 1), 0
), reinterpret_tensor(buf3, (64, 128), (128, 1), 0
), primals_6, buf5, primals_4, buf6
class QnetNew(nn.Module):
def __init__(self):
super(QnetNew, self).__init__()
self.fc1 = nn.Linear(4, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 2)
def get_action(self, obs, epsilon):
out = self.forward(obs)
coin = random.random()
if coin < epsilon:
return random.randint(0, 1)
else:
return out.argmax().item()
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
linklab/link_rl_book_codes
|
Qnet
| false
| 10,417
|
[
"MIT"
] | 0
|
b272b46d5ecd2802f34648440ff53641c68cbbf0
|
https://github.com/linklab/link_rl_book_codes/tree/b272b46d5ecd2802f34648440ff53641c68cbbf0
|
ScaledDotAttention
|
import torch
import torch.nn as nn
from torch.nn import LayerNorm
def scaled_dot_attention(q, k, v, mask=None, noise=0, dropout=lambda x: x):
"""
:param q: queries, (batch, time1, channels1)
:param k: keys, (batch, time2, channels1)
:param v: values, (batch, time2, channels2)
:param mask: boolean mask, (batch, time1, time2)
:param dropout: a dropout function - this allows keeping dropout as a module -> better control when training/eval
:return: (batch, time1, channels2), (batch, time1, time2)
"""
weights = torch.matmul(q, k.transpose(2, 1))
if mask is not None:
weights = weights.masked_fill(~mask, float('-inf'))
if noise:
weights += noise * torch.randn(weights.shape)
weights = torch.softmax(weights, dim=-1)
weights = dropout(weights)
result = torch.matmul(weights, v)
return result, weights
def mask(x, lengths, dim=-1):
assert dim != 0, 'Masking not available for batch dimension'
assert len(lengths) == x.shape[0
], 'Lengths must contain as many elements as there are items in the batch'
lengths = torch.as_tensor(lengths)
to_expand = [1] * (x.ndim - 1) + [-1]
mask = torch.arange(x.shape[dim]).expand(to_expand).transpose(dim, -1
).expand(x.shape)
mask = mask < lengths.expand(to_expand).transpose(0, -1)
return mask
class Conv1d(nn.Conv1d):
"""A wrapper around nn.Conv1d, that works on (batch, time, channels)"""
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
dilation=1, groups=1, bias=True, padding=0):
super(Conv1d, self).__init__(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, dilation=
dilation, groups=groups, bias=bias, padding=padding)
def forward(self, x):
return super().forward(x.transpose(2, 1)).transpose(2, 1)
class ScaledDotAttention(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, noise=0,
normalize=False, dropout=False):
super(ScaledDotAttention, self).__init__()
self.noise = noise
self.dropout = torch.nn.Dropout(p=dropout)
self.normalize = normalize
self.fc_query = Conv1d(in_channels, hidden_channels)
self.fc_keys = Conv1d(in_channels, hidden_channels)
if normalize:
self.qnorm = LayerNorm(in_channels)
self.knorm = LayerNorm(in_channels)
self.fc_keys.weight = torch.nn.Parameter(self.fc_query.weight.clone())
self.fc_keys.bias = torch.nn.Parameter(self.fc_query.bias.clone())
self.fc_values = Conv1d(in_channels, hidden_channels)
self.fc_out = Conv1d(hidden_channels, out_channels)
def forward(self, q, k, v, mask=None):
"""
:param q: queries, (batch, time1, channels1)
:param k: keys, (batch, time2, channels1)
:param v: values, (batch, time2, channels2)
:param mask: boolean mask, (batch, time1, time2)
:return: (batch, time1, channels2), (batch, time1, time2)
"""
noise = self.noise if self.training else 0
if self.normalize:
q = self.qnorm(q)
k = self.knorm(k)
alignment, weights = scaled_dot_attention(self.fc_query(q), self.
fc_keys(k), self.fc_values(v), mask, noise=noise, dropout=self.
dropout)
alignment = self.fc_out(alignment)
return alignment, weights
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'in_channels': 4, 'hidden_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 math as tl_math
import torch.nn as nn
from torch.nn import LayerNorm
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_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__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
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 = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4), (16, 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, 4, 4), (16, 4, 1))
assert_size_stride(primals_8, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(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 = buf0
del buf0
triton_poi_fused_convolution_0[grid(16, 4)](primals_4, buf2, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
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 = buf2
del buf2
triton_poi_fused_convolution_0[grid(16, 4)](primals_7, buf4, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf5 = extern_kernels.convolution(buf4, primals_8, 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 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf6, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf7 = buf3
del buf3
triton_poi_fused_convolution_1[grid(64)](buf7, primals_6, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_6
buf8 = buf4
del buf4
extern_kernels.bmm(reinterpret_tensor(buf6, (4, 4, 4), (16, 1, 4),
0), buf7, out=buf8)
buf9 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(64)](buf8, buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf10 = buf8
del buf8
triton_poi_fused__softmax_3[grid(64)](buf9, buf10, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf11 = buf5
del buf5
triton_poi_fused_convolution_1[grid(64)](buf11, primals_9, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf12 = buf9
del buf9
extern_kernels.bmm(buf10, reinterpret_tensor(buf11, (4, 4, 4), (16,
1, 4), 0), out=buf12)
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_convolution_0[grid(16, 4)](buf12, buf13, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf14 = extern_kernels.convolution(buf13, primals_10, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf14, (4, 4, 4), (16, 4, 1))
del buf13
buf15 = buf14
del buf14
triton_poi_fused_convolution_1[grid(64)](buf15, primals_11, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_11
return reinterpret_tensor(buf15, (4, 4, 4), (16, 1, 4), 0
), buf10, primals_2, primals_5, primals_8, primals_10, reinterpret_tensor(
primals_1, (4, 4, 4), (16, 1, 4), 0), reinterpret_tensor(primals_4,
(4, 4, 4), (16, 1, 4), 0), reinterpret_tensor(primals_7, (4, 4, 4),
(16, 1, 4), 0), buf10, reinterpret_tensor(buf12, (4, 4, 4), (16, 1,
4), 0), buf11, buf6, reinterpret_tensor(buf7, (4, 4, 4), (16, 1, 4), 0)
def scaled_dot_attention(q, k, v, mask=None, noise=0, dropout=lambda x: x):
"""
:param q: queries, (batch, time1, channels1)
:param k: keys, (batch, time2, channels1)
:param v: values, (batch, time2, channels2)
:param mask: boolean mask, (batch, time1, time2)
:param dropout: a dropout function - this allows keeping dropout as a module -> better control when training/eval
:return: (batch, time1, channels2), (batch, time1, time2)
"""
weights = torch.matmul(q, k.transpose(2, 1))
if mask is not None:
weights = weights.masked_fill(~mask, float('-inf'))
if noise:
weights += noise * torch.randn(weights.shape)
weights = torch.softmax(weights, dim=-1)
weights = dropout(weights)
result = torch.matmul(weights, v)
return result, weights
def mask(x, lengths, dim=-1):
assert dim != 0, 'Masking not available for batch dimension'
assert len(lengths) == x.shape[0
], 'Lengths must contain as many elements as there are items in the batch'
lengths = torch.as_tensor(lengths)
to_expand = [1] * (x.ndim - 1) + [-1]
mask = torch.arange(x.shape[dim]).expand(to_expand).transpose(dim, -1
).expand(x.shape)
mask = mask < lengths.expand(to_expand).transpose(0, -1)
return mask
class Conv1d(nn.Conv1d):
"""A wrapper around nn.Conv1d, that works on (batch, time, channels)"""
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
dilation=1, groups=1, bias=True, padding=0):
super(Conv1d, self).__init__(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, dilation=
dilation, groups=groups, bias=bias, padding=padding)
def forward(self, x):
return super().forward(x.transpose(2, 1)).transpose(2, 1)
class ScaledDotAttentionNew(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, noise=0,
normalize=False, dropout=False):
super(ScaledDotAttentionNew, self).__init__()
self.noise = noise
self.dropout = torch.nn.Dropout(p=dropout)
self.normalize = normalize
self.fc_query = Conv1d(in_channels, hidden_channels)
self.fc_keys = Conv1d(in_channels, hidden_channels)
if normalize:
self.qnorm = LayerNorm(in_channels)
self.knorm = LayerNorm(in_channels)
self.fc_keys.weight = torch.nn.Parameter(self.fc_query.weight.clone())
self.fc_keys.bias = torch.nn.Parameter(self.fc_query.bias.clone())
self.fc_values = Conv1d(in_channels, hidden_channels)
self.fc_out = Conv1d(hidden_channels, out_channels)
def forward(self, input_0, input_1, input_2):
primals_2 = self.fc_query.weight
primals_3 = self.fc_query.bias
primals_5 = self.fc_keys.weight
primals_6 = self.fc_keys.bias
primals_8 = self.fc_values.weight
primals_9 = self.fc_values.bias
primals_10 = self.fc_out.weight
primals_11 = self.fc_out.bias
primals_1 = input_0
primals_4 = input_1
primals_7 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1]
|
iclementine/speedyspeech
|
ScaledDotAttention
| false
| 10,418
|
[
"BSD-3-Clause"
] | 0
|
db527587a3699b71082d61c9e9fad7ed795d1980
|
https://github.com/iclementine/speedyspeech/tree/db527587a3699b71082d61c9e9fad7ed795d1980
|
Decoder
|
import torch
import torch.nn.functional as F
from torch import nn
def weights_init_(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight, gain=1)
torch.nn.init.constant_(m.bias, 0)
class Decoder(torch.nn.Module):
def __init__(self, input_dim, out_dim, hidden_size=128):
super(Decoder, self).__init__()
self.linear1 = torch.nn.Linear(input_dim, hidden_size)
self.linear2 = torch.nn.Linear(hidden_size, hidden_size)
self.linear3 = torch.nn.Linear(hidden_size, out_dim)
self.apply(weights_init_)
def forward(self, x):
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = self.linear3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
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, (128, 4), (4, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 128), (128, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (4, 128), (128, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 128), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1,
primals_2, buf6, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_4, (128, 128), (1, 128), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf3,
primals_5, buf5, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_6, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 128), (128, 1), 0
), reinterpret_tensor(buf3, (64, 128), (128, 1), 0
), primals_6, buf5, primals_4, buf6
def weights_init_(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight, gain=1)
torch.nn.init.constant_(m.bias, 0)
class DecoderNew(torch.nn.Module):
def __init__(self, input_dim, out_dim, hidden_size=128):
super(DecoderNew, self).__init__()
self.linear1 = torch.nn.Linear(input_dim, hidden_size)
self.linear2 = torch.nn.Linear(hidden_size, hidden_size)
self.linear3 = torch.nn.Linear(hidden_size, out_dim)
self.apply(weights_init_)
def forward(self, input_0):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_6 = self.linear3.weight
primals_7 = self.linear3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jiaj15/SAIL
|
Decoder
| false
| 10,419
|
[
"MIT"
] | 0
|
734be06a2b0ae70801f59c191b86332592da97cf
|
https://github.com/jiaj15/SAIL/tree/734be06a2b0ae70801f59c191b86332592da97cf
|
PolicyNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PolicyNetwork(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size=256):
super(PolicyNetwork, self).__init__()
self.num_actions = num_actions
self.linear1 = nn.Linear(num_inputs, hidden_size)
self.linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, state):
x = F.relu(self.linear1(state))
x = F.softmax(self.linear2(x), dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 256), (256, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf5, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_4, (256, 4), (1, 256),
0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf3
return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), buf4, primals_4, buf5
class PolicyNetworkNew(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size=256):
super(PolicyNetworkNew, self).__init__()
self.num_actions = num_actions
self.linear1 = nn.Linear(num_inputs, hidden_size)
self.linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, input_0):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
linklab/link_rl_book_codes
|
PolicyNetwork
| false
| 10,420
|
[
"MIT"
] | 0
|
b272b46d5ecd2802f34648440ff53641c68cbbf0
|
https://github.com/linklab/link_rl_book_codes/tree/b272b46d5ecd2802f34648440ff53641c68cbbf0
|
ActorCriticNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ActorCriticNetwork(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size=256):
super(ActorCriticNetwork, self).__init__()
self.num_actions = num_actions
self.critic_linear1 = nn.Linear(num_inputs, hidden_size)
self.critic_linear2 = nn.Linear(hidden_size, 1)
self.actor_linear1 = nn.Linear(num_inputs, hidden_size)
self.actor_linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, state_tensor):
value = F.relu(self.critic_linear1(state_tensor))
value = self.critic_linear2(value)
policy_dist = F.relu(self.actor_linear1(state_tensor))
policy_dist = F.softmax(self.actor_linear2(policy_dist), dim=1)
return value, policy_dist
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 256), (256, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (256, 4), (4, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (4, 256), (256, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf10 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf10, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_4, (256, 1), (1, 256),
0), alpha=1, beta=1, out=buf3)
del primals_5
buf4 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 256), (1, 4), 0), out=buf4)
del primals_6
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf4
buf9 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf5,
primals_7, buf9, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_8, (256, 4), (1, 256),
0), alpha=1, beta=1, out=buf6)
del primals_9
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf6
triton_poi_fused__softmax_2[grid(256)](buf7, buf8, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf7
return reinterpret_tensor(buf3, (4, 4, 4, 1), (16, 4, 1, 1), 0
), buf8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), reinterpret_tensor(buf5, (64, 256), (256, 1), 0
), buf8, primals_8, buf9, primals_4, buf10
class ActorCriticNetworkNew(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size=256):
super(ActorCriticNetworkNew, self).__init__()
self.num_actions = num_actions
self.critic_linear1 = nn.Linear(num_inputs, hidden_size)
self.critic_linear2 = nn.Linear(hidden_size, 1)
self.actor_linear1 = nn.Linear(num_inputs, hidden_size)
self.actor_linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, input_0):
primals_1 = self.critic_linear1.weight
primals_2 = self.critic_linear1.bias
primals_4 = self.critic_linear2.weight
primals_5 = self.critic_linear2.bias
primals_6 = self.actor_linear1.weight
primals_7 = self.actor_linear1.bias
primals_8 = self.actor_linear2.weight
primals_9 = self.actor_linear2.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]
|
linklab/link_rl_book_codes
|
ActorCriticNetwork
| false
| 10,421
|
[
"MIT"
] | 0
|
b272b46d5ecd2802f34648440ff53641c68cbbf0
|
https://github.com/linklab/link_rl_book_codes/tree/b272b46d5ecd2802f34648440ff53641c68cbbf0
|
SE
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def swish(x):
return x * x.sigmoid()
class SE(nn.Module):
"""Squeeze-and-Excitation block with Swish."""
def __init__(self, in_planes, se_planes):
super(SE, self).__init__()
self.se1 = nn.Conv2d(in_planes, se_planes, kernel_size=1, bias=True)
self.se2 = nn.Conv2d(se_planes, in_planes, kernel_size=1, bias=True)
def forward(self, x):
out = F.adaptive_avg_pool2d(x, (1, 1))
out = swish(self.se1(out))
out = self.se2(out).sigmoid()
out = x * out
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'se_planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_mul_sigmoid_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1, 1), (4, 1, 1, 1))
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
triton_poi_fused_convolution_mul_sigmoid_1[grid(16)](buf3,
primals_3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf5 = extern_kernels.convolution(buf4, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 1, 1), (4, 1, 1, 1))
buf6 = buf5
del buf5
triton_poi_fused_convolution_2[grid(16)](buf6, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(256)](primals_1, buf6, buf7,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf7, primals_1, primals_2, primals_4, buf1, buf3, buf4, buf6
def swish(x):
return x * x.sigmoid()
class SENew(nn.Module):
"""Squeeze-and-Excitation block with Swish."""
def __init__(self, in_planes, se_planes):
super(SENew, self).__init__()
self.se1 = nn.Conv2d(in_planes, se_planes, kernel_size=1, bias=True)
self.se2 = nn.Conv2d(se_planes, in_planes, kernel_size=1, bias=True)
def forward(self, input_0):
primals_2 = self.se1.weight
primals_3 = self.se1.bias
primals_4 = self.se2.weight
primals_5 = self.se2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
liormagram/pytorch-cifar
|
SE
| false
| 10,422
|
[
"MIT"
] | 0
|
2ed0fabe6cbd4a468c5c4d155fb76c5b9ad4a764
|
https://github.com/liormagram/pytorch-cifar/tree/2ed0fabe6cbd4a468c5c4d155fb76c5b9ad4a764
|
MultiHeadQKVAttention
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_k': 4, 'd_v': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
del primals_4
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf1)
del primals_6
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf2)
del primals_8
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4, 16)](buf0, primals_5, buf3, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_5
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_7, buf4, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_7
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_9, buf8, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_9
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_11, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_11
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttentionNew(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, input_0, input_1, input_2):
primals_4 = self.q_projector.weight
primals_5 = self.q_projector.bias
primals_6 = self.k_projector.weight
primals_7 = self.k_projector.bias
primals_8 = self.v_projector.weight
primals_9 = self.v_projector.bias
primals_10 = self.o_projector.weight
primals_11 = self.o_projector.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
karayanni/torch-scae
|
MultiHeadQKVAttention
| false
| 10,423
|
[
"Apache-2.0"
] | 0
|
e044662d8942d8d1923d13d071f375144cf4a1e8
|
https://github.com/karayanni/torch-scae/tree/e044662d8942d8d1923d13d071f375144cf4a1e8
|
AFMLayer
|
import itertools
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import *
import torch.onnx
import torch as torch
class AFMLayer(nn.Module):
"""Attentonal Factorization Machine models pairwise (order-2) feature
interactions without linear term and bias.
Input shape
- A list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.
Output shape
- 2D tensor with shape: ``(batch_size, 1)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **attention_factor** : Positive integer, dimensionality of the
attention network output space.
- **l2_reg_w** : float between 0 and 1. L2 regularizer strength
applied to attention network.
- **dropout_rate** : float between in [0,1). Fraction of the attention net output units to dropout.
- **seed** : A Python integer to use as random seed.
References
- [Attentional Factorization Machines : Learning the Weight of Feature
Interactions via Attention Networks](https://arxiv.org/pdf/1708.04617.pdf)
"""
def __init__(self, in_features, attention_factor=4, l2_reg_w=0,
dropout_rate=0, seed=1024, device='cpu'):
super(AFMLayer, self).__init__()
self.attention_factor = attention_factor
self.l2_reg_w = l2_reg_w
self.dropout_rate = dropout_rate
self.seed = seed
embedding_size = in_features
self.attention_W = nn.Parameter(torch.Tensor(embedding_size, self.
attention_factor))
self.attention_b = nn.Parameter(torch.Tensor(self.attention_factor))
self.projection_h = nn.Parameter(torch.Tensor(self.attention_factor, 1)
)
self.projection_p = nn.Parameter(torch.Tensor(embedding_size, 1))
for tensor in [self.attention_W, self.projection_h, self.projection_p]:
nn.init.xavier_normal_(tensor)
for tensor in [self.attention_b]:
nn.init.zeros_(tensor)
self.dropout = nn.Dropout(dropout_rate)
self
def forward(self, inputs):
embeds_vec_list = inputs
row = []
col = []
for r, c in itertools.combinations(embeds_vec_list, 2):
row.append(r)
col.append(c)
p = torch.cat(row, dim=1)
q = torch.cat(col, dim=1)
inner_product = p * q
bi_interaction = inner_product
attention_temp = F.relu(torch.tensordot(bi_interaction, self.
attention_W, dims=([-1], [0])) + self.attention_b)
self.normalized_att_score = F.softmax(torch.tensordot(
attention_temp, self.projection_h, dims=([-1], [0])), dim=1)
attention_output = torch.sum(self.normalized_att_score *
bi_interaction, dim=1)
attention_output = self.dropout(attention_output)
afm_out = torch.tensordot(attention_output, self.projection_p, dims
=([-1], [0]))
return afm_out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
assert_size_stride = torch._C._dynamo.guards.assert_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_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 24
x0 = xindex % 4
x2 = xindex // 96
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (x0 + 4 * (-4 + x1) + 16 * x2), tmp9 & xmask,
other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (x0 + 4 * (-8 + x1) + 16 * x2), tmp14 & xmask,
other=0.0)
tmp16 = tmp0 >= tmp12
tmp17 = tl.full([1], 16, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr0 + (64 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 &
xmask, other=0.0)
tmp21 = tmp0 >= tmp17
tmp22 = tl.full([1], 20, tl.int64)
tmp23 = tmp0 < tmp22
tmp24 = tmp21 & tmp23
tmp25 = tl.load(in_ptr0 + (64 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 &
xmask, other=0.0)
tmp26 = tmp0 >= tmp22
tl.full([1], 24, tl.int64)
tmp29 = tl.load(in_ptr0 + (128 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 &
xmask, other=0.0)
tmp30 = tl.where(tmp24, tmp25, 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)
tmp35 = tl.load(in_ptr0 + (64 + x0 + 4 * x1 + 16 * x2), tmp4 & xmask,
other=0.0)
tmp36 = tl.load(in_ptr0 + (128 + x0 + 4 * (-4 + x1) + 16 * x2), tmp9 &
xmask, other=0.0)
tmp37 = tl.load(in_ptr0 + (192 + x0 + 4 * (-8 + x1) + 16 * x2), tmp14 &
xmask, other=0.0)
tmp38 = tl.load(in_ptr0 + (128 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 &
xmask, other=0.0)
tmp39 = tl.load(in_ptr0 + (192 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 &
xmask, other=0.0)
tmp40 = tl.load(in_ptr0 + (192 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 &
xmask, other=0.0)
tmp41 = tl.where(tmp24, tmp39, tmp40)
tmp42 = tl.where(tmp19, tmp38, tmp41)
tmp43 = tl.where(tmp14, tmp37, tmp42)
tmp44 = tl.where(tmp9, tmp36, tmp43)
tmp45 = tl.where(tmp4, tmp35, tmp44)
tmp46 = tmp34 * tmp45
tl.store(in_out_ptr0 + x3, tmp46, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 384
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_per_fused__softmax_2(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 4
rnumel = 24
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 24 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tmp6 / tmp10
tl.store(out_ptr2 + (r1 + 24 * x0), tmp11, rmask & xmask)
@triton.jit
def triton_per_fused_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
rnumel = 24
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r2 = rindex
x1 = xindex // 4
x0 = xindex % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (r2 + 24 * x1), rmask & xmask, eviction_policy
='evict_last', other=0.0)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * r2 + 96 * x1), rmask & xmask, other=0.0)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(rmask & xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
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), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 1), (1, 1))
assert_size_stride(primals_5, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_cat_mul_0[grid(384)](buf2, primals_1, 384, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_1
buf3 = empty_strided_cuda((96, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (96, 4), (4, 1), 0),
primals_2, out=buf3)
del primals_2
buf4 = reinterpret_tensor(buf3, (4, 24, 4), (96, 4, 1), 0)
del buf3
buf11 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_1[grid(384)](buf4,
primals_3, buf11, 384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf5 = empty_strided_cuda((96, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (96, 4), (4, 1), 0),
primals_4, out=buf5)
buf8 = empty_strided_cuda((4, 24, 1), (24, 1, 1), torch.float32)
triton_per_fused__softmax_2[grid(4)](buf5, buf8, 4, 24, XBLOCK=1,
num_warps=2, num_stages=1)
del buf5
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_per_fused_mul_sum_3[grid(16)](buf8, buf2, buf9, 16, 24,
XBLOCK=1, num_warps=2, num_stages=1)
buf10 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf9, primals_5, out=buf10)
return buf10, buf8, buf2, buf8, reinterpret_tensor(buf9, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_5, (1, 4), (1, 1), 0
), reinterpret_tensor(buf4, (4, 96), (1, 4), 0), reinterpret_tensor(
primals_4, (1, 4), (1, 1), 0), buf11
class AFMLayerNew(nn.Module):
"""Attentonal Factorization Machine models pairwise (order-2) feature
interactions without linear term and bias.
Input shape
- A list of 3D tensor with shape: ``(batch_size,1,embedding_size)``.
Output shape
- 2D tensor with shape: ``(batch_size, 1)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **attention_factor** : Positive integer, dimensionality of the
attention network output space.
- **l2_reg_w** : float between 0 and 1. L2 regularizer strength
applied to attention network.
- **dropout_rate** : float between in [0,1). Fraction of the attention net output units to dropout.
- **seed** : A Python integer to use as random seed.
References
- [Attentional Factorization Machines : Learning the Weight of Feature
Interactions via Attention Networks](https://arxiv.org/pdf/1708.04617.pdf)
"""
def __init__(self, in_features, attention_factor=4, l2_reg_w=0,
dropout_rate=0, seed=1024, device='cpu'):
super(AFMLayerNew, self).__init__()
self.attention_factor = attention_factor
self.l2_reg_w = l2_reg_w
self.dropout_rate = dropout_rate
self.seed = seed
embedding_size = in_features
self.attention_W = nn.Parameter(torch.Tensor(embedding_size, self.
attention_factor))
self.attention_b = nn.Parameter(torch.Tensor(self.attention_factor))
self.projection_h = nn.Parameter(torch.Tensor(self.attention_factor, 1)
)
self.projection_p = nn.Parameter(torch.Tensor(embedding_size, 1))
for tensor in [self.attention_W, self.projection_h, self.projection_p]:
nn.init.xavier_normal_(tensor)
for tensor in [self.attention_b]:
nn.init.zeros_(tensor)
self.dropout = nn.Dropout(dropout_rate)
self
def forward(self, input_0):
primals_2 = self.attention_W
primals_3 = self.attention_b
primals_4 = self.projection_h
primals_5 = self.projection_p
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
AFMLayer
| false
| 10,424
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
DRRN
|
import torch
import torch.nn as nn
from math import sqrt
class DRRN(nn.Module):
def __init__(self):
super(DRRN, self).__init__()
self.input = nn.Conv2d(in_channels=1, out_channels=128, kernel_size
=3, stride=1, padding=1, bias=False)
self.conv1 = nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=3, stride=1, padding=1, bias=False)
self.conv2 = nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=3, stride=1, padding=1, bias=False)
self.output = nn.Conv2d(in_channels=128, out_channels=1,
kernel_size=3, stride=1, padding=1, bias=False)
self.relu = nn.ReLU(inplace=True)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, sqrt(2.0 / n))
def forward(self, x):
residual = x
inputs = self.input(self.relu(x))
out = inputs
for _ in range(25):
out = self.conv2(self.relu(self.conv1(self.relu(out))))
out = torch.add(out, inputs)
out = self.output(self.relu(out))
out = torch.add(out, residual)
return out
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, None)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, None)
@triton.jit
def triton_poi_fused_relu_1(in_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_out_ptr0 + x0, None)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(in_out_ptr0 + x0, tmp2, None)
@triton.jit
def triton_poi_fused_add_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)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + x0, None)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x0, tmp4, None)
@triton.jit
def triton_poi_fused_add_3(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)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + x0, None)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, None)
tl.store(out_ptr0 + x0, tmp1, None)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_2, (128, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_3, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_4, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_5, (1, 128, 3, 3), (1152, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 64, 64), (4096, 4096, 64, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(16384)](primals_1, buf0, 16384, 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, 128, 64, 64), (524288, 4096, 64, 1))
buf2 = buf1
del buf1
triton_poi_fused_relu_1[grid(2097152)](buf2, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf3 = extern_kernels.convolution(buf2, primals_3, 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, 4096, 64, 1))
buf4 = buf3
del buf3
triton_poi_fused_relu_1[grid(2097152)](buf4, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf5 = extern_kernels.convolution(buf4, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf6 = buf5
del buf5
triton_poi_fused_add_relu_2[grid(2097152)](buf6, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf7 = extern_kernels.convolution(buf6, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf8 = buf7
del buf7
triton_poi_fused_relu_1[grid(2097152)](buf8, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf10 = buf9
del buf9
triton_poi_fused_add_relu_2[grid(2097152)](buf10, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf11 = extern_kernels.convolution(buf10, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf12 = buf11
del buf11
triton_poi_fused_relu_1[grid(2097152)](buf12, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf13 = extern_kernels.convolution(buf12, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf14 = buf13
del buf13
triton_poi_fused_add_relu_2[grid(2097152)](buf14, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf15 = extern_kernels.convolution(buf14, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf15, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf16 = buf15
del buf15
triton_poi_fused_relu_1[grid(2097152)](buf16, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf17 = extern_kernels.convolution(buf16, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf18 = buf17
del buf17
triton_poi_fused_add_relu_2[grid(2097152)](buf18, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf19 = extern_kernels.convolution(buf18, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf20 = buf19
del buf19
triton_poi_fused_relu_1[grid(2097152)](buf20, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf21 = extern_kernels.convolution(buf20, primals_4, 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, 64, 64), (524288, 4096, 64, 1))
buf22 = buf21
del buf21
triton_poi_fused_add_relu_2[grid(2097152)](buf22, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf23 = extern_kernels.convolution(buf22, primals_3, 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, 64, 64), (524288, 4096, 64, 1))
buf24 = buf23
del buf23
triton_poi_fused_relu_1[grid(2097152)](buf24, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf25 = extern_kernels.convolution(buf24, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf25, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf26 = buf25
del buf25
triton_poi_fused_add_relu_2[grid(2097152)](buf26, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf27 = extern_kernels.convolution(buf26, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf28 = buf27
del buf27
triton_poi_fused_relu_1[grid(2097152)](buf28, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf29 = extern_kernels.convolution(buf28, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf29, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf30 = buf29
del buf29
triton_poi_fused_add_relu_2[grid(2097152)](buf30, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf31 = extern_kernels.convolution(buf30, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf31, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf32 = buf31
del buf31
triton_poi_fused_relu_1[grid(2097152)](buf32, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf33 = extern_kernels.convolution(buf32, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf33, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf34 = buf33
del buf33
triton_poi_fused_add_relu_2[grid(2097152)](buf34, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf35 = extern_kernels.convolution(buf34, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf36 = buf35
del buf35
triton_poi_fused_relu_1[grid(2097152)](buf36, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf37 = extern_kernels.convolution(buf36, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf37, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf38 = buf37
del buf37
triton_poi_fused_add_relu_2[grid(2097152)](buf38, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf39 = extern_kernels.convolution(buf38, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf39, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf40 = buf39
del buf39
triton_poi_fused_relu_1[grid(2097152)](buf40, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf41 = extern_kernels.convolution(buf40, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf41, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf42 = buf41
del buf41
triton_poi_fused_add_relu_2[grid(2097152)](buf42, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf43 = extern_kernels.convolution(buf42, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf44 = buf43
del buf43
triton_poi_fused_relu_1[grid(2097152)](buf44, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf45 = extern_kernels.convolution(buf44, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf45, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf46 = buf45
del buf45
triton_poi_fused_add_relu_2[grid(2097152)](buf46, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf47 = extern_kernels.convolution(buf46, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf47, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf48 = buf47
del buf47
triton_poi_fused_relu_1[grid(2097152)](buf48, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf49 = extern_kernels.convolution(buf48, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf49, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf50 = buf49
del buf49
triton_poi_fused_add_relu_2[grid(2097152)](buf50, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf51 = extern_kernels.convolution(buf50, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf51, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf52 = buf51
del buf51
triton_poi_fused_relu_1[grid(2097152)](buf52, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf53 = extern_kernels.convolution(buf52, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf53, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf54 = buf53
del buf53
triton_poi_fused_add_relu_2[grid(2097152)](buf54, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf55 = extern_kernels.convolution(buf54, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf55, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf56 = buf55
del buf55
triton_poi_fused_relu_1[grid(2097152)](buf56, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf57 = extern_kernels.convolution(buf56, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf57, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf58 = buf57
del buf57
triton_poi_fused_add_relu_2[grid(2097152)](buf58, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf59 = extern_kernels.convolution(buf58, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf59, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf60 = buf59
del buf59
triton_poi_fused_relu_1[grid(2097152)](buf60, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf61 = extern_kernels.convolution(buf60, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf61, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf62 = buf61
del buf61
triton_poi_fused_add_relu_2[grid(2097152)](buf62, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf63 = extern_kernels.convolution(buf62, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf63, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf64 = buf63
del buf63
triton_poi_fused_relu_1[grid(2097152)](buf64, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf65 = extern_kernels.convolution(buf64, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf65, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf66 = buf65
del buf65
triton_poi_fused_add_relu_2[grid(2097152)](buf66, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf67 = extern_kernels.convolution(buf66, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf67, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf68 = buf67
del buf67
triton_poi_fused_relu_1[grid(2097152)](buf68, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf69 = extern_kernels.convolution(buf68, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf69, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf70 = buf69
del buf69
triton_poi_fused_add_relu_2[grid(2097152)](buf70, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf71 = extern_kernels.convolution(buf70, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf71, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf72 = buf71
del buf71
triton_poi_fused_relu_1[grid(2097152)](buf72, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf73 = extern_kernels.convolution(buf72, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf73, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf74 = buf73
del buf73
triton_poi_fused_add_relu_2[grid(2097152)](buf74, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf75 = extern_kernels.convolution(buf74, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf75, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf76 = buf75
del buf75
triton_poi_fused_relu_1[grid(2097152)](buf76, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf77 = extern_kernels.convolution(buf76, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf77, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf78 = buf77
del buf77
triton_poi_fused_add_relu_2[grid(2097152)](buf78, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf79 = extern_kernels.convolution(buf78, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf79, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf80 = buf79
del buf79
triton_poi_fused_relu_1[grid(2097152)](buf80, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf81 = extern_kernels.convolution(buf80, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf81, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf82 = buf81
del buf81
triton_poi_fused_add_relu_2[grid(2097152)](buf82, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf83 = extern_kernels.convolution(buf82, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf83, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf84 = buf83
del buf83
triton_poi_fused_relu_1[grid(2097152)](buf84, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf85 = extern_kernels.convolution(buf84, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf85, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf86 = buf85
del buf85
triton_poi_fused_add_relu_2[grid(2097152)](buf86, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf87 = extern_kernels.convolution(buf86, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf87, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf88 = buf87
del buf87
triton_poi_fused_relu_1[grid(2097152)](buf88, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf89 = extern_kernels.convolution(buf88, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf89, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf90 = buf89
del buf89
triton_poi_fused_add_relu_2[grid(2097152)](buf90, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf91 = extern_kernels.convolution(buf90, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf91, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf92 = buf91
del buf91
triton_poi_fused_relu_1[grid(2097152)](buf92, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf93 = extern_kernels.convolution(buf92, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf93, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf94 = buf93
del buf93
triton_poi_fused_add_relu_2[grid(2097152)](buf94, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf95 = extern_kernels.convolution(buf94, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf95, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf96 = buf95
del buf95
triton_poi_fused_relu_1[grid(2097152)](buf96, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf97 = extern_kernels.convolution(buf96, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf97, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf98 = buf97
del buf97
triton_poi_fused_add_relu_2[grid(2097152)](buf98, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf99 = extern_kernels.convolution(buf98, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf99, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf100 = buf99
del buf99
triton_poi_fused_relu_1[grid(2097152)](buf100, 2097152, XBLOCK=512,
num_warps=8, num_stages=1)
buf101 = extern_kernels.convolution(buf100, primals_4, stride=(1, 1
), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf101, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf102 = buf101
del buf101
triton_poi_fused_add_relu_2[grid(2097152)](buf102, buf2, 2097152,
XBLOCK=512, num_warps=8, num_stages=1)
buf103 = extern_kernels.convolution(buf102, primals_5, stride=(1, 1
), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf103, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf104 = buf103
del buf103
triton_poi_fused_add_3[grid(16384)](buf104, buf0, primals_1, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
return (buf104, primals_2, primals_3, primals_4, primals_5, buf0, buf2,
buf4, buf6, buf8, buf10, buf12, buf14, buf16, buf18, buf20, buf22,
buf24, buf26, buf28, buf30, buf32, buf34, buf36, buf38, buf40,
buf42, buf44, buf46, buf48, buf50, buf52, buf54, buf56, buf58,
buf60, buf62, buf64, buf66, buf68, buf70, buf72, buf74, buf76,
buf78, buf80, buf82, buf84, buf86, buf88, buf90, buf92, buf94,
buf96, buf98, buf100, buf102)
class DRRNNew(nn.Module):
def __init__(self):
super(DRRNNew, self).__init__()
self.input = nn.Conv2d(in_channels=1, out_channels=128, kernel_size
=3, stride=1, padding=1, bias=False)
self.conv1 = nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=3, stride=1, padding=1, bias=False)
self.conv2 = nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=3, stride=1, padding=1, bias=False)
self.output = nn.Conv2d(in_channels=128, out_channels=1,
kernel_size=3, stride=1, padding=1, bias=False)
self.relu = nn.ReLU(inplace=True)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, sqrt(2.0 / n))
def forward(self, input_0):
primals_2 = self.input.weight
primals_3 = self.conv1.weight
primals_4 = self.conv2.weight
primals_5 = self.output.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
loyo1990/DRRN-pytorch
|
DRRN
| false
| 10,425
|
[
"MIT"
] | 0
|
63d7dfd4c6bcb4f7b668fc2f5b4e2031cbba6619
|
https://github.com/loyo1990/DRRN-pytorch/tree/63d7dfd4c6bcb4f7b668fc2f5b4e2031cbba6619
|
UpSampleX2
|
import torch
from torchvision.transforms import *
class DeconvBlock(torch.nn.Module):
def __init__(self, input_size, output_size, kernel_size=4, stride=2,
padding=1, bias=True, activation='prelu', norm=None):
super(DeconvBlock, self).__init__()
self.deconv = torch.nn.ConvTranspose2d(input_size, output_size,
kernel_size, stride, padding, bias=bias)
self.norm = norm
if self.norm == 'batch':
self.bn = torch.nn.BatchNorm2d(output_size)
elif self.norm == 'instance':
self.bn = torch.nn.InstanceNorm2d(output_size)
self.activation = activation
if self.activation == 'relu':
self.act = torch.nn.ReLU(True)
elif self.activation == 'prelu':
self.act = torch.nn.PReLU()
elif self.activation == 'lrelu':
self.act = torch.nn.LeakyReLU(0.2, True)
elif self.activation == 'tanh':
self.act = torch.nn.Tanh()
elif self.activation == 'sigmoid':
self.act = torch.nn.Sigmoid()
def forward(self, x):
if self.norm is not None:
out = self.bn(self.deconv(x))
else:
out = self.deconv(x)
if self.activation is not None:
return self.act(out)
else:
return out
class UpSampleX2(torch.nn.Module):
def __init__(self, num_filter, kernel_size=3, stride=2, padding=1, bias
=True, activation='prelu', norm=None):
super(UpSampleX2, self).__init__()
self.down_conv = DeconvBlock(num_filter, num_filter, kernel_size,
stride, padding, activation, norm=None)
def forward(self, x):
return self.down_conv(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_filter': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torchvision.transforms 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__prelu_kernel_convolution_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 784
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 49 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp7 = tmp6 * tmp2
tmp8 = tl.where(tmp4, tmp2, tmp7)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp8, 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, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 7, 7), (196, 49, 7, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 7, 7), (196, 49, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__prelu_kernel_convolution_0[grid(784)](buf1,
primals_2, primals_4, buf2, 784, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_2
return buf2, primals_1, primals_3, primals_4, buf1
class DeconvBlock(torch.nn.Module):
def __init__(self, input_size, output_size, kernel_size=4, stride=2,
padding=1, bias=True, activation='prelu', norm=None):
super(DeconvBlock, self).__init__()
self.deconv = torch.nn.ConvTranspose2d(input_size, output_size,
kernel_size, stride, padding, bias=bias)
self.norm = norm
if self.norm == 'batch':
self.bn = torch.nn.BatchNorm2d(output_size)
elif self.norm == 'instance':
self.bn = torch.nn.InstanceNorm2d(output_size)
self.activation = activation
if self.activation == 'relu':
self.act = torch.nn.ReLU(True)
elif self.activation == 'prelu':
self.act = torch.nn.PReLU()
elif self.activation == 'lrelu':
self.act = torch.nn.LeakyReLU(0.2, True)
elif self.activation == 'tanh':
self.act = torch.nn.Tanh()
elif self.activation == 'sigmoid':
self.act = torch.nn.Sigmoid()
def forward(self, x):
if self.norm is not None:
out = self.bn(self.deconv(x))
else:
out = self.deconv(x)
if self.activation is not None:
return self.act(out)
else:
return out
class UpSampleX2New(torch.nn.Module):
def __init__(self, num_filter, kernel_size=3, stride=2, padding=1, bias
=True, activation='prelu', norm=None):
super(UpSampleX2New, self).__init__()
self.down_conv = DeconvBlock(num_filter, num_filter, kernel_size,
stride, padding, activation, norm=None)
def forward(self, input_0):
primals_1 = self.down_conv.deconv.weight
primals_2 = self.down_conv.deconv.bias
primals_4 = self.down_conv.act.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
lizatish/My_CNN
|
UpSampleX2
| false
| 10,426
|
[
"MIT"
] | 0
|
b13818bcce2f8a3697d20e34157e3dce53f953ee
|
https://github.com/lizatish/My_CNN/tree/b13818bcce2f8a3697d20e34157e3dce53f953ee
|
InteractingLayer
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import *
import torch.onnx
import torch as torch
class InteractingLayer(nn.Module):
"""A Layer used in AutoInt that model the correlations between different feature fields by multi-head self-attention mechanism.
Input shape
- A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.
Output shape
- 3D tensor with shape:``(batch_size,field_size,embedding_size)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **head_num**: int.The head number in multi-head self-attention network.
- **use_res**: bool.Whether or not use standard residual connections before output.
- **seed**: A Python integer to use as random seed.
References
- [Song W, Shi C, Xiao Z, et al. AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks[J]. arXiv preprint arXiv:1810.11921, 2018.](https://arxiv.org/abs/1810.11921)
"""
def __init__(self, embedding_size, head_num=2, use_res=True, scaling=
False, seed=1024, device='cpu'):
super(InteractingLayer, self).__init__()
if head_num <= 0:
raise ValueError('head_num must be a int > 0')
if embedding_size % head_num != 0:
raise ValueError(
'embedding_size is not an integer multiple of head_num!')
self.att_embedding_size = embedding_size // head_num
self.head_num = head_num
self.use_res = use_res
self.scaling = scaling
self.seed = seed
self.W_Query = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
self.W_key = nn.Parameter(torch.Tensor(embedding_size, embedding_size))
self.W_Value = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
if self.use_res:
self.W_Res = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
for tensor in self.parameters():
nn.init.normal_(tensor, mean=0.0, std=0.05)
self
def forward(self, inputs):
if len(inputs.shape) != 3:
raise ValueError(
'Unexpected inputs dimensions %d, expect to be 3 dimensions' %
len(inputs.shape))
querys = torch.tensordot(inputs, self.W_Query, dims=([-1], [0]))
keys = torch.tensordot(inputs, self.W_key, dims=([-1], [0]))
values = torch.tensordot(inputs, self.W_Value, dims=([-1], [0]))
querys = torch.stack(torch.split(querys, self.att_embedding_size,
dim=2))
keys = torch.stack(torch.split(keys, self.att_embedding_size, dim=2))
values = torch.stack(torch.split(values, self.att_embedding_size,
dim=2))
inner_product = torch.einsum('bnik,bnjk->bnij', querys, keys)
if self.scaling:
inner_product /= self.att_embedding_size ** 0.5
self.normalized_att_scores = F.softmax(inner_product, dim=-1)
result = torch.matmul(self.normalized_att_scores, values)
result = torch.cat(torch.split(result, 1), dim=-1)
result = torch.squeeze(result, dim=0)
if self.use_res:
result += torch.tensordot(inputs, self.W_Res, dims=([-1], [0]))
result = F.relu(result)
return result
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embedding_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from sklearn.metrics import *
import torch.onnx
import torch as torch
assert_size_stride = torch._C._dynamo.guards.assert_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_stack_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 8
x0 = xindex % 2
x1 = xindex // 2 % 4
x3 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr0 + (2 + x0 + 4 * x1 + 16 * (-4 + 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__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 128
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_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp11 = tl.load(in_out_ptr0 + x2, xmask)
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (2 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp9 = tl.load(in_ptr0 + (32 + 2 * x1 + (-2 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tmp12 = tmp10 + tmp11
tmp13 = tl.full([1], 0, tl.int32)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp15 = 0.0
tmp16 = tmp14 <= tmp15
tl.store(in_out_ptr0 + x2, tmp14, xmask)
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), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
primals_3, out=buf1)
del primals_3
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
primals_4, out=buf2)
del primals_4
buf3 = empty_strided_cuda((8, 4, 2), (8, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_stack_0[grid(64)](buf0, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf0, (8, 4, 2), (8, 2, 1), 0)
del buf0
triton_poi_fused_stack_0[grid(64)](buf1, buf4, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((8, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf4, (8, 2, 4), (8, 1,
2), 0), out=buf5)
buf6 = empty_strided_cuda((2, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(128)](buf5, buf6, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (2, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_2[grid(128)](buf6, buf7, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (8, 4, 2), (8, 2, 1), 0)
del buf1
triton_poi_fused_stack_0[grid(64)](buf2, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf2, (8, 4, 2), (8, 2, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (8, 4, 4), (16, 4, 1),
0), buf8, out=buf9)
buf10 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
primals_5, out=buf10)
del primals_5
buf11 = reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0)
del buf10
buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(64)](buf11, buf9,
buf12, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf9
return buf11, buf7, buf7, buf12, reinterpret_tensor(primals_1, (4, 16),
(1, 4), 0), reinterpret_tensor(buf8, (8, 2, 4), (8, 1, 2), 0
), reinterpret_tensor(buf3, (8, 2, 4), (8, 1, 2), 0), buf4
class InteractingLayerNew(nn.Module):
"""A Layer used in AutoInt that model the correlations between different feature fields by multi-head self-attention mechanism.
Input shape
- A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``.
Output shape
- 3D tensor with shape:``(batch_size,field_size,embedding_size)``.
Arguments
- **in_features** : Positive integer, dimensionality of input features.
- **head_num**: int.The head number in multi-head self-attention network.
- **use_res**: bool.Whether or not use standard residual connections before output.
- **seed**: A Python integer to use as random seed.
References
- [Song W, Shi C, Xiao Z, et al. AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks[J]. arXiv preprint arXiv:1810.11921, 2018.](https://arxiv.org/abs/1810.11921)
"""
def __init__(self, embedding_size, head_num=2, use_res=True, scaling=
False, seed=1024, device='cpu'):
super(InteractingLayerNew, self).__init__()
if head_num <= 0:
raise ValueError('head_num must be a int > 0')
if embedding_size % head_num != 0:
raise ValueError(
'embedding_size is not an integer multiple of head_num!')
self.att_embedding_size = embedding_size // head_num
self.head_num = head_num
self.use_res = use_res
self.scaling = scaling
self.seed = seed
self.W_Query = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
self.W_key = nn.Parameter(torch.Tensor(embedding_size, embedding_size))
self.W_Value = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
if self.use_res:
self.W_Res = nn.Parameter(torch.Tensor(embedding_size,
embedding_size))
for tensor in self.parameters():
nn.init.normal_(tensor, mean=0.0, std=0.05)
self
def forward(self, input_0):
primals_2 = self.W_Query
primals_3 = self.W_key
primals_4 = self.W_Value
primals_5 = self.W_Res
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
dulvqingyunLT/DeepCTR-Torch
|
InteractingLayer
| false
| 10,427
|
[
"Apache-2.0"
] | 0
|
f40cf08f3469aa471f9ca69e44c5de51180341cc
|
https://github.com/dulvqingyunLT/DeepCTR-Torch/tree/f40cf08f3469aa471f9ca69e44c5de51180341cc
|
CriticMlp
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def init_weights(layer, gain):
for p in layer.parameters():
if len(p.data.shape) >= 2:
nn.init.orthogonal_(p, gain=gain)
else:
p.data.zero_()
def all_init_weights(m, gain=2 ** 0.5):
init_weights(m, gain)
class CriticMlp(nn.Module):
def __init__(self, obs_size, n_agent, n_action, global_encode_size,
local_encode_size, fc1_size, fc2_size):
super(CriticMlp, self).__init__()
self.obs_size = obs_size
self.n_agent = n_agent
self.n_action = n_action
self.global_encode_fc1 = nn.Linear(obs_size * n_agent,
global_encode_size)
self.global_encode_fc2 = nn.Linear(global_encode_size,
global_encode_size)
self.local_encode_fc = nn.Linear(obs_size, local_encode_size)
self.fc1 = nn.Linear(global_encode_size + local_encode_size, fc1_size)
self.fc2 = nn.Linear(fc1_size, fc2_size)
self.fc3 = nn.Linear(fc2_size, n_action)
self.apply(all_init_weights)
init_weights(self.fc3, gain=1)
def forward(self, obs_j):
global_obs = obs_j.view(-1, self.obs_size * self.n_agent)
global_obs = F.relu(self.global_encode_fc1(global_obs))
global_obs = F.relu(self.global_encode_fc2(global_obs))
local_obs = obs_j.view(-1, self.obs_size)
local_obs = F.relu(self.local_encode_fc(local_obs))
global_obs = global_obs.repeat_interleave(self.n_agent, dim=0)
x = torch.cat((global_obs, local_obs), dim=1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
q = self.fc3(x)
q = q.view(-1, self.n_agent, self.n_action)
return q
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'n_agent': 4, 'n_action': 4,
'global_encode_size': 4, 'local_encode_size': 4, 'fc1_size': 4,
'fc2_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
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 = 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)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * (x1 // 4) + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp15 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp12 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-4 + x0), tmp12 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp17 = tmp15 + tmp16
tmp18 = triton_helpers.maximum(tmp8, tmp17)
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp12, tmp18, tmp19)
tmp21 = tl.where(tmp4, tmp11, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_4(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 16), (16, 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, 8), (8, 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, (4, 4), (4, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 16), (16, 1),
0), reinterpret_tensor(primals_2, (16, 4), (1, 16), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(64)](buf1, primals_3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf2)
buf3 = 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=buf3)
del primals_6
buf4 = empty_strided_cuda((64, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(512)](buf2, primals_5, buf3, primals_7,
buf4, 512, XBLOCK=128, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_8, (8, 4), (1, 8
), 0), out=buf5)
buf6 = buf5
del buf5
triton_poi_fused_relu_2[grid(256)](buf6, primals_9, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_9
buf7 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf6, reinterpret_tensor(primals_10, (4, 4), (1,
4), 0), out=buf7)
buf8 = buf7
del buf7
triton_poi_fused_relu_2[grid(256)](buf8, primals_11, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_11
buf9 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, buf8, reinterpret_tensor(
primals_12, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf9)
del primals_13
buf10 = empty_strided_cuda((64, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(256)](buf3,
primals_7, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf3
del primals_7
buf11 = empty_strided_cuda((16, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_4[grid(64)](buf2,
primals_5, buf11, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf2
del primals_5
return (reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0), primals_1,
buf1, buf4, buf6, buf8, primals_12, primals_10, primals_8, buf10,
buf11, primals_4)
def init_weights(layer, gain):
for p in layer.parameters():
if len(p.data.shape) >= 2:
nn.init.orthogonal_(p, gain=gain)
else:
p.data.zero_()
def all_init_weights(m, gain=2 ** 0.5):
init_weights(m, gain)
class CriticMlpNew(nn.Module):
def __init__(self, obs_size, n_agent, n_action, global_encode_size,
local_encode_size, fc1_size, fc2_size):
super(CriticMlpNew, self).__init__()
self.obs_size = obs_size
self.n_agent = n_agent
self.n_action = n_action
self.global_encode_fc1 = nn.Linear(obs_size * n_agent,
global_encode_size)
self.global_encode_fc2 = nn.Linear(global_encode_size,
global_encode_size)
self.local_encode_fc = nn.Linear(obs_size, local_encode_size)
self.fc1 = nn.Linear(global_encode_size + local_encode_size, fc1_size)
self.fc2 = nn.Linear(fc1_size, fc2_size)
self.fc3 = nn.Linear(fc2_size, n_action)
self.apply(all_init_weights)
init_weights(self.fc3, gain=1)
def forward(self, input_0):
primals_2 = self.global_encode_fc1.weight
primals_3 = self.global_encode_fc1.bias
primals_4 = self.global_encode_fc2.weight
primals_5 = self.global_encode_fc2.bias
primals_6 = self.local_encode_fc.weight
primals_7 = self.local_encode_fc.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_12 = self.fc3.weight
primals_13 = self.fc3.bias
primals_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]
|
heavenlysf/thesis
|
CriticMlp
| false
| 10,428
|
[
"MIT"
] | 0
|
646553c45860f337c91a48ab7f666a174784472f
|
https://github.com/heavenlysf/thesis/tree/646553c45860f337c91a48ab7f666a174784472f
|
LayerNorm
|
import torch
import torch.nn as nn
from torch.nn import Parameter
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-08, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = Parameter(torch.Tensor(num_features).uniform_())
self.beta = Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_mean_mul_std_sub_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, in_ptr2, 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
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp28 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 64.0
tmp20 = tmp4 / tmp19
tmp21 = 63.0
tmp22 = tmp18 / tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-08
tmp25 = tmp23 + tmp24
tmp26 = tmp0 - tmp20
tmp27 = tmp26 / tmp25
tmp29 = tmp27 * tmp28
tmp31 = tmp29 + tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
tl.store(out_ptr0 + (r1 + 64 * x0), tmp31, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = buf0
del buf0
buf5 = reinterpret_tensor(buf3, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_mean_mul_std_sub_0[grid(4)](buf1, buf5,
primals_1, primals_2, primals_3, buf6, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del primals_2
del primals_3
return buf6, primals_1, reinterpret_tensor(buf1, (4, 1, 1, 1), (1, 1, 1,
1), 0), buf5
class LayerNormNew(nn.Module):
def __init__(self, num_features, eps=1e-08, affine=True):
super(LayerNormNew, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = Parameter(torch.Tensor(num_features).uniform_())
self.beta = Parameter(torch.zeros(num_features))
def forward(self, input_0):
primals_2 = self.gamma
primals_3 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
kangzhiq/DeepFillv2_Pytorch
|
LayerNorm
| false
| 10,429
|
[
"MIT"
] | 0
|
9c7ed61b25bb995713f89108b712490737abe1b1
|
https://github.com/kangzhiq/DeepFillv2_Pytorch/tree/9c7ed61b25bb995713f89108b712490737abe1b1
|
SAB
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class SAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
def forward(self, x, presence=None):
return self.mab(x, x, presence)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_5(in_ptr0, in_ptr1,
in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4, 16)](buf0, primals_3, buf3, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_5, buf4, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_7, buf8, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
triton_poi_fused_add_4[grid(64)](buf12, primals_9, primals_1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_5[grid(64)](buf12,
buf13, primals_11, buf14, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf13
del primals_11
return buf14, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), reinterpret_tensor(buf12, (16, 4), (4, 1), 0
), buf15, primals_10, primals_8, reinterpret_tensor(buf8, (16, 1, 4
), (4, 1, 1), 0), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class SABNew(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
def forward(self, input_0):
primals_2 = self.mab.mqkv.q_projector.weight
primals_3 = self.mab.mqkv.q_projector.bias
primals_4 = self.mab.mqkv.k_projector.weight
primals_5 = self.mab.mqkv.k_projector.bias
primals_6 = self.mab.mqkv.v_projector.weight
primals_7 = self.mab.mqkv.v_projector.bias
primals_8 = self.mab.mqkv.o_projector.weight
primals_9 = self.mab.mqkv.o_projector.bias
primals_10 = self.mab.fc.weight
primals_11 = self.mab.fc.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
karayanni/torch-scae
|
SAB
| false
| 10,430
|
[
"Apache-2.0"
] | 0
|
e044662d8942d8d1923d13d071f375144cf4a1e8
|
https://github.com/karayanni/torch-scae/tree/e044662d8942d8d1923d13d071f375144cf4a1e8
|
MAB
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_5(in_ptr0, in_ptr1,
in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4, 16)](buf0, primals_4, buf3, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_6, buf4, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_8, buf8, 4, 16,
XBLOCK=16, YBLOCK=2, num_warps=1, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
triton_poi_fused_add_4[grid(64)](buf12, primals_10, primals_1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_5[grid(64)](buf12,
buf13, primals_12, buf14, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf13
del primals_12
return buf14, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), reinterpret_tensor(buf12, (16, 4), (4, 1), 0
), buf15, primals_11, primals_9, reinterpret_tensor(buf8, (16, 1, 4
), (4, 1, 1), 0), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MABNew(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, input_0, input_1):
primals_3 = self.mqkv.q_projector.weight
primals_4 = self.mqkv.q_projector.bias
primals_5 = self.mqkv.k_projector.weight
primals_6 = self.mqkv.k_projector.bias
primals_7 = self.mqkv.v_projector.weight
primals_8 = self.mqkv.v_projector.bias
primals_9 = self.mqkv.o_projector.weight
primals_10 = self.mqkv.o_projector.bias
primals_11 = self.fc.weight
primals_12 = self.fc.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
karayanni/torch-scae
|
MAB
| false
| 10,431
|
[
"Apache-2.0"
] | 0
|
e044662d8942d8d1923d13d071f375144cf4a1e8
|
https://github.com/karayanni/torch-scae/tree/e044662d8942d8d1923d13d071f375144cf4a1e8
|
DiscriminatorHingeLoss
|
import torch
import torch.nn as nn
class DiscriminatorHingeLoss(nn.Module):
def __init__(self, reduction='mean'):
super(DiscriminatorHingeLoss, self).__init__()
if reduction not in ['mean', 'sum']:
raise ValueError(
'Valid values for the reduction param are `mean`, `sum`')
self.reduction = reduction
def forward(self, fake_out, real_out):
real_loss = -torch.minimum(torch.zeros_like(real_out), real_out - 1
).mean()
fake_loss = -torch.minimum(torch.zeros_like(fake_out), -1 - fake_out
).mean()
return real_loss + fake_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mean_minimum_neg_rsub_sub_zeros_like_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)
tmp8 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 - tmp1
tmp3 = 0.0
tmp4 = triton_helpers.minimum(tmp3, tmp2)
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp9 = -1.0
tmp10 = tmp9 - tmp8
tmp11 = triton_helpers.minimum(tmp3, tmp10)
tmp12 = tl.broadcast_to(tmp11, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tmp15 = 256.0
tmp16 = tmp7 / tmp15
tmp17 = -tmp16
tmp18 = tmp14 / tmp15
tmp19 = -tmp18
tmp20 = tmp17 + tmp19
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp20, 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)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mean_minimum_neg_rsub_sub_zeros_like_0[grid(1)](
buf2, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class DiscriminatorHingeLossNew(nn.Module):
def __init__(self, reduction='mean'):
super(DiscriminatorHingeLossNew, self).__init__()
if reduction not in ['mean', 'sum']:
raise ValueError(
'Valid values for the reduction param are `mean`, `sum`')
self.reduction = reduction
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
kpandey008/SAGAN
|
DiscriminatorHingeLoss
| false
| 10,432
|
[
"MIT"
] | 0
|
8e673d2ccabeb0450faf30dcb347b9ff2d710ae2
|
https://github.com/kpandey008/SAGAN/tree/8e673d2ccabeb0450faf30dcb347b9ff2d710ae2
|
TransposeConv2dLayer
|
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.nn import Parameter
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-08, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = Parameter(torch.Tensor(num_features).uniform_())
self.beta = Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
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 Conv2dLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, pad_type='zero', activation='elu', norm=
'none', sn=False):
super(Conv2dLayer, self).__init__()
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
if norm == 'bn':
self.norm = nn.BatchNorm2d(out_channels)
elif norm == 'in':
self.norm = nn.InstanceNorm2d(out_channels)
elif norm == 'ln':
self.norm = LayerNorm(out_channels)
elif norm == 'none':
self.norm = None
else:
assert 0, 'Unsupported normalization: {}'.format(norm)
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'elu':
self.activation = nn.ELU(inplace=True)
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'sigmoid':
self.activation = nn.Sigmoid()
elif activation == 'none':
self.activation = None
else:
assert 0, 'Unsupported activation: {}'.format(activation)
if sn:
self.conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels,
kernel_size, stride, padding=0, dilation=dilation))
else:
self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size,
stride, padding=0, dilation=dilation)
def forward(self, x):
x = self.pad(x)
x = self.conv2d(x)
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
class TransposeConv2dLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, pad_type='zero', activation='lrelu', norm=
'none', sn=False, scale_factor=2):
super(TransposeConv2dLayer, self).__init__()
self.scale_factor = scale_factor
self.conv2d = Conv2dLayer(in_channels, out_channels, kernel_size,
stride, padding, dilation, pad_type, activation, norm, sn)
def forward(self, x):
x = F.interpolate(x, scale_factor=self.scale_factor, mode='nearest')
x = self.conv2d(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from 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__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_convolution_leaky_relu_leaky_relu_backward_1(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 25 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp8 = tmp7 > tmp3
tl.store(in_out_ptr0 + x3, tmp7, xmask)
tl.store(out_ptr0 + x3, tmp8, 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, 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=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 5, 5), (100, 25, 5, 1))
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.bool)
triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_1[grid(400)
](buf2, primals_3, buf3, 400, XBLOCK=256, num_warps=4, num_stages=1
)
del primals_3
return buf2, primals_2, buf0, buf3
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-08, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = Parameter(torch.Tensor(num_features).uniform_())
self.beta = Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
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 Conv2dLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, pad_type='zero', activation='elu', norm=
'none', sn=False):
super(Conv2dLayer, self).__init__()
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
if norm == 'bn':
self.norm = nn.BatchNorm2d(out_channels)
elif norm == 'in':
self.norm = nn.InstanceNorm2d(out_channels)
elif norm == 'ln':
self.norm = LayerNorm(out_channels)
elif norm == 'none':
self.norm = None
else:
assert 0, 'Unsupported normalization: {}'.format(norm)
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'elu':
self.activation = nn.ELU(inplace=True)
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'sigmoid':
self.activation = nn.Sigmoid()
elif activation == 'none':
self.activation = None
else:
assert 0, 'Unsupported activation: {}'.format(activation)
if sn:
self.conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels,
kernel_size, stride, padding=0, dilation=dilation))
else:
self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size,
stride, padding=0, dilation=dilation)
def forward(self, x):
x = self.pad(x)
x = self.conv2d(x)
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
class TransposeConv2dLayerNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, pad_type='zero', activation='lrelu', norm=
'none', sn=False, scale_factor=2):
super(TransposeConv2dLayerNew, self).__init__()
self.scale_factor = scale_factor
self.conv2d = Conv2dLayer(in_channels, out_channels, kernel_size,
stride, padding, dilation, pad_type, activation, norm, sn)
def forward(self, input_0):
primals_1 = self.conv2d.conv2d.weight
primals_3 = self.conv2d.conv2d.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
kangzhiq/DeepFillv2_Pytorch
|
TransposeConv2dLayer
| false
| 10,433
|
[
"MIT"
] | 0
|
9c7ed61b25bb995713f89108b712490737abe1b1
|
https://github.com/kangzhiq/DeepFillv2_Pytorch/tree/9c7ed61b25bb995713f89108b712490737abe1b1
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 50, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(50, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def get_inputs():
return [torch.rand([4, 3, 32, 32])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 156800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 784 % 50
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 39200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 14
x3 = xindex // 14
x2 = xindex // 9800
x4 = xindex % 9800
tmp0 = tl.load(in_ptr0 + (2 * x0 + 56 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 56 * x3), xmask, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (28 + 2 * x0 + 56 * x3), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (29 + 2 * x0 + 56 * x3), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (x4 + 9824 * x2), tmp6, xmask)
tl.store(out_ptr1 + (x4 + 9856 * x2), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 100 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 20 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 20 * x1), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (10 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (11 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 480
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 120
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 336
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 84
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (50, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (50,), (1,))
assert_size_stride(primals_3, (4, 3, 32, 32), (3072, 1024, 32, 1))
assert_size_stride(primals_4, (16, 50, 5, 5), (1250, 25, 5, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (120, 400), (400, 1))
assert_size_stride(primals_7, (120,), (1,))
assert_size_stride(primals_8, (84, 120), (120, 1))
assert_size_stride(primals_9, (84,), (1,))
assert_size_stride(primals_10, (10, 84), (84, 1))
assert_size_stride(primals_11, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_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, 50, 28, 28), (39200, 784, 28, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(156800)](buf1, primals_2,
156800, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 50, 14, 14), (9824, 196, 14, 1),
torch.float32)
buf3 = empty_strided_cuda((4, 50, 14, 14), (9856, 196, 14, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(39200)](buf1, buf2,
buf3, 39200, XBLOCK=512, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 16, 10, 10), (1600, 100, 10, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(6400)](buf5, primals_5,
6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.int8)
buf7 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.float32
)
triton_poi_fused_max_pool2d_with_indices_3[grid(1600)](buf5, buf6,
buf7, 1600, XBLOCK=128, num_warps=4, num_stages=1)
buf8 = empty_strided_cuda((4, 120), (120, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 400), (400, 1), 0),
reinterpret_tensor(primals_6, (400, 120), (1, 400), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(480)](buf9, primals_7, 480, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 84), (84, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_8, (120, 84), (1,
120), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(336)](buf11, primals_9, 336, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_11, buf11, reinterpret_tensor(
primals_10, (84, 10), (1, 84), 0), alpha=1, beta=1, out=buf12)
del primals_11
return (buf12, primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5,
buf6, reinterpret_tensor(buf7, (4, 400), (400, 1), 0), buf9, buf11,
primals_10, primals_8, primals_6)
class NetNew(nn.Module):
def __init__(self):
super(NetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 50, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(50, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_10 = self.fc3.weight
primals_11 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
lykasbongbongbong/Pytorch
|
Net
| false
| 10,434
|
[
"MIT"
] | 0
|
f01d89fb51ac939f5a110f5ab6190c11917e66fc
|
https://github.com/lykasbongbongbong/Pytorch/tree/f01d89fb51ac939f5a110f5ab6190c11917e66fc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.