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
|
|---|---|---|---|---|---|---|---|---|---|---|
FocalLoss
|
import torch
import torch.nn as nn
class FocalLoss(nn.Module):
def __init__(self, gamma=0, eps=1e-07):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.eps = eps
self.ce = torch.nn.CrossEntropyLoss()
def forward(self, input, target):
logp = self.ce(input, target)
p = torch.exp(-logp)
loss = (1 - p) ** self.gamma * logp
return loss.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = -tmp18
tmp20 = 0.015625
tmp21 = tmp19 * tmp20
tmp22 = -tmp21
tmp23 = tl_math.exp(tmp22)
tmp24 = 1.0
tmp24 - tmp23
tmp26 = tmp24 * tmp21
tmp27 = tmp26 / tmp24
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp27, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1[grid
(1)](buf2, buf0, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class FocalLossNew(nn.Module):
def __init__(self, gamma=0, eps=1e-07):
super(FocalLossNew, self).__init__()
self.gamma = gamma
self.eps = eps
self.ce = torch.nn.CrossEntropyLoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BaoLocPham/hum2song
|
FocalLoss
| false
| 13,371
|
[
"MIT"
] | 108
|
706b7fdf838944e2aabe0ae331c0867cb67f6fbc
|
https://github.com/BaoLocPham/hum2song/tree/706b7fdf838944e2aabe0ae331c0867cb67f6fbc
|
Scale
|
import torch
import torch.nn as nn
class Scale(nn.Module):
"""
A learnable scale parameter
"""
def __init__(self, scale=1.0):
super(Scale, self).__init__()
self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float))
def forward(self, x):
return x * self.scale
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, 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 = tmp0 * tmp2
tl.store(out_ptr0 + x0, tmp3, 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, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_2, primals_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
return buf0, primals_2
class ScaleNew(nn.Module):
"""
A learnable scale parameter
"""
def __init__(self, scale=1.0):
super(ScaleNew, self).__init__()
self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float))
def forward(self, input_0):
primals_1 = self.scale
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
BUPT-PRIV/BalancedGroupSoftmax
|
Scale
| false
| 13,372
|
[
"Apache-2.0"
] | 333
|
90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
https://github.com/BUPT-PRIV/BalancedGroupSoftmax/tree/90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
BalancedL1Loss
|
import functools
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
if weight is not None:
loss = loss * weight
if avg_factor is None:
loss = reduce_loss(loss, reduction)
elif reduction == 'mean':
loss = loss.sum() / avg_factor
elif reduction != 'none':
raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> import torch
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred, target, weight=None, reduction='mean', avg_factor=
None, **kwargs):
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
@weighted_loss
def balanced_l1_loss(pred, target, beta=1.0, alpha=0.5, gamma=1.5,
reduction='mean'):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
b = np.e ** (gamma / alpha) - 1
loss = torch.where(diff < beta, alpha / b * (b * diff + 1) * torch.log(
b * diff / beta + 1) - alpha * diff, gamma * diff + gamma / b -
alpha * beta)
return loss
class BalancedL1Loss(nn.Module):
"""Balanced L1 Loss
arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)
"""
def __init__(self, alpha=0.5, gamma=1.5, beta=1.0, reduction='mean',
loss_weight=1.0):
super(BalancedL1Loss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
loss_bbox = self.loss_weight * balanced_l1_loss(pred, target,
weight, alpha=self.alpha, gamma=self.gamma, beta=self.beta,
reduction=reduction, avg_factor=avg_factor, **kwargs)
return loss_bbox
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import functools
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_add_div_log_lt_mean_mul_sub_where_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 = tl_math.abs(tmp2)
tmp4 = 1.0
tmp5 = tmp3 < tmp4
tmp6 = 19.085536923187664
tmp7 = tmp3 * tmp6
tmp8 = tmp7 + tmp4
tmp9 = 0.02619784824562798
tmp10 = tmp8 * tmp9
tmp11 = tmp7 * tmp4
tmp12 = tmp11 + tmp4
tmp13 = tl_math.log(tmp12)
tmp14 = tmp10 * tmp13
tmp15 = 0.5
tmp16 = tmp3 * tmp15
tmp17 = tmp14 - tmp16
tmp18 = 1.5
tmp19 = tmp3 * tmp18
tmp20 = 0.07859354473688394
tmp21 = tmp19 + tmp20
tmp22 = tmp21 - tmp15
tmp23 = tl.where(tmp5, tmp17, tmp22)
tmp24 = tl.broadcast_to(tmp23, [RBLOCK])
tmp26 = triton_helpers.promote_to_tensor(tl.sum(tmp24, 0))
tmp27 = 256.0
tmp28 = tmp26 / tmp27
tmp29 = tmp28 * tmp4
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp29, 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_abs_add_div_log_lt_mean_mul_sub_where_0[grid(1)](buf1,
arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
if weight is not None:
loss = loss * weight
if avg_factor is None:
loss = reduce_loss(loss, reduction)
elif reduction == 'mean':
loss = loss.sum() / avg_factor
elif reduction != 'none':
raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> import torch
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred, target, weight=None, reduction='mean', avg_factor=
None, **kwargs):
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
@weighted_loss
def balanced_l1_loss(pred, target, beta=1.0, alpha=0.5, gamma=1.5,
reduction='mean'):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
b = np.e ** (gamma / alpha) - 1
loss = torch.where(diff < beta, alpha / b * (b * diff + 1) * torch.log(
b * diff / beta + 1) - alpha * diff, gamma * diff + gamma / b -
alpha * beta)
return loss
class BalancedL1LossNew(nn.Module):
"""Balanced L1 Loss
arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)
"""
def __init__(self, alpha=0.5, gamma=1.5, beta=1.0, reduction='mean',
loss_weight=1.0):
super(BalancedL1LossNew, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BUPT-PRIV/BalancedGroupSoftmax
|
BalancedL1Loss
| false
| 13,373
|
[
"Apache-2.0"
] | 333
|
90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
https://github.com/BUPT-PRIV/BalancedGroupSoftmax/tree/90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
SmoothL1Loss
|
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
if weight is not None:
loss = loss * weight
if avg_factor is None:
loss = reduce_loss(loss, reduction)
elif reduction == 'mean':
loss = loss.sum() / avg_factor
elif reduction != 'none':
raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> import torch
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred, target, weight=None, reduction='mean', avg_factor=
None, **kwargs):
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta
)
return loss
class SmoothL1Loss(nn.Module):
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
loss_bbox = self.loss_weight * smooth_l1_loss(pred, target, weight,
beta=self.beta, reduction=reduction, avg_factor=avg_factor, **
kwargs)
return loss_bbox
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import functools
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_div_lt_mean_mul_sub_where_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 = tl_math.abs(tmp2)
tmp4 = 1.0
tmp5 = tmp3 < tmp4
tmp6 = 0.5
tmp7 = tmp3 * tmp6
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp4
tmp10 = tmp3 - tmp6
tmp11 = tl.where(tmp5, tmp9, tmp10)
tmp12 = tl.broadcast_to(tmp11, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tmp15 = 256.0
tmp16 = tmp14 / tmp15
tmp17 = tmp16 * tmp4
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, 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_abs_div_lt_mean_mul_sub_where_0[grid(1)](buf1,
arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
if weight is not None:
loss = loss * weight
if avg_factor is None:
loss = reduce_loss(loss, reduction)
elif reduction == 'mean':
loss = loss.sum() / avg_factor
elif reduction != 'none':
raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> import torch
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred, target, weight=None, reduction='mean', avg_factor=
None, **kwargs):
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta
)
return loss
class SmoothL1LossNew(nn.Module):
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
super(SmoothL1LossNew, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BUPT-PRIV/BalancedGroupSoftmax
|
SmoothL1Loss
| false
| 13,374
|
[
"Apache-2.0"
] | 333
|
90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
https://github.com/BUPT-PRIV/BalancedGroupSoftmax/tree/90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
SoftDiceLossSquared
|
import torch
import numpy as np
from torch import nn
import torch.nn.functional
def sum_tensor(inp, axes, keepdim=False):
axes = np.unique(axes).astype(int)
if keepdim:
for ax in axes:
inp = inp.sum(int(ax), keepdim=True)
else:
for ax in sorted(axes, reverse=True):
inp = inp.sum(int(ax))
return inp
class SoftDiceLossSquared(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
squares the terms in the denominator as proposed by Milletari et al.
"""
super(SoftDiceLossSquared, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, x, y, loss_mask=None):
shp_x = x.shape
shp_y = y.shape
if self.batch_dice:
axes = [0] + list(range(2, len(shp_x)))
else:
axes = list(range(2, len(shp_x)))
if self.apply_nonlin is not None:
x = self.apply_nonlin(x)
with torch.no_grad():
if len(shp_x) != len(shp_y):
y = y.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(x.shape, y.shape)]):
y_onehot = y
else:
y = y.long()
y_onehot = torch.zeros(shp_x)
if x.device.type == 'cuda':
y_onehot = y_onehot
y_onehot.scatter_(1, y, 1).float()
intersect = x * y_onehot
denominator = x ** 2 + y_onehot ** 2
intersect = sum_tensor(intersect, axes, False) + self.smooth
denominator = sum_tensor(denominator, axes, False) + self.smooth
dc = 2 * intersect / denominator
if not self.do_bg:
if self.batch_dice:
dc = dc[1:]
else:
dc = dc[:, 1:]
dc = dc.mean()
return -dc
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import numpy as np
from torch import nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_pow_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp1 * tmp1
tmp5 = tmp3 + tmp4
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp5, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_pow_0[grid(256)](arg0_1, arg1_1, buf0,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0, buf1
def sum_tensor(inp, axes, keepdim=False):
axes = np.unique(axes).astype(int)
if keepdim:
for ax in axes:
inp = inp.sum(int(ax), keepdim=True)
else:
for ax in sorted(axes, reverse=True):
inp = inp.sum(int(ax))
return inp
class SoftDiceLossSquaredNew(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
squares the terms in the denominator as proposed by Milletari et al.
"""
super(SoftDiceLossSquaredNew, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BRAIN-Lab-UNC/BrainExtraction-TissueSegmentation-Macaque
|
SoftDiceLossSquared
| false
| 13,375
|
[
"MIT"
] | 770
|
b5329035d9e32c8a27151cf2396eaf209396a334
|
https://github.com/BRAIN-Lab-UNC/BrainExtraction-TissueSegmentation-Macaque/tree/b5329035d9e32c8a27151cf2396eaf209396a334
|
PPMConcat
|
import torch
import torch.nn as nn
import torch._C
import torch.serialization
from torch import optim as optim
class PPMConcat(nn.ModuleList):
"""Pyramid Pooling Module that only concat the features of each layer.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
Module.
"""
def __init__(self, pool_scales=(1, 3, 6, 8)):
super(PPMConcat, self).__init__([nn.AdaptiveAvgPool2d(pool_scale) for
pool_scale in pool_scales])
def forward(self, feats):
"""Forward function."""
ppm_outs = []
for ppm in self:
ppm_out = ppm(feats)
ppm_outs.append(ppm_out.view(*feats.shape[:2], -1))
concat_outs = torch.cat(ppm_outs, dim=2)
return concat_outs
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch._C
import torch.serialization
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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_cat_mean_0(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.store(out_ptr1 + 110 * x0, tmp6, xmask)
@triton.jit
def triton_poi_fused__adaptive_avg_pool2d_cat_1(in_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x3 = xindex % 9
tmp0 = 4 * x1 // 3
tmp1 = 2 + 4 * x1 // 3
tmp2 = tmp0 < tmp1
tmp3 = 4 * x0 // 3
tmp4 = 2 + 4 * x0 // 3
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 // 3),
tmp6 & xmask, other=0.0)
tmp8 = 1 + 4 * x0 // 3
tmp9 = tmp8 < tmp4
tmp10 = tmp2 & tmp9
tmp11 = tl.load(in_ptr0 + (1 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp10 & xmask, other=0.0)
tmp12 = tmp11 + tmp7
tmp13 = 1 + 4 * x1 // 3
tmp14 = tmp13 < tmp1
tmp15 = tmp14 & tmp5
tmp16 = tl.load(in_ptr0 + (4 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp15 & xmask, other=0.0)
tmp17 = tmp16 + tmp12
tmp18 = tmp14 & tmp9
tmp19 = tl.load(in_ptr0 + (5 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp18 & xmask, other=0.0)
tmp20 = tmp19 + tmp17
tmp21 = 1.0
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp6, tmp21, tmp22)
tmp24 = tl.where(tmp10, tmp21, tmp22)
tmp25 = tmp24 + tmp23
tmp26 = tl.where(tmp15, tmp21, tmp22)
tmp27 = tmp26 + tmp25
tmp28 = tl.where(tmp18, tmp21, tmp22)
tmp29 = tmp28 + tmp27
tmp30 = tmp20 / tmp29
tl.store(out_ptr1 + (x3 + 110 * x2), tmp30, xmask)
@triton.jit
def triton_poi_fused__adaptive_avg_pool2d_cat_2(in_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 6 % 6
x0 = xindex % 6
x2 = xindex // 36
x3 = xindex % 36
tmp0 = 2 * x1 // 3
tmp1 = (9 + 4 * x1) // 6
tmp2 = tmp0 < tmp1
tmp3 = 2 * x0 // 3
tmp4 = (9 + 4 * x0) // 6
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 // 3),
tmp6 & xmask, eviction_policy='evict_last', other=0.0)
tmp8 = 1 + 2 * x0 // 3
tmp9 = tmp8 < tmp4
tmp10 = tmp2 & tmp9
tmp11 = tl.load(in_ptr0 + (1 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp10 & xmask, eviction_policy='evict_last', other=0.0)
tmp12 = tmp11 + tmp7
tmp13 = 1 + 2 * x1 // 3
tmp14 = tmp13 < tmp1
tmp15 = tmp14 & tmp5
tmp16 = tl.load(in_ptr0 + (4 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp15 & xmask, eviction_policy='evict_last', other=0.0)
tmp17 = tmp16 + tmp12
tmp18 = tmp14 & tmp9
tmp19 = tl.load(in_ptr0 + (5 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp18 & xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 + tmp17
tmp21 = 1.0
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp6, tmp21, tmp22)
tmp24 = tl.where(tmp10, tmp21, tmp22)
tmp25 = tmp24 + tmp23
tmp26 = tl.where(tmp15, tmp21, tmp22)
tmp27 = tmp26 + tmp25
tmp28 = tl.where(tmp18, tmp21, tmp22)
tmp29 = tmp28 + tmp27
tmp30 = tmp20 / tmp29
tl.store(out_ptr1 + (x3 + 110 * x2), tmp30, xmask)
@triton.jit
def triton_poi_fused__adaptive_avg_pool2d_cat_3(in_ptr0, out_ptr1, 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
x3 = xindex % 64
tmp0 = x1 // 2
tmp1 = (11 + 4 * x1) // 8
tmp2 = tmp0 < tmp1
tmp3 = x0 // 2
tmp4 = (11 + 4 * x0) // 8
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (4 * (x1 // 2) + 16 * x2 + x0 // 2), tmp6 &
xmask, eviction_policy='evict_last', other=0.0)
tmp8 = 1 + x0 // 2
tmp9 = tmp8 < tmp4
tmp10 = tmp2 & tmp9
tmp11 = tl.load(in_ptr0 + (1 + 4 * (x1 // 2) + 16 * x2 + x0 // 2),
tmp10 & xmask, eviction_policy='evict_last', other=0.0)
tmp12 = tmp11 + tmp7
tmp13 = 1 + x1 // 2
tmp14 = tmp13 < tmp1
tmp15 = tmp14 & tmp5
tmp16 = tl.load(in_ptr0 + (4 + 4 * (x1 // 2) + 16 * x2 + x0 // 2),
tmp15 & xmask, eviction_policy='evict_last', other=0.0)
tmp17 = tmp16 + tmp12
tmp18 = tmp14 & tmp9
tmp19 = tl.load(in_ptr0 + (5 + 4 * (x1 // 2) + 16 * x2 + x0 // 2),
tmp18 & xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 + tmp17
tmp21 = 1.0
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp6, tmp21, tmp22)
tmp24 = tl.where(tmp10, tmp21, tmp22)
tmp25 = tmp24 + tmp23
tmp26 = tl.where(tmp15, tmp21, tmp22)
tmp27 = tmp26 + tmp25
tmp28 = tl.where(tmp18, tmp21, tmp22)
tmp29 = tmp28 + tmp27
tmp30 = tmp20 / tmp29
tl.store(out_ptr1 + (x3 + 110 * x2), tmp30, 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)
buf8 = empty_strided_cuda((4, 4, 110), (440, 110, 1), torch.float32)
buf4 = reinterpret_tensor(buf8, (4, 4, 1), (440, 110, 1), 0)
get_raw_stream(0)
triton_per_fused_cat_mean_0[grid(16)](arg0_1, buf4, 16, 16, XBLOCK=
1, num_warps=2, num_stages=1)
buf5 = reinterpret_tensor(buf8, (4, 4, 9), (440, 110, 1), 1)
triton_poi_fused__adaptive_avg_pool2d_cat_1[grid(144)](arg0_1, buf5,
144, XBLOCK=128, num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf8, (4, 4, 36), (440, 110, 1), 10)
triton_poi_fused__adaptive_avg_pool2d_cat_2[grid(576)](arg0_1, buf6,
576, XBLOCK=128, num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf8, (4, 4, 64), (440, 110, 1), 46)
triton_poi_fused__adaptive_avg_pool2d_cat_3[grid(1024)](arg0_1,
buf7, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf8,
class PPMConcatNew(nn.ModuleList):
"""Pyramid Pooling Module that only concat the features of each layer.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
Module.
"""
def __init__(self, pool_scales=(1, 3, 6, 8)):
super(PPMConcatNew, self).__init__([nn.AdaptiveAvgPool2d(pool_scale
) for pool_scale in pool_scales])
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Atten4Vis/DemystifyLocalViT
|
PPMConcat
| false
| 13,376
|
[
"MIT"
] | 64
|
2e2327caec6d56ae2c8aa861b32bb62f3cdb786e
|
https://github.com/Atten4Vis/DemystifyLocalViT/tree/2e2327caec6d56ae2c8aa861b32bb62f3cdb786e
|
Encoder
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Lambda(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x):
return self.func(x)
class FFN(nn.Module):
"""
Feed-Forward Network
"""
def __init__(self, d_inner_hid, d_model, dropout_rate):
super(FFN, self).__init__()
self.dropout_rate = dropout_rate
self.fc1 = torch.nn.Linear(in_features=d_model, out_features=
d_inner_hid)
self.fc2 = torch.nn.Linear(in_features=d_inner_hid, out_features=
d_model)
def forward(self, x):
hidden = self.fc1(x)
hidden = F.relu(hidden)
if self.dropout_rate:
hidden = F.dropout(hidden, p=self.dropout_rate)
out = self.fc2(hidden)
return out
class MultiHeadAttention(nn.Module):
"""
Multi-Head Attention
"""
def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.0):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_key = d_key
self.d_value = d_value
self.d_model = d_model
self.dropout_rate = dropout_rate
self.q_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.k_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.v_fc = torch.nn.Linear(in_features=d_model, out_features=
d_value * n_head, bias=False)
self.proj_fc = torch.nn.Linear(in_features=d_value * n_head,
out_features=d_model, bias=False)
def _prepare_qkv(self, queries, keys, values, cache=None):
if keys is None:
keys, values = queries, queries
static_kv = False
else:
static_kv = True
q = self.q_fc(queries)
q = torch.reshape(q, shape=[q.size(0), q.size(1), self.n_head, self
.d_key])
q = q.permute(0, 2, 1, 3)
if cache is not None and static_kv and 'static_k' in cache:
k = cache['static_k']
v = cache['static_v']
else:
k = self.k_fc(keys)
v = self.v_fc(values)
k = torch.reshape(k, shape=[k.size(0), k.size(1), self.n_head,
self.d_key])
k = k.permute(0, 2, 1, 3)
v = torch.reshape(v, shape=[v.size(0), v.size(1), self.n_head,
self.d_value])
v = v.permute(0, 2, 1, 3)
if cache is not None:
if static_kv and 'static_k' not in cache:
cache['static_k'], cache['static_v'] = k, v
elif not static_kv:
cache_k, cache_v = cache['k'], cache['v']
k = torch.cat([cache_k, k], dim=2)
v = torch.cat([cache_v, v], dim=2)
cache['k'], cache['v'] = k, v
return q, k, v
def forward(self, queries, keys, values, attn_bias, cache=None):
keys = queries if keys is None else keys
values = keys if values is None else values
q, k, v = self._prepare_qkv(queries, keys, values, cache)
product = torch.matmul(q, k.transpose(2, 3))
product = product * self.d_model ** -0.5
if attn_bias is not None:
product += attn_bias
weights = F.softmax(product, dim=-1)
if self.dropout_rate:
weights = F.dropout(weights, p=self.dropout_rate)
out = torch.matmul(weights, v)
out = out.permute(0, 2, 1, 3)
out = torch.reshape(out, shape=[out.size(0), out.size(1), out.shape
[2] * out.shape[3]])
out = self.proj_fc(out)
return out
class LambdaXY(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x, y):
return self.func(x, y)
class PrePostProcessLayer(nn.Module):
"""
PrePostProcessLayer
"""
def __init__(self, process_cmd, d_model, dropout_rate):
super(PrePostProcessLayer, self).__init__()
self.process_cmd = process_cmd
self.functors = nn.ModuleList()
cur_a_len = 0
cur_n_len = 0
cur_d_len = 0
for cmd in self.process_cmd:
if cmd == 'a':
self.functors.add_module('add_res_connect_{}'.format(
cur_a_len), LambdaXY(lambda x, y: x + y if y is not
None else x))
cur_a_len += 1
elif cmd == 'n':
layerNorm = torch.nn.LayerNorm(normalized_shape=d_model,
elementwise_affine=True, eps=1e-05)
self.functors.add_module('layer_norm_%d' % cur_n_len, layerNorm
)
cur_n_len += 1
elif cmd == 'd':
self.functors.add_module('add_drop_{}'.format(cur_d_len),
Lambda(lambda x: F.dropout(x, p=dropout_rate) if
dropout_rate else x))
cur_d_len += 1
def forward(self, x, residual=None):
for i, (cmd, functor) in enumerate(zip(self.process_cmd, self.functors)
):
if cmd == 'a':
x = functor(x, residual)
else:
x = functor(x)
return x
class EncoderLayer(nn.Module):
"""
EncoderLayer
"""
def __init__(self, n_head, d_key, d_value, d_model, d_inner_hid,
prepostprocess_dropout, attention_dropout, relu_dropout,
preprocess_cmd='n', postprocess_cmd='da'):
super(EncoderLayer, self).__init__()
self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head,
attention_dropout)
self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.ffn = FFN(d_inner_hid, d_model, relu_dropout)
self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, enc_input, attn_bias):
attn_output = self.self_attn(self.preprocesser1(enc_input), None,
None, attn_bias)
attn_output = self.postprocesser1(attn_output, enc_input)
ffn_output = self.ffn(self.preprocesser2(attn_output))
ffn_output = self.postprocesser2(ffn_output, attn_output)
return ffn_output
class Encoder(nn.Module):
"""
encoder
"""
def __init__(self, n_layer, n_head, d_key, d_value, d_model,
d_inner_hid, prepostprocess_dropout, attention_dropout,
relu_dropout, preprocess_cmd='n', postprocess_cmd='da'):
super(Encoder, self).__init__()
self.encoder_layers = nn.ModuleList()
for i in range(n_layer):
encoderLayer = EncoderLayer(n_head, d_key, d_value, d_model,
d_inner_hid, prepostprocess_dropout, attention_dropout,
relu_dropout, preprocess_cmd, postprocess_cmd)
self.encoder_layers.add_module('layer_%d' % i, encoderLayer)
self.processer = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, enc_input, attn_bias):
for encoder_layer in self.encoder_layers:
enc_output = encoder_layer(enc_input, attn_bias)
enc_input = enc_output
enc_output = self.processer(enc_output)
return enc_output
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_layer': 1, 'n_head': 4, 'd_key': 4, 'd_value': 4,
'd_model': 4, 'd_inner_hid': 4, 'prepostprocess_dropout': 0.5,
'attention_dropout': 0.5, 'relu_dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, 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_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__softmax_add_mul_4(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x2), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp5 * tmp1
tmp8 = tmp6 + tmp7
tmp9 = triton_helpers.maximum(tmp4, tmp8)
tmp11 = tmp10 * tmp1
tmp13 = tmp11 + tmp12
tmp14 = triton_helpers.maximum(tmp9, tmp13)
tmp16 = tmp15 * tmp1
tmp18 = tmp16 + tmp17
tmp19 = triton_helpers.maximum(tmp14, tmp18)
tmp20 = tmp4 - tmp19
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp8 - tmp19
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp19
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp24 + tmp26
tmp28 = tmp18 - tmp19
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp27 + tmp29
tl.store(out_ptr0 + x2, tmp19, xmask)
tl.store(out_ptr1 + x2, tmp30, xmask)
@triton.jit
def triton_poi_fused__softmax_add_mul_5(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex % 64
x5 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last')
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp9 = tmp7 / tmp8
tl.store(in_out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_6(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 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_7(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (16, 4), (4, 1))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16, 4), (4, 1))
assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_8, (4, 16), (16, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4,), (1,))
assert_size_stride(primals_16, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_3, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 16), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf4)
buf5 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 16), (1, 4), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf3, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_clone_3[grid(64, 4)](buf4, buf7, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0)
del buf4
extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1), 0), out=buf8)
buf9 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_mul_4[grid(64)](buf8, primals_7, buf9,
buf10, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf8
triton_poi_fused__softmax_add_mul_5[grid(256)](buf11, primals_7,
buf9, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf12 = torch.ops.aten.native_dropout.default(buf11, 0.5, True)
buf13 = buf12[0]
buf14 = buf12[1]
del buf12
buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf5, buf15, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf16 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(buf13, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf15, (16, 4, 4), (16, 4, 1), 0), out=buf16
)
buf17 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf16, buf17, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf16
buf18 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf17, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_8, (16, 4), (1, 16), 0), out=buf18)
buf19 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf18, (4, 4, 4), (16, 4, 1), 0), 0.5, True)
buf20 = buf19[0]
buf21 = buf19[1]
del buf19
buf22 = buf20
del buf20
triton_poi_fused_add_6[grid(64)](buf22, primals_3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf23 = buf1
del buf1
buf24 = buf0
del buf0
triton_poi_fused_native_layer_norm_0[grid(16)](buf22, buf23, buf24,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf25 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_native_layer_norm_1[grid(64)](buf22, buf23, buf24,
primals_9, primals_10, buf25, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_10
buf26 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf25, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf26)
buf27 = reinterpret_tensor(buf26, (4, 4, 4), (16, 4, 1), 0)
del buf26
buf39 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_7[grid(64)](buf27,
primals_12, buf39, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
buf28 = torch.ops.aten.native_dropout.default(buf27, 0.5, True)
buf29 = buf28[0]
buf30 = buf28[1]
del buf28
buf31 = reinterpret_tensor(buf27, (16, 4), (4, 1), 0)
del buf27
extern_kernels.addmm(primals_14, reinterpret_tensor(buf29, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf31)
del primals_14
buf32 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf31, (4, 4, 4), (16, 4, 1), 0), 0.5, True)
buf33 = buf32[0]
buf34 = buf32[1]
del buf32
buf35 = buf33
del buf33
triton_poi_fused_add_6[grid(64)](buf35, buf22, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf36 = buf24
del buf24
buf37 = buf23
del buf23
triton_poi_fused_native_layer_norm_0[grid(16)](buf35, buf36, buf37,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf38 = reinterpret_tensor(buf31, (4, 4, 4), (16, 4, 1), 0)
del buf31
triton_poi_fused_native_layer_norm_1[grid(64)](buf35, buf36, buf37,
primals_15, primals_16, buf38, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf36
del buf37
del primals_16
return (buf38, primals_3, primals_9, primals_15, reinterpret_tensor(
buf2, (16, 4), (4, 1), 0), buf11, buf14, reinterpret_tensor(buf17,
(16, 16), (16, 1), 0), buf21, buf22, reinterpret_tensor(buf25, (16,
4), (4, 1), 0), buf30, reinterpret_tensor(buf29, (16, 4), (4, 1), 0
), buf34, buf35, primals_13, buf39, primals_11, primals_8,
reinterpret_tensor(buf13, (16, 4, 4), (16, 1, 4), 0),
reinterpret_tensor(buf15, (16, 4, 4), (16, 1, 4), 0),
reinterpret_tensor(buf6, (16, 4, 4), (16, 1, 4), 0),
reinterpret_tensor(buf7, (16, 4, 4), (16, 1, 4), 0), primals_6,
primals_5, primals_4)
class Lambda(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x):
return self.func(x)
class FFN(nn.Module):
"""
Feed-Forward Network
"""
def __init__(self, d_inner_hid, d_model, dropout_rate):
super(FFN, self).__init__()
self.dropout_rate = dropout_rate
self.fc1 = torch.nn.Linear(in_features=d_model, out_features=
d_inner_hid)
self.fc2 = torch.nn.Linear(in_features=d_inner_hid, out_features=
d_model)
def forward(self, x):
hidden = self.fc1(x)
hidden = F.relu(hidden)
if self.dropout_rate:
hidden = F.dropout(hidden, p=self.dropout_rate)
out = self.fc2(hidden)
return out
class MultiHeadAttention(nn.Module):
"""
Multi-Head Attention
"""
def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.0):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_key = d_key
self.d_value = d_value
self.d_model = d_model
self.dropout_rate = dropout_rate
self.q_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.k_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.v_fc = torch.nn.Linear(in_features=d_model, out_features=
d_value * n_head, bias=False)
self.proj_fc = torch.nn.Linear(in_features=d_value * n_head,
out_features=d_model, bias=False)
def _prepare_qkv(self, queries, keys, values, cache=None):
if keys is None:
keys, values = queries, queries
static_kv = False
else:
static_kv = True
q = self.q_fc(queries)
q = torch.reshape(q, shape=[q.size(0), q.size(1), self.n_head, self
.d_key])
q = q.permute(0, 2, 1, 3)
if cache is not None and static_kv and 'static_k' in cache:
k = cache['static_k']
v = cache['static_v']
else:
k = self.k_fc(keys)
v = self.v_fc(values)
k = torch.reshape(k, shape=[k.size(0), k.size(1), self.n_head,
self.d_key])
k = k.permute(0, 2, 1, 3)
v = torch.reshape(v, shape=[v.size(0), v.size(1), self.n_head,
self.d_value])
v = v.permute(0, 2, 1, 3)
if cache is not None:
if static_kv and 'static_k' not in cache:
cache['static_k'], cache['static_v'] = k, v
elif not static_kv:
cache_k, cache_v = cache['k'], cache['v']
k = torch.cat([cache_k, k], dim=2)
v = torch.cat([cache_v, v], dim=2)
cache['k'], cache['v'] = k, v
return q, k, v
def forward(self, queries, keys, values, attn_bias, cache=None):
keys = queries if keys is None else keys
values = keys if values is None else values
q, k, v = self._prepare_qkv(queries, keys, values, cache)
product = torch.matmul(q, k.transpose(2, 3))
product = product * self.d_model ** -0.5
if attn_bias is not None:
product += attn_bias
weights = F.softmax(product, dim=-1)
if self.dropout_rate:
weights = F.dropout(weights, p=self.dropout_rate)
out = torch.matmul(weights, v)
out = out.permute(0, 2, 1, 3)
out = torch.reshape(out, shape=[out.size(0), out.size(1), out.shape
[2] * out.shape[3]])
out = self.proj_fc(out)
return out
class LambdaXY(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x, y):
return self.func(x, y)
class PrePostProcessLayer(nn.Module):
"""
PrePostProcessLayer
"""
def __init__(self, process_cmd, d_model, dropout_rate):
super(PrePostProcessLayer, self).__init__()
self.process_cmd = process_cmd
self.functors = nn.ModuleList()
cur_a_len = 0
cur_n_len = 0
cur_d_len = 0
for cmd in self.process_cmd:
if cmd == 'a':
self.functors.add_module('add_res_connect_{}'.format(
cur_a_len), LambdaXY(lambda x, y: x + y if y is not
None else x))
cur_a_len += 1
elif cmd == 'n':
layerNorm = torch.nn.LayerNorm(normalized_shape=d_model,
elementwise_affine=True, eps=1e-05)
self.functors.add_module('layer_norm_%d' % cur_n_len, layerNorm
)
cur_n_len += 1
elif cmd == 'd':
self.functors.add_module('add_drop_{}'.format(cur_d_len),
Lambda(lambda x: F.dropout(x, p=dropout_rate) if
dropout_rate else x))
cur_d_len += 1
def forward(self, x, residual=None):
for i, (cmd, functor) in enumerate(zip(self.process_cmd, self.functors)
):
if cmd == 'a':
x = functor(x, residual)
else:
x = functor(x)
return x
class EncoderLayer(nn.Module):
"""
EncoderLayer
"""
def __init__(self, n_head, d_key, d_value, d_model, d_inner_hid,
prepostprocess_dropout, attention_dropout, relu_dropout,
preprocess_cmd='n', postprocess_cmd='da'):
super(EncoderLayer, self).__init__()
self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head,
attention_dropout)
self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.ffn = FFN(d_inner_hid, d_model, relu_dropout)
self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, enc_input, attn_bias):
attn_output = self.self_attn(self.preprocesser1(enc_input), None,
None, attn_bias)
attn_output = self.postprocesser1(attn_output, enc_input)
ffn_output = self.ffn(self.preprocesser2(attn_output))
ffn_output = self.postprocesser2(ffn_output, attn_output)
return ffn_output
class EncoderNew(nn.Module):
"""
encoder
"""
def __init__(self, n_layer, n_head, d_key, d_value, d_model,
d_inner_hid, prepostprocess_dropout, attention_dropout,
relu_dropout, preprocess_cmd='n', postprocess_cmd='da'):
super(EncoderNew, self).__init__()
self.encoder_layers = nn.ModuleList()
for i in range(n_layer):
encoderLayer = EncoderLayer(n_head, d_key, d_value, d_model,
d_inner_hid, prepostprocess_dropout, attention_dropout,
relu_dropout, preprocess_cmd, postprocess_cmd)
self.encoder_layers.add_module('layer_%d' % i, encoderLayer)
self.processer = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, input_0, input_1):
primals_1 = (self.encoder_layers.layer_0.preprocesser1.functors.
layer_norm_0.weight)
primals_2 = (self.encoder_layers.layer_0.preprocesser1.functors.
layer_norm_0.bias)
primals_4 = self.encoder_layers.layer_0.self_attn.q_fc.weight
primals_5 = self.encoder_layers.layer_0.self_attn.k_fc.weight
primals_6 = self.encoder_layers.layer_0.self_attn.v_fc.weight
primals_8 = self.encoder_layers.layer_0.self_attn.proj_fc.weight
primals_9 = (self.encoder_layers.layer_0.preprocesser2.functors.
layer_norm_0.weight)
primals_10 = (self.encoder_layers.layer_0.preprocesser2.functors.
layer_norm_0.bias)
primals_11 = self.encoder_layers.layer_0.ffn.fc1.weight
primals_12 = self.encoder_layers.layer_0.ffn.fc1.bias
primals_13 = self.encoder_layers.layer_0.ffn.fc2.weight
primals_14 = self.encoder_layers.layer_0.ffn.fc2.bias
primals_15 = self.processer.functors.layer_norm_0.weight
primals_16 = self.processer.functors.layer_norm_0.bias
primals_3 = 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,
primals_15, primals_16])
return output[0]
|
BHD233/PaddleOCR2Pytorch
|
Encoder
| false
| 13,377
|
[
"Apache-2.0"
] | 364
|
f114069b3e2669c6adf0adf9596756205f184c9c
|
https://github.com/BHD233/PaddleOCR2Pytorch/tree/f114069b3e2669c6adf0adf9596756205f184c9c
|
SEModule
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def hardsigmoid(x):
return F.relu6(x + 3.0, inplace=True) / 6.0
class SEModule(nn.Module):
def __init__(self, channel, reduction=4):
super(SEModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv1 = nn.Conv2d(in_channels=channel, out_channels=channel //
reduction, kernel_size=1, stride=1, padding=0, bias=True)
self.conv2 = nn.Conv2d(in_channels=channel // reduction,
out_channels=channel, kernel_size=1, stride=1, padding=0, bias=True
)
def forward(self, inputs):
outputs = self.avg_pool(inputs)
outputs = self.conv1(outputs)
outputs = F.relu(outputs)
outputs = self.conv2(outputs)
outputs = hardsigmoid(outputs)
return torch.mul(inputs, outputs)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channel': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_convolution_div_hardtanh_mul_2(in_ptr0, in_ptr1,
in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex // 16
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = 3.0
tmp5 = tmp3 + tmp4
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = 6.0
tmp9 = triton_helpers.minimum(tmp7, tmp8)
tmp10 = 0.16666666666666666
tmp11 = tmp9 * tmp10
tmp12 = tmp0 * tmp11
tl.store(out_ptr0 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused_add_convolution_hardtanh_backward_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 3.0
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tmp7 = 6.0
tmp8 = tmp4 >= tmp7
tmp9 = tmp6 | tmp8
tl.store(out_ptr0 + x2, tmp9, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 1, 1), (1, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(4)](buf3, primals_3, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_3
buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 1, 1), (4, 1, 1, 1))
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_convolution_div_hardtanh_mul_2[grid(256)](
primals_1, buf4, primals_5, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
buf6 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool)
triton_poi_fused_add_convolution_hardtanh_backward_3[grid(16)](buf4,
primals_5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf4
del primals_5
return buf5, primals_1, primals_2, primals_4, buf1, buf3, buf6
def hardsigmoid(x):
return F.relu6(x + 3.0, inplace=True) / 6.0
class SEModuleNew(nn.Module):
def __init__(self, channel, reduction=4):
super(SEModuleNew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv1 = nn.Conv2d(in_channels=channel, out_channels=channel //
reduction, kernel_size=1, stride=1, padding=0, bias=True)
self.conv2 = nn.Conv2d(in_channels=channel // reduction,
out_channels=channel, kernel_size=1, stride=1, padding=0, bias=True
)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
BHD233/PaddleOCR2Pytorch
|
SEModule
| false
| 13,378
|
[
"Apache-2.0"
] | 364
|
f114069b3e2669c6adf0adf9596756205f184c9c
|
https://github.com/BHD233/PaddleOCR2Pytorch/tree/f114069b3e2669c6adf0adf9596756205f184c9c
|
MultiheadAttention
|
import torch
import torch.nn as nn
import torch._C
import torch.serialization
from torch import optim as optim
class MultiheadAttention(nn.Module):
"""A warpper for torch.nn.MultiheadAttention.
This module implements MultiheadAttention with residual connection,
and positional encoding used in DETR is also passed as input.
Args:
embed_dims (int): The embedding dimension.
num_heads (int): Parallel attention heads. Same as
`nn.MultiheadAttention`.
dropout (float): A Dropout layer on attn_output_weights. Default 0.0.
"""
def __init__(self, embed_dims, num_heads, dropout=0.0):
super(MultiheadAttention, self).__init__()
assert embed_dims % num_heads == 0, f'embed_dims must be divisible by num_heads. got {embed_dims} and {num_heads}.'
self.embed_dims = embed_dims
self.num_heads = num_heads
self.dropout = dropout
self.attn = nn.MultiheadAttention(embed_dims, num_heads, dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, x, key=None, value=None, residual=None, query_pos=
None, key_pos=None, attn_mask=None, key_padding_mask=None):
"""Forward function for `MultiheadAttention`.
Args:
x (Tensor): The input query with shape [num_query, bs,
embed_dims]. Same in `nn.MultiheadAttention.forward`.
key (Tensor): The key tensor with shape [num_key, bs,
embed_dims]. Same in `nn.MultiheadAttention.forward`.
Default None. If None, the `query` will be used.
value (Tensor): The value tensor with same shape as `key`.
Same in `nn.MultiheadAttention.forward`. Default None.
If None, the `key` will be used.
residual (Tensor): The tensor used for addition, with the
same shape as `x`. Default None. If None, `x` will be used.
query_pos (Tensor): The positional encoding for query, with
the same shape as `x`. Default None. If not None, it will
be added to `x` before forward function.
key_pos (Tensor): The positional encoding for `key`, with the
same shape as `key`. Default None. If not None, it will
be added to `key` before forward function. If None, and
`query_pos` has the same shape as `key`, then `query_pos`
will be used for `key_pos`.
attn_mask (Tensor): ByteTensor mask with shape [num_query,
num_key]. Same in `nn.MultiheadAttention.forward`.
Default None.
key_padding_mask (Tensor): ByteTensor with shape [bs, num_key].
Same in `nn.MultiheadAttention.forward`. Default None.
Returns:
Tensor: forwarded results with shape [num_query, bs, embed_dims].
"""
query = x
if key is None:
key = query
if value is None:
value = key
if residual is None:
residual = x
if key_pos is None:
if query_pos is not None and key is not None:
if query_pos.shape == key.shape:
key_pos = query_pos
if query_pos is not None:
query = query + query_pos
if key_pos is not None:
key = key + key_pos
out = self.attn(query, key, value=value, attn_mask=attn_mask,
key_padding_mask=key_padding_mask)[0]
return residual + self.dropout(out)
def __repr__(self):
"""str: a string that describes the module"""
repr_str = self.__class__.__name__
repr_str += f'(embed_dims={self.embed_dims}, '
repr_str += f'num_heads={self.num_heads}, '
repr_str += f'dropout={self.dropout})'
return repr_str
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embed_dims': 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._C
import torch.serialization
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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 4),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 8),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf2)
del primals_2
buf3 = reinterpret_tensor(buf0, (4, 4, 1), (1, 4, 16), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](buf3, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf5
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4,
1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
extern_kernels.mm(reinterpret_tensor(buf8, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf9)
buf10 = buf9
del buf9
triton_poi_fused_add_4[grid(16)](buf10, primals_1, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf10, primals_1, buf6, reinterpret_tensor(buf8, (4, 4), (4, 1), 0
), primals_4, reinterpret_tensor(buf2, (4, 1, 4), (1, 1, 4), 0
), reinterpret_tensor(buf3, (4, 1, 4), (1, 1, 4), 0
), reinterpret_tensor(buf1, (4, 4, 1), (1, 4, 1), 0)
class MultiheadAttentionNew(nn.Module):
"""A warpper for torch.nn.MultiheadAttention.
This module implements MultiheadAttention with residual connection,
and positional encoding used in DETR is also passed as input.
Args:
embed_dims (int): The embedding dimension.
num_heads (int): Parallel attention heads. Same as
`nn.MultiheadAttention`.
dropout (float): A Dropout layer on attn_output_weights. Default 0.0.
"""
def __init__(self, embed_dims, num_heads, dropout=0.0):
super(MultiheadAttentionNew, self).__init__()
assert embed_dims % num_heads == 0, f'embed_dims must be divisible by num_heads. got {embed_dims} and {num_heads}.'
self.embed_dims = embed_dims
self.num_heads = num_heads
self.dropout = dropout
self.attn = nn.MultiheadAttention(embed_dims, num_heads, dropout)
self.dropout = nn.Dropout(dropout)
def __repr__(self):
"""str: a string that describes the module"""
repr_str = self.__class__.__name__
repr_str += f'(embed_dims={self.embed_dims}, '
repr_str += f'num_heads={self.num_heads}, '
repr_str += f'dropout={self.dropout})'
return repr_str
def forward(self, input_0):
primals_2 = self.attn.in_proj_weight
primals_3 = self.attn.in_proj_bias
primals_1 = self.attn.out_proj.weight
primals_5 = self.attn.out_proj.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Atten4Vis/DemystifyLocalViT
|
MultiheadAttention
| false
| 13,379
|
[
"MIT"
] | 64
|
2e2327caec6d56ae2c8aa861b32bb62f3cdb786e
|
https://github.com/Atten4Vis/DemystifyLocalViT/tree/2e2327caec6d56ae2c8aa861b32bb62f3cdb786e
|
MetricCalcLayer
|
import torch
import torch.nn as nn
class MetricCalcLayer(nn.Module):
"""
Description
-----------
Calculate metric in equation 3 of paper.
Parameters
----------
nhid : int
The dimension of mapped features in the graph generating procedure.
"""
def __init__(self, nhid):
super().__init__()
self.weight = nn.Parameter(torch.FloatTensor(1, nhid))
nn.init.xavier_uniform_(self.weight)
def forward(self, h):
"""
Parameters
----------
h : tensor
The result of the Hadamard product in equation 3 of paper.
"""
return h * self.weight
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nhid': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_2, primals_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
return buf0, primals_2
class MetricCalcLayerNew(nn.Module):
"""
Description
-----------
Calculate metric in equation 3 of paper.
Parameters
----------
nhid : int
The dimension of mapped features in the graph generating procedure.
"""
def __init__(self, nhid):
super().__init__()
self.weight = nn.Parameter(torch.FloatTensor(1, nhid))
nn.init.xavier_uniform_(self.weight)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
BUPT-GAMMA/OpenHGNN
|
MetricCalcLayer
| false
| 13,380
|
[
"Apache-2.0"
] | 235
|
5f218dad4ed1415aa6d842bc20785c61e74e5405
|
https://github.com/BUPT-GAMMA/OpenHGNN/tree/5f218dad4ed1415aa6d842bc20785c61e74e5405
|
GCN
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class GraphConvolution(nn.Module):
"""
Description
-----------
The downstream GCN layer.
"""
def __init__(self, in_features, out_features, bias=True):
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)
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
reset_parameters(self)
def forward(self, inputs, adj):
"""
Parameters
----------
inputs : tensor
The feature matrix.
adj : tensor
The adjacent matrix.
"""
support = torch.mm(inputs, self.weight)
output = torch.mm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
class GCN(nn.Module):
"""
Description
-----------
The downstream GCN model.
"""
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dropout = dropout
def forward(self, x, adj):
"""
Parameters
----------
x : tensor
The feature matrix.
adj : tensor
The adjacent matrix.
"""
x = F.relu(self.gc1(x, adj))
x = F.dropout(x, self.dropout, training=self.training)
x = self.gc2(x, adj)
return x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'nfeat': 4, 'nhid': 4, 'nclass': 4, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import math
import torch.nn as nn
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_relu_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 = 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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_2, primals_1, out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, buf0, out=buf1)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_relu_0[grid(16)](buf2, primals_4, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del primals_4
buf3 = buf0
del buf0
extern_kernels.mm(buf2, primals_5, out=buf3)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_3, buf3, alpha=1, beta=1,
out=buf4)
del buf3
del primals_6
return buf4, buf2, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0)
class GraphConvolution(nn.Module):
"""
Description
-----------
The downstream GCN layer.
"""
def __init__(self, in_features, out_features, bias=True):
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)
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
reset_parameters(self)
def forward(self, inputs, adj):
"""
Parameters
----------
inputs : tensor
The feature matrix.
adj : tensor
The adjacent matrix.
"""
support = torch.mm(inputs, self.weight)
output = torch.mm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
class GCNNew(nn.Module):
"""
Description
-----------
The downstream GCN model.
"""
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCNNew, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dropout = dropout
def forward(self, input_0, input_1):
primals_1 = self.gc1.weight
primals_4 = self.gc1.bias
primals_2 = self.gc2.weight
primals_6 = self.gc2.bias
primals_3 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
BUPT-GAMMA/OpenHGNN
|
GCN
| false
| 13,381
|
[
"Apache-2.0"
] | 235
|
5f218dad4ed1415aa6d842bc20785c61e74e5405
|
https://github.com/BUPT-GAMMA/OpenHGNN/tree/5f218dad4ed1415aa6d842bc20785c61e74e5405
|
ScoreCap
|
import torch
from torch import nn
import torch.nn
import torch.optim
class ScoreCap(nn.Module):
def __init__(self, cap: 'float'):
super().__init__()
self.cap = cap
def forward(self, input):
return torch.clip(input, max=self.cap)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'cap': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
import torch.nn
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_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 = triton_helpers.minimum(tmp0, tmp1)
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ScoreCapNew(nn.Module):
def __init__(self, cap: 'float'):
super().__init__()
self.cap = cap
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BerenLuthien/ReAgent
|
ScoreCap
| false
| 13,382
|
[
"BSD-3-Clause"
] | 1,156
|
52f666670a7fa03206812ef48949f6b934d400f7
|
https://github.com/BerenLuthien/ReAgent/tree/52f666670a7fa03206812ef48949f6b934d400f7
|
Conv2dZeros
|
import torch
import torch.nn as nn
class _ActNorm(nn.Module):
"""
Activation Normalization
Initialize the bias and scale with a given minibatch,
so that the output per-channel have zero mean and unit variance for that.
After initialization, `bias` and `logs` will be trained as parameters.
"""
def __init__(self, num_features, scale=1.0):
super().__init__()
size = [1, num_features, 1, 1]
self.register_parameter('bias', nn.Parameter(torch.zeros(*size)))
self.register_parameter('logs', nn.Parameter(torch.zeros(*size)))
self.num_features = num_features
self.scale = float(scale)
self.inited = False
def _check_input_dim(self, input):
return NotImplemented
def initialize_parameters(self, input):
self._check_input_dim(input)
if not self.training:
return
assert input.device == self.bias.device
with torch.no_grad():
bias = thops.mean(input.clone(), dim=[0, 2, 3], keepdim=True
) * -1.0
vars = thops.mean((input.clone() + bias) ** 2, dim=[0, 2, 3],
keepdim=True)
logs = torch.log(self.scale / (torch.sqrt(vars) + 1e-06))
self.bias.data.copy_(bias.data)
self.logs.data.copy_(logs.data)
self.inited = True
def _center(self, input, reverse=False):
if not reverse:
return input + self.bias
else:
return input - self.bias
def _scale(self, input, logdet=None, reverse=False):
logs = self.logs
if not reverse:
input = input * torch.exp(logs)
else:
input = input * torch.exp(-logs)
if logdet is not None:
"""
logs is log_std of `mean of channels`
so we need to multiply pixels
"""
dlogdet = thops.sum(logs) * thops.pixels(input)
if reverse:
dlogdet *= -1
logdet = logdet + dlogdet
return input, logdet
def forward(self, input, logdet=None, reverse=False):
if not self.inited:
self.initialize_parameters(input)
self._check_input_dim(input)
if not reverse:
input = self._center(input, reverse)
input, logdet = self._scale(input, logdet, reverse)
else:
input, logdet = self._scale(input, logdet, reverse)
input = self._center(input, reverse)
return input, logdet
class ActNorm2d(_ActNorm):
def __init__(self, num_features, scale=1.0):
super().__init__(num_features, scale)
def _check_input_dim(self, input):
assert len(input.size()) == 4
assert input.size(1
) == self.num_features, '[ActNorm]: input should be in shape as `BCHW`, channels should be {} rather than {}'.format(
self.num_features, input.size())
class Conv2d(nn.Conv2d):
pad_dict = {'same': lambda kernel, stride: [(((k - 1) * s + 1) // 2) for
k, s in zip(kernel, stride)], 'valid': lambda kernel, stride: [(0) for
_ in kernel]}
@staticmethod
def get_padding(padding, kernel_size, stride):
if isinstance(padding, str):
if isinstance(kernel_size, int):
kernel_size = [kernel_size, kernel_size]
if isinstance(stride, int):
stride = [stride, stride]
padding = padding.lower()
try:
padding = Conv2d.pad_dict[padding](kernel_size, stride)
except KeyError:
raise ValueError('{} is not supported'.format(padding))
return padding
def __init__(self, in_channels, out_channels, kernel_size=[3, 3],
stride=[1, 1], padding='same', do_actnorm=True, weight_std=0.05):
padding = Conv2d.get_padding(padding, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, bias=not do_actnorm)
self.weight.data.normal_(mean=0.0, std=weight_std)
if not do_actnorm:
self.bias.data.zero_()
else:
self.actnorm = ActNorm2d(out_channels)
self.do_actnorm = do_actnorm
def forward(self, input):
x = super().forward(input)
if self.do_actnorm:
x, _ = self.actnorm(x)
return x
class Conv2dZeros(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size=[3, 3],
stride=[1, 1], padding='same', logscale_factor=3):
padding = Conv2d.get_padding(padding, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding)
self.logscale_factor = logscale_factor
self.register_parameter('logs', nn.Parameter(torch.zeros(
out_channels, 1, 1)))
self.weight.data.zero_()
self.bias.data.zero_()
def forward(self, input):
output = super().forward(input)
return output * torch.exp(self.logs * self.logscale_factor)
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 math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_exp_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = 3.0
tmp5 = tmp3 * tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp2 * tmp6
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 1, 1), (1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_exp_mul_0[grid(256)](buf1, primals_2,
primals_4, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf2, primals_1, primals_3, primals_4, buf1
class _ActNorm(nn.Module):
"""
Activation Normalization
Initialize the bias and scale with a given minibatch,
so that the output per-channel have zero mean and unit variance for that.
After initialization, `bias` and `logs` will be trained as parameters.
"""
def __init__(self, num_features, scale=1.0):
super().__init__()
size = [1, num_features, 1, 1]
self.register_parameter('bias', nn.Parameter(torch.zeros(*size)))
self.register_parameter('logs', nn.Parameter(torch.zeros(*size)))
self.num_features = num_features
self.scale = float(scale)
self.inited = False
def _check_input_dim(self, input):
return NotImplemented
def initialize_parameters(self, input):
self._check_input_dim(input)
if not self.training:
return
assert input.device == self.bias.device
with torch.no_grad():
bias = thops.mean(input.clone(), dim=[0, 2, 3], keepdim=True
) * -1.0
vars = thops.mean((input.clone() + bias) ** 2, dim=[0, 2, 3],
keepdim=True)
logs = torch.log(self.scale / (torch.sqrt(vars) + 1e-06))
self.bias.data.copy_(bias.data)
self.logs.data.copy_(logs.data)
self.inited = True
def _center(self, input, reverse=False):
if not reverse:
return input + self.bias
else:
return input - self.bias
def _scale(self, input, logdet=None, reverse=False):
logs = self.logs
if not reverse:
input = input * torch.exp(logs)
else:
input = input * torch.exp(-logs)
if logdet is not None:
"""
logs is log_std of `mean of channels`
so we need to multiply pixels
"""
dlogdet = thops.sum(logs) * thops.pixels(input)
if reverse:
dlogdet *= -1
logdet = logdet + dlogdet
return input, logdet
def forward(self, input, logdet=None, reverse=False):
if not self.inited:
self.initialize_parameters(input)
self._check_input_dim(input)
if not reverse:
input = self._center(input, reverse)
input, logdet = self._scale(input, logdet, reverse)
else:
input, logdet = self._scale(input, logdet, reverse)
input = self._center(input, reverse)
return input, logdet
class ActNorm2d(_ActNorm):
def __init__(self, num_features, scale=1.0):
super().__init__(num_features, scale)
def _check_input_dim(self, input):
assert len(input.size()) == 4
assert input.size(1
) == self.num_features, '[ActNorm]: input should be in shape as `BCHW`, channels should be {} rather than {}'.format(
self.num_features, input.size())
class Conv2d(nn.Conv2d):
pad_dict = {'same': lambda kernel, stride: [(((k - 1) * s + 1) // 2) for
k, s in zip(kernel, stride)], 'valid': lambda kernel, stride: [(0) for
_ in kernel]}
@staticmethod
def get_padding(padding, kernel_size, stride):
if isinstance(padding, str):
if isinstance(kernel_size, int):
kernel_size = [kernel_size, kernel_size]
if isinstance(stride, int):
stride = [stride, stride]
padding = padding.lower()
try:
padding = Conv2d.pad_dict[padding](kernel_size, stride)
except KeyError:
raise ValueError('{} is not supported'.format(padding))
return padding
def __init__(self, in_channels, out_channels, kernel_size=[3, 3],
stride=[1, 1], padding='same', do_actnorm=True, weight_std=0.05):
padding = Conv2d.get_padding(padding, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, bias=not do_actnorm)
self.weight.data.normal_(mean=0.0, std=weight_std)
if not do_actnorm:
self.bias.data.zero_()
else:
self.actnorm = ActNorm2d(out_channels)
self.do_actnorm = do_actnorm
def forward(self, input):
x = super().forward(input)
if self.do_actnorm:
x, _ = self.actnorm(x)
return x
class Conv2dZerosNew(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size=[3, 3],
stride=[1, 1], padding='same', logscale_factor=3):
padding = Conv2d.get_padding(padding, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding)
self.logscale_factor = logscale_factor
self.register_parameter('logs', nn.Parameter(torch.zeros(
out_channels, 1, 1)))
self.weight.data.zero_()
self.bias.data.zero_()
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_4 = self.logs
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
BQZic/glow-pytorch
|
Conv2dZeros
| false
| 13,383
|
[
"MIT"
] | 479
|
4b43042326bbe644ccfda3c81a138375321808ed
|
https://github.com/BQZic/glow-pytorch/tree/4b43042326bbe644ccfda3c81a138375321808ed
|
Embedder
|
import math
import torch
from torch import nn
import torch.nn
import torch.optim
class Embedder(nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
self.dim_in = dim_in
self.dim_out = dim_out
self.linear = nn.Linear(self.dim_in, self.dim_out)
def forward(self, x):
output = self.linear(x) * math.sqrt(self.dim_out)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_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 import nn
import torch.nn
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_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](buf1, primals_2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
class EmbedderNew(nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
self.dim_in = dim_in
self.dim_out = dim_out
self.linear = nn.Linear(self.dim_in, self.dim_out)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
BerenLuthien/ReAgent
|
Embedder
| false
| 13,384
|
[
"BSD-3-Clause"
] | 1,156
|
52f666670a7fa03206812ef48949f6b934d400f7
|
https://github.com/BerenLuthien/ReAgent/tree/52f666670a7fa03206812ef48949f6b934d400f7
|
ConvWS2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1,
groups=1, eps=1e-05):
c_in = weight.size(0)
weight_flat = weight.view(c_in, -1)
mean = weight_flat.mean(dim=1, keepdim=True).view(c_in, 1, 1, 1)
std = weight_flat.std(dim=1, keepdim=True).view(c_in, 1, 1, 1)
weight = (weight - mean) / (std + eps)
return F.conv2d(input, weight, bias, stride, padding, dilation, groups)
class ConvWS2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, eps=1e-05):
super(ConvWS2d, self).__init__(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, dilation=dilation,
groups=groups, bias=bias)
self.eps = eps
def forward(self, x):
return conv_ws_2d(x, self.weight, self.bias, self.stride, self.
padding, self.dilation, self.groups, self.eps)
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 libdevice
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_mean_std_sub_0(in_out_ptr0, in_out_ptr1,
in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.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 = tmp0 - tmp20
tmp25 = 1e-05
tmp26 = tmp23 + tmp25
tmp27 = tmp24 / tmp26
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp23, xmask)
tl.store(out_ptr0 + (r1 + 64 * x0), tmp27, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf3 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1), (1, 1), 0)
del buf0
buf5 = reinterpret_tensor(buf3, (4, 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_std_sub_0[grid(4)](buf1, buf5,
primals_1, buf6, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf7 = extern_kernels.convolution(primals_3, buf6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 4, 1, 1), (4, 1, 1, 1))
buf8 = buf7
del buf7
triton_poi_fused_convolution_1[grid(16)](buf8, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
return buf8, primals_1, primals_3, buf1, buf5, buf6
def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1,
groups=1, eps=1e-05):
c_in = weight.size(0)
weight_flat = weight.view(c_in, -1)
mean = weight_flat.mean(dim=1, keepdim=True).view(c_in, 1, 1, 1)
std = weight_flat.std(dim=1, keepdim=True).view(c_in, 1, 1, 1)
weight = (weight - mean) / (std + eps)
return F.conv2d(input, weight, bias, stride, padding, dilation, groups)
class ConvWS2dNew(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, eps=1e-05):
super(ConvWS2dNew, self).__init__(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, dilation=dilation,
groups=groups, bias=bias)
self.eps = eps
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]
|
BUPT-PRIV/BalancedGroupSoftmax
|
ConvWS2d
| false
| 13,385
|
[
"Apache-2.0"
] | 333
|
90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
https://github.com/BUPT-PRIV/BalancedGroupSoftmax/tree/90e04fd8ccecd2bc61bbe6053a741ae708da2794
|
GeLU
|
import math
import torch
import torch.nn as nn
def gelu(x):
"""Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
Also see https://arxiv.org/abs/1606.08415
"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class GeLU(nn.Module):
"""Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
Also see https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super().__init__()
def forward(self, x):
return gelu(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_erf_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865475
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_erf_mul_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def gelu(x):
"""Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
Also see https://arxiv.org/abs/1606.08415
"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class GeLUNew(nn.Module):
"""Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
Also see https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BigRedT/gpv-1
|
GeLU
| false
| 13,386
|
[
"Apache-2.0"
] | 45
|
6a0c2173b44961cb492d00f94864c461aa77641d
|
https://github.com/BigRedT/gpv-1/tree/6a0c2173b44961cb492d00f94864c461aa77641d
|
ModuloMapIDList
|
import abc
import torch
import torch.nn
import torch.optim
class MapIDList(torch.nn.Module):
@abc.abstractmethod
def forward(self, raw_values: 'torch.Tensor') ->torch.Tensor:
pass
class ModuloMapIDList(MapIDList):
def __init__(self, modulo: 'int'):
super().__init__()
self.modulo = modulo
def forward(self, raw_values: 'torch.Tensor') ->torch.Tensor:
return torch.remainder(raw_values, self.modulo)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'modulo': 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 abc
import torch.nn
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_remainder_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 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 != tmp3
tmp5 = libdevice.signbit(tmp2) if tmp2.dtype is tl.float32 else tmp2 < 0
tmp6 = libdevice.signbit(tmp1) if tmp1.dtype is tl.float32 else tmp1 < 0
tmp7 = tmp5 != tmp6
tmp8 = tmp4 & tmp7
tmp9 = tmp2 + tmp1
tmp10 = tl.where(tmp8, tmp9, tmp2)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_remainder_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class MapIDList(torch.nn.Module):
@abc.abstractmethod
def forward(self, raw_values: 'torch.Tensor') ->torch.Tensor:
pass
class ModuloMapIDListNew(MapIDList):
def __init__(self, modulo: 'int'):
super().__init__()
self.modulo = modulo
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BerenLuthien/ReAgent
|
ModuloMapIDList
| false
| 13,387
|
[
"BSD-3-Clause"
] | 1,156
|
52f666670a7fa03206812ef48949f6b934d400f7
|
https://github.com/BerenLuthien/ReAgent/tree/52f666670a7fa03206812ef48949f6b934d400f7
|
Discriminator
|
import math
import torch
import torch.nn as nn
import torch.utils.data
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class Discriminator(nn.Module):
def __init__(self, hidden_dim):
super(Discriminator, self).__init__()
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
self.reset_parameters()
def reset_parameters(self):
size = self.weight.size(0)
uniform(size, self.weight)
def forward(self, x, summary):
x = torch.matmul(x, torch.matmul(self.weight, summary))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_2, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf1)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(64, 4)](buf1, buf2, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(primals_3, (16, 4, 4), (16, 4,
1), 0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0),
out=buf3)
del buf2
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(
primals_3, (16, 4, 4), (16, 1, 4), 0)
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DiscriminatorNew(nn.Module):
def __init__(self, hidden_dim):
super(DiscriminatorNew, self).__init__()
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
self.reset_parameters()
def reset_parameters(self):
size = self.weight.size(0)
uniform(size, self.weight)
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Bawaw/pytorch_geometric
|
Discriminator
| false
| 13,388
|
[
"MIT"
] | 62
|
868548d4396fc66e39b08e2ff19091a367ddac13
|
https://github.com/Bawaw/pytorch_geometric/tree/868548d4396fc66e39b08e2ff19091a367ddac13
|
Concat
|
import torch
from torch import nn
import torch.nn
import torch.optim
class Concat(nn.Module):
def forward(self, state: 'torch.Tensor', action: 'torch.Tensor'):
return torch.cat((state, action), dim=-1)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.nn
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
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, 8), (128, 32, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](arg0_1, arg1_1, buf0, 512, XBLOCK
=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class ConcatNew(nn.Module):
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BerenLuthien/ReAgent
|
Concat
| false
| 13,389
|
[
"BSD-3-Clause"
] | 1,156
|
52f666670a7fa03206812ef48949f6b934d400f7
|
https://github.com/BerenLuthien/ReAgent/tree/52f666670a7fa03206812ef48949f6b934d400f7
|
MsgNorm
|
import torch
import torch.nn.functional as F
class MsgNorm(torch.nn.Module):
def __init__(self, learn_msg_scale=False):
super(MsgNorm, self).__init__()
self.msg_scale = torch.nn.Parameter(torch.Tensor([1.0]),
requires_grad=learn_msg_scale)
def forward(self, x, msg, p=2):
msg = F.normalize(msg, p=p, dim=1)
x_norm = x.norm(p=p, dim=1, keepdim=True)
msg = msg * x_norm * self.msg_scale
return msg
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
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_linalg_vector_norm_mul_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp16 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp24 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr2 + 0)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp17 = tmp16 * tmp16
tmp19 = tmp18 * tmp18
tmp20 = tmp17 + tmp19
tmp22 = tmp21 * tmp21
tmp23 = tmp20 + tmp22
tmp25 = tmp24 * tmp24
tmp26 = tmp23 + tmp25
tmp27 = libdevice.sqrt(tmp26)
tmp28 = tmp15 * tmp27
tmp31 = tmp28 * tmp30
tl.store(in_out_ptr0 + x3, tmp31, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_div_linalg_vector_norm_mul_0[grid(256)](buf1,
arg0_1, arg1_1, arg2_1, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf1,
class MsgNormNew(torch.nn.Module):
def __init__(self, learn_msg_scale=False):
super(MsgNormNew, self).__init__()
self.msg_scale = torch.nn.Parameter(torch.Tensor([1.0]),
requires_grad=learn_msg_scale)
def forward(self, input_0, input_1):
arg2_1 = self.msg_scale
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
Basvanstein/nasbench301
|
MsgNorm
| false
| 13,390
|
[
"Apache-2.0"
] | 55
|
2984dec45c760d47762f50efe39b71e9d1ac22e0
|
https://github.com/Basvanstein/nasbench301/tree/2984dec45c760d47762f50efe39b71e9d1ac22e0
|
DepthWiseSeperableConv
|
import torch
import torch.nn as nn
class DepthWiseSeperableConv(nn.Module):
def __init__(self, in_dim, out_dim, *args, **kwargs):
super().__init__()
if 'groups' in kwargs:
del kwargs['groups']
self.depthwise = nn.Conv2d(in_dim, in_dim, *args, groups=in_dim, **
kwargs)
self.pointwise = nn.Conv2d(in_dim, out_dim, kernel_size=1)
def forward(self, x):
out = self.depthwise(x)
out = self.pointwise(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 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, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 4, 4), (16, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16)](buf1, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1, 1), (4, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(16)](buf3, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class DepthWiseSeperableConvNew(nn.Module):
def __init__(self, in_dim, out_dim, *args, **kwargs):
super().__init__()
if 'groups' in kwargs:
del kwargs['groups']
self.depthwise = nn.Conv2d(in_dim, in_dim, *args, groups=in_dim, **
kwargs)
self.pointwise = nn.Conv2d(in_dim, out_dim, kernel_size=1)
def forward(self, input_0):
primals_1 = self.depthwise.weight
primals_2 = self.depthwise.bias
primals_4 = self.pointwise.weight
primals_5 = self.pointwise.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
BishmoyPaul/lama
|
DepthWiseSeperableConv
| false
| 13,391
|
[
"Apache-2.0"
] | 2,133
|
c7f5af9c167a15e2b0b741b1419237de52c4af05
|
https://github.com/BishmoyPaul/lama/tree/c7f5af9c167a15e2b0b741b1419237de52c4af05
|
Zero
|
import torch
import torch.nn as nn
class Zero(nn.Module):
def __init__(self):
super(Zero, self).__init__()
def forward(self, x):
return x * 0
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ZeroNew(nn.Module):
def __init__(self):
super(ZeroNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BayesWatch/pytorch-prunes
|
Zero
| false
| 13,392
|
[
"MIT"
] | 143
|
bc85a5c52865a2daf515ad4d3c26dcab88e3d941
|
https://github.com/BayesWatch/pytorch-prunes/tree/bc85a5c52865a2daf515ad4d3c26dcab88e3d941
|
EncoderLayer
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Lambda(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x):
return self.func(x)
class FFN(nn.Module):
"""
Feed-Forward Network
"""
def __init__(self, d_inner_hid, d_model, dropout_rate):
super(FFN, self).__init__()
self.dropout_rate = dropout_rate
self.fc1 = torch.nn.Linear(in_features=d_model, out_features=
d_inner_hid)
self.fc2 = torch.nn.Linear(in_features=d_inner_hid, out_features=
d_model)
def forward(self, x):
hidden = self.fc1(x)
hidden = F.relu(hidden)
if self.dropout_rate:
hidden = F.dropout(hidden, p=self.dropout_rate)
out = self.fc2(hidden)
return out
class MultiHeadAttention(nn.Module):
"""
Multi-Head Attention
"""
def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.0):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_key = d_key
self.d_value = d_value
self.d_model = d_model
self.dropout_rate = dropout_rate
self.q_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.k_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.v_fc = torch.nn.Linear(in_features=d_model, out_features=
d_value * n_head, bias=False)
self.proj_fc = torch.nn.Linear(in_features=d_value * n_head,
out_features=d_model, bias=False)
def _prepare_qkv(self, queries, keys, values, cache=None):
if keys is None:
keys, values = queries, queries
static_kv = False
else:
static_kv = True
q = self.q_fc(queries)
q = torch.reshape(q, shape=[q.size(0), q.size(1), self.n_head, self
.d_key])
q = q.permute(0, 2, 1, 3)
if cache is not None and static_kv and 'static_k' in cache:
k = cache['static_k']
v = cache['static_v']
else:
k = self.k_fc(keys)
v = self.v_fc(values)
k = torch.reshape(k, shape=[k.size(0), k.size(1), self.n_head,
self.d_key])
k = k.permute(0, 2, 1, 3)
v = torch.reshape(v, shape=[v.size(0), v.size(1), self.n_head,
self.d_value])
v = v.permute(0, 2, 1, 3)
if cache is not None:
if static_kv and 'static_k' not in cache:
cache['static_k'], cache['static_v'] = k, v
elif not static_kv:
cache_k, cache_v = cache['k'], cache['v']
k = torch.cat([cache_k, k], dim=2)
v = torch.cat([cache_v, v], dim=2)
cache['k'], cache['v'] = k, v
return q, k, v
def forward(self, queries, keys, values, attn_bias, cache=None):
keys = queries if keys is None else keys
values = keys if values is None else values
q, k, v = self._prepare_qkv(queries, keys, values, cache)
product = torch.matmul(q, k.transpose(2, 3))
product = product * self.d_model ** -0.5
if attn_bias is not None:
product += attn_bias
weights = F.softmax(product, dim=-1)
if self.dropout_rate:
weights = F.dropout(weights, p=self.dropout_rate)
out = torch.matmul(weights, v)
out = out.permute(0, 2, 1, 3)
out = torch.reshape(out, shape=[out.size(0), out.size(1), out.shape
[2] * out.shape[3]])
out = self.proj_fc(out)
return out
class LambdaXY(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x, y):
return self.func(x, y)
class PrePostProcessLayer(nn.Module):
"""
PrePostProcessLayer
"""
def __init__(self, process_cmd, d_model, dropout_rate):
super(PrePostProcessLayer, self).__init__()
self.process_cmd = process_cmd
self.functors = nn.ModuleList()
cur_a_len = 0
cur_n_len = 0
cur_d_len = 0
for cmd in self.process_cmd:
if cmd == 'a':
self.functors.add_module('add_res_connect_{}'.format(
cur_a_len), LambdaXY(lambda x, y: x + y if y is not
None else x))
cur_a_len += 1
elif cmd == 'n':
layerNorm = torch.nn.LayerNorm(normalized_shape=d_model,
elementwise_affine=True, eps=1e-05)
self.functors.add_module('layer_norm_%d' % cur_n_len, layerNorm
)
cur_n_len += 1
elif cmd == 'd':
self.functors.add_module('add_drop_{}'.format(cur_d_len),
Lambda(lambda x: F.dropout(x, p=dropout_rate) if
dropout_rate else x))
cur_d_len += 1
def forward(self, x, residual=None):
for i, (cmd, functor) in enumerate(zip(self.process_cmd, self.functors)
):
if cmd == 'a':
x = functor(x, residual)
else:
x = functor(x)
return x
class EncoderLayer(nn.Module):
"""
EncoderLayer
"""
def __init__(self, n_head, d_key, d_value, d_model, d_inner_hid,
prepostprocess_dropout, attention_dropout, relu_dropout,
preprocess_cmd='n', postprocess_cmd='da'):
super(EncoderLayer, self).__init__()
self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head,
attention_dropout)
self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.ffn = FFN(d_inner_hid, d_model, relu_dropout)
self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, enc_input, attn_bias):
attn_output = self.self_attn(self.preprocesser1(enc_input), None,
None, attn_bias)
attn_output = self.postprocesser1(attn_output, enc_input)
ffn_output = self.ffn(self.preprocesser2(attn_output))
ffn_output = self.postprocesser2(ffn_output, attn_output)
return ffn_output
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_head': 4, 'd_key': 4, 'd_value': 4, 'd_model': 4,
'd_inner_hid': 4, 'prepostprocess_dropout': 0.5,
'attention_dropout': 0.5, 'relu_dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, 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_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__softmax_add_mul_4(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x2), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp5 * tmp1
tmp8 = tmp6 + tmp7
tmp9 = triton_helpers.maximum(tmp4, tmp8)
tmp11 = tmp10 * tmp1
tmp13 = tmp11 + tmp12
tmp14 = triton_helpers.maximum(tmp9, tmp13)
tmp16 = tmp15 * tmp1
tmp18 = tmp16 + tmp17
tmp19 = triton_helpers.maximum(tmp14, tmp18)
tmp20 = tmp4 - tmp19
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp8 - tmp19
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp19
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp24 + tmp26
tmp28 = tmp18 - tmp19
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp27 + tmp29
tl.store(out_ptr0 + x2, tmp19, xmask)
tl.store(out_ptr1 + x2, tmp30, xmask)
@triton.jit
def triton_poi_fused__softmax_add_mul_5(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex % 64
x5 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last')
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp9 = tmp7 / tmp8
tl.store(in_out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_6(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 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_7(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (16, 4), (4, 1))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16, 4), (4, 1))
assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_8, (4, 16), (16, 1))
assert_size_stride(primals_9, (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((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_3, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 16), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf4)
buf5 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 16), (1, 4), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf3, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_clone_3[grid(64, 4)](buf4, buf7, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0)
del buf4
extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1), 0), out=buf8)
buf9 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_mul_4[grid(64)](buf8, primals_7, buf9,
buf10, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf8
triton_poi_fused__softmax_add_mul_5[grid(256)](buf11, primals_7,
buf9, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf12 = torch.ops.aten.native_dropout.default(buf11, 0.5, True)
buf13 = buf12[0]
buf14 = buf12[1]
del buf12
buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf5, buf15, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf16 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(buf13, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf15, (16, 4, 4), (16, 4, 1), 0), out=buf16
)
buf17 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf16, buf17, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf16
buf18 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf17, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_8, (16, 4), (1, 16), 0), out=buf18)
buf19 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf18, (4, 4, 4), (16, 4, 1), 0), 0.5, True)
buf20 = buf19[0]
buf21 = buf19[1]
del buf19
buf22 = buf20
del buf20
triton_poi_fused_add_6[grid(64)](buf22, primals_3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf23 = buf1
del buf1
buf24 = buf0
del buf0
triton_poi_fused_native_layer_norm_0[grid(16)](buf22, buf23, buf24,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf25 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_native_layer_norm_1[grid(64)](buf22, buf23, buf24,
primals_9, primals_10, buf25, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf23
del buf24
del primals_10
buf26 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf25, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf26)
buf27 = reinterpret_tensor(buf26, (4, 4, 4), (16, 4, 1), 0)
del buf26
buf36 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_7[grid(64)](buf27,
primals_12, buf36, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
buf28 = torch.ops.aten.native_dropout.default(buf27, 0.5, True)
buf29 = buf28[0]
buf30 = buf28[1]
del buf28
buf31 = reinterpret_tensor(buf27, (16, 4), (4, 1), 0)
del buf27
extern_kernels.addmm(primals_14, reinterpret_tensor(buf29, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf31)
del primals_14
buf32 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf31, (4, 4, 4), (16, 4, 1), 0), 0.5, True)
del buf31
buf33 = buf32[0]
buf34 = buf32[1]
del buf32
buf35 = buf33
del buf33
triton_poi_fused_add_6[grid(64)](buf35, buf22, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf35, primals_3, primals_9, reinterpret_tensor(buf2, (16, 4), (
4, 1), 0), buf11, buf14, reinterpret_tensor(buf17, (16, 16), (16, 1), 0
), buf21, buf22, reinterpret_tensor(buf25, (16, 4), (4, 1), 0
), buf30, reinterpret_tensor(buf29, (16, 4), (4, 1), 0
), buf34, primals_13, buf36, primals_11, primals_8, reinterpret_tensor(
buf13, (16, 4, 4), (16, 1, 4), 0), reinterpret_tensor(buf15, (16, 4,
4), (16, 1, 4), 0), reinterpret_tensor(buf6, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf7, (16, 4, 4), (16, 1, 4), 0
), primals_6, primals_5, primals_4
class Lambda(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x):
return self.func(x)
class FFN(nn.Module):
"""
Feed-Forward Network
"""
def __init__(self, d_inner_hid, d_model, dropout_rate):
super(FFN, self).__init__()
self.dropout_rate = dropout_rate
self.fc1 = torch.nn.Linear(in_features=d_model, out_features=
d_inner_hid)
self.fc2 = torch.nn.Linear(in_features=d_inner_hid, out_features=
d_model)
def forward(self, x):
hidden = self.fc1(x)
hidden = F.relu(hidden)
if self.dropout_rate:
hidden = F.dropout(hidden, p=self.dropout_rate)
out = self.fc2(hidden)
return out
class MultiHeadAttention(nn.Module):
"""
Multi-Head Attention
"""
def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.0):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_key = d_key
self.d_value = d_value
self.d_model = d_model
self.dropout_rate = dropout_rate
self.q_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.k_fc = torch.nn.Linear(in_features=d_model, out_features=d_key *
n_head, bias=False)
self.v_fc = torch.nn.Linear(in_features=d_model, out_features=
d_value * n_head, bias=False)
self.proj_fc = torch.nn.Linear(in_features=d_value * n_head,
out_features=d_model, bias=False)
def _prepare_qkv(self, queries, keys, values, cache=None):
if keys is None:
keys, values = queries, queries
static_kv = False
else:
static_kv = True
q = self.q_fc(queries)
q = torch.reshape(q, shape=[q.size(0), q.size(1), self.n_head, self
.d_key])
q = q.permute(0, 2, 1, 3)
if cache is not None and static_kv and 'static_k' in cache:
k = cache['static_k']
v = cache['static_v']
else:
k = self.k_fc(keys)
v = self.v_fc(values)
k = torch.reshape(k, shape=[k.size(0), k.size(1), self.n_head,
self.d_key])
k = k.permute(0, 2, 1, 3)
v = torch.reshape(v, shape=[v.size(0), v.size(1), self.n_head,
self.d_value])
v = v.permute(0, 2, 1, 3)
if cache is not None:
if static_kv and 'static_k' not in cache:
cache['static_k'], cache['static_v'] = k, v
elif not static_kv:
cache_k, cache_v = cache['k'], cache['v']
k = torch.cat([cache_k, k], dim=2)
v = torch.cat([cache_v, v], dim=2)
cache['k'], cache['v'] = k, v
return q, k, v
def forward(self, queries, keys, values, attn_bias, cache=None):
keys = queries if keys is None else keys
values = keys if values is None else values
q, k, v = self._prepare_qkv(queries, keys, values, cache)
product = torch.matmul(q, k.transpose(2, 3))
product = product * self.d_model ** -0.5
if attn_bias is not None:
product += attn_bias
weights = F.softmax(product, dim=-1)
if self.dropout_rate:
weights = F.dropout(weights, p=self.dropout_rate)
out = torch.matmul(weights, v)
out = out.permute(0, 2, 1, 3)
out = torch.reshape(out, shape=[out.size(0), out.size(1), out.shape
[2] * out.shape[3]])
out = self.proj_fc(out)
return out
class LambdaXY(nn.Module):
"""An easy way to create a pytorch layer for a simple `func`."""
def __init__(self, func):
"""create a layer that simply calls `func` with `x`"""
super().__init__()
self.func = func
def forward(self, x, y):
return self.func(x, y)
class PrePostProcessLayer(nn.Module):
"""
PrePostProcessLayer
"""
def __init__(self, process_cmd, d_model, dropout_rate):
super(PrePostProcessLayer, self).__init__()
self.process_cmd = process_cmd
self.functors = nn.ModuleList()
cur_a_len = 0
cur_n_len = 0
cur_d_len = 0
for cmd in self.process_cmd:
if cmd == 'a':
self.functors.add_module('add_res_connect_{}'.format(
cur_a_len), LambdaXY(lambda x, y: x + y if y is not
None else x))
cur_a_len += 1
elif cmd == 'n':
layerNorm = torch.nn.LayerNorm(normalized_shape=d_model,
elementwise_affine=True, eps=1e-05)
self.functors.add_module('layer_norm_%d' % cur_n_len, layerNorm
)
cur_n_len += 1
elif cmd == 'd':
self.functors.add_module('add_drop_{}'.format(cur_d_len),
Lambda(lambda x: F.dropout(x, p=dropout_rate) if
dropout_rate else x))
cur_d_len += 1
def forward(self, x, residual=None):
for i, (cmd, functor) in enumerate(zip(self.process_cmd, self.functors)
):
if cmd == 'a':
x = functor(x, residual)
else:
x = functor(x)
return x
class EncoderLayerNew(nn.Module):
"""
EncoderLayer
"""
def __init__(self, n_head, d_key, d_value, d_model, d_inner_hid,
prepostprocess_dropout, attention_dropout, relu_dropout,
preprocess_cmd='n', postprocess_cmd='da'):
super(EncoderLayerNew, self).__init__()
self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head,
attention_dropout)
self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model,
prepostprocess_dropout)
self.ffn = FFN(d_inner_hid, d_model, relu_dropout)
self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model,
prepostprocess_dropout)
def forward(self, input_0, input_1):
primals_1 = self.preprocesser1.functors.layer_norm_0.weight
primals_2 = self.preprocesser1.functors.layer_norm_0.bias
primals_4 = self.self_attn.q_fc.weight
primals_5 = self.self_attn.k_fc.weight
primals_6 = self.self_attn.v_fc.weight
primals_8 = self.self_attn.proj_fc.weight
primals_9 = self.preprocesser2.functors.layer_norm_0.weight
primals_10 = self.preprocesser2.functors.layer_norm_0.bias
primals_11 = self.ffn.fc1.weight
primals_12 = self.ffn.fc1.bias
primals_13 = self.ffn.fc2.weight
primals_14 = self.ffn.fc2.bias
primals_3 = 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]
|
BHD233/PaddleOCR2Pytorch
|
EncoderLayer
| false
| 13,393
|
[
"Apache-2.0"
] | 364
|
f114069b3e2669c6adf0adf9596756205f184c9c
|
https://github.com/BHD233/PaddleOCR2Pytorch/tree/f114069b3e2669c6adf0adf9596756205f184c9c
|
Normalize
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1.0 / self.power)
out = x.div(norm)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_pow_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = tmp0 / tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_pow_sum_0[grid(256)](arg0_1, buf0, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class NormalizeNew(nn.Module):
def __init__(self, power=2):
super(NormalizeNew, self).__init__()
self.power = power
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Bhaskers-Blu-Org2/metric-transfer.pytorch
|
Normalize
| false
| 13,394
|
[
"MIT"
] | 51
|
b0ae8ed6e6f62357100d799defbb61a78c831a87
|
https://github.com/Bhaskers-Blu-Org2/metric-transfer.pytorch/tree/b0ae8ed6e6f62357100d799defbb61a78c831a87
|
AvgPoolPad
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torch import optim as optim
class AvgPoolPad(nn.Module):
def __init__(self, stride=2, padding=1):
super(AvgPoolPad, self).__init__()
self.pad = nn.ZeroPad2d((1, 0, 1, 0))
self.pool = nn.AvgPool2d(3, stride=stride, padding=padding,
count_include_pad=False)
def forward(self, x):
x = self.pad(x)
x = self.pool(x)
x = x[:, :, 1:, 1:]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_avg_pool2d_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x4 = xindex
tmp0 = -1 + 2 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 5, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + 2 * x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = -2 + 2 * x1
tmp12 = tmp11 >= tmp1
tmp13 = -2 + 2 * x0
tmp14 = tmp13 >= tmp1
tmp15 = tmp12 & tmp14
tmp16 = tmp15 & tmp10
tmp17 = tl.load(in_ptr0 + (-10 + 2 * x0 + 8 * x1 + 16 * x2), tmp16 &
xmask, eviction_policy='evict_last', other=0.0)
tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype)
tmp19 = tl.where(tmp10, tmp17, tmp18)
tmp20 = 2 * x0
tmp21 = tmp20 >= tmp1
tmp22 = tmp20 < tmp3
tmp23 = tmp21 & tmp22
tmp24 = tmp5 & tmp23
tmp25 = tmp12 & tmp7
tmp26 = tmp25 & tmp24
tmp27 = tl.load(in_ptr0 + (-9 + 2 * x0 + 8 * x1 + 16 * x2), tmp26 &
xmask, eviction_policy='evict_last', other=0.0)
tmp28 = tl.full(tmp27.shape, 0.0, tmp27.dtype)
tmp29 = tl.where(tmp24, tmp27, tmp28)
tmp30 = tmp29 + tmp19
tmp31 = 1 + 2 * x0
tmp32 = tmp31 >= tmp1
tmp33 = tmp31 < tmp3
tmp34 = tmp32 & tmp33
tmp35 = tmp5 & tmp34
tmp36 = tmp12 & tmp21
tmp37 = tmp36 & tmp35
tmp38 = tl.load(in_ptr0 + (-8 + 2 * x0 + 8 * x1 + 16 * x2), tmp37 &
xmask, eviction_policy='evict_last', other=0.0)
tmp39 = tl.full(tmp38.shape, 0.0, tmp38.dtype)
tmp40 = tl.where(tmp35, tmp38, tmp39)
tmp41 = tmp40 + tmp30
tmp42 = 2 * x1
tmp43 = tmp42 >= tmp1
tmp44 = tmp42 < tmp3
tmp45 = tmp43 & tmp44
tmp46 = tmp45 & tmp9
tmp47 = tmp2 & tmp14
tmp48 = tmp47 & tmp46
tmp49 = tl.load(in_ptr0 + (-6 + 2 * x0 + 8 * x1 + 16 * x2), tmp48 &
xmask, eviction_policy='evict_last', other=0.0)
tmp50 = tl.full(tmp49.shape, 0.0, tmp49.dtype)
tmp51 = tl.where(tmp46, tmp49, tmp50)
tmp52 = tmp51 + tmp41
tmp53 = tmp45 & tmp23
tmp54 = tmp2 & tmp7
tmp55 = tmp54 & tmp53
tmp56 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x1 + 16 * x2), tmp55 &
xmask, eviction_policy='evict_last', other=0.0)
tmp57 = tl.full(tmp56.shape, 0.0, tmp56.dtype)
tmp58 = tl.where(tmp53, tmp56, tmp57)
tmp59 = tmp58 + tmp52
tmp60 = tmp45 & tmp34
tmp61 = tmp2 & tmp21
tmp62 = tmp61 & tmp60
tmp63 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x1 + 16 * x2), tmp62 &
xmask, eviction_policy='evict_last', other=0.0)
tmp64 = tl.full(tmp63.shape, 0.0, tmp63.dtype)
tmp65 = tl.where(tmp60, tmp63, tmp64)
tmp66 = tmp65 + tmp59
tmp67 = 1 + 2 * x1
tmp68 = tmp67 >= tmp1
tmp69 = tmp67 < tmp3
tmp70 = tmp68 & tmp69
tmp71 = tmp70 & tmp9
tmp72 = tmp43 & tmp14
tmp73 = tmp72 & tmp71
tmp74 = tl.load(in_ptr0 + (-2 + 2 * x0 + 8 * x1 + 16 * x2), tmp73 &
xmask, eviction_policy='evict_last', other=0.0)
tmp75 = tl.full(tmp74.shape, 0.0, tmp74.dtype)
tmp76 = tl.where(tmp71, tmp74, tmp75)
tmp77 = tmp76 + tmp66
tmp78 = tmp70 & tmp23
tmp79 = tmp43 & tmp7
tmp80 = tmp79 & tmp78
tmp81 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x1 + 16 * x2), tmp80 &
xmask, eviction_policy='evict_last', other=0.0)
tmp82 = tl.full(tmp81.shape, 0.0, tmp81.dtype)
tmp83 = tl.where(tmp78, tmp81, tmp82)
tmp84 = tmp83 + tmp77
tmp85 = tmp70 & tmp34
tmp86 = tmp43 & tmp21
tmp87 = tmp86 & tmp85
tmp88 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp87 & xmask,
eviction_policy='evict_last', other=0.0)
tmp89 = tl.full(tmp88.shape, 0.0, tmp88.dtype)
tmp90 = tl.where(tmp85, tmp88, tmp89)
tmp91 = tmp90 + tmp84
tmp92 = (0 * (0 >= -1 + 2 * x0) + (-1 + 2 * x0) * (-1 + 2 * x0 > 0)) * (
0 * (0 >= -1 + 2 * x1) + (-1 + 2 * x1) * (-1 + 2 * x1 > 0)) + (5 *
(5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 5)) * (5 * (5 <= 2 +
2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 5)) + -1 * (0 * (0 >= -1 + 2 *
x0) + (-1 + 2 * x0) * (-1 + 2 * x0 > 0)) * (5 * (5 <= 2 + 2 * x1) +
(2 + 2 * x1) * (2 + 2 * x1 < 5)) + -1 * (0 * (0 >= -1 + 2 * x1) + (
-1 + 2 * x1) * (-1 + 2 * x1 > 0)) * (5 * (5 <= 2 + 2 * x0) + (2 + 2 *
x0) * (2 + 2 * x0 < 5))
tmp93 = tmp91 / tmp92
tl.store(out_ptr0 + x4, tmp93, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_constant_pad_nd_0[grid(144)](arg0_1,
buf0, 144, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4, 2, 2), (36, 9, 3, 1), 4),
class AvgPoolPadNew(nn.Module):
def __init__(self, stride=2, padding=1):
super(AvgPoolPadNew, self).__init__()
self.pad = nn.ZeroPad2d((1, 0, 1, 0))
self.pool = nn.AvgPool2d(3, stride=stride, padding=padding,
count_include_pad=False)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BarneyQiao/CondenseNetV2
|
AvgPoolPad
| false
| 13,395
|
[
"MIT"
] | 80
|
c771957cb8fe466d0ecbafe9060e4c342a33fc4d
|
https://github.com/BarneyQiao/CondenseNetV2/tree/c771957cb8fe466d0ecbafe9060e4c342a33fc4d
|
HighwayLayer
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
class HighwayLayer(nn.Module):
def __init__(self, input_dim, transform_activation=F.relu,
gate_activation=F.softmax, gate_bias=-2):
super().__init__()
self.highway_transform_activation = transform_activation
self.highway_gate_activation = gate_activation
self.highway_transform = nn.Linear(input_dim, input_dim)
self.highway_gate = nn.Linear(input_dim, input_dim)
self.highway_gate.bias.data.fill_(gate_bias)
def forward(self, x):
transform_output = self.highway_transform_activation(self.
highway_transform(x))
gate_output = self.highway_gate_activation(self.highway_gate(x))
transformation_part = torch.mul(transform_output, gate_output)
carry_part = torch.mul(torch.FloatTensor([1.0]).type_as(gate_output
) - gate_output, x)
return torch.add(transformation_part, carry_part)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax__to_copy_add_mul_relu_sub_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp9 = tl.load(in_ptr1 + x3, xmask)
tmp15 = tl.load(in_ptr2 + x3, xmask)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = triton_helpers.maximum(tmp10, tmp9)
tmp12 = tmp11 * tmp8
tmp13 = 1.0
tmp14 = tmp13 - tmp8
tmp16 = tmp14 * tmp15
tmp17 = tmp12 + tmp16
tl.store(in_out_ptr0 + x3, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((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((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = buf3
del buf3
triton_poi_fused__softmax__to_copy_add_mul_relu_sub_1[grid(256)](buf4,
buf2, buf0, primals_3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
return buf4, primals_3, buf0, buf1
class HighwayLayerNew(nn.Module):
def __init__(self, input_dim, transform_activation=F.relu,
gate_activation=F.softmax, gate_bias=-2):
super().__init__()
self.highway_transform_activation = transform_activation
self.highway_gate_activation = gate_activation
self.highway_transform = nn.Linear(input_dim, input_dim)
self.highway_gate = nn.Linear(input_dim, input_dim)
self.highway_gate.bias.data.fill_(gate_bias)
def forward(self, input_0):
primals_1 = self.highway_transform.weight
primals_2 = self.highway_transform.bias
primals_4 = self.highway_gate.weight
primals_5 = self.highway_gate.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Ayansam1152/translate
|
HighwayLayer
| false
| 13,396
|
[
"BSD-3-Clause"
] | 748
|
33d397fc25fb1072abd2975c77c602a2d031c6c4
|
https://github.com/Ayansam1152/translate/tree/33d397fc25fb1072abd2975c77c602a2d031c6c4
|
GeLU
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GeLU(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return 0.5 * x * (1 + F.tanh(0.7978845608 * (x + 0.044715 * x * x * x))
)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_tanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.044715
tmp4 = tmp0 * tmp3
tmp5 = tmp4 * tmp0
tmp6 = tmp5 * tmp0
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_tanh_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class GeLUNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Blind-Aid/sentiment-discovery
|
GeLU
| false
| 13,397
|
[
"BSD-3-Clause"
] | 1,093
|
081c7c855e00864b52e97cac0b0e097cc86d9731
|
https://github.com/Blind-Aid/sentiment-discovery/tree/081c7c855e00864b52e97cac0b0e097cc86d9731
|
MultiheadAttention
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
def combine_heads(X):
"""
Combine heads (the inverse of split heads):
1) Transpose X from (batch size, nheads, sequence length, d_head) to
(batch size, sequence length, nheads, d_head)
2) Combine (reshape) last 2 dimensions (nheads, d_head) into 1 (d_model)
Inputs:
X : [batch size * nheads, sequence length, d_head]
nheads : integer
d_head : integer
Outputs:
[batch_size, seq_len, d_model]
"""
X = X.transpose(1, 2)
nheads, d_head = X.shape[-2:]
return X.contiguous().view(list(X.shape[:-2]) + [nheads * d_head])
def create_src_lengths_mask(batch_size, src_lengths):
max_srclen = src_lengths.max()
src_indices = torch.arange(0, max_srclen).unsqueeze(0).type_as(src_lengths)
src_indices = src_indices.expand(batch_size, max_srclen)
src_lengths = src_lengths.unsqueeze(dim=1).expand(batch_size, max_srclen)
return (src_indices < src_lengths).int().detach()
def apply_masks(scores, batch_size, unseen_mask, src_lengths):
seq_len = scores.shape[-1]
sequence_mask = torch.ones(seq_len, seq_len).unsqueeze(0).int()
if unseen_mask:
sequence_mask = torch.tril(torch.ones(seq_len, seq_len), diagonal=0
).unsqueeze(0).int()
if src_lengths is not None:
src_lengths_mask = create_src_lengths_mask(batch_size=batch_size,
src_lengths=src_lengths).unsqueeze(-2)
sequence_mask = sequence_mask & src_lengths_mask
sequence_mask = sequence_mask.unsqueeze(1)
scores = scores.masked_fill(sequence_mask == 0, -np.inf)
return scores
def scaled_dot_prod_attn(query, key, value, unseen_mask=False, src_lengths=None
):
"""
Scaled Dot Product Attention
Implements equation:
Attention(Q, K, V) = softmax(QK^T/\\sqrt{d_k})V
Inputs:
query : [batch size, nheads, sequence length, d_k]
key : [batch size, nheads, sequence length, d_k]
value : [batch size, nheads, sequence length, d_v]
unseen_mask: if True, only attend to previous sequence positions
src_lengths_mask: if True, mask padding based on src_lengths
Outputs:
attn: [batch size, sequence length, d_v]
Note that in this implementation d_q = d_k = d_v = dim
"""
d_k = query.shape[-1]
scores = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(d_k)
if unseen_mask or src_lengths is not None:
scores = apply_masks(scores=scores, batch_size=query.shape[0],
unseen_mask=unseen_mask, src_lengths=src_lengths)
p_attn = F.softmax(scores, dim=-1)
return torch.matmul(p_attn, value), p_attn
def split_heads(X, nheads):
"""
Split heads:
1) Split (reshape) last dimension (size d_model) into nheads, d_head
2) Transpose X from (batch size, sequence length, nheads, d_head) to
(batch size, nheads, sequence length, d_head)
Inputs:
X : [batch size, sequence length, nheads * d_head]
nheads : integer
Outputs:
[batch size, nheads, sequence length, d_head]
"""
last_dim = X.shape[-1]
assert last_dim % nheads == 0
X_last_dim_split = X.view(list(X.shape[:-1]) + [nheads, last_dim // nheads]
)
return X_last_dim_split.transpose(1, 2)
class MultiheadAttention(nn.Module):
"""
Multiheaded Scaled Dot Product Attention
Implements equation:
MultiHead(Q, K, V) = Concat(head_1,...,head_h)W^O
where head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)
Similarly to the above, d_k = d_v = d_model / h
Inputs
init:
nheads : integer # of attention heads
d_model : model dimensionality
d_head : dimensionality of a single head
forward:
query : [batch size, sequence length, d_model]
key: [batch size, sequence length, d_model]
value: [batch size, sequence length, d_model]
unseen_mask: if True, only attend to previous sequence positions
src_lengths_mask: if True, mask padding based on src_lengths
Output
result : [batch_size, sequence length, d_model]
"""
def __init__(self, nheads, d_model):
"""Take in model size and number of heads."""
super(MultiheadAttention, self).__init__()
assert d_model % nheads == 0
self.d_head = d_model // nheads
self.nheads = nheads
self.Q_fc = nn.Linear(d_model, d_model, bias=False)
self.K_fc = nn.Linear(d_model, d_model, bias=False)
self.V_fc = nn.Linear(d_model, d_model, bias=False)
self.output_fc = nn.Linear(d_model, d_model, bias=False)
self.attn = None
def forward(self, query, key, value, unseen_mask=False, src_lengths=None):
query = split_heads(self.Q_fc(query), self.nheads)
key = split_heads(self.K_fc(key), self.nheads)
value = split_heads(self.V_fc(value), self.nheads)
x, self.attn = scaled_dot_prod_attn(query=query, key=key, value=
value, unseen_mask=unseen_mask, src_lengths=src_lengths)
x = combine_heads(x)
return self.output_fc(x)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'nheads': 4, 'd_model': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp1
tmp16 = tl_math.exp(tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 4, 4), (16, 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, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, buf3, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(16, 4)](buf1, buf4, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
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_2[grid(256)](buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(16, 4)](buf2, buf8, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_0[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_7, (4, 4), (1, 4), 0), out=buf11)
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), buf7, reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_4, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), primals_7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
def combine_heads(X):
"""
Combine heads (the inverse of split heads):
1) Transpose X from (batch size, nheads, sequence length, d_head) to
(batch size, sequence length, nheads, d_head)
2) Combine (reshape) last 2 dimensions (nheads, d_head) into 1 (d_model)
Inputs:
X : [batch size * nheads, sequence length, d_head]
nheads : integer
d_head : integer
Outputs:
[batch_size, seq_len, d_model]
"""
X = X.transpose(1, 2)
nheads, d_head = X.shape[-2:]
return X.contiguous().view(list(X.shape[:-2]) + [nheads * d_head])
def create_src_lengths_mask(batch_size, src_lengths):
max_srclen = src_lengths.max()
src_indices = torch.arange(0, max_srclen).unsqueeze(0).type_as(src_lengths)
src_indices = src_indices.expand(batch_size, max_srclen)
src_lengths = src_lengths.unsqueeze(dim=1).expand(batch_size, max_srclen)
return (src_indices < src_lengths).int().detach()
def apply_masks(scores, batch_size, unseen_mask, src_lengths):
seq_len = scores.shape[-1]
sequence_mask = torch.ones(seq_len, seq_len).unsqueeze(0).int()
if unseen_mask:
sequence_mask = torch.tril(torch.ones(seq_len, seq_len), diagonal=0
).unsqueeze(0).int()
if src_lengths is not None:
src_lengths_mask = create_src_lengths_mask(batch_size=batch_size,
src_lengths=src_lengths).unsqueeze(-2)
sequence_mask = sequence_mask & src_lengths_mask
sequence_mask = sequence_mask.unsqueeze(1)
scores = scores.masked_fill(sequence_mask == 0, -np.inf)
return scores
def scaled_dot_prod_attn(query, key, value, unseen_mask=False, src_lengths=None
):
"""
Scaled Dot Product Attention
Implements equation:
Attention(Q, K, V) = softmax(QK^T/\\sqrt{d_k})V
Inputs:
query : [batch size, nheads, sequence length, d_k]
key : [batch size, nheads, sequence length, d_k]
value : [batch size, nheads, sequence length, d_v]
unseen_mask: if True, only attend to previous sequence positions
src_lengths_mask: if True, mask padding based on src_lengths
Outputs:
attn: [batch size, sequence length, d_v]
Note that in this implementation d_q = d_k = d_v = dim
"""
d_k = query.shape[-1]
scores = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(d_k)
if unseen_mask or src_lengths is not None:
scores = apply_masks(scores=scores, batch_size=query.shape[0],
unseen_mask=unseen_mask, src_lengths=src_lengths)
p_attn = F.softmax(scores, dim=-1)
return torch.matmul(p_attn, value), p_attn
def split_heads(X, nheads):
"""
Split heads:
1) Split (reshape) last dimension (size d_model) into nheads, d_head
2) Transpose X from (batch size, sequence length, nheads, d_head) to
(batch size, nheads, sequence length, d_head)
Inputs:
X : [batch size, sequence length, nheads * d_head]
nheads : integer
Outputs:
[batch size, nheads, sequence length, d_head]
"""
last_dim = X.shape[-1]
assert last_dim % nheads == 0
X_last_dim_split = X.view(list(X.shape[:-1]) + [nheads, last_dim // nheads]
)
return X_last_dim_split.transpose(1, 2)
class MultiheadAttentionNew(nn.Module):
"""
Multiheaded Scaled Dot Product Attention
Implements equation:
MultiHead(Q, K, V) = Concat(head_1,...,head_h)W^O
where head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)
Similarly to the above, d_k = d_v = d_model / h
Inputs
init:
nheads : integer # of attention heads
d_model : model dimensionality
d_head : dimensionality of a single head
forward:
query : [batch size, sequence length, d_model]
key: [batch size, sequence length, d_model]
value: [batch size, sequence length, d_model]
unseen_mask: if True, only attend to previous sequence positions
src_lengths_mask: if True, mask padding based on src_lengths
Output
result : [batch_size, sequence length, d_model]
"""
def __init__(self, nheads, d_model):
"""Take in model size and number of heads."""
super(MultiheadAttentionNew, self).__init__()
assert d_model % nheads == 0
self.d_head = d_model // nheads
self.nheads = nheads
self.Q_fc = nn.Linear(d_model, d_model, bias=False)
self.K_fc = nn.Linear(d_model, d_model, bias=False)
self.V_fc = nn.Linear(d_model, d_model, bias=False)
self.output_fc = nn.Linear(d_model, d_model, bias=False)
self.attn = None
def forward(self, input_0, input_1, input_2):
primals_1 = self.Q_fc.weight
primals_3 = self.K_fc.weight
primals_5 = self.V_fc.weight
primals_7 = self.output_fc.weight
primals_2 = input_0
primals_4 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Ayansam1152/translate
|
MultiheadAttention
| false
| 13,398
|
[
"BSD-3-Clause"
] | 748
|
33d397fc25fb1072abd2975c77c602a2d031c6c4
|
https://github.com/Ayansam1152/translate/tree/33d397fc25fb1072abd2975c77c602a2d031c6c4
|
SmoothL1Loss
|
import torch
import torch.utils.data
def smooth_l1_loss(input, target, beta=1.0 / 9, size_average=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - target)
cond = n < beta
loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta)
if size_average:
return loss.mean()
return loss.sum()
class SmoothL1Loss(torch.nn.Module):
def __init__(self, beta=1.0 / 9):
super(SmoothL1Loss, self).__init__()
self.beta = beta
def forward(self, input, target, size_average=True):
return smooth_l1_loss(input, target, self.beta, size_average)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_div_lt_mean_mul_pow_sub_where_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 = tl_math.abs(tmp2)
tmp4 = 0.1111111111111111
tmp5 = tmp3 < tmp4
tmp6 = tmp3 * tmp3
tmp7 = 0.5
tmp8 = tmp6 * tmp7
tmp9 = 9.0
tmp10 = tmp8 * tmp9
tmp11 = 0.05555555555555555
tmp12 = tmp3 - tmp11
tmp13 = tl.where(tmp5, tmp10, tmp12)
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = 256.0
tmp18 = tmp16 / tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp18, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_div_lt_mean_mul_pow_sub_where_0[grid(1)](buf1,
arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def smooth_l1_loss(input, target, beta=1.0 / 9, size_average=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - target)
cond = n < beta
loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta)
if size_average:
return loss.mean()
return loss.sum()
class SmoothL1LossNew(torch.nn.Module):
def __init__(self, beta=1.0 / 9):
super(SmoothL1LossNew, self).__init__()
self.beta = beta
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BorisLestsov/retinamask
|
SmoothL1Loss
| false
| 13,399
|
[
"MIT"
] | 706
|
265a65f018c64220bcea946d306fc7b07a692b16
|
https://github.com/BorisLestsov/retinamask/tree/265a65f018c64220bcea946d306fc7b07a692b16
|
WordPredictor
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
class WordPredictor(nn.Module):
def __init__(self, encoder_output_dim, hidden_dim, output_dim,
topk_labels_per_source_token=None, use_self_attention=False):
super().__init__()
self.encoder_output_dim = encoder_output_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
self.topk_labels_per_source_token = topk_labels_per_source_token
self.use_self_attention = use_self_attention
if self.use_self_attention:
self.init_layer = nn.Linear(encoder_output_dim, encoder_output_dim)
self.attn_layer = nn.Linear(2 * encoder_output_dim, 1)
self.hidden_layer = nn.Linear(2 * encoder_output_dim, hidden_dim)
self.output_layer = nn.Linear(hidden_dim, output_dim)
else:
self.hidden_layer = nn.Linear(encoder_output_dim, hidden_dim)
self.output_layer = nn.Linear(hidden_dim, output_dim)
def forward(self, encoder_output):
encoder_hiddens, *_ = encoder_output
assert encoder_hiddens.dim()
if self.use_self_attention:
init_state = self._get_init_state(encoder_hiddens)
attn_scores = self._attention(encoder_hiddens, init_state)
attned_state = (encoder_hiddens * attn_scores).sum(0)
pred_input = torch.cat([init_state, attned_state], 1)
pred_hidden = F.relu(self.hidden_layer(pred_input))
logits = self.output_layer(pred_hidden)
else:
hidden = F.relu(self.hidden_layer(encoder_hiddens))
mean_hidden = torch.mean(hidden, 0)
max_hidden = torch.max(hidden, 0)[0]
logits = self.output_layer(mean_hidden + max_hidden)
return logits
def _get_init_state(self, encoder_hiddens):
x = torch.mean(encoder_hiddens, 0)
x = F.relu(self.init_layer(x))
return x
def _attention(self, encoder_hiddens, init_state):
init_state = init_state.unsqueeze(0).expand_as(encoder_hiddens)
attn_input = torch.cat([init_state, encoder_hiddens], 2)
attn_scores = F.relu(self.attn_layer(attn_input))
attn_scores = F.softmax(attn_scores, 0)
return attn_scores
def get_normalized_probs(self, net_output, log_probs):
"""Get normalized probabilities (or log probs) from a net's output."""
logits = net_output
if log_probs:
return F.log_softmax(logits, dim=1)
else:
return F.softmax(logits, dim=1)
def get_topk_predicted_tokens(self, net_output, src_tokens, log_probs:
'bool'):
"""
Get self.topk_labels_per_source_token top predicted words for vocab
reduction (per source token).
"""
assert isinstance(self.topk_labels_per_source_token, int
) and self.topk_labels_per_source_token > 0, 'topk_labels_per_source_token must be a positive int, or None'
k = src_tokens.size(1) * self.topk_labels_per_source_token
probs = self.get_normalized_probs(net_output, log_probs)
_, topk_indices = torch.topk(probs, k, dim=1)
return topk_indices
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'encoder_output_dim': 4, 'hidden_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_max_mean_relu_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp23 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp40 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = tmp5 + tmp1
tmp7 = triton_helpers.maximum(tmp3, tmp6)
tmp8 = tmp4 > tmp7
tmp9 = tmp4 == tmp7
tmp10 = tmp4 != tmp4
tmp11 = tmp7 != tmp7
tmp12 = tmp10 > tmp11
tmp13 = tmp8 | tmp12
tmp14 = tmp10 & tmp11
tmp15 = tmp9 | tmp14
tmp16 = tl.full([1], 0, tl.int64)
tmp17 = tl.full([1], 1, tl.int64)
tmp18 = tmp16 < tmp17
tmp19 = tmp15 & tmp18
tmp20 = tmp13 | tmp19
tmp21 = tl.where(tmp20, tmp4, tmp7)
tmp22 = tl.where(tmp20, tmp16, tmp17)
tmp24 = tmp23 + tmp1
tmp25 = triton_helpers.maximum(tmp3, tmp24)
tmp26 = tmp21 > tmp25
tmp27 = tmp21 == tmp25
tmp28 = tmp21 != tmp21
tmp29 = tmp25 != tmp25
tmp30 = tmp28 > tmp29
tmp31 = tmp26 | tmp30
tmp32 = tmp28 & tmp29
tmp33 = tmp27 | tmp32
tmp34 = tl.full([1], 2, tl.int64)
tmp35 = tmp22 < tmp34
tmp36 = tmp33 & tmp35
tmp37 = tmp31 | tmp36
tmp38 = tl.where(tmp37, tmp21, tmp25)
tmp39 = tl.where(tmp37, tmp22, tmp34)
tmp41 = tmp40 + tmp1
tmp42 = triton_helpers.maximum(tmp3, tmp41)
tmp43 = tmp38 > tmp42
tmp44 = tmp38 == tmp42
tmp45 = tmp38 != tmp38
tmp46 = tmp42 != tmp42
tmp47 = tmp45 > tmp46
tmp48 = tmp43 | tmp47
tmp49 = tmp45 & tmp46
tmp50 = tmp44 | tmp49
tmp51 = tl.full([1], 3, tl.int64)
tmp52 = tmp39 < tmp51
tmp53 = tmp50 & tmp52
tmp54 = tmp48 | tmp53
tl.where(tmp54, tmp38, tmp42)
tmp56 = tl.where(tmp54, tmp39, tmp51)
tmp57 = tmp4 + tmp7
tmp58 = tmp57 + tmp25
tmp59 = tmp58 + tmp42
tmp60 = 4.0
tmp61 = tmp59 / tmp60
tmp62 = triton_helpers.maximum(tmp4, tmp7)
tmp63 = triton_helpers.maximum(tmp62, tmp25)
tmp64 = triton_helpers.maximum(tmp63, tmp42)
tmp65 = tmp61 + tmp64
tl.store(out_ptr0 + x2, tmp56, xmask)
tl.store(out_ptr1 + x2, tmp65, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_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
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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((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((4, 4), (4, 1), torch.int64)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_max_mean_relu_0[grid(16)](buf0, primals_3,
buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf2, reinterpret_tensor(primals_4,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
del primals_5
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf0,
primals_3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf0
del primals_3
return buf3, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf2, primals_4, reinterpret_tensor(buf1, (1, 4, 4), (16, 4, 1), 0
), buf4
class WordPredictorNew(nn.Module):
def __init__(self, encoder_output_dim, hidden_dim, output_dim,
topk_labels_per_source_token=None, use_self_attention=False):
super().__init__()
self.encoder_output_dim = encoder_output_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
self.topk_labels_per_source_token = topk_labels_per_source_token
self.use_self_attention = use_self_attention
if self.use_self_attention:
self.init_layer = nn.Linear(encoder_output_dim, encoder_output_dim)
self.attn_layer = nn.Linear(2 * encoder_output_dim, 1)
self.hidden_layer = nn.Linear(2 * encoder_output_dim, hidden_dim)
self.output_layer = nn.Linear(hidden_dim, output_dim)
else:
self.hidden_layer = nn.Linear(encoder_output_dim, hidden_dim)
self.output_layer = nn.Linear(hidden_dim, output_dim)
def _get_init_state(self, encoder_hiddens):
x = torch.mean(encoder_hiddens, 0)
x = F.relu(self.init_layer(x))
return x
def _attention(self, encoder_hiddens, init_state):
init_state = init_state.unsqueeze(0).expand_as(encoder_hiddens)
attn_input = torch.cat([init_state, encoder_hiddens], 2)
attn_scores = F.relu(self.attn_layer(attn_input))
attn_scores = F.softmax(attn_scores, 0)
return attn_scores
def get_normalized_probs(self, net_output, log_probs):
"""Get normalized probabilities (or log probs) from a net's output."""
logits = net_output
if log_probs:
return F.log_softmax(logits, dim=1)
else:
return F.softmax(logits, dim=1)
def get_topk_predicted_tokens(self, net_output, src_tokens, log_probs:
'bool'):
"""
Get self.topk_labels_per_source_token top predicted words for vocab
reduction (per source token).
"""
assert isinstance(self.topk_labels_per_source_token, int
) and self.topk_labels_per_source_token > 0, 'topk_labels_per_source_token must be a positive int, or None'
k = src_tokens.size(1) * self.topk_labels_per_source_token
probs = self.get_normalized_probs(net_output, log_probs)
_, topk_indices = torch.topk(probs, k, dim=1)
return topk_indices
def forward(self, input_0):
primals_2 = self.hidden_layer.weight
primals_3 = self.hidden_layer.bias
primals_4 = self.output_layer.weight
primals_5 = self.output_layer.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Ayansam1152/translate
|
WordPredictor
| false
| 13,400
|
[
"BSD-3-Clause"
] | 748
|
33d397fc25fb1072abd2975c77c602a2d031c6c4
|
https://github.com/Ayansam1152/translate/tree/33d397fc25fb1072abd2975c77c602a2d031c6c4
|
ReconstructionLoss
|
import torch
from functools import reduce
import torch.nn as nn
class BaseModule(nn.Module):
"""
Implements the basic module.
All other modules inherit from this one
"""
def load_w(self, checkpoint_path):
"""
Loads a checkpoint into the state_dict.
:param checkpoint_path: the checkpoint file to be loaded.
"""
self.load_state_dict(torch.load(checkpoint_path))
def __repr__(self):
"""
String representation
"""
good_old = super(BaseModule, self).__repr__()
addition = 'Total number of parameters: {:,}'.format(self.n_parameters)
return good_old + '\n' + addition
def __call__(self, *args, **kwargs):
return super(BaseModule, self).__call__(*args, **kwargs)
@property
def n_parameters(self):
"""
Number of parameters of the model.
"""
n_parameters = 0
for p in self.parameters():
if hasattr(p, 'mask'):
n_parameters += torch.sum(p.mask).item()
else:
n_parameters += reduce(mul, p.shape)
return int(n_parameters)
class ReconstructionLoss(BaseModule):
"""
Implements the reconstruction loss.
"""
def __init__(self):
"""
Class constructor.
"""
super(ReconstructionLoss, self).__init__()
def forward(self, x, x_r):
"""
Forward propagation.
:param x: the batch of input samples.
:param x_r: the batch of reconstructions.
:return: the mean reconstruction loss (averaged along the batch axis).
"""
L = torch.pow(x - x_r, 2)
while L.dim() > 1:
L = torch.sum(L, dim=-1)
return torch.mean(L)
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 functools import reduce
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_pow_sub_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 16 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr1 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr1 + (2 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr1 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr1 + (4 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp24 = tl.load(in_ptr1 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr1 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp34 = tl.load(in_ptr1 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp39 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp40 = tl.load(in_ptr1 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp43 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp44 = tl.load(in_ptr1 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp48 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp49 = tl.load(in_ptr1 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp53 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp54 = tl.load(in_ptr1 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp59 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp60 = tl.load(in_ptr1 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp63 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp64 = tl.load(in_ptr1 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp68 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp69 = tl.load(in_ptr1 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp73 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp74 = tl.load(in_ptr1 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp21 = tmp19 - tmp20
tmp22 = tmp21 * tmp21
tmp25 = tmp23 - tmp24
tmp26 = tmp25 * tmp25
tmp27 = tmp22 + tmp26
tmp30 = tmp28 - tmp29
tmp31 = tmp30 * tmp30
tmp32 = tmp27 + tmp31
tmp35 = tmp33 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tmp32 + tmp36
tmp38 = tmp18 + tmp37
tmp41 = tmp39 - tmp40
tmp42 = tmp41 * tmp41
tmp45 = tmp43 - tmp44
tmp46 = tmp45 * tmp45
tmp47 = tmp42 + tmp46
tmp50 = tmp48 - tmp49
tmp51 = tmp50 * tmp50
tmp52 = tmp47 + tmp51
tmp55 = tmp53 - tmp54
tmp56 = tmp55 * tmp55
tmp57 = tmp52 + tmp56
tmp58 = tmp38 + tmp57
tmp61 = tmp59 - tmp60
tmp62 = tmp61 * tmp61
tmp65 = tmp63 - tmp64
tmp66 = tmp65 * tmp65
tmp67 = tmp62 + tmp66
tmp70 = tmp68 - tmp69
tmp71 = tmp70 * tmp70
tmp72 = tmp67 + tmp71
tmp75 = tmp73 - tmp74
tmp76 = tmp75 * tmp75
tmp77 = tmp72 + tmp76
tmp78 = tmp58 + tmp77
tl.store(out_ptr0 + x0, tmp78, xmask)
@triton.jit
def triton_per_fused_mean_sum_1(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 4.0
tmp11 = tmp9 / tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_pow_sub_sum_0[grid(16)](arg0_1, arg1_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_mean_sum_1[grid(1)](buf2, buf0, 1, 4, XBLOCK=1,
num_warps=2, num_stages=1)
del buf0
return buf2,
class BaseModule(nn.Module):
"""
Implements the basic module.
All other modules inherit from this one
"""
def load_w(self, checkpoint_path):
"""
Loads a checkpoint into the state_dict.
:param checkpoint_path: the checkpoint file to be loaded.
"""
self.load_state_dict(torch.load(checkpoint_path))
def __repr__(self):
"""
String representation
"""
good_old = super(BaseModule, self).__repr__()
addition = 'Total number of parameters: {:,}'.format(self.n_parameters)
return good_old + '\n' + addition
def __call__(self, *args, **kwargs):
return super(BaseModule, self).__call__(*args, **kwargs)
@property
def n_parameters(self):
"""
Number of parameters of the model.
"""
n_parameters = 0
for p in self.parameters():
if hasattr(p, 'mask'):
n_parameters += torch.sum(p.mask).item()
else:
n_parameters += reduce(mul, p.shape)
return int(n_parameters)
class ReconstructionLossNew(BaseModule):
"""
Implements the reconstruction loss.
"""
def __init__(self):
"""
Class constructor.
"""
super(ReconstructionLossNew, self).__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BotanAtomic/anomaly-detection
|
ReconstructionLoss
| false
| 13,401
|
[
"MIT"
] | 179
|
6617880f19a4955d70a34a3bbee83f157eb087f8
|
https://github.com/BotanAtomic/anomaly-detection/tree/6617880f19a4955d70a34a3bbee83f157eb087f8
|
FixedNorm
|
import torch
import torch.nn as nn
class FixedNorm(nn.Module):
def __init__(self, d):
super().__init__()
self.dd = d ** (-1.0 / 2)
def forward(self, x):
norm_x = x.norm(2, dim=-1, keepdim=True)
x_normed = x / (norm_x * self.dd + 1e-12)
return x_normed
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_linalg_vector_norm_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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 0.5
tmp14 = tmp12 * tmp13
tmp15 = 1e-12
tmp16 = tmp14 + tmp15
tmp17 = tmp0 / 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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_linalg_vector_norm_mul_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class FixedNormNew(nn.Module):
def __init__(self, d):
super().__init__()
self.dd = d ** (-1.0 / 2)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BlinkDL/RWKV-LM
|
FixedNorm
| false
| 13,402
|
[
"BSD-2-Clause"
] | 102
|
b48aa1d430a71ced8ae6a665c47f5dbd95f6f6ab
|
https://github.com/BlinkDL/RWKV-LM/tree/b48aa1d430a71ced8ae6a665c47f5dbd95f6f6ab
|
SelfAttention
|
import torch
import torch.nn as nn
def init_drop(dropout):
if dropout > 0:
return nn.Dropout(dropout)
else:
return lambda x: x
class SelfAttention(nn.Module):
def __init__(self, hidden_dim, attn_drop, txt):
"""
Description
-----------
This part is used to calculate type-level attention and semantic-level attention, and utilize them to generate :math:`z^{sc}` and :math:`z^{mp}`.
.. math::
w_{n}&=\\frac{1}{|V|}\\sum\\limits_{i\\in V} \\textbf{a}^\\top \\cdot \\tanh\\left(\\textbf{W}h_i^{n}+\\textbf{b}\\right) \\\\
\\beta_{n}&=\\frac{\\exp\\left(w_{n}\\right)}{\\sum_{i=1}^M\\exp\\left(w_{i}\\right)} \\\\
z &= \\sum_{n=1}^M \\beta_{n}\\cdot h^{n}
Parameters
----------
txt : str
A str to identify view, MP or SC
Returns
-------
z : matrix
The fused embedding matrix
"""
super(SelfAttention, self).__init__()
self.fc = nn.Linear(hidden_dim, hidden_dim, bias=True)
nn.init.xavier_normal_(self.fc.weight, gain=1.414)
self.tanh = nn.Tanh()
self.att = nn.Parameter(torch.empty(size=(1, hidden_dim)),
requires_grad=True)
nn.init.xavier_normal_(self.att.data, gain=1.414)
self.softmax = nn.Softmax(dim=0)
self.attn_drop = init_drop(attn_drop)
self.txt = txt
def forward(self, embeds):
beta = []
attn_curr = self.attn_drop(self.att)
for embed in embeds:
sp = self.tanh(self.fc(embed)).mean(dim=0)
beta.append(attn_curr.matmul(sp.t()))
beta = torch.cat(beta, dim=-1).view(-1)
beta = self.softmax(beta)
None
z = 0
for i in range(len(embeds)):
z += embeds[i] * beta[i]
return z
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_dim': 4, 'attn_drop': 0.5, 'txt': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mean_tanh_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)
tmp2 = tl.load(in_ptr0 + (16 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (32 + x0), xmask)
tmp8 = tl.load(in_ptr0 + (48 + x0), xmask)
tmp1 = libdevice.tanh(tmp0)
tmp3 = libdevice.tanh(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = libdevice.tanh(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = libdevice.tanh(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = 4.0
tmp12 = tmp10 / tmp11
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = triton_helpers.max2(tmp1, 1)[:, None]
tmp4 = tmp0 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp3, None)
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None)
@triton.jit
def triton_poi_fused_add_mul_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tl.load(in_ptr2 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp7 = tl.load(in_ptr3 + 0)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp13 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp14 = tl.load(in_ptr1 + 1)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp21 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp22 = tl.load(in_ptr1 + 2)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp29 = tl.load(in_ptr0 + (192 + x0), xmask)
tmp30 = tl.load(in_ptr1 + 3)
tmp31 = tl.broadcast_to(tmp30, [XBLOCK])
tmp5 = tmp2 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp9 = tmp6 / tmp8
tmp10 = tmp0 * tmp9
tmp11 = 0.0
tmp12 = tmp10 + tmp11
tmp16 = tmp15 - tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 / tmp8
tmp19 = tmp13 * tmp18
tmp20 = tmp12 + tmp19
tmp24 = tmp23 - tmp4
tmp25 = tl_math.exp(tmp24)
tmp26 = tmp25 / tmp8
tmp27 = tmp21 * tmp26
tmp28 = tmp20 + tmp27
tmp32 = tmp31 - tmp4
tmp33 = tl_math.exp(tmp32)
tmp34 = tmp33 / tmp8
tmp35 = tmp29 * tmp34
tmp36 = tmp28 + tmp35
tl.store(out_ptr0 + x0, tmp36, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(primals_2, (16,
4), (4, 1), 64), reinterpret_tensor(primals_3, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf1)
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(primals_2, (16,
4), (4, 1), 128), reinterpret_tensor(primals_3, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf2)
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(primals_2, (16,
4), (4, 1), 192), reinterpret_tensor(primals_3, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf3)
del primals_3
del primals_4
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_tanh_0[grid(16)](buf0, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((1, 16), (16, 1), torch.float32)
buf5 = reinterpret_tensor(buf12, (1, 4), (16, 1), 0)
extern_kernels.mm(primals_1, reinterpret_tensor(buf4, (4, 4), (1, 4
), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mean_tanh_0[grid(16)](buf1, buf6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf12, (1, 4), (16, 1), 4)
extern_kernels.mm(primals_1, reinterpret_tensor(buf6, (4, 4), (1, 4
), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mean_tanh_0[grid(16)](buf2, buf8, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf12, (1, 4), (16, 1), 8)
extern_kernels.mm(primals_1, reinterpret_tensor(buf8, (4, 4), (1, 4
), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mean_tanh_0[grid(16)](buf3, buf10, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf12, (1, 4), (16, 1), 12)
extern_kernels.mm(primals_1, reinterpret_tensor(buf10, (4, 4), (1,
4), 0), out=buf11)
buf13 = empty_strided_cuda((1,), (1,), torch.float32)
buf14 = empty_strided_cuda((1,), (1,), torch.float32)
triton_per_fused__softmax_1[grid(1)](buf12, buf13, buf14, 1, 16,
XBLOCK=1, num_warps=2, num_stages=1)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_mul_2[grid(64)](primals_2, buf12, buf13, buf14,
buf15, 64, XBLOCK=64, num_warps=1, num_stages=1)
return buf15, primals_1, reinterpret_tensor(primals_2, (4, 4, 4), (16,
4, 1), 0), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 64
), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 128
), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 192
), buf0, buf1, buf2, buf3, buf12, buf13, buf14, buf10, buf8, buf6, buf4
def init_drop(dropout):
if dropout > 0:
return nn.Dropout(dropout)
else:
return lambda x: x
class SelfAttentionNew(nn.Module):
def __init__(self, hidden_dim, attn_drop, txt):
"""
Description
-----------
This part is used to calculate type-level attention and semantic-level attention, and utilize them to generate :math:`z^{sc}` and :math:`z^{mp}`.
.. math::
w_{n}&=\\frac{1}{|V|}\\sum\\limits_{i\\in V} \\textbf{a}^\\top \\cdot \\tanh\\left(\\textbf{W}h_i^{n}+\\textbf{b}\\right) \\\\
\\beta_{n}&=\\frac{\\exp\\left(w_{n}\\right)}{\\sum_{i=1}^M\\exp\\left(w_{i}\\right)} \\\\
z &= \\sum_{n=1}^M \\beta_{n}\\cdot h^{n}
Parameters
----------
txt : str
A str to identify view, MP or SC
Returns
-------
z : matrix
The fused embedding matrix
"""
super(SelfAttentionNew, self).__init__()
self.fc = nn.Linear(hidden_dim, hidden_dim, bias=True)
nn.init.xavier_normal_(self.fc.weight, gain=1.414)
self.tanh = nn.Tanh()
self.att = nn.Parameter(torch.empty(size=(1, hidden_dim)),
requires_grad=True)
nn.init.xavier_normal_(self.att.data, gain=1.414)
self.softmax = nn.Softmax(dim=0)
self.attn_drop = init_drop(attn_drop)
self.txt = txt
def forward(self, input_0):
primals_1 = self.att
primals_3 = self.fc.weight
primals_4 = self.fc.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
BUPT-GAMMA/OpenHGNN
|
SelfAttention
| false
| 13,403
|
[
"Apache-2.0"
] | 235
|
5f218dad4ed1415aa6d842bc20785c61e74e5405
|
https://github.com/BUPT-GAMMA/OpenHGNN/tree/5f218dad4ed1415aa6d842bc20785c61e74e5405
|
HouseHolderFlow
|
import torch
import torch.utils.data
import torch.nn as nn
class HouseHolderFlow(nn.Module):
def forward(self, v, z):
"""
:param v: batch_size (B) x latent_size (L)
:param z: batch_size (B) x latent_size (L)
:return: z_new = z - 2* v v_T / norm(v,2) * z
"""
vvT = torch.bmm(v.unsqueeze(2), v.unsqueeze(1))
vvTz = torch.bmm(vvT, z.unsqueeze(2)).squeeze(2)
norm_sq = torch.sum(v * v, 1).unsqueeze(1)
norm_sq = norm_sq.expand(norm_sq.size(0), v.size(1))
z_new = z - 2 * vvTz / norm_sq
return z_new
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_div_mul_sub_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)
tmp4 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp5 = tmp4 * tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp13 = tmp12 * tmp12
tmp14 = tmp11 + tmp13
tmp15 = tmp3 / tmp14
tmp16 = tmp0 - tmp15
tl.store(in_out_ptr0 + x2, tmp16, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 4, 1), (4, 1, 1),
0), reinterpret_tensor(arg0_1, (4, 1, 4), (4, 4, 1), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf0, reinterpret_tensor(arg1_1, (4, 4, 1), (4,
1, 1), 0), out=buf1)
del buf0
buf2 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
del buf1
get_raw_stream(0)
triton_poi_fused_div_mul_sub_0[grid(16)](buf2, arg1_1, arg0_1, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class HouseHolderFlowNew(nn.Module):
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BratChar/variational-item-response-theory-public
|
HouseHolderFlow
| false
| 13,404
|
[
"MIT"
] | 52
|
12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
https://github.com/BratChar/variational-item-response-theory-public/tree/12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
LayerNorm
|
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.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
assert_size_stride = torch._C._dynamo.guards.assert_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-05
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-05, affine=True):
super(LayerNormNew, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.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]
|
Boyiliee/PONO
|
LayerNorm
| false
| 13,405
|
[
"MIT"
] | 133
|
b9108e8bf8ba0228635532ba5bdc973b7393d045
|
https://github.com/Boyiliee/PONO/tree/b9108e8bf8ba0228635532ba5bdc973b7393d045
|
ItemInferenceNetwork
|
import torch
import torch.utils.data
import torch.nn as nn
class ItemInferenceNetwork(nn.Module):
def __init__(self, num_item, item_feat_dim):
super().__init__()
self.mu_lookup = nn.Embedding(num_item, item_feat_dim)
self.logvar_lookup = nn.Embedding(num_item, item_feat_dim)
def forward(self, item_index):
item_index = item_index.squeeze(1)
mu = self.mu_lookup(item_index.long())
logvar = self.logvar_lookup(item_index.long())
return mu, logvar
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_item': 4, 'item_feat_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.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
@triton.jit
def triton_poi_fused__to_copy_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0.to(tl.int64)
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused_embedding_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask)
tmp7 = tl.load(in_ptr2 + (x0 + 4 * tmp4), xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused__to_copy_0[grid(256)](primals_1, buf0, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_embedding_1[grid(1024)](buf0, primals_2, primals_3,
buf1, buf2, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_3
return buf1, buf2, buf0
class ItemInferenceNetworkNew(nn.Module):
def __init__(self, num_item, item_feat_dim):
super().__init__()
self.mu_lookup = nn.Embedding(num_item, item_feat_dim)
self.logvar_lookup = nn.Embedding(num_item, item_feat_dim)
def forward(self, input_0):
primals_2 = self.mu_lookup.weight
primals_3 = self.logvar_lookup.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
BratChar/variational-item-response-theory-public
|
ItemInferenceNetwork
| false
| 13,406
|
[
"MIT"
] | 52
|
12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
https://github.com/BratChar/variational-item-response-theory-public/tree/12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
TargetContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class TargetContextGate(nn.Module):
"""Apply the context gate only to the target context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(TargetContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh(z * target + source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_2(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)
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_out_ptr0 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp6 = tmp4 + tmp5
tmp7 = tmp3 + tmp6
tmp8 = libdevice.tanh(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) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_6, (4, 4),
(1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf3, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf4)
del primals_8
del primals_9
buf5 = buf2
del buf2
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf5, buf1, buf4,
primals_7, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_7
return buf5, primals_3, buf0, buf1, buf3, buf4, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class TargetContextGateNew(nn.Module):
"""Apply the context gate only to the target context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(TargetContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
BradLin0819/kg2text
|
TargetContextGate
| false
| 13,407
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
ContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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, 12), (12, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_4, (12, 4), (1,
12), 0), out=buf1)
del primals_4
buf2 = buf1
del buf1
triton_poi_fused_sigmoid_1[grid(16)](buf2, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
del primals_6
del primals_7
buf4 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_2[grid(32)](primals_1, primals_2, buf4, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf4, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf5)
del primals_8
del primals_9
return buf2, buf3, buf5, primals_3, buf0, buf2, buf4
class ContextGateNew(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGateNew, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, input_0, input_1, input_2):
primals_4 = self.gate.weight
primals_5 = self.gate.bias
primals_1 = self.source_proj.weight
primals_7 = self.source_proj.bias
primals_8 = self.target_proj.weight
primals_9 = self.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0], output[1], output[2]
|
BradLin0819/kg2text
|
ContextGate
| false
| 13,408
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
DenseSAGEConv
|
import math
import torch
import torch.nn.functional as F
import torch.utils.data
from torch.nn import Parameter
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DenseSAGEConv(torch.nn.Module):
"""See :class:`torch_geometric.nn.conv.sage_conv.SAGEConv`.
:rtype: :class:`Tensor`
"""
def __init__(self, in_channels, out_channels, normalize=True, bias=True):
super(DenseSAGEConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.normalize = normalize
self.weight = Parameter(torch.Tensor(self.in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
uniform(self.in_channels, self.bias)
def forward(self, x, adj, mask=None, add_loop=True):
"""
Args:
x (Tensor): Node feature tensor :math:`\\mathbf{X} \\in \\mathbb{R}^{B
\\times N \\times F}`, with batch-size :math:`B`, (maximum)
number of nodes :math:`N` for each graph, and feature
dimension :math:`F`.
adj (Tensor): Adjacency tensor :math:`\\mathbf{A} \\in \\mathbb{R}^{B
\\times N \\times N}`.
mask (ByteTensor, optional): Mask matrix
:math:`\\mathbf{M} \\in {\\{ 0, 1 \\}}^{B \\times N}` indicating
the valid nodes for each graph. (default: :obj:`None`)
add_loop (bool, optional): If set to :obj:`False`, the layer will
not automatically add self-loops to the adjacency matrices.
(default: :obj:`True`)
"""
x = x.unsqueeze(0) if x.dim() == 2 else x
adj = adj.unsqueeze(0) if adj.dim() == 2 else adj
B, N, _ = x.size()
if add_loop:
eye = torch.eye(N, dtype=adj.dtype, device=adj.device)
adj = adj + eye.unsqueeze(0).expand_as(adj)
out = torch.matmul(adj, x)
out = out / adj.sum(dim=-1, keepdim=True)
out = torch.matmul(out, self.weight)
if self.bias is not None:
out = out + self.bias
if self.normalize:
out = F.normalize(out, p=2, dim=-1)
if mask is not None:
mask = mask.view(B, N, 1)
out = out * mask
return out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.
in_channels, self.out_channels)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.utils.data
from torch.nn import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = x1
tmp2 = x0
tmp3 = tmp1 == tmp2
tmp4 = 1.0
tmp5 = 0.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 + tmp6
tl.store(out_ptr0 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_clone_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 % 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_div_sum_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
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(in_out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_min_linalg_vector_norm_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + 1)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + 2)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK])
tmp17 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr1 + 3)
tmp19 = tl.broadcast_to(tmp18, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tmp3 * tmp3
tmp8 = tmp5 + tmp7
tmp9 = tmp8 * tmp8
tmp10 = tmp4 + tmp9
tmp14 = tmp11 + tmp13
tmp15 = tmp14 * tmp14
tmp16 = tmp10 + tmp15
tmp20 = tmp17 + tmp19
tmp21 = tmp20 * tmp20
tmp22 = tmp16 + tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-12
tmp25 = triton_helpers.maximum(tmp23, tmp24)
tl.store(out_ptr0 + x0, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_div_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 / tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_2, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(256)](primals_1, buf1, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_1
buf2 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_div_sum_2[grid(256)](buf3, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
del buf0
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0),
primals_3, out=buf4)
del primals_3
buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_clamp_min_linalg_vector_norm_3[grid(64)](buf4,
primals_4, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf6 = buf1
del buf1
triton_poi_fused_add_div_4[grid(256)](buf4, primals_4, buf5, buf6,
256, XBLOCK=128, num_warps=4, num_stages=1)
del buf5
return buf6, primals_4, buf4, reinterpret_tensor(buf3, (4, 64), (1, 4), 0)
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DenseSAGEConvNew(torch.nn.Module):
"""See :class:`torch_geometric.nn.conv.sage_conv.SAGEConv`.
:rtype: :class:`Tensor`
"""
def __init__(self, in_channels, out_channels, normalize=True, bias=True):
super(DenseSAGEConvNew, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.normalize = normalize
self.weight = Parameter(torch.Tensor(self.in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
uniform(self.in_channels, self.bias)
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.
in_channels, self.out_channels)
def forward(self, input_0, input_1):
primals_3 = self.weight
primals_4 = self.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Bawaw/pytorch_geometric
|
DenseSAGEConv
| false
| 13,409
|
[
"MIT"
] | 62
|
868548d4396fc66e39b08e2ff19091a367ddac13
|
https://github.com/Bawaw/pytorch_geometric/tree/868548d4396fc66e39b08e2ff19091a367ddac13
|
AverageAttention
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.dropout_1 = nn.Dropout(dropout)
self.relu = nn.ReLU()
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x):
"""Layer definition.
Args:
x: ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor): Output ``(batch_size, input_len, model_dim)``.
"""
inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))
output = self.dropout_2(self.w_2(inter))
return output + x
def update_dropout(self, dropout):
self.dropout_1.p = dropout
self.dropout_2.p = dropout
class AverageAttention(nn.Module):
"""
Average Attention module from
"Accelerating Neural Transformer via an Average Attention Network"
:cite:`DBLP:journals/corr/abs-1805-00631`.
Args:
model_dim (int): the dimension of keys/values/queries,
must be divisible by head_count
dropout (float): dropout parameter
"""
def __init__(self, model_dim, dropout=0.1, aan_useffn=False):
self.model_dim = model_dim
self.aan_useffn = aan_useffn
super(AverageAttention, self).__init__()
if aan_useffn:
self.average_layer = PositionwiseFeedForward(model_dim,
model_dim, dropout)
self.gating_layer = nn.Linear(model_dim * 2, model_dim * 2)
def cumulative_average_mask(self, batch_size, inputs_len, device):
"""
Builds the mask to compute the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Figure 3
Args:
batch_size (int): batch size
inputs_len (int): length of the inputs
Returns:
(FloatTensor):
* A Tensor of shape ``(batch_size, input_len, input_len)``
"""
triangle = torch.tril(torch.ones(inputs_len, inputs_len, dtype=
torch.float, device=device))
weights = torch.ones(1, inputs_len, dtype=torch.float, device=device
) / torch.arange(1, inputs_len + 1, dtype=torch.float, device=
device)
mask = triangle * weights.transpose(0, 1)
return mask.unsqueeze(0).expand(batch_size, inputs_len, inputs_len)
def cumulative_average(self, inputs, mask_or_step, layer_cache=None,
step=None):
"""
Computes the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Equations (1) (5) (6)
Args:
inputs (FloatTensor): sequence to average
``(batch_size, input_len, dimension)``
mask_or_step: if cache is set, this is assumed
to be the current step of the
dynamic decoding. Otherwise, it is the mask matrix
used to compute the cumulative average.
layer_cache: a dictionary containing the cumulative average
of the previous step.
Returns:
a tensor of the same shape and type as ``inputs``.
"""
if layer_cache is not None:
step = mask_or_step
average_attention = (inputs + step * layer_cache['prev_g']) / (step
+ 1)
layer_cache['prev_g'] = average_attention
return average_attention
else:
mask = mask_or_step
return torch.matmul(mask, inputs)
def forward(self, inputs, mask=None, layer_cache=None, step=None):
"""
Args:
inputs (FloatTensor): ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor, FloatTensor):
* gating_outputs ``(batch_size, input_len, model_dim)``
* average_outputs average attention
``(batch_size, input_len, model_dim)``
"""
batch_size = inputs.size(0)
inputs_len = inputs.size(1)
average_outputs = self.cumulative_average(inputs, self.
cumulative_average_mask(batch_size, inputs_len, inputs.device) if
layer_cache is None else step, layer_cache=layer_cache)
if self.aan_useffn:
average_outputs = self.average_layer(average_outputs)
gating_outputs = self.gating_layer(torch.cat((inputs,
average_outputs), -1))
input_gate, forget_gate = torch.chunk(gating_outputs, 2, dim=2)
gating_outputs = torch.sigmoid(input_gate) * inputs + torch.sigmoid(
forget_gate) * average_outputs
return gating_outputs, average_outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'model_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.cuda
import torch.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_mul_ones_tril_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = x0 + -1 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 <= tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = 1 + x1
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp3 / tmp7
tmp9 = tmp5 * tmp8
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_sigmoid_backward_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, 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 + 8 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x2, xmask)
tmp6 = tl.load(in_ptr0 + (4 + x0 + 8 * x1), xmask)
tmp7 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp5 = tmp3 * tmp4
tmp8 = tmp6 + tmp7
tmp9 = tl.sigmoid(tmp8)
tmp11 = tmp9 * tmp10
tmp12 = tmp5 + tmp11
tmp13 = 1.0
tmp14 = tmp13 - tmp9
tmp15 = tmp9 * tmp14
tmp16 = tmp13 - tmp3
tmp17 = tmp3 * tmp16
tl.store(out_ptr0 + x2, tmp12, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (8, 8), (8, 1))
assert_size_stride(primals_3, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_ones_tril_0[grid(16)](buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 4), (0, 4, 1), 0
), primals_1, out=buf1)
del buf0
buf2 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_1[grid(128)](primals_1, buf1, buf2, 128,
XBLOCK=128, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 8), (8, 1), 0),
reinterpret_tensor(primals_2, (8, 8), (1, 8), 0), out=buf3)
del primals_2
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_sigmoid_backward_2[grid(64)](buf3,
primals_3, primals_1, buf1, buf4, buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf3
del primals_3
return buf4, buf1, primals_1, buf1, reinterpret_tensor(buf2, (16, 8), (
8, 1), 0), buf5, buf6
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.dropout_1 = nn.Dropout(dropout)
self.relu = nn.ReLU()
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x):
"""Layer definition.
Args:
x: ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor): Output ``(batch_size, input_len, model_dim)``.
"""
inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))
output = self.dropout_2(self.w_2(inter))
return output + x
def update_dropout(self, dropout):
self.dropout_1.p = dropout
self.dropout_2.p = dropout
class AverageAttentionNew(nn.Module):
"""
Average Attention module from
"Accelerating Neural Transformer via an Average Attention Network"
:cite:`DBLP:journals/corr/abs-1805-00631`.
Args:
model_dim (int): the dimension of keys/values/queries,
must be divisible by head_count
dropout (float): dropout parameter
"""
def __init__(self, model_dim, dropout=0.1, aan_useffn=False):
self.model_dim = model_dim
self.aan_useffn = aan_useffn
super(AverageAttentionNew, self).__init__()
if aan_useffn:
self.average_layer = PositionwiseFeedForward(model_dim,
model_dim, dropout)
self.gating_layer = nn.Linear(model_dim * 2, model_dim * 2)
def cumulative_average_mask(self, batch_size, inputs_len, device):
"""
Builds the mask to compute the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Figure 3
Args:
batch_size (int): batch size
inputs_len (int): length of the inputs
Returns:
(FloatTensor):
* A Tensor of shape ``(batch_size, input_len, input_len)``
"""
triangle = torch.tril(torch.ones(inputs_len, inputs_len, dtype=
torch.float, device=device))
weights = torch.ones(1, inputs_len, dtype=torch.float, device=device
) / torch.arange(1, inputs_len + 1, dtype=torch.float, device=
device)
mask = triangle * weights.transpose(0, 1)
return mask.unsqueeze(0).expand(batch_size, inputs_len, inputs_len)
def cumulative_average(self, inputs, mask_or_step, layer_cache=None,
step=None):
"""
Computes the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Equations (1) (5) (6)
Args:
inputs (FloatTensor): sequence to average
``(batch_size, input_len, dimension)``
mask_or_step: if cache is set, this is assumed
to be the current step of the
dynamic decoding. Otherwise, it is the mask matrix
used to compute the cumulative average.
layer_cache: a dictionary containing the cumulative average
of the previous step.
Returns:
a tensor of the same shape and type as ``inputs``.
"""
if layer_cache is not None:
step = mask_or_step
average_attention = (inputs + step * layer_cache['prev_g']) / (step
+ 1)
layer_cache['prev_g'] = average_attention
return average_attention
else:
mask = mask_or_step
return torch.matmul(mask, inputs)
def forward(self, input_0):
primals_2 = self.gating_layer.weight
primals_3 = self.gating_layer.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
BradLin0819/kg2text
|
AverageAttention
| false
| 13,410
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
PONO
|
import torch
import torch.nn as nn
class PONO(nn.Module):
def __init__(self, input_size=None, return_stats=False, affine=False,
eps=1e-05):
super(PONO, self).__init__()
self.return_stats = return_stats
self.input_size = input_size
self.eps = eps
self.affine = affine
if affine:
self.beta = nn.Parameter(torch.zeros(1, 1, *input_size))
self.gamma = nn.Parameter(torch.ones(1, 1, *input_size))
else:
self.beta, self.gamma = None, None
def forward(self, x):
mean = x.mean(dim=1, keepdim=True)
std = (x.var(dim=1, keepdim=True) + self.eps).sqrt()
x = (x - mean) / std
if self.affine:
x = x * self.gamma + self.beta
return x, mean, std
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mean_sqrt_var_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = 3.0
tmp21 = tmp19 / tmp20
tmp22 = 1e-05
tmp23 = tmp21 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tl.store(out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_div_sub_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 / tmp3
tl.store(out_ptr0 + x3, 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, 1, 4, 4), (16, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mean_sqrt_var_0[grid(64)](arg0_1, buf0, buf1,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_div_sub_1[grid(256)](arg0_1, buf0, buf1, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf2, buf0, buf1
class PONONew(nn.Module):
def __init__(self, input_size=None, return_stats=False, affine=False,
eps=1e-05):
super(PONONew, self).__init__()
self.return_stats = return_stats
self.input_size = input_size
self.eps = eps
self.affine = affine
if affine:
self.beta = nn.Parameter(torch.zeros(1, 1, *input_size))
self.gamma = nn.Parameter(torch.ones(1, 1, *input_size))
else:
self.beta, self.gamma = None, None
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1], output[2]
|
Boyiliee/PONO
|
PONO
| false
| 13,411
|
[
"MIT"
] | 133
|
b9108e8bf8ba0228635532ba5bdc973b7393d045
|
https://github.com/Boyiliee/PONO/tree/b9108e8bf8ba0228635532ba5bdc973b7393d045
|
SELayer
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SELayer(nn.Module):
def __init__(self, in_channels, reduction):
super().__init__()
mid_channels = in_channels // reduction
self.fc1 = nn.Linear(in_channels, mid_channels)
self.fc2 = nn.Linear(mid_channels, in_channels)
def forward(self, x):
n_batches, n_channels, _, _ = x.size()
y = F.adaptive_avg_pool2d(x, output_size=1).view(n_batches, n_channels)
y = F.relu(self.fc1(y), inplace=True)
y = F.sigmoid(self.fc2(y)).view(n_batches, n_channels, 1, 1)
return x * y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'reduction': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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, (1, 4), (4, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (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 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 1), (1, 4), 0), out=buf2)
del primals_2
buf3 = buf2
del buf2
triton_poi_fused_relu_1[grid(4)](buf3, primals_3, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf3, reinterpret_tensor(primals_4,
(1, 4), (1, 1), 0), alpha=1, beta=1, out=buf4)
del primals_5
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_2[grid(256)](primals_1, buf4, buf5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
return buf5, primals_1, reinterpret_tensor(buf1, (4, 4), (4, 1), 0
), buf3, buf4, primals_4
class SELayerNew(nn.Module):
def __init__(self, in_channels, reduction):
super().__init__()
mid_channels = in_channels // reduction
self.fc1 = nn.Linear(in_channels, mid_channels)
self.fc2 = nn.Linear(mid_channels, in_channels)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
BrandonHanx/pytorch_image_classification
|
SELayer
| false
| 13,412
|
[
"MIT"
] | 1,114
|
13f037c442f251c5cd938672245b39df157f1c98
|
https://github.com/BrandonHanx/pytorch_image_classification/tree/13f037c442f251c5cd938672245b39df157f1c98
|
SourceContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class SourceContextGate(nn.Module):
"""Apply the context gate only to the source context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(SourceContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh(target + z * source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tl.sigmoid(tmp3)
tmp6 = tmp4 * tmp5
tmp7 = tmp2 + tmp6
tmp8 = libdevice.tanh(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) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, 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((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf3, reinterpret_tensor(primals_8, (8, 4), (1, 8
), 0), out=buf4)
del primals_8
buf5 = buf4
del buf4
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf5, primals_9,
buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_9
return buf5, primals_3, buf0, buf1, buf2, buf3, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class SourceContextGateNew(nn.Module):
"""Apply the context gate only to the source context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(SourceContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
BradLin0819/kg2text
|
SourceContextGate
| false
| 13,413
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
KL_loss_softmax
|
import torch
import torch.nn as nn
import torch.nn.init
class KL_loss_softmax(nn.Module):
"""
Compute KL_divergence between all prediction score (already sum=1, omit softmax function)
"""
def __init__(self):
super(KL_loss_softmax, self).__init__()
self.KL_loss = nn.KLDivLoss(reduce=False)
def forward(self, im, s):
img_prob = torch.log(im)
s_prob = s
KL_loss = self.KL_loss(img_prob, s_prob)
loss = KL_loss.sum()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_log_mul_sub_sum_xlogy_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp9 = tl.load(in_ptr1 + r0, None)
tmp1 = libdevice.isnan(tmp0).to(tl.int1)
tmp2 = 0.0
tmp3 = tmp0 == tmp2
tmp4 = tl_math.log(tmp0)
tmp5 = tmp0 * tmp4
tmp6 = tl.where(tmp3, tmp2, tmp5)
tmp7 = float('nan')
tmp8 = tl.where(tmp1, tmp7, tmp6)
tmp10 = tl_math.log(tmp9)
tmp11 = tmp0 * tmp10
tmp12 = tmp8 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_log_mul_sub_sum_xlogy_0[grid(1)](arg1_1, arg0_1,
buf0, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class KL_loss_softmaxNew(nn.Module):
"""
Compute KL_divergence between all prediction score (already sum=1, omit softmax function)
"""
def __init__(self):
super(KL_loss_softmaxNew, self).__init__()
self.KL_loss = nn.KLDivLoss(reduce=False)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
BruceW91/CVSE
|
KL_loss_softmax
| false
| 13,414
|
[
"MIT"
] | 152
|
20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
https://github.com/BruceW91/CVSE/tree/20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
GlobalAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda
import torch.distributed
def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments
), 'Not all arguments have the same value: ' + str(args)
def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return torch.arange(0, max_len, device=lengths.device).type_as(lengths
).repeat(batch_size, 1).lt(lengths.unsqueeze(1))
class GlobalAttention(nn.Module):
"""
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
Constructs a unit mapping a query `q` of size `dim`
and a source matrix `H` of size `n x dim`, to an output
of size `dim`.
.. mermaid::
graph BT
A[Query]
subgraph RNN
C[H 1]
D[H 2]
E[H N]
end
F[Attn]
G[Output]
A --> F
C --> F
D --> F
E --> F
C -.-> G
D -.-> G
E -.-> G
F --> G
All models compute the output as
:math:`c = \\sum_{j=1}^{\\text{SeqLength}} a_j H_j` where
:math:`a_j` is the softmax of a score function.
Then then apply a projection layer to [q, c].
However they
differ on how they compute the attention score.
* Luong Attention (dot, general):
* dot: :math:`\\text{score}(H_j,q) = H_j^T q`
* general: :math:`\\text{score}(H_j, q) = H_j^T W_a q`
* Bahdanau Attention (mlp):
* :math:`\\text{score}(H_j, q) = v_a^T \\text{tanh}(W_a q + U_a h_j)`
Args:
dim (int): dimensionality of query and key
coverage (bool): use coverage term
attn_type (str): type of attention to use, options [dot,general,mlp]
attn_func (str): attention function to use, options [softmax,sparsemax]
"""
def __init__(self, dim, coverage=False, attn_type='dot', attn_func=
'softmax'):
super(GlobalAttention, self).__init__()
self.dim = dim
assert attn_type in ['dot', 'general', 'mlp'
], 'Please select a valid attention type (got {:s}).'.format(
attn_type)
self.attn_type = attn_type
assert attn_func in ['softmax', 'sparsemax'
], 'Please select a valid attention function.'
self.attn_func = attn_func
if self.attn_type == 'general':
self.linear_in = nn.Linear(dim, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = nn.Linear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=True)
self.v = nn.Linear(dim, 1, bias=False)
out_bias = self.attn_type == 'mlp'
self.linear_out = nn.Linear(dim * 2, dim, bias=out_bias)
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def score(self, h_t, h_s):
"""
Args:
h_t (FloatTensor): sequence of queries ``(batch, tgt_len, dim)``
h_s (FloatTensor): sequence of sources ``(batch, src_len, dim``
Returns:
FloatTensor: raw attention scores (unnormalized) for each src index
``(batch, tgt_len, src_len)``
"""
src_batch, src_len, src_dim = h_s.size()
tgt_batch, tgt_len, tgt_dim = h_t.size()
aeq(src_batch, tgt_batch)
aeq(src_dim, tgt_dim)
aeq(self.dim, src_dim)
if self.attn_type in ['general', 'dot']:
if self.attn_type == 'general':
h_t_ = h_t.view(tgt_batch * tgt_len, tgt_dim)
h_t_ = self.linear_in(h_t_)
h_t = h_t_.view(tgt_batch, tgt_len, tgt_dim)
h_s_ = h_s.transpose(1, 2)
return torch.bmm(h_t, h_s_)
else:
dim = self.dim
wq = self.linear_query(h_t.view(-1, dim))
wq = wq.view(tgt_batch, tgt_len, 1, dim)
wq = wq.expand(tgt_batch, tgt_len, src_len, dim)
uh = self.linear_context(h_s.contiguous().view(-1, dim))
uh = uh.view(src_batch, 1, src_len, dim)
uh = uh.expand(src_batch, tgt_len, src_len, dim)
wquh = torch.tanh(wq + uh)
return self.v(wquh.view(-1, dim)).view(tgt_batch, tgt_len, src_len)
def forward(self, source, memory_bank, memory_lengths=None, coverage=None):
"""
Args:
source (FloatTensor): query vectors ``(batch, tgt_len, dim)``
memory_bank (FloatTensor): source vectors ``(batch, src_len, dim)``
memory_lengths (LongTensor): the source context lengths ``(batch,)``
coverage (FloatTensor): None (not supported yet)
Returns:
(FloatTensor, FloatTensor):
* Computed vector ``(tgt_len, batch, dim)``
* Attention distribtutions for each query
``(tgt_len, batch, src_len)``
"""
if source.dim() == 2:
one_step = True
source = source.unsqueeze(1)
else:
one_step = False
batch, source_l, dim = memory_bank.size()
batch_, target_l, dim_ = source.size()
aeq(batch, batch_)
aeq(dim, dim_)
aeq(self.dim, dim)
if coverage is not None:
batch_, source_l_ = coverage.size()
aeq(batch, batch_)
aeq(source_l, source_l_)
if coverage is not None:
cover = coverage.view(-1).unsqueeze(1)
memory_bank += self.linear_cover(cover).view_as(memory_bank)
memory_bank = torch.tanh(memory_bank)
align = self.score(source, memory_bank)
if memory_lengths is not None:
mask = sequence_mask(memory_lengths, max_len=align.size(-1))
mask = mask.unsqueeze(1)
align.masked_fill_(~mask, -float('inf'))
if self.attn_func == 'softmax':
align_vectors = F.softmax(align.view(batch * target_l, source_l
), -1)
else:
align_vectors = sparsemax(align.view(batch * target_l, source_l
), -1)
align_vectors = align_vectors.view(batch, target_l, source_l)
c = torch.bmm(align_vectors, memory_bank)
concat_c = torch.cat([c, source], 2).view(batch * target_l, dim * 2)
attn_h = self.linear_out(concat_c).view(batch, target_l, dim)
if self.attn_type in ['general', 'dot']:
attn_h = torch.tanh(attn_h)
if one_step:
attn_h = attn_h.squeeze(1)
align_vectors = align_vectors.squeeze(1)
batch_, dim_ = attn_h.size()
aeq(batch, batch_)
aeq(dim, dim_)
batch_, source_l_ = align_vectors.size()
aeq(batch, batch_)
aeq(source_l, source_l_)
else:
attn_h = attn_h.transpose(0, 1).contiguous()
align_vectors = align_vectors.transpose(0, 1).contiguous()
target_l_, batch_, dim_ = attn_h.size()
aeq(target_l, target_l_)
aeq(batch, batch_)
aeq(dim, dim_)
target_l_, batch_, source_l_ = align_vectors.size()
aeq(target_l, target_l_)
aeq(batch, batch_)
aeq(source_l, source_l_)
return attn_h, align_vectors
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.cuda
import torch.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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_clone_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
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(out_ptr0 + x3, tmp1, xmask)
@triton.jit
def triton_poi_fused_clone_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 % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 8), (8, 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(primals_1, reinterpret_tensor(primals_2, (4, 4,
4), (16, 1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1),
0), primals_2, out=buf3)
del primals_2
buf4 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_2[grid(128)](buf3, primals_1, buf4, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf5 = reinterpret_tensor(buf3, (16, 4), (4, 1), 0)
del buf3
extern_kernels.mm(reinterpret_tensor(buf4, (16, 8), (8, 1), 0),
reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), out=buf5)
del primals_3
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(64)](buf2, buf7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf2
return buf6, buf7, reinterpret_tensor(buf4, (16, 8), (8, 1), 0), buf5
def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments
), 'Not all arguments have the same value: ' + str(args)
def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return torch.arange(0, max_len, device=lengths.device).type_as(lengths
).repeat(batch_size, 1).lt(lengths.unsqueeze(1))
class GlobalAttentionNew(nn.Module):
"""
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
Constructs a unit mapping a query `q` of size `dim`
and a source matrix `H` of size `n x dim`, to an output
of size `dim`.
.. mermaid::
graph BT
A[Query]
subgraph RNN
C[H 1]
D[H 2]
E[H N]
end
F[Attn]
G[Output]
A --> F
C --> F
D --> F
E --> F
C -.-> G
D -.-> G
E -.-> G
F --> G
All models compute the output as
:math:`c = \\sum_{j=1}^{\\text{SeqLength}} a_j H_j` where
:math:`a_j` is the softmax of a score function.
Then then apply a projection layer to [q, c].
However they
differ on how they compute the attention score.
* Luong Attention (dot, general):
* dot: :math:`\\text{score}(H_j,q) = H_j^T q`
* general: :math:`\\text{score}(H_j, q) = H_j^T W_a q`
* Bahdanau Attention (mlp):
* :math:`\\text{score}(H_j, q) = v_a^T \\text{tanh}(W_a q + U_a h_j)`
Args:
dim (int): dimensionality of query and key
coverage (bool): use coverage term
attn_type (str): type of attention to use, options [dot,general,mlp]
attn_func (str): attention function to use, options [softmax,sparsemax]
"""
def __init__(self, dim, coverage=False, attn_type='dot', attn_func=
'softmax'):
super(GlobalAttentionNew, self).__init__()
self.dim = dim
assert attn_type in ['dot', 'general', 'mlp'
], 'Please select a valid attention type (got {:s}).'.format(
attn_type)
self.attn_type = attn_type
assert attn_func in ['softmax', 'sparsemax'
], 'Please select a valid attention function.'
self.attn_func = attn_func
if self.attn_type == 'general':
self.linear_in = nn.Linear(dim, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = nn.Linear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=True)
self.v = nn.Linear(dim, 1, bias=False)
out_bias = self.attn_type == 'mlp'
self.linear_out = nn.Linear(dim * 2, dim, bias=out_bias)
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def score(self, h_t, h_s):
"""
Args:
h_t (FloatTensor): sequence of queries ``(batch, tgt_len, dim)``
h_s (FloatTensor): sequence of sources ``(batch, src_len, dim``
Returns:
FloatTensor: raw attention scores (unnormalized) for each src index
``(batch, tgt_len, src_len)``
"""
src_batch, src_len, src_dim = h_s.size()
tgt_batch, tgt_len, tgt_dim = h_t.size()
aeq(src_batch, tgt_batch)
aeq(src_dim, tgt_dim)
aeq(self.dim, src_dim)
if self.attn_type in ['general', 'dot']:
if self.attn_type == 'general':
h_t_ = h_t.view(tgt_batch * tgt_len, tgt_dim)
h_t_ = self.linear_in(h_t_)
h_t = h_t_.view(tgt_batch, tgt_len, tgt_dim)
h_s_ = h_s.transpose(1, 2)
return torch.bmm(h_t, h_s_)
else:
dim = self.dim
wq = self.linear_query(h_t.view(-1, dim))
wq = wq.view(tgt_batch, tgt_len, 1, dim)
wq = wq.expand(tgt_batch, tgt_len, src_len, dim)
uh = self.linear_context(h_s.contiguous().view(-1, dim))
uh = uh.view(src_batch, 1, src_len, dim)
uh = uh.expand(src_batch, tgt_len, src_len, dim)
wquh = torch.tanh(wq + uh)
return self.v(wquh.view(-1, dim)).view(tgt_batch, tgt_len, src_len)
def forward(self, input_0, input_1):
primals_3 = self.linear_out.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
BradLin0819/kg2text
|
GlobalAttention
| false
| 13,415
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
resblock
|
import torch
import torch.nn as nn
class mfm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfm, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, x):
x = self.filter(x)
out = torch.split(x, self.out_channels, 1)
return torch.max(out[0], out[1])
class resblock(nn.Module):
def __init__(self, in_channels, out_channels):
super(resblock, self).__init__()
self.conv1 = mfm(in_channels, out_channels, kernel_size=3, stride=1,
padding=1)
self.conv2 = mfm(out_channels, out_channels, kernel_size=3, stride=
1, padding=1)
def forward(self, x):
res = x
out = self.conv1(x)
out = self.conv2(out)
out = out + res
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_eq_gt_lt_maximum_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 64
x3 = xindex % 64
x1 = xindex // 16 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 128 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x3 + 128 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = triton_helpers.maximum(tmp2, tmp5)
tmp7 = tmp2 == tmp5
tmp8 = tmp2 > tmp5
tmp9 = tmp2 < tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
tl.store(out_ptr2 + x4, tmp8, xmask)
tl.store(out_ptr3 + x4, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_eq_gt_lt_maximum_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 64
x3 = xindex % 64
x1 = xindex // 16 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 128 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x3 + 128 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr2 + x4, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = triton_helpers.maximum(tmp2, tmp5)
tmp8 = tmp6 + tmp7
tmp9 = tmp2 == tmp5
tmp10 = tmp2 > tmp5
tmp11 = tmp2 < tmp5
tl.store(out_ptr0 + x4, tmp8, xmask)
tl.store(out_ptr1 + x4, tmp9, xmask)
tl.store(out_ptr2 + x4, tmp10, xmask)
tl.store(out_ptr3 + x4, tmp11, 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, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 4, 4), (128, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_gt_lt_maximum_0[grid(256)](buf0, primals_3,
buf1, buf7, buf8, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_3
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 8, 4, 4), (128, 16, 4, 1))
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_eq_gt_lt_maximum_1[grid(256)](buf2, primals_5,
primals_1, buf3, buf4, buf5, buf6, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del primals_5
return (buf3, primals_1, primals_2, primals_4, buf1, buf4, buf5, buf6,
buf7, buf8, buf9)
class mfm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfm, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, x):
x = self.filter(x)
out = torch.split(x, self.out_channels, 1)
return torch.max(out[0], out[1])
class resblockNew(nn.Module):
def __init__(self, in_channels, out_channels):
super(resblockNew, self).__init__()
self.conv1 = mfm(in_channels, out_channels, kernel_size=3, stride=1,
padding=1)
self.conv2 = mfm(out_channels, out_channels, kernel_size=3, stride=
1, padding=1)
def forward(self, input_0):
primals_2 = self.conv1.filter.weight
primals_3 = self.conv1.filter.bias
primals_4 = self.conv2.filter.weight
primals_5 = self.conv2.filter.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
BradyFU/DVG
|
resblock
| false
| 13,416
|
[
"MIT"
] | 102
|
53fd50cdc51d783b33394726b8f8a2b2216f157b
|
https://github.com/BradyFU/DVG/tree/53fd50cdc51d783b33394726b8f8a2b2216f157b
|
mfm
|
import torch
import torch.nn as nn
class mfm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfm, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, x):
x = self.filter(x)
out = torch.split(x, self.out_channels, 1)
return torch.max(out[0], out[1])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
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_eq_gt_lt_maximum_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 64
x3 = xindex % 64
x1 = xindex // 16 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 128 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x3 + 128 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = triton_helpers.maximum(tmp2, tmp5)
tmp7 = tmp2 == tmp5
tmp8 = tmp2 > tmp5
tmp9 = tmp2 < tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
tl.store(out_ptr2 + x4, tmp8, xmask)
tl.store(out_ptr3 + x4, tmp9, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 4, 4), (128, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_gt_lt_maximum_0[grid(256)](buf0, primals_2,
buf1, buf2, buf3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf1, primals_1, primals_3, buf2, buf3, buf4
class mfmNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfmNew, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, input_0):
primals_1 = self.filter.weight
primals_2 = self.filter.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
BradyFU/DVG
|
mfm
| false
| 13,417
|
[
"MIT"
] | 102
|
53fd50cdc51d783b33394726b8f8a2b2216f157b
|
https://github.com/BradyFU/DVG/tree/53fd50cdc51d783b33394726b8f8a2b2216f157b
|
LR
|
import torch
class LR(torch.nn.Module):
def __init__(self, input_size, output_size):
super(LR, self).__init__()
self.lr = torch.ones(input_size)
self.lr = torch.nn.Parameter(self.lr)
def forward(self, grad):
return self.lr * grad
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
return buf0, primals_2
class LRNew(torch.nn.Module):
def __init__(self, input_size, output_size):
super(LRNew, self).__init__()
self.lr = torch.ones(input_size)
self.lr = torch.nn.Parameter(self.lr)
def forward(self, input_0):
primals_1 = self.lr
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Brikwerk/learn2learn
|
LR
| false
| 13,418
|
[
"MIT"
] | 1,774
|
7997c13c26ec627d13ce77ba98427260df78ada8
|
https://github.com/Brikwerk/learn2learn/tree/7997c13c26ec627d13ce77ba98427260df78ada8
|
BothContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class BothContextGate(nn.Module):
"""Apply the context gate to both contexts"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(BothContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh((1.0 - z) * target + z * source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_rsub_sigmoid_tanh_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp4 = tl.load(in_ptr1 + x0, xmask)
tmp6 = tl.load(in_ptr2 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp2 = 1.0
tmp3 = tmp2 - tmp1
tmp5 = tmp3 * tmp4
tmp7 = tmp1 * tmp6
tmp8 = tmp5 + tmp7
tmp9 = libdevice.tanh(tmp8)
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, 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((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf3, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf4)
del primals_8
del primals_9
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_rsub_sigmoid_tanh_2[grid(16)](buf1, buf4,
buf2, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
return buf5, primals_3, buf0, buf1, buf2, buf3, buf4, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class BothContextGateNew(nn.Module):
"""Apply the context gate to both contexts"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(BothContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
BradLin0819/kg2text
|
BothContextGate
| false
| 13,419
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
PlanarFlow
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
class PlanarFlow(nn.Module):
"""Planar normalizing flow [Rezende & Mohamed 2015].
Provides a tighter bound on the ELBO by giving more expressive
power to the approximate distribution, such as by introducing
covariance between terms.
@param in_features: integer
number of input dimensions. this is often
the dimensionality of the latent variables
"""
def __init__(self, in_features):
super(PlanarFlow, self).__init__()
self.u = nn.Parameter(torch.randn(in_features))
self.w = nn.Parameter(torch.randn(in_features))
self.b = nn.Parameter(torch.ones(1))
def forward(self, z):
uw = torch.dot(self.u, self.w)
muw = -1 + F.softplus(uw)
uhat = self.u + (muw - uw) * torch.transpose(self.w, 0, -1
) / torch.sum(self.w ** 2)
zwb = torch.mv(z, self.w) + self.b
f_z = z + uhat.view(1, -1) * torch.tanh(zwb).view(-1, 1)
psi = (1 - torch.tanh(zwb) ** 2).view(-1, 1) * self.w.view(1, -1)
psi_u = torch.mv(psi, uhat)
logdet_jacobian = torch.log(torch.abs(1 + psi_u) + 1e-08)
return f_z, logdet_jacobian
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_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, math as tl_math
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
@triton.jit
def triton_per_fused_abs_add_div_dot_log_mul_mv_pow_softplus_sub_sum_0(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp10 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + 0)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + 1)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp19 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr1 + 2)
tmp21 = tl.broadcast_to(tmp20, [XBLOCK, RBLOCK])
tmp24 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr1 + 3)
tmp26 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
tmp29 = tl.load(in_ptr3 + 0)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp37 = tl.load(in_ptr0 + 0)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp52 = tl.load(in_ptr0 + 1)
tmp53 = tl.broadcast_to(tmp52, [XBLOCK, RBLOCK])
tmp60 = tl.load(in_ptr0 + 2)
tmp61 = tl.broadcast_to(tmp60, [XBLOCK, RBLOCK])
tmp68 = tl.load(in_ptr0 + 3)
tmp69 = tl.broadcast_to(tmp68, [XBLOCK, RBLOCK])
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.sum(tmp3, 1)[:, None]
tmp6 = tmp1 * tmp1
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp13 = tmp10 * tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp22 = tmp19 * tmp21
tmp23 = tmp18 + tmp22
tmp27 = tmp24 * tmp26
tmp28 = tmp23 + tmp27
tmp31 = tmp28 + tmp30
tmp32 = libdevice.tanh(tmp31)
tmp33 = tmp32 * tmp32
tmp34 = 1.0
tmp35 = tmp34 - tmp33
tmp36 = tmp35 * tmp12
tmp39 = 20.0
tmp40 = tmp5 > tmp39
tmp41 = tl_math.exp(tmp5)
tmp42 = libdevice.log1p(tmp41)
tmp43 = tl.where(tmp40, tmp5, tmp42)
tmp44 = -1.0
tmp45 = tmp43 + tmp44
tmp46 = tmp45 - tmp5
tmp47 = tmp46 * tmp12
tmp48 = tmp47 / tmp9
tmp49 = tmp38 + tmp48
tmp50 = tmp36 * tmp49
tmp51 = tmp35 * tmp16
tmp54 = tmp46 * tmp16
tmp55 = tmp54 / tmp9
tmp56 = tmp53 + tmp55
tmp57 = tmp51 * tmp56
tmp58 = tmp50 + tmp57
tmp59 = tmp35 * tmp21
tmp62 = tmp46 * tmp21
tmp63 = tmp62 / tmp9
tmp64 = tmp61 + tmp63
tmp65 = tmp59 * tmp64
tmp66 = tmp58 + tmp65
tmp67 = tmp35 * tmp26
tmp70 = tmp46 * tmp26
tmp71 = tmp70 / tmp9
tmp72 = tmp69 + tmp71
tmp73 = tmp67 * tmp72
tmp74 = tmp66 + tmp73
tmp75 = tmp74 + tmp34
tmp76 = tl_math.abs(tmp75)
tmp77 = 1e-08
tmp78 = tmp76 + tmp77
tmp79 = tl_math.log(tmp78)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp31, None)
tl.store(in_out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp79, None)
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp5, None)
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp9, None)
@triton.jit
def triton_poi_fused_add_mul_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp12 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr4 + 0)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp18 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp4 = 20.0
tmp5 = tmp3 > tmp4
tmp6 = tl_math.exp(tmp3)
tmp7 = libdevice.log1p(tmp6)
tmp8 = tl.where(tmp5, tmp3, tmp7)
tmp9 = -1.0
tmp10 = tmp8 + tmp9
tmp11 = tmp10 - tmp3
tmp13 = tmp11 * tmp12
tmp16 = tmp13 / tmp15
tmp17 = tmp1 + tmp16
tmp19 = libdevice.tanh(tmp18)
tmp20 = tmp17 * tmp19
tmp21 = tmp0 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
buf4 = empty_strided_cuda((4,), (1,), torch.float32)
buf5 = buf4
del buf4
get_raw_stream(0)
triton_per_fused_abs_add_div_dot_log_mul_mv_pow_softplus_sub_sum_0[grid
(1)](buf5, primals_1, primals_2, primals_3, primals_4, buf0,
buf1, buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_1[grid(16)](primals_3, primals_1, buf0,
primals_2, buf1, buf2, buf3, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf0
del buf1
del buf2
return buf3, buf5, primals_1, primals_2, primals_3, primals_4
class PlanarFlowNew(nn.Module):
"""Planar normalizing flow [Rezende & Mohamed 2015].
Provides a tighter bound on the ELBO by giving more expressive
power to the approximate distribution, such as by introducing
covariance between terms.
@param in_features: integer
number of input dimensions. this is often
the dimensionality of the latent variables
"""
def __init__(self, in_features):
super(PlanarFlowNew, self).__init__()
self.u = nn.Parameter(torch.randn(in_features))
self.w = nn.Parameter(torch.randn(in_features))
self.b = nn.Parameter(torch.ones(1))
def forward(self, input_0):
primals_1 = self.u
primals_2 = self.w
primals_4 = self.b
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
BratChar/variational-item-response-theory-public
|
PlanarFlow
| false
| 13,420
|
[
"MIT"
] | 52
|
12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
https://github.com/BratChar/variational-item-response-theory-public/tree/12862157e99506a0ed7018f1b8a485d4e61fb5bf
|
group
|
import torch
import torch.nn as nn
class mfm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfm, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, x):
x = self.filter(x)
out = torch.split(x, self.out_channels, 1)
return torch.max(out[0], out[1])
class group(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding
):
super(group, self).__init__()
self.conv_a = mfm(in_channels, in_channels, 1, 1, 0)
self.conv = mfm(in_channels, out_channels, kernel_size, stride, padding
)
def forward(self, x):
x = self.conv_a(x)
x = self.conv(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,
'stride': 1, 'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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_eq_gt_lt_maximum_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 64
x3 = xindex % 64
x1 = xindex // 16 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 128 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x3 + 128 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = triton_helpers.maximum(tmp2, tmp5)
tmp7 = tmp2 == tmp5
tmp8 = tmp2 > tmp5
tmp9 = tmp2 < tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
tl.store(out_ptr2 + x4, tmp8, xmask)
tl.store(out_ptr3 + x4, tmp9, xmask)
@triton.jit
def triton_poi_fused_eq_gt_lt_maximum_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 1296
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 324
x3 = xindex % 324
x1 = xindex // 81 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 648 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (324 + x3 + 648 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = triton_helpers.maximum(tmp2, tmp5)
tmp7 = tmp2 == tmp5
tmp8 = tmp2 > tmp5
tmp9 = tmp2 < tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
tl.store(out_ptr2 + x4, tmp8, xmask)
tl.store(out_ptr3 + x4, tmp9, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (8, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (8, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 4, 4), (128, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_gt_lt_maximum_0[grid(256)](buf0, primals_2,
buf1, buf7, buf8, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 8, 9, 9), (648, 81, 9, 1))
buf3 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.bool)
buf5 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.bool)
buf6 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.bool)
triton_poi_fused_eq_gt_lt_maximum_1[grid(1296)](buf2, primals_5,
buf3, buf4, buf5, buf6, 1296, XBLOCK=256, num_warps=4, num_stages=1
)
del buf2
del primals_5
return (buf3, primals_1, primals_3, primals_4, buf1, buf4, buf5, buf6,
buf7, buf8, buf9)
class mfm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, type=1):
super(mfm, self).__init__()
self.out_channels = out_channels
if type == 1:
self.filter = nn.Conv2d(in_channels, 2 * out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
else:
self.filter = nn.Linear(in_channels, 2 * out_channels)
def forward(self, x):
x = self.filter(x)
out = torch.split(x, self.out_channels, 1)
return torch.max(out[0], out[1])
class groupNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding
):
super(groupNew, self).__init__()
self.conv_a = mfm(in_channels, in_channels, 1, 1, 0)
self.conv = mfm(in_channels, out_channels, kernel_size, stride, padding
)
def forward(self, input_0):
primals_1 = self.conv_a.filter.weight
primals_2 = self.conv_a.filter.bias
primals_4 = self.conv.filter.weight
primals_5 = self.conv.filter.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
BradyFU/DVG
|
group
| false
| 13,421
|
[
"MIT"
] | 102
|
53fd50cdc51d783b33394726b8f8a2b2216f157b
|
https://github.com/BradyFU/DVG/tree/53fd50cdc51d783b33394726b8f8a2b2216f157b
|
MultiheadAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def fill_with_neg_inf(t):
"""FP16-compatible function that fills a tensor with -inf."""
return t.float().fill_(float('-inf')).type_as(t)
def _get_full_incremental_state_key(module_instance, key):
module_name = module_instance.__class__.__name__
if not hasattr(module_instance, '_fairseq_instance_id'):
INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1
module_instance._fairseq_instance_id = INCREMENTAL_STATE_INSTANCE_ID[
module_name]
return '{}.{}.{}'.format(module_name, module_instance.
_fairseq_instance_id, key)
def get_incremental_state(module, incremental_state, key):
"""Helper for getting incremental state for an nn.Module."""
full_key = _get_full_incremental_state_key(module, key)
if incremental_state is None or full_key not in incremental_state:
return None
return incremental_state[full_key]
def set_incremental_state(module, incremental_state, key, value):
"""Helper for setting incremental state for an nn.Module."""
if incremental_state is not None:
full_key = _get_full_incremental_state_key(module, key)
incremental_state[full_key] = value
class MultiheadAttention(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self._mask = None
self.in_proj_weight = nn.Parameter(torch.Tensor(3 * embed_dim,
embed_dim))
if bias:
self.in_proj_bias = nn.Parameter(torch.Tensor(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
def forward(self, query, key, value, mask_future_timesteps=False,
key_padding_mask=None, incremental_state=None, need_weights=True,
static_kv=False):
"""Input shape: Time x Batch x Channel
Self-attention can be implemented by passing in the same arguments for
query, key and value. Future timesteps can be masked with the
`mask_future_timesteps` argument. Padding elements can be excluded from
the key by passing a binary ByteTensor (`key_padding_mask`) with shape:
batch x src_len, where padding elements are indicated by 1s.
"""
qkv_same = query.data_ptr() == key.data_ptr() == value.data_ptr()
kv_same = key.data_ptr() == value.data_ptr()
tgt_len, bsz, embed_dim = query.size()
assert embed_dim == self.embed_dim
assert list(query.size()) == [tgt_len, bsz, embed_dim]
assert key.size() == value.size()
if incremental_state is not None:
saved_state = self._get_input_buffer(incremental_state)
if 'prev_key' in saved_state:
if static_kv:
assert kv_same and not qkv_same
key = value = None
else:
saved_state = None
if qkv_same:
q, k, v = self.in_proj_qkv(query)
elif kv_same:
q = self.in_proj_q(query)
if key is None:
assert value is None
k = v = q.new(0)
else:
k, v = self.in_proj_kv(key)
else:
q = self.in_proj_q(query)
k = self.in_proj_k(key)
v = self.in_proj_v(value)
q *= self.scaling
if saved_state is not None:
if 'prev_key' in saved_state:
k = torch.cat((saved_state['prev_key'], k), dim=0)
if 'prev_value' in saved_state:
v = torch.cat((saved_state['prev_value'], v), dim=0)
saved_state['prev_key'] = k
saved_state['prev_value'] = v
self._set_input_buffer(incremental_state, saved_state)
src_len = k.size(0)
if key_padding_mask is not None:
assert key_padding_mask.size(0) == bsz
assert key_padding_mask.size(1) == src_len
q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
k = k.contiguous().view(src_len, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
v = v.contiguous().view(src_len, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
attn_weights = torch.bmm(q, k.transpose(1, 2))
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len,
src_len]
if mask_future_timesteps and incremental_state is None:
assert query.size() == key.size(
), 'mask_future_timesteps only applies to self-attention'
attn_weights += self.buffered_mask(attn_weights).unsqueeze(0)
if key_padding_mask is not None:
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len,
src_len)
attn_weights = attn_weights.float().masked_fill(key_padding_mask
.unsqueeze(1).unsqueeze(2), float('-inf')).type_as(attn_weights
)
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len,
src_len)
attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(
attn_weights)
attn_weights = F.dropout(attn_weights, p=self.dropout, training=
self.training)
attn = torch.bmm(attn_weights, v)
assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.
head_dim]
attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn = self.out_proj(attn)
if need_weights:
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len,
src_len)
attn_weights = attn_weights.sum(dim=1) / self.num_heads
else:
attn_weights = None
return attn, attn_weights
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=None, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
if end is not None:
weight = weight[:end, :]
if bias is not None:
bias = bias[:end]
if start is not None:
weight = weight[start:, :]
if bias is not None:
bias = bias[start:]
return F.linear(input.type_as(weight), weight, bias)
def buffered_mask(self, tensor):
attn = self.out_proj(attn)
if need_weights:
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len,
src_len)
attn_weights = attn_weights.sum(dim=1) / self.num_heads
else:
attn_weights = None
return attn, attn_weights
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query):
return self._in_proj(query, end=self.embed_dim)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=None, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
if end is not None:
weight = weight[:end, :]
if bias is not None:
bias = bias[:end]
if start is not None:
weight = weight[start:, :]
if bias is not None:
bias = bias[start:]
return F.linear(input.type_as(weight), weight, bias)
def buffered_mask(self, tensor):
dim = tensor.size(-1)
if self._mask is None:
self._mask = torch.triu(fill_with_neg_inf(tensor.new(dim, dim)), 1)
if self._mask.size(0) < dim:
self._mask = torch.triu(fill_with_neg_inf(self._mask.resize_(
dim, dim)), 1)
return self._mask[:dim, :dim]
def reorder_incremental_state(self, incremental_state, new_order):
"""Reorder buffered internal state (for incremental generation)."""
input_buffer = self._get_input_buffer(incremental_state)
if input_buffer is not None:
for k in input_buffer.keys():
input_buffer[k] = input_buffer[k].index_select(1, new_order)
self._set_input_buffer(incremental_state, input_buffer)
def _get_input_buffer(self, incremental_state):
return get_incremental_state(self, incremental_state, 'attn_state'
) or {}
def _set_input_buffer(self, incremental_state, buffer):
set_incremental_state(self, incremental_state, 'attn_state', buffer)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'embed_dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_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 = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_div_sum_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 % 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 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 4),
reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 16), alpha=1,
beta=1, out=buf1)
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8),
reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha=1,
beta=1, out=buf2)
del primals_4
buf3 = reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](buf3, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (1, 16, 0),
0), reinterpret_tensor(buf1, (16, 1, 4), (1, 1, 16), 0), out=buf4)
buf5 = empty_strided_cuda((16, 4, 4), (16, 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=128,
num_warps=4, num_stages=1)
del buf5
buf7 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (16, 4, 1), (1,
16, 1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 16)](buf7, buf8, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_7, reinterpret_tensor(buf8, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf9)
del primals_7
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_div_sum_4[grid(64)](buf6, buf10, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0
), buf10, 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
), buf6, reinterpret_tensor(buf8, (16, 4), (4, 1), 0
), primals_6, reinterpret_tensor(buf2, (16, 1, 4), (1, 1, 16), 0
), reinterpret_tensor(buf3, (16, 1, 4), (1, 1, 16), 0
), reinterpret_tensor(buf1, (16, 4, 1), (1, 16, 1), 0)
def fill_with_neg_inf(t):
"""FP16-compatible function that fills a tensor with -inf."""
return t.float().fill_(float('-inf')).type_as(t)
def _get_full_incremental_state_key(module_instance, key):
module_name = module_instance.__class__.__name__
if not hasattr(module_instance, '_fairseq_instance_id'):
INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1
module_instance._fairseq_instance_id = INCREMENTAL_STATE_INSTANCE_ID[
module_name]
return '{}.{}.{}'.format(module_name, module_instance.
_fairseq_instance_id, key)
def get_incremental_state(module, incremental_state, key):
"""Helper for getting incremental state for an nn.Module."""
full_key = _get_full_incremental_state_key(module, key)
if incremental_state is None or full_key not in incremental_state:
return None
return incremental_state[full_key]
def set_incremental_state(module, incremental_state, key, value):
"""Helper for setting incremental state for an nn.Module."""
if incremental_state is not None:
full_key = _get_full_incremental_state_key(module, key)
incremental_state[full_key] = value
class MultiheadAttentionNew(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self._mask = None
self.in_proj_weight = nn.Parameter(torch.Tensor(3 * embed_dim,
embed_dim))
if bias:
self.in_proj_bias = nn.Parameter(torch.Tensor(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=None, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
if end is not None:
weight = weight[:end, :]
if bias is not None:
bias = bias[:end]
if start is not None:
weight = weight[start:, :]
if bias is not None:
bias = bias[start:]
return F.linear(input.type_as(weight), weight, bias)
def buffered_mask(self, tensor):
attn = self.out_proj(attn)
if need_weights:
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len,
src_len)
attn_weights = attn_weights.sum(dim=1) / self.num_heads
else:
attn_weights = None
return attn, attn_weights
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query):
return self._in_proj(query, end=self.embed_dim)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=None, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
if end is not None:
weight = weight[:end, :]
if bias is not None:
bias = bias[:end]
if start is not None:
weight = weight[start:, :]
if bias is not None:
bias = bias[start:]
return F.linear(input.type_as(weight), weight, bias)
def buffered_mask(self, tensor):
dim = tensor.size(-1)
if self._mask is None:
self._mask = torch.triu(fill_with_neg_inf(tensor.new(dim, dim)), 1)
if self._mask.size(0) < dim:
self._mask = torch.triu(fill_with_neg_inf(self._mask.resize_(
dim, dim)), 1)
return self._mask[:dim, :dim]
def reorder_incremental_state(self, incremental_state, new_order):
"""Reorder buffered internal state (for incremental generation)."""
input_buffer = self._get_input_buffer(incremental_state)
if input_buffer is not None:
for k in input_buffer.keys():
input_buffer[k] = input_buffer[k].index_select(1, new_order)
self._set_input_buffer(incremental_state, input_buffer)
def _get_input_buffer(self, incremental_state):
return get_incremental_state(self, incremental_state, 'attn_state'
) or {}
def _set_input_buffer(self, incremental_state, buffer):
set_incremental_state(self, incremental_state, 'attn_state', buffer)
def forward(self, input_0, input_1, input_2):
primals_4 = self.in_proj_weight
primals_5 = self.in_proj_bias
primals_6 = self.out_proj.weight
primals_7 = self.out_proj.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
Blind-Aid/sentiment-discovery
|
MultiheadAttention
| false
| 13,422
|
[
"BSD-3-Clause"
] | 1,093
|
081c7c855e00864b52e97cac0b0e097cc86d9731
|
https://github.com/Blind-Aid/sentiment-discovery/tree/081c7c855e00864b52e97cac0b0e097cc86d9731
|
HypergradTransform
|
import torch
class HypergradTransform(torch.nn.Module):
"""Hypergradient-style per-parameter learning rates"""
def __init__(self, param, lr=0.01):
super(HypergradTransform, self).__init__()
self.lr = lr * torch.ones_like(param, requires_grad=True)
self.lr = torch.nn.Parameter(self.lr)
def forward(self, grad):
return self.lr * grad
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'param': torch.rand([4, 4])}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
return buf0, primals_2
class HypergradTransformNew(torch.nn.Module):
"""Hypergradient-style per-parameter learning rates"""
def __init__(self, param, lr=0.01):
super(HypergradTransformNew, self).__init__()
self.lr = lr * torch.ones_like(param, requires_grad=True)
self.lr = torch.nn.Parameter(self.lr)
def forward(self, input_0):
primals_1 = self.lr
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Brikwerk/learn2learn
|
HypergradTransform
| false
| 13,423
|
[
"MIT"
] | 1,774
|
7997c13c26ec627d13ce77ba98427260df78ada8
|
https://github.com/Brikwerk/learn2learn/tree/7997c13c26ec627d13ce77ba98427260df78ada8
|
EncoderImagePrecomp
|
import torch
import numpy as np
from collections import OrderedDict
import torch.nn as nn
import torch.nn.init
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class EncoderImagePrecomp(nn.Module):
def __init__(self, img_dim, embed_size, no_imgnorm=False):
super(EncoderImagePrecomp, self).__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
self.fc = nn.Linear(img_dim, embed_size)
self.init_weights()
def init_weights(self):
"""Xavier initialization for the fully connected layer
"""
r = np.sqrt(6.0) / np.sqrt(self.fc.in_features + self.fc.out_features)
self.fc.weight.data.uniform_(-r, r)
self.fc.bias.data.fill_(0)
def forward(self, images):
"""Extract image feature vectors."""
features = self.fc(images)
if not self.no_imgnorm:
features = l2norm(features, dim=-1)
"""features_mean: visual initial memory"""
features_mean = torch.mean(features, 1)
"""choose whether to l2norm"""
return features, features_mean
def load_state_dict(self, state_dict):
"""Copies parameters. overwritting the default one to
accept state_dict from Full model
"""
own_state = self.state_dict()
new_state = OrderedDict()
for name, param in state_dict.items():
if name in own_state:
new_state[name] = param
super(EncoderImagePrecomp, self).load_state_dict(new_state)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'img_dim': 4, 'embed_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 collections import OrderedDict
import torch.nn as nn
import torch.nn.init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_pow_sqrt_sum_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')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused_mean_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_pow_sqrt_sum_0[grid(256)](buf0, buf1, 256,
XBLOCK=128, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_mean_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf1, buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class EncoderImagePrecompNew(nn.Module):
def __init__(self, img_dim, embed_size, no_imgnorm=False):
super(EncoderImagePrecompNew, self).__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
self.fc = nn.Linear(img_dim, embed_size)
self.init_weights()
def init_weights(self):
"""Xavier initialization for the fully connected layer
"""
r = np.sqrt(6.0) / np.sqrt(self.fc.in_features + self.fc.out_features)
self.fc.weight.data.uniform_(-r, r)
self.fc.bias.data.fill_(0)
def load_state_dict(self, state_dict):
"""Copies parameters. overwritting the default one to
accept state_dict from Full model
"""
own_state = self.state_dict()
new_state = OrderedDict()
for name, param in state_dict.items():
if name in own_state:
new_state[name] = param
super(EncoderImagePrecompNew, self).load_state_dict(new_state)
def forward(self, input_0):
primals_1 = self.fc.weight
primals_2 = self.fc.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
BruceW91/CVSE
|
EncoderImagePrecomp
| false
| 13,424
|
[
"MIT"
] | 152
|
20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
https://github.com/BruceW91/CVSE/tree/20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
JointsMSELoss
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torch.multiprocessing
class JointsMSELoss(nn.Module):
def __init__(self, use_target_weight):
super(JointsMSELoss, self).__init__()
self.criterion = nn.MSELoss(size_average=True)
self.use_target_weight = use_target_weight
def forward(self, output, target, target_weight):
batch_size = output.size(0)
num_joints = output.size(1)
heatmaps_pred = output.reshape((batch_size, num_joints, -1)).split(1, 1
)
heatmaps_gt = target.reshape((batch_size, num_joints, -1)).split(1, 1)
loss = 0
for idx in range(num_joints):
heatmap_pred = heatmaps_pred[idx].squeeze()
heatmap_gt = heatmaps_gt[idx].squeeze()
if self.use_target_weight:
loss += self.criterion(heatmap_pred.mul(target_weight[:,
idx]), heatmap_gt.mul(target_weight[:, idx]))
else:
loss += self.criterion(heatmap_pred, heatmap_gt)
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'use_target_weight': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mse_loss_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp33 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 - tmp4
tmp6 = tmp5 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp12 = tmp10 * tmp11
tmp14 = tmp13 * tmp11
tmp15 = tmp12 - tmp14
tmp16 = tmp15 * tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = tl.sum(tmp17, 1)[:, None]
tmp22 = tmp20 * tmp21
tmp24 = tmp23 * tmp21
tmp25 = tmp22 - tmp24
tmp26 = tmp25 * tmp25
tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK])
tmp29 = tl.sum(tmp27, 1)[:, None]
tmp32 = tmp30 * tmp31
tmp34 = tmp33 * tmp31
tmp35 = tmp32 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
tmp39 = tl.sum(tmp37, 1)[:, None]
tmp40 = 4.0
tmp41 = tmp9 / tmp40
tmp42 = 0.0
tmp43 = tmp41 + tmp42
tmp44 = tmp19 / tmp40
tmp45 = tmp43 + tmp44
tmp46 = tmp29 / tmp40
tmp47 = tmp45 + tmp46
tmp48 = tmp39 / tmp40
tmp49 = tmp47 + tmp48
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp49, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf4 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mse_loss_mul_0[grid(1)](buf4, arg0_1, arg2_1,
arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf4,
class JointsMSELossNew(nn.Module):
def __init__(self, use_target_weight):
super(JointsMSELossNew, self).__init__()
self.criterion = nn.MSELoss(size_average=True)
self.use_target_weight = use_target_weight
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
CHUNYUWANG/imu-human-pose-pytorch
|
JointsMSELoss
| false
| 13,425
|
[
"MIT"
] | 72
|
f4813336571789f46eabdfb520e7ed5b20ac04ea
|
https://github.com/CHUNYUWANG/imu-human-pose-pytorch/tree/f4813336571789f46eabdfb520e7ed5b20ac04ea
|
Multi_feature_fusing
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class Multi_feature_fusing(nn.Module):
"""
Emb the features from both modalities to the joint attribute label space.
"""
def __init__(self, embed_dim, fuse_type='weight_sum'):
"""
param image_dim: dim of visual feature
param embed_dim: dim of embedding space
"""
super(Multi_feature_fusing, self).__init__()
self.fuse_type = fuse_type
self.embed_dim = embed_dim
if fuse_type == 'concat':
input_dim = int(2 * embed_dim)
self.joint_emb_v = nn.Linear(input_dim, embed_dim)
self.joint_emb_t = nn.Linear(input_dim, embed_dim)
self.init_weights_concat()
if fuse_type == 'adap_sum':
self.joint_emb_v = nn.Linear(embed_dim, 1)
self.joint_emb_t = nn.Linear(embed_dim, 1)
self.init_weights_adap_sum()
def init_weights_concat(self):
"""Xavier initialization"""
r = np.sqrt(6.0) / np.sqrt(self.embed_dim + 2 * self.embed_dim)
self.joint_emb_v.weight.data.uniform_(-r, r)
self.joint_emb_v.bias.data.fill_(0)
self.joint_emb_t.weight.data.uniform_(-r, r)
self.joint_emb_t.bias.data.fill_(0)
def init_weights_adap_sum(self):
"""Xavier initialization"""
r = np.sqrt(6.0) / np.sqrt(self.embed_dim + 1)
self.joint_emb_v.weight.data.uniform_(-r, r)
self.joint_emb_v.bias.data.fill_(0)
self.joint_emb_t.weight.data.uniform_(-r, r)
self.joint_emb_t.bias.data.fill_(0)
def forward(self, v_emb_instance, t_emb_instance, v_emb_concept,
t_emb_concept, alpha=0.75):
"""
Forward propagation.
:param v_emb_instance, t_emb_instance: instance-level visual or textual features, shape: (batch_size, emb_dim)
:param v_emb_concept, t_emb_concept: consensus-level concept features, shape: (batch_size, emb_dim)
:return: joint embbeding features for both modalities
"""
if self.fuse_type == 'multiple':
v_fused_emb = v_emb_instance.mul(v_emb_concept)
v_fused_emb = l2norm(v_fused_emb)
t_fused_emb = t_emb_instance.mul(t_emb_concept)
t_fused_emb = l2norm(t_fused_emb)
elif self.fuse_type == 'concat':
v_fused_emb = torch.cat([v_emb_instance, v_emb_concept], dim=1)
v_fused_emb = self.joint_emb_instance_v(v_fused_emb)
v_fused_emb = l2norm(v_fused_emb)
t_fused_emb = torch.cat([t_emb_instance, t_emb_concept], dim=1)
t_fused_emb = self.joint_emb_instance_v(t_fused_emb)
t_fused_emb = l2norm(t_fused_emb)
elif self.fuse_type == 'adap_sum':
v_mean = (v_emb_instance + v_emb_concept) / 2
v_emb_instance_mat = self.joint_emb_instance_v(v_mean)
alpha_v = F.sigmoid(v_emb_instance_mat)
v_fused_emb = alpha_v * v_emb_instance + (1 - alpha_v
) * v_emb_concept
v_fused_emb = l2norm(v_fused_emb)
t_mean = (t_emb_instance + t_emb_concept) / 2
t_emb_instance_mat = self.joint_emb_instance_t(t_mean)
alpha_t = F.sigmoid(t_emb_instance_mat)
t_fused_emb = alpha_t * t_emb_instance + (1 - alpha_t
) * t_emb_concept
t_fused_emb = l2norm(t_fused_emb)
elif self.fuse_type == 'weight_sum':
v_fused_emb = alpha * v_emb_instance + (1 - alpha) * v_emb_concept
v_fused_emb = l2norm(v_fused_emb)
t_fused_emb = alpha * t_emb_instance + (1 - alpha) * t_emb_concept
t_fused_emb = l2norm(t_fused_emb)
return v_fused_emb, t_fused_emb
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 [[], {'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
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
import torch.nn as nn
import torch.nn.init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_pow_sqrt_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp8 = 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'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = 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'
)
tmp24 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 0.75
tmp2 = tmp0 * tmp1
tmp4 = 0.25
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp7 = tmp6 * tmp6
tmp9 = tmp8 * tmp1
tmp11 = tmp10 * tmp4
tmp12 = tmp9 + tmp11
tmp13 = tmp12 * tmp12
tmp14 = tmp7 + tmp13
tmp16 = tmp15 * tmp1
tmp18 = tmp17 * tmp4
tmp19 = tmp16 + tmp18
tmp20 = tmp19 * tmp19
tmp21 = tmp14 + tmp20
tmp23 = tmp22 * tmp1
tmp25 = tmp24 * tmp4
tmp26 = tmp23 + tmp25
tmp27 = tmp26 * tmp26
tmp28 = tmp21 + tmp27
tmp29 = libdevice.sqrt(tmp28)
tmp30 = 1e-12
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x0, tmp31, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp7 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp1 = 0.75
tmp2 = tmp0 * tmp1
tmp4 = 0.25
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x2, tmp8, 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, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_pow_sqrt_sum_0[grid(64)](arg0_1, arg1_1,
buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mul_1[grid(256)](arg0_1, arg1_1, buf0,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
buf2 = buf0
del buf0
triton_poi_fused_add_mul_pow_sqrt_sum_0[grid(64)](arg2_1, arg3_1,
buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mul_1[grid(256)](arg2_1, arg3_1, buf2,
buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg2_1
del arg3_1
del buf2
return buf1, buf3
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class Multi_feature_fusingNew(nn.Module):
"""
Emb the features from both modalities to the joint attribute label space.
"""
def __init__(self, embed_dim, fuse_type='weight_sum'):
"""
param image_dim: dim of visual feature
param embed_dim: dim of embedding space
"""
super(Multi_feature_fusingNew, self).__init__()
self.fuse_type = fuse_type
self.embed_dim = embed_dim
if fuse_type == 'concat':
input_dim = int(2 * embed_dim)
self.joint_emb_v = nn.Linear(input_dim, embed_dim)
self.joint_emb_t = nn.Linear(input_dim, embed_dim)
self.init_weights_concat()
if fuse_type == 'adap_sum':
self.joint_emb_v = nn.Linear(embed_dim, 1)
self.joint_emb_t = nn.Linear(embed_dim, 1)
self.init_weights_adap_sum()
def init_weights_concat(self):
"""Xavier initialization"""
r = np.sqrt(6.0) / np.sqrt(self.embed_dim + 2 * self.embed_dim)
self.joint_emb_v.weight.data.uniform_(-r, r)
self.joint_emb_v.bias.data.fill_(0)
self.joint_emb_t.weight.data.uniform_(-r, r)
self.joint_emb_t.bias.data.fill_(0)
def init_weights_adap_sum(self):
"""Xavier initialization"""
r = np.sqrt(6.0) / np.sqrt(self.embed_dim + 1)
self.joint_emb_v.weight.data.uniform_(-r, r)
self.joint_emb_v.bias.data.fill_(0)
self.joint_emb_t.weight.data.uniform_(-r, r)
self.joint_emb_t.bias.data.fill_(0)
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]
|
BruceW91/CVSE
|
Multi_feature_fusing
| false
| 13,426
|
[
"MIT"
] | 152
|
20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
https://github.com/BruceW91/CVSE/tree/20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
MetaCurvatureTransform
|
import torch
import numpy as np
class MetaCurvatureTransform(torch.nn.Module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/optim/transforms/module_transform.py)
**Description**
Implements the Meta-Curvature transform of Park and Oliva, 2019.
Unlike `ModuleTranform` and `KroneckerTransform`, this class does not wrap other Modules but is directly
called on a weight to instantiate the transform.
**Arguments**
* **param** (Tensor) - The weight whose gradients will be transformed.
* **lr** (float, *optional*, default=1.0) - Scaling factor of the udpate. (non-learnable)
**References**
1. Park & Oliva. 2019. Meta-curvature.
**Example**
~~~python
classifier = torch.nn.Linear(784, 10, bias=False)
metacurvature_update = MetaCurvatureTransform(classifier.weight)
loss(classifier(X), y).backward()
update = metacurvature_update(classifier.weight.grad)
classifier.weight.data.add_(-lr, update) # Not a differentiable update. See l2l.optim.DifferentiableSGD.
~~~
"""
def __init__(self, param, lr=1.0):
super(MetaCurvatureTransform, self).__init__()
self.lr = lr
shape = param.shape
if len(shape) == 1:
self.dim = 1
self.mc = torch.nn.Parameter(torch.ones_like(param))
elif len(shape) == 2:
self.dim = 2
self.mc_in = torch.nn.Parameter(torch.eye(shape[0]))
self.mc_out = torch.nn.Parameter(torch.eye(shape[1]))
elif len(shape) == 4:
self.dim = 4
self.n_in = shape[0]
self.n_out = shape[1]
self.n_f = int(np.prod(shape) / (self.n_in * self.n_out))
self.mc_in = torch.nn.Parameter(torch.eye(self.n_in))
self.mc_out = torch.nn.Parameter(torch.eye(self.n_out))
self.mc_f = torch.nn.Parameter(torch.eye(self.n_f))
else:
raise NotImplementedError('Parameter with shape', shape,
'is not supported by MetaCurvature.')
def forward(self, grad):
if self.dim == 1:
update = self.mc * grad
elif self.dim == 2:
update = self.mc_in @ grad @ self.mc_out
else:
update = grad.permute(2, 3, 0, 1).contiguous()
shape = update.shape
update = update.view(-1, self.n_out) @ self.mc_out
update = self.mc_f @ update.view(self.n_f, -1)
update = update.view(self.n_f, self.n_in, self.n_out)
update = update.permute(1, 0, 2).contiguous().view(self.n_in, -1)
update = self.mc_in @ update
update = update.view(self.n_in, self.n_f, self.n_out).permute(1,
0, 2).contiguous().view(shape)
update = update.permute(2, 3, 0, 1).contiguous()
return self.lr * update
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'param': torch.rand([4, 4])}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import numpy as np
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_view_1(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 + (4 * x1 + 16 * (y0 // 4) + y0 % 4), xmask &
ymask, eviction_policy='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(in_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, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_2, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf1)
del primals_1
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
triton_poi_fused_clone_view_1[grid(64, 4)](buf1, buf2, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
buf3 = buf1
del buf1
extern_kernels.mm(buf2, primals_3, out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_mul_2[grid(256)](buf4, 256, XBLOCK=256, num_warps=
4, num_stages=1)
return buf4, reinterpret_tensor(buf0, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 64), (1, 4), 0), reinterpret_tensor(
primals_3, (4, 4), (1, 4), 0)
class MetaCurvatureTransformNew(torch.nn.Module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/optim/transforms/module_transform.py)
**Description**
Implements the Meta-Curvature transform of Park and Oliva, 2019.
Unlike `ModuleTranform` and `KroneckerTransform`, this class does not wrap other Modules but is directly
called on a weight to instantiate the transform.
**Arguments**
* **param** (Tensor) - The weight whose gradients will be transformed.
* **lr** (float, *optional*, default=1.0) - Scaling factor of the udpate. (non-learnable)
**References**
1. Park & Oliva. 2019. Meta-curvature.
**Example**
~~~python
classifier = torch.nn.Linear(784, 10, bias=False)
metacurvature_update = MetaCurvatureTransform(classifier.weight)
loss(classifier(X), y).backward()
update = metacurvature_update(classifier.weight.grad)
classifier.weight.data.add_(-lr, update) # Not a differentiable update. See l2l.optim.DifferentiableSGD.
~~~
"""
def __init__(self, param, lr=1.0):
super(MetaCurvatureTransformNew, self).__init__()
self.lr = lr
shape = param.shape
if len(shape) == 1:
self.dim = 1
self.mc = torch.nn.Parameter(torch.ones_like(param))
elif len(shape) == 2:
self.dim = 2
self.mc_in = torch.nn.Parameter(torch.eye(shape[0]))
self.mc_out = torch.nn.Parameter(torch.eye(shape[1]))
elif len(shape) == 4:
self.dim = 4
self.n_in = shape[0]
self.n_out = shape[1]
self.n_f = int(np.prod(shape) / (self.n_in * self.n_out))
self.mc_in = torch.nn.Parameter(torch.eye(self.n_in))
self.mc_out = torch.nn.Parameter(torch.eye(self.n_out))
self.mc_f = torch.nn.Parameter(torch.eye(self.n_f))
else:
raise NotImplementedError('Parameter with shape', shape,
'is not supported by MetaCurvature.')
def forward(self, input_0):
primals_1 = self.mc_in
primals_3 = self.mc_out
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Brikwerk/learn2learn
|
MetaCurvatureTransform
| false
| 13,427
|
[
"MIT"
] | 1,774
|
7997c13c26ec627d13ce77ba98427260df78ada8
|
https://github.com/Brikwerk/learn2learn/tree/7997c13c26ec627d13ce77ba98427260df78ada8
|
EncoderImageWeightNormPrecomp
|
import torch
from collections import OrderedDict
import torch.nn as nn
import torch.nn.init
from torch.nn.utils.weight_norm import weight_norm
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class EncoderImageWeightNormPrecomp(nn.Module):
def __init__(self, img_dim, embed_size, no_imgnorm=False):
super(EncoderImageWeightNormPrecomp, self).__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
self.fc = weight_norm(nn.Linear(img_dim, embed_size), dim=None)
def forward(self, images):
"""Extract image feature vectors."""
features = self.fc(images)
if not self.no_imgnorm:
features = l2norm(features, dim=-1)
return features
def load_state_dict(self, state_dict):
"""Copies parameters. overwritting the default one to
accept state_dict from Full model
"""
own_state = self.state_dict()
new_state = OrderedDict()
for name, param in state_dict.items():
if name in own_state:
new_state[name] = param
super(EncoderImageWeightNormPrecomp, self).load_state_dict(new_state)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'img_dim': 4, 'embed_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from collections import OrderedDict
import torch.nn as nn
import torch.nn.init
from torch.nn.utils.weight_norm import weight_norm
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_div_mul_norm_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp6 = tl.load(in_ptr1 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tmp5 = libdevice.sqrt(tmp4)
tmp8 = tmp7 / tmp5
tmp9 = tmp0 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp5, None)
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp9, None)
@triton.jit
def triton_poi_fused_add_div_pow_sqrt_sum_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_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))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_mul_norm_0[grid(1)](buf1, primals_2, primals_1,
buf2, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_4, (64,
4), (4, 1), 0), reinterpret_tensor(buf2, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_3
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_pow_sqrt_sum_1[grid(256)](buf3, buf4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
return buf4, buf2, primals_1, primals_2, buf1, reinterpret_tensor(primals_4
, (64, 4), (4, 1), 0), buf3
def l2norm(X, dim=-1, eps=1e-12):
"""L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
X = torch.div(X, norm)
return X
class EncoderImageWeightNormPrecompNew(nn.Module):
def __init__(self, img_dim, embed_size, no_imgnorm=False):
super(EncoderImageWeightNormPrecompNew, self).__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
self.fc = weight_norm(nn.Linear(img_dim, embed_size), dim=None)
def load_state_dict(self, state_dict):
"""Copies parameters. overwritting the default one to
accept state_dict from Full model
"""
own_state = self.state_dict()
new_state = OrderedDict()
for name, param in state_dict.items():
if name in own_state:
new_state[name] = param
super(EncoderImageWeightNormPrecompNew, self).load_state_dict(new_state
)
def forward(self, input_0):
primals_3 = self.fc.bias
primals_1 = self.fc.weight_g
primals_2 = self.fc.weight_v
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
BruceW91/CVSE
|
EncoderImageWeightNormPrecomp
| false
| 13,428
|
[
"MIT"
] | 152
|
20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
https://github.com/BruceW91/CVSE/tree/20fa1ff50d1dcb4a7b3799071fa78038e52db804
|
GraphConv
|
import torch
from torch import nn
import torch.nn
import torch.autograd
def sparse_bmm(sparse_matrix, dense_matrix_batch):
"""
Perform torch.bmm on an unbatched sparse matrix and a batched dense matrix.
Args:
sparse_matrix (torch.sparse.FloatTensor): Shape = (m, n)
dense_matrix_batch (torch.FloatTensor): Shape = (b, n, p)
Returns:
(torch.FloatTensor):
Result of the batched matrix multiplication. Shape = (b, n, p)
"""
m = sparse_matrix.shape[0]
b, n, p = dense_matrix_batch.shape
dense_matrix = dense_matrix_batch.transpose(0, 1).reshape(n, b * p)
result = torch.sparse.mm(sparse_matrix, dense_matrix)
return result.reshape(m, b, p).transpose(0, 1)
class GraphConv(nn.Module):
"""A simple graph convolution layer, similar to the one defined by *Kipf et al.* in
`Semi-Supervised Classification with Graph Convolutional Networks`_ ICLR 2017
This operation with self_layer=False is equivalent to :math:`(A H W)` where:
- :math:`H` is the node features with shape (batch_size, num_nodes, input_dim)
- :math:`W` is a weight matrix of shape (input_dim, output_dim)
- :math:`A` is the adjacency matrix of shape (num_nodes, num_nodes).
It can include self-loop.
With normalize_adj=True, it is equivalent to :math:`(D^{-1} A H W)`, where:
- :math:`D` is a diagonal matrix with :math:`D_{ii}` = the sum of the i-th row of A.
In other words, :math:`D` is the incoming degree of each node.
With self_layer=True, it is equivalent to the above plus :math:`(H W_{\\text{self}})`, where:
- :math:`W_{\\text{self}}` is a separate weight matrix to filter each node's self features.
Note that when self_layer is True, A should not include self-loop.
Args:
input_dim (int): The number of features in each input node.
output_dim (int): The number of features in each output node.
bias (bool): Whether to add bias after the node-wise linear layer.
Example:
>>> node_feat = torch.rand(1, 3, 5)
>>> i = torch.LongTensor(
... [[0, 1, 1, 2, 2, 0], [1, 0, 2, 1, 0, 2]])
>>> v = torch.FloatTensor([1, 1, 1, 1, 1, 1])
>>> adj = torch.sparse.FloatTensor(i, v, torch.Size([3, 3]))
>>> model = GraphConv(5, 10)
>>> output = model(node_feat, adj)
>>> # pre-normalize adj
>>> adj = normalize_adj(adj)
>>> output = model(node_feat, adj, normalize_adj=False)
.. _Semi-Supervised Classification with Graph Convolutional Networks:
https://arxiv.org/abs/1609.02907
"""
def __init__(self, input_dim, output_dim, self_layer=True, bias=True):
super(GraphConv, self).__init__()
self.self_layer = self_layer
self.linear = nn.Linear(input_dim, output_dim, bias=bias)
if self_layer:
self.linear_self = nn.Linear(input_dim, output_dim, bias=bias)
else:
self.linear_self = None
self.initialize()
def initialize(self):
nn.init.xavier_uniform_(self.linear.weight.data)
if self.linear.bias is not None:
self.linear.bias.data.uniform_(-1.0, 1.0)
if self.self_layer:
nn.init.xavier_uniform_(self.linear_self.weight.data)
if self.linear_self.bias is not None:
self.linear_self.bias.data.uniform_(-1.0, 1.0)
def forward(self, node_feat, adj, normalize_adj=True):
"""
Args:
node_feat (torch.FloatTensor):
Shape = (batch_size, num_nodes, input_dim)
The input features of each node.
adj (torch.sparse.FloatTensor or torch.FloatTensor):
Shape = (num_nodes, num_nodes)
The adjacency matrix. adj[i, j] is non-zero if there's an
incoming edge from j to i. Should not include self-loop if
self_layer is True.
normalize_adj (bool):
Set this to true to apply normalization to adjacency; that is,
each output feature will be divided by the number of incoming
neighbors. If normalization is not desired, or if the adjacency
matrix is pre-normalized, set this to False to improve
performance.
Returns:
(torch.FloatTensor):
The output features of each node.
Shape = (batch_size, num_nodes, output_dim)
"""
if adj.type().endswith('sparse.FloatTensor'):
if normalize_adj:
norm = torch.sparse.mm(adj, torch.ones((adj.shape[0], 1),
device=node_feat.device))
result = sparse_bmm(adj, self.linear(node_feat)) / norm
else:
result = sparse_bmm(adj, self.linear(node_feat))
elif normalize_adj:
norm = torch.matmul(adj, torch.ones((adj.shape[0], 1), device=
node_feat.device))
result = torch.matmul(adj, self.linear(node_feat)) / norm
else:
result = torch.matmul(adj, self.linear(node_feat))
if self.self_layer:
result += self.linear_self(node_feat)
return result
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_ones_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 = 1.0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_div_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 / tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_ones_0[grid(4)](buf0, 4, XBLOCK=4, num_warps=1,
num_stages=1)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
buf0, out=buf1)
del buf0
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(primals_2, (64,
4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_3
del primals_4
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (16, 4, 4), (16, 4,
1), 0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0),
out=buf3)
buf4 = buf2
del buf2
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf4)
del primals_5
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_add_div_1[grid(256)](buf5, buf1, buf4, primals_6,
256, XBLOCK=128, num_warps=4, num_stages=1)
del buf4
del primals_6
return buf5, buf1, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_1, (16, 4, 4), (16, 1, 4), 0)
def sparse_bmm(sparse_matrix, dense_matrix_batch):
"""
Perform torch.bmm on an unbatched sparse matrix and a batched dense matrix.
Args:
sparse_matrix (torch.sparse.FloatTensor): Shape = (m, n)
dense_matrix_batch (torch.FloatTensor): Shape = (b, n, p)
Returns:
(torch.FloatTensor):
Result of the batched matrix multiplication. Shape = (b, n, p)
"""
m = sparse_matrix.shape[0]
b, n, p = dense_matrix_batch.shape
dense_matrix = dense_matrix_batch.transpose(0, 1).reshape(n, b * p)
result = torch.sparse.mm(sparse_matrix, dense_matrix)
return result.reshape(m, b, p).transpose(0, 1)
class GraphConvNew(nn.Module):
"""A simple graph convolution layer, similar to the one defined by *Kipf et al.* in
`Semi-Supervised Classification with Graph Convolutional Networks`_ ICLR 2017
This operation with self_layer=False is equivalent to :math:`(A H W)` where:
- :math:`H` is the node features with shape (batch_size, num_nodes, input_dim)
- :math:`W` is a weight matrix of shape (input_dim, output_dim)
- :math:`A` is the adjacency matrix of shape (num_nodes, num_nodes).
It can include self-loop.
With normalize_adj=True, it is equivalent to :math:`(D^{-1} A H W)`, where:
- :math:`D` is a diagonal matrix with :math:`D_{ii}` = the sum of the i-th row of A.
In other words, :math:`D` is the incoming degree of each node.
With self_layer=True, it is equivalent to the above plus :math:`(H W_{\\text{self}})`, where:
- :math:`W_{\\text{self}}` is a separate weight matrix to filter each node's self features.
Note that when self_layer is True, A should not include self-loop.
Args:
input_dim (int): The number of features in each input node.
output_dim (int): The number of features in each output node.
bias (bool): Whether to add bias after the node-wise linear layer.
Example:
>>> node_feat = torch.rand(1, 3, 5)
>>> i = torch.LongTensor(
... [[0, 1, 1, 2, 2, 0], [1, 0, 2, 1, 0, 2]])
>>> v = torch.FloatTensor([1, 1, 1, 1, 1, 1])
>>> adj = torch.sparse.FloatTensor(i, v, torch.Size([3, 3]))
>>> model = GraphConv(5, 10)
>>> output = model(node_feat, adj)
>>> # pre-normalize adj
>>> adj = normalize_adj(adj)
>>> output = model(node_feat, adj, normalize_adj=False)
.. _Semi-Supervised Classification with Graph Convolutional Networks:
https://arxiv.org/abs/1609.02907
"""
def __init__(self, input_dim, output_dim, self_layer=True, bias=True):
super(GraphConvNew, self).__init__()
self.self_layer = self_layer
self.linear = nn.Linear(input_dim, output_dim, bias=bias)
if self_layer:
self.linear_self = nn.Linear(input_dim, output_dim, bias=bias)
else:
self.linear_self = None
self.initialize()
def initialize(self):
nn.init.xavier_uniform_(self.linear.weight.data)
if self.linear.bias is not None:
self.linear.bias.data.uniform_(-1.0, 1.0)
if self.self_layer:
nn.init.xavier_uniform_(self.linear_self.weight.data)
if self.linear_self.bias is not None:
self.linear_self.bias.data.uniform_(-1.0, 1.0)
def forward(self, input_0, input_1):
primals_3 = self.linear.weight
primals_4 = self.linear.bias
primals_5 = self.linear_self.weight
primals_6 = self.linear_self.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]
|
Burningdust21/kaolin
|
GraphConv
| false
| 13,429
|
[
"ECL-2.0",
"Apache-2.0"
] | 3,747
|
23e8a0fa4e2cb0249cee4c3c0c1ab1f7e6793531
|
https://github.com/Burningdust21/kaolin/tree/23e8a0fa4e2cb0249cee4c3c0c1ab1f7e6793531
|
Encoder
|
import torch
import torch.nn as nn
import torch.nn
import torch.nn.init
import torch.optim
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class Encoder(Model):
""" Linear encoder """
def __init__(self, c_in, c_out, affine=True):
super(Encoder, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in // 2)
self.fc2 = nn.Linear(c_in // 2, c_in)
def forward(self, x):
x = torch.relu(x)
x = self.fc1(x)
return self.fc2(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4, 'c_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn
import torch.nn.init
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_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
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, (2, 4), (4, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (4, 2), (2, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 2), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(2, 4), (1, 2), 0), alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf1, primals_4
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class EncoderNew(Model):
""" Linear encoder """
def __init__(self, c_in, c_out, affine=True):
super(EncoderNew, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in // 2)
self.fc2 = nn.Linear(c_in // 2, c_in)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data
|
Encoder
| false
| 13,430
|
[
"MIT"
] | 51
|
2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
https://github.com/CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data/tree/2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
LinearDrop
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn
import torch.nn.init
import torch.optim
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class LinearDrop(Model):
""" Linear block with dropout """
def __init__(self, c_in, c_out, affine=True):
super(LinearDrop, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in * 2)
self.fc2 = nn.Linear(c_in * 2, c_out)
def forward(self, x):
x = torch.relu(x)
x = F.dropout(self.fc1(x))
out = F.dropout(self.fc2(x))
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4, 'c_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn
import torch.nn.init
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_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
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, (8, 4), (4, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (4, 8), (8, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 8), (8, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 8), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
buf2 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf1, (4, 4, 4, 8), (128, 32, 8, 1), 0), 0.5, True)
del buf1
buf3 = buf2[0]
buf4 = buf2[1]
del buf2
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf3, (64, 8), (
8, 1), 0), reinterpret_tensor(primals_4, (8, 4), (1, 8), 0),
alpha=1, beta=1, out=buf5)
del primals_5
buf6 = torch.ops.aten.native_dropout.default(reinterpret_tensor(
buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0), 0.5, True)
del buf5
buf7 = buf6[0]
buf8 = buf6[1]
del buf6
return buf7, reinterpret_tensor(buf0, (64, 4), (4, 1), 0
), buf4, reinterpret_tensor(buf3, (64, 8), (8, 1), 0), buf8, primals_4
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class LinearDropNew(Model):
""" Linear block with dropout """
def __init__(self, c_in, c_out, affine=True):
super(LinearDropNew, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in * 2)
self.fc2 = nn.Linear(c_in * 2, c_out)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data
|
LinearDrop
| false
| 13,431
|
[
"MIT"
] | 51
|
2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
https://github.com/CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data/tree/2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
InstanceNormLayer
|
import torch
import torch.nn as nn
class InstanceNormLayer(nn.Module):
"""Implements instance normalization layer."""
def __init__(self, epsilon=1e-08):
super().__init__()
self.epsilon = epsilon
def forward(self, x):
if len(x.shape) != 4:
raise ValueError(
f'The input tensor should be with shape [batch_size, num_channels, height, width], but {x.shape} received!'
)
x = x - torch.mean(x, dim=[2, 3], keepdim=True)
x = x / torch.sqrt(torch.mean(x ** 2, dim=[2, 3], keepdim=True) +
self.epsilon)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mean_pow_sqrt_sub_0(in_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
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
tmp7 = tmp0 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.where(xmask, tmp9, 0)
tmp12 = tl.sum(tmp11, 1)[:, None]
tmp13 = tmp12 / tmp5
tmp14 = 1e-08
tmp15 = tmp13 + tmp14
tmp16 = libdevice.sqrt(tmp15)
tmp17 = tmp7 / tmp16
tl.store(out_ptr2 + (r1 + 16 * x0), tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_mean_pow_sqrt_sub_0[grid(16)](arg0_1, buf2,
16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf2,
class InstanceNormLayerNew(nn.Module):
"""Implements instance normalization layer."""
def __init__(self, epsilon=1e-08):
super().__init__()
self.epsilon = epsilon
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CV-IP/interfacegan
|
InstanceNormLayer
| false
| 13,432
|
[
"MIT"
] | 855
|
5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
https://github.com/CV-IP/interfacegan/tree/5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
Attention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
"""
several score types like dot,general and concat
"""
def __init__(self, method='dot', hidden_size=None):
super(Attention, self).__init__()
self.method = method
if self.method != 'dot':
self.hidden_size = hidden_size
if self.method == 'general':
self.W = nn.Linear(hidden_size, hidden_size)
elif self.method == 'concat':
self.W = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.rand(1, hidden_size))
nn.init.xavier_normal_(self.v.data)
def forward(self, query, key, value, mask=None, dropout=0):
if self.method == 'general':
scores = self.general(query, key)
elif self.method == 'concat':
scores = self.concat(query, key)
else:
scores = self.dot(query, key)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1000000000.0)
p_attn = F.softmax(scores, dim=-1)
if not dropout:
p_attn = F.dropout(p_attn, dropout)
return torch.matmul(p_attn, value), p_attn
def dot(self, query, key):
scores = torch.matmul(query, key.transpose(-2, -1))
return scores
def general(self, query, key):
scores = torch.matmul(self.W(query), key.transpose(-2, -1))
return scores
def concat(self, query, key):
scores = torch.cat((query.expand(-1, key.size(1), -1), key), dim=2)
scores = self.W(scores)
scores = F.tanh(scores)
scores = torch.matmul(scores, self.v.t()).transpose(-2, -1)
return scores
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
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_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_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 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg1_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(arg0_1, (16, 4, 4), (16, 1, 4), 0),
out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf3
)
del arg2_1
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0), buf2
class AttentionNew(nn.Module):
"""
several score types like dot,general and concat
"""
def __init__(self, method='dot', hidden_size=None):
super(AttentionNew, self).__init__()
self.method = method
if self.method != 'dot':
self.hidden_size = hidden_size
if self.method == 'general':
self.W = nn.Linear(hidden_size, hidden_size)
elif self.method == 'concat':
self.W = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.rand(1, hidden_size))
nn.init.xavier_normal_(self.v.data)
def dot(self, query, key):
scores = torch.matmul(query, key.transpose(-2, -1))
return scores
def general(self, query, key):
scores = torch.matmul(self.W(query), key.transpose(-2, -1))
return scores
def concat(self, query, key):
scores = torch.cat((query.expand(-1, key.size(1), -1), key), dim=2)
scores = self.W(scores)
scores = F.tanh(scores)
scores = torch.matmul(scores, self.v.t()).transpose(-2, -1)
return scores
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0], output[1]
|
CNLPT/lightNLP
|
Attention
| false
| 13,433
|
[
"Apache-2.0"
] | 889
|
c7f128422ba5b16f514bb294145cb3b562e95829
|
https://github.com/CNLPT/lightNLP/tree/c7f128422ba5b16f514bb294145cb3b562e95829
|
MSBlock
|
import torch
import torch.nn as nn
class MSBlock(nn.Module):
def __init__(self, c_in, rate=4):
super(MSBlock, self).__init__()
self.rate = rate
self.conv = nn.Conv2d(c_in, 32, 3, stride=1, padding=1)
self.relu = nn.ReLU(inplace=True)
dilation = self.rate * 1 if self.rate >= 1 else 1
self.conv1 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu1 = nn.ReLU(inplace=True)
dilation = self.rate * 2 if self.rate >= 1 else 1
self.conv2 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu2 = nn.ReLU(inplace=True)
dilation = self.rate * 3 if self.rate >= 1 else 1
self.conv3 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu3 = nn.ReLU(inplace=True)
self._initialize_weights()
def forward(self, x):
o = self.relu(self.conv(x))
o1 = self.relu1(self.conv1(o))
o2 = self.relu2(self.conv2(o))
o3 = self.relu3(self.conv3(o))
out = o + o1 + o2 + o3
return out
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
m.weight.data.normal_(0, 0.01)
if m.bias is not None:
m.bias.data.zero_()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 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_add_convolution_relu_threshold_backward_1(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 32
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x3, None)
tmp2 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr3 + x3, None)
tmp8 = tl.load(in_ptr4 + x1, None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x3, None)
tmp13 = tl.load(in_ptr6 + x1, None, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = triton_helpers.maximum(tmp4, tmp9)
tmp11 = tmp6 + tmp10
tmp14 = tmp12 + tmp13
tmp15 = triton_helpers.maximum(tmp4, tmp14)
tmp16 = tmp11 + tmp15
tmp17 = 0.0
tmp18 = tmp15 <= tmp17
tmp19 = tmp10 <= tmp17
tmp20 = tmp5 <= tmp17
tl.store(out_ptr0 + x3, tmp16, None)
tl.store(out_ptr1 + x3, tmp18, None)
tl.store(out_ptr2 + x3, tmp19, None)
tl.store(out_ptr3 + x3, tmp20, None)
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, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 4, 4), (512, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(2048)](buf1, primals_2,
2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(4, 4), dilation=(4, 4), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 4, 4), (512, 16, 4, 1))
buf3 = extern_kernels.convolution(buf1, primals_6, stride=(1, 1),
padding=(8, 8), dilation=(8, 8), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 32, 4, 4), (512, 16, 4, 1))
buf4 = extern_kernels.convolution(buf1, primals_8, stride=(1, 1),
padding=(12, 12), dilation=(12, 12), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 4, 4), (512, 16, 4, 1))
buf5 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.float32
)
buf6 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.bool)
buf7 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.bool)
buf8 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.bool)
triton_poi_fused_add_convolution_relu_threshold_backward_1[grid(2048)](
buf1, buf2, primals_5, buf3, primals_7, buf4, primals_9, buf5,
buf6, buf7, buf8, 2048, XBLOCK=128, num_warps=4, num_stages=1)
del buf2
del buf3
del buf4
del primals_5
del primals_7
del primals_9
return (buf5, primals_1, primals_3, primals_4, primals_6, primals_8,
buf1, buf6, buf7, buf8)
class MSBlockNew(nn.Module):
def __init__(self, c_in, rate=4):
super(MSBlockNew, self).__init__()
self.rate = rate
self.conv = nn.Conv2d(c_in, 32, 3, stride=1, padding=1)
self.relu = nn.ReLU(inplace=True)
dilation = self.rate * 1 if self.rate >= 1 else 1
self.conv1 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu1 = nn.ReLU(inplace=True)
dilation = self.rate * 2 if self.rate >= 1 else 1
self.conv2 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu2 = nn.ReLU(inplace=True)
dilation = self.rate * 3 if self.rate >= 1 else 1
self.conv3 = nn.Conv2d(32, 32, 3, stride=1, dilation=dilation,
padding=dilation)
self.relu3 = nn.ReLU(inplace=True)
self._initialize_weights()
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
m.weight.data.normal_(0, 0.01)
if m.bias is not None:
m.bias.data.zero_()
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_4 = self.conv1.weight
primals_5 = self.conv1.bias
primals_6 = self.conv2.weight
primals_7 = self.conv2.bias
primals_8 = self.conv3.weight
primals_9 = self.conv3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
CM-BF/FeatureFlow
|
MSBlock
| false
| 13,434
|
[
"MIT"
] | 161
|
06642697922f17211e5faa353e24b1a0946885b1
|
https://github.com/CM-BF/FeatureFlow/tree/06642697922f17211e5faa353e24b1a0946885b1
|
LinearBlock
|
import torch
import torch.nn as nn
import torch.nn
import torch.nn.init
import torch.optim
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class LinearBlock(Model):
""" Linear block consisting of two fully connected layers
Example
-------
x: torch.Size([2, 10, 12])
out: [batch_size, c_out, d//2]
out: torch.Size([2, 10, 6])
"""
def __init__(self, c_in, c_out, affine=True):
super(LinearBlock, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in * 2)
self.fc2 = nn.Linear(c_in * 2, c_out)
def forward(self, x):
x = torch.relu(x)
x = self.fc1(x)
out = self.fc2(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4, 'c_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn
import torch.nn.init
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_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
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, (8, 4), (4, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (4, 8), (8, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 8), (8, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 8), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf1, primals_4
class Model(nn.Module):
""" Class representing sampleable neural network model """
def num_params(self):
""" Get the number of model parameters. """
return sum(p.numel() for p in self.parameters())
def summary(self, hashsummary=False):
None
None
self.num_params()
None
None
if hashsummary:
None
for idx, hashvalue in enumerate(self.hashsummary()):
None
def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()
).hexdigest() for x in child.parameters())
return result
def loss(self, x_data, y_true, reduce='mean'):
""" Forward propagate network and return a value of loss function """
if reduce not in (None, 'sum', 'mean'):
raise ValueError('`reduce` must be either None, `sum`, or `mean`!')
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred, reduce=reduce)
def loss_value(self, x_data, y_true, y_pred, reduce=None):
""" Calculate a value of loss function """
raise NotImplementedError
class LinearBlockNew(Model):
""" Linear block consisting of two fully connected layers
Example
-------
x: torch.Size([2, 10, 12])
out: [batch_size, c_out, d//2]
out: torch.Size([2, 10, 6])
"""
def __init__(self, c_in, c_out, affine=True):
super(LinearBlockNew, self).__init__()
assert c_out % 2 == 0
self.fc1 = nn.Linear(c_in, c_in * 2)
self.fc2 = nn.Linear(c_in * 2, c_out)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data
|
LinearBlock
| false
| 13,435
|
[
"MIT"
] | 51
|
2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
https://github.com/CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data/tree/2b1213f944cf5f2c60799099a469989a1f0a6d3a
|
CharbonnierLoss
|
import torch
import torch.nn as nn
class CharbonnierLoss(nn.Module):
"""Charbonnier Loss (L1)"""
def __init__(self, eps=1e-06):
super(CharbonnierLoss, self).__init__()
self.eps = eps
def forward(self, x, y):
diff = x - y
loss = torch.mean(torch.sqrt(diff * diff + self.eps))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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_mul_sqrt_sub_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 = 1e-06
tmp5 = tmp3 + tmp4
tmp6 = libdevice.sqrt(tmp5)
tmp7 = tl.broadcast_to(tmp6, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = 256.0
tmp11 = tmp9 / tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mean_mul_sqrt_sub_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 CharbonnierLossNew(nn.Module):
"""Charbonnier Loss (L1)"""
def __init__(self, eps=1e-06):
super(CharbonnierLossNew, self).__init__()
self.eps = eps
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
CM-BF/FeatureFlow
|
CharbonnierLoss
| false
| 13,436
|
[
"MIT"
] | 161
|
06642697922f17211e5faa353e24b1a0946885b1
|
https://github.com/CM-BF/FeatureFlow/tree/06642697922f17211e5faa353e24b1a0946885b1
|
down
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.functional import F
from torch.nn import functional as F
class down(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average Pooling --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels, filterSize):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used as input and output channels for the
second convolutional layer.
filterSize : int
filter size for the convolution filter. input N would create
a N x N filter.
"""
super(down, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, filterSize, stride=
1, padding=int((filterSize - 1) / 2))
self.conv2 = nn.Conv2d(outChannels, outChannels, filterSize, stride
=1, padding=int((filterSize - 1) / 2))
def forward(self, x):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.avg_pool2d(x, 2)
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(x), negative_slope=0.1)
return x
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'inChannels': 4, 'outChannels': 4, 'filterSize': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 15376
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 961 % 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.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 14400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 900 % 4
x2 = xindex // 3600
x4 = xindex % 3600
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + (x4 + 3712 * x2), tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 64, 64), (16384, 4096, 64, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_0[grid(16384)](primals_1, buf0, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 31, 31), (3844, 961, 31, 1))
buf2 = empty_strided_cuda((4, 4, 31, 31), (3844, 961, 31, 1), torch
.bool)
buf3 = empty_strided_cuda((4, 4, 31, 31), (3844, 961, 31, 1), torch
.float32)
triton_poi_fused_convolution_leaky_relu_1[grid(15376)](buf1,
primals_3, buf2, buf3, 15376, XBLOCK=256, num_warps=4, num_stages=1
)
del buf1
del primals_3
buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 30, 30), (3600, 900, 30, 1))
buf5 = empty_strided_cuda((4, 4, 30, 30), (3712, 900, 30, 1), torch
.bool)
buf6 = empty_strided_cuda((4, 4, 30, 30), (3600, 900, 30, 1), torch
.float32)
triton_poi_fused_convolution_leaky_relu_2[grid(14400)](buf4,
primals_5, buf5, buf6, 14400, XBLOCK=256, num_warps=4, num_stages=1
)
del buf4
del primals_5
return buf6, primals_2, primals_4, buf0, buf2, buf3, buf5
class downNew(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average Pooling --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels, filterSize):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used as input and output channels for the
second convolutional layer.
filterSize : int
filter size for the convolution filter. input N would create
a N x N filter.
"""
super(downNew, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, filterSize, stride=
1, padding=int((filterSize - 1) / 2))
self.conv2 = nn.Conv2d(outChannels, outChannels, filterSize, stride
=1, padding=int((filterSize - 1) / 2))
def forward(self, 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]
|
CM-BF/FeatureFlow
|
down
| false
| 13,437
|
[
"MIT"
] | 161
|
06642697922f17211e5faa353e24b1a0946885b1
|
https://github.com/CM-BF/FeatureFlow/tree/06642697922f17211e5faa353e24b1a0946885b1
|
_Residual_Block
|
import torch
import torch.nn as nn
class _Residual_Block(nn.Module):
def __init__(self, inc=64, outc=64, groups=1):
super(_Residual_Block, self).__init__()
if inc is not outc:
self.conv_expand = nn.Conv2d(in_channels=inc, out_channels=outc,
kernel_size=1, stride=1, padding=0, groups=1, bias=False)
else:
self.conv_expand = None
self.conv1 = nn.Conv2d(in_channels=inc, out_channels=outc,
kernel_size=3, stride=1, padding=1, groups=groups, bias=False)
self.bn1 = nn.InstanceNorm2d(outc, eps=0.001)
self.relu1 = nn.LeakyReLU(0.2, inplace=True)
self.conv2 = nn.Conv2d(in_channels=outc, out_channels=outc,
kernel_size=3, stride=1, padding=1, groups=groups, bias=False)
self.bn2 = nn.InstanceNorm2d(outc, eps=0.001)
self.relu2 = nn.LeakyReLU(0.2, inplace=True)
def forward(self, x):
if self.conv_expand is not None:
identity_data = self.conv_expand(x)
else:
identity_data = x
output = self.relu1(self.bn1(self.conv1(x)))
output = self.conv2(output)
output = self.relu2(self.bn2(torch.add(output, identity_data)))
return output
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
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_red_fused__native_batch_norm_legit_leaky_relu_0(in_ptr0,
out_ptr0, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr,
RBLOCK: tl.constexpr):
xnumel = 256
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_weight = tl.zeros([XBLOCK, RBLOCK], tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp2_mean_next, tmp2_m2_next, tmp2_weight_next = (triton_helpers.
welford_reduce(tmp1, tmp2_mean, tmp2_m2, tmp2_weight, roffset == 0)
)
tmp2_mean = tl.where(rmask & xmask, tmp2_mean_next, tmp2_mean)
tmp2_m2 = tl.where(rmask & xmask, tmp2_m2_next, tmp2_m2)
tmp2_weight = tl.where(rmask & xmask, tmp2_weight_next, tmp2_weight)
tmp2_tmp, tmp3_tmp, tmp4_tmp = triton_helpers.welford(tmp2_mean,
tmp2_m2, tmp2_weight, 1)
tmp2 = tmp2_tmp[:, None]
tmp3 = tmp3_tmp[:, None]
tmp4_tmp[:, None]
tl.store(out_ptr0 + x0, tmp2, xmask)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp5 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp6 = tmp5 - tmp2
tmp7 = 4096.0
tmp8 = tmp3 / tmp7
tmp9 = 0.001
tmp10 = tmp8 + tmp9
tmp11 = libdevice.rsqrt(tmp10)
tmp12 = tmp6 * tmp11
tmp13 = 0.0
tmp14 = tmp12 > tmp13
tmp15 = 0.2
tmp16 = tmp12 * tmp15
tmp17 = tl.where(tmp14, tmp12, tmp16)
tl.store(out_ptr2 + (r1 + 4096 * x0), tmp17, rmask & xmask)
tmp18 = 4096.0
tmp19 = tmp3 / tmp18
tmp20 = 0.001
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tl.store(out_ptr3 + x0, tmp22, xmask)
@triton.jit
def triton_red_fused__native_batch_norm_legit_leaky_relu_leaky_relu_backward_1(
in_ptr0, in_ptr1, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel,
rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 256
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
tmp4_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp4_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp4_weight = tl.zeros([XBLOCK, RBLOCK], tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp4_mean_next, tmp4_m2_next, tmp4_weight_next = (triton_helpers.
welford_reduce(tmp3, tmp4_mean, tmp4_m2, tmp4_weight, roffset == 0)
)
tmp4_mean = tl.where(rmask & xmask, tmp4_mean_next, tmp4_mean)
tmp4_m2 = tl.where(rmask & xmask, tmp4_m2_next, tmp4_m2)
tmp4_weight = tl.where(rmask & xmask, tmp4_weight_next, tmp4_weight)
tmp4_tmp, tmp5_tmp, tmp6_tmp = triton_helpers.welford(tmp4_mean,
tmp4_m2, tmp4_weight, 1)
tmp4 = tmp4_tmp[:, None]
tmp5 = tmp5_tmp[:, None]
tmp6_tmp[:, None]
tl.store(out_ptr0 + x0, tmp4, xmask)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp7 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp8 = tl.load(in_ptr1 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp9 = tmp7 + tmp8
tmp10 = tmp9 - tmp4
tmp11 = 4096.0
tmp12 = tmp5 / tmp11
tmp13 = 0.001
tmp14 = tmp12 + tmp13
tmp15 = libdevice.rsqrt(tmp14)
tmp16 = tmp10 * tmp15
tmp17 = 0.0
tmp18 = tmp16 > tmp17
tmp19 = 0.2
tmp20 = tmp16 * tmp19
tmp21 = tl.where(tmp18, tmp16, tmp20)
tmp22 = tmp21 > tmp17
tl.store(out_ptr2 + (r1 + 4096 * x0), tmp21, rmask & xmask)
tl.store(out_ptr3 + (r1 + 4096 * x0), tmp22, rmask & xmask)
tmp23 = 4096.0
tmp24 = tmp5 / tmp23
tmp25 = 0.001
tmp26 = tmp24 + tmp25
tmp27 = libdevice.rsqrt(tmp26)
tl.store(out_ptr4 + x0, tmp27, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 64, 64, 64), (262144, 4096, 64, 1))
assert_size_stride(primals_2, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_3, (64, 64, 3, 3), (576, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf1 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256), torch
.float32)
buf5 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
buf4 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256), torch
.float32)
get_raw_stream(0)
triton_red_fused__native_batch_norm_legit_leaky_relu_0[grid(256)](buf0,
buf1, buf5, buf4, 256, 4096, XBLOCK=1, RBLOCK=2048, num_warps=
16, num_stages=1)
buf6 = extern_kernels.convolution(buf5, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf7 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256), torch
.float32)
buf11 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
buf12 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.bool)
buf10 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256),
torch.float32)
triton_red_fused__native_batch_norm_legit_leaky_relu_leaky_relu_backward_1[
grid(256)](buf6, primals_1, buf7, buf11, buf12, buf10, 256,
4096, XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1)
return buf11, primals_1, primals_2, primals_3, buf0, reinterpret_tensor(
buf4, (256,), (1,), 0), buf5, buf6, reinterpret_tensor(buf10, (256,
), (1,), 0), buf12, reinterpret_tensor(buf7, (1, 256, 1, 1), (256,
1, 1, 1), 0), reinterpret_tensor(buf1, (1, 256, 1, 1), (256, 1, 1,
1), 0)
class _Residual_BlockNew(nn.Module):
def __init__(self, inc=64, outc=64, groups=1):
super(_Residual_BlockNew, self).__init__()
if inc is not outc:
self.conv_expand = nn.Conv2d(in_channels=inc, out_channels=outc,
kernel_size=1, stride=1, padding=0, groups=1, bias=False)
else:
self.conv_expand = None
self.conv1 = nn.Conv2d(in_channels=inc, out_channels=outc,
kernel_size=3, stride=1, padding=1, groups=groups, bias=False)
self.bn1 = nn.InstanceNorm2d(outc, eps=0.001)
self.relu1 = nn.LeakyReLU(0.2, inplace=True)
self.conv2 = nn.Conv2d(in_channels=outc, out_channels=outc,
kernel_size=3, stride=1, padding=1, groups=groups, bias=False)
self.bn2 = nn.InstanceNorm2d(outc, eps=0.001)
self.relu2 = nn.LeakyReLU(0.2, inplace=True)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv2.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
BradyFU/DVG
|
_Residual_Block
| false
| 13,438
|
[
"MIT"
] | 102
|
53fd50cdc51d783b33394726b8f8a2b2216f157b
|
https://github.com/BradyFU/DVG/tree/53fd50cdc51d783b33394726b8f8a2b2216f157b
|
RNN_net
|
import torch
import torch.nn as nn
class RNN_net(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN_net, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, input_, hidden):
combined = torch.cat((input_, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def init_hidden(self):
return torch.zeros(1, self.hidden_size)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import 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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused__log_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
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 8), (8, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 8), (8, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, buf0, reinterpret_tensor(primals_3,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf1)
del primals_3
del primals_4
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, buf0, reinterpret_tensor(primals_5,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf2)
del primals_5
del primals_6
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused__log_softmax_2[grid(16)](buf3, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf3
return buf4, buf1, buf0, buf4
class RNN_netNew(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN_netNew, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax(dim=1)
def init_hidden(self):
return torch.zeros(1, self.hidden_size)
def forward(self, input_0, input_1):
primals_3 = self.i2h.weight
primals_4 = self.i2h.bias
primals_5 = self.i2o.weight
primals_6 = self.i2o.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], output[1]
|
CMOONCS/DeepLearning
|
RNN_net
| false
| 13,439
|
[
"MIT"
] | 86
|
748107d27e466bb18559b828642a4cace6431dc2
|
https://github.com/CMOONCS/DeepLearning/tree/748107d27e466bb18559b828642a4cace6431dc2
|
TLU
|
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class TLU(nn.Module):
def __init__(self, num_features):
super(TLU, self).__init__()
self.num_features = num_features
self.tau = Parameter(torch.Tensor(1, num_features, 1, 1),
requires_grad=True)
self.reset_parameters()
def reset_parameters(self):
nn.init.zeros_(self.tau)
def forward(self, x):
return torch.max(x, self.tau)
def extra_repr(self):
return '{num_features}'.format(**self.__dict__)
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 import triton_helpers
import torch.nn as nn
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_eq_gt_maximum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tmp0 == tmp1
tmp4 = tmp0 > tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr1 + x3, tmp3, xmask)
tl.store(out_ptr2 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2 = 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))
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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_gt_maximum_0[grid(256)](primals_2, primals_1,
buf0, buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0, buf1, buf2
class TLUNew(nn.Module):
def __init__(self, num_features):
super(TLUNew, self).__init__()
self.num_features = num_features
self.tau = Parameter(torch.Tensor(1, num_features, 1, 1),
requires_grad=True)
self.reset_parameters()
def reset_parameters(self):
nn.init.zeros_(self.tau)
def extra_repr(self):
return '{num_features}'.format(**self.__dict__)
def forward(self, input_0):
primals_1 = self.tau
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
COATZ/ShapeConv
|
TLU
| false
| 13,440
|
[
"Apache-2.0"
] | 57
|
f34f4e95ee2b69ac645fd5ba608e3c11cfadfded
|
https://github.com/COATZ/ShapeConv/tree/f34f4e95ee2b69ac645fd5ba608e3c11cfadfded
|
PixelNormLayer
|
import torch
import torch.nn as nn
class PixelNormLayer(nn.Module):
"""Implements pixel-wise feature vector normalization layer."""
def __init__(self, epsilon=1e-08):
super().__init__()
self.epsilon = epsilon
def forward(self, x):
return x / torch.sqrt(torch.mean(x ** 2, dim=1, keepdim=True) +
self.epsilon)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_pow_sqrt_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = 1e-08
tmp15 = tmp13 + tmp14
tmp16 = libdevice.sqrt(tmp15)
tmp17 = tmp0 / tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_pow_sqrt_0[grid(256)](arg0_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class PixelNormLayerNew(nn.Module):
"""Implements pixel-wise feature vector normalization layer."""
def __init__(self, epsilon=1e-08):
super().__init__()
self.epsilon = epsilon
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CV-IP/interfacegan
|
PixelNormLayer
| false
| 13,441
|
[
"MIT"
] | 855
|
5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
https://github.com/CV-IP/interfacegan/tree/5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
Upsample
|
import torch
import torch.nn as nn
import torch.nn.parallel
class Upsample(nn.Module):
def __init__(self, n_iter):
super(Upsample, self).__init__()
self.n_iter = n_iter
def forward(self, img):
for _ in range(self.n_iter):
img = nn.functional.interpolate(img, scale_factor=2.0, mode=
'bicubic')
return img
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_iter': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_0(
in_out_ptr1, in_out_ptr2, in_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 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = libdevice.floor(tmp5)
tmp7 = tmp6.to(tl.int32)
tmp8 = tl.full([1], 1, tl.int64)
tmp9 = tmp7 - tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full([1], 3, tl.int64)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tmp14 = x0
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp15 + tmp2
tmp17 = tmp16 * tmp2
tmp18 = tmp17 - tmp2
tmp19 = libdevice.floor(tmp18)
tmp20 = tmp19.to(tl.int32)
tmp21 = tmp20 - tmp8
tmp22 = triton_helpers.maximum(tmp21, tmp10)
tmp23 = triton_helpers.minimum(tmp22, tmp12)
tmp24 = tl.load(in_ptr0 + (tmp23 + 4 * tmp13 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp25 = tmp18 - tmp19
tmp26 = 0.0
tmp27 = triton_helpers.maximum(tmp25, tmp26)
tmp28 = 1.0
tmp29 = triton_helpers.minimum(tmp27, tmp28)
tmp30 = tmp29 + tmp28
tmp31 = -0.75
tmp32 = tmp30 * tmp31
tmp33 = -3.75
tmp34 = tmp32 - tmp33
tmp35 = tmp34 * tmp30
tmp36 = -6.0
tmp37 = tmp35 + tmp36
tmp38 = tmp37 * tmp30
tmp39 = -3.0
tmp40 = tmp38 - tmp39
tmp41 = tmp24 * tmp40
tmp42 = triton_helpers.maximum(tmp20, tmp10)
tmp43 = triton_helpers.minimum(tmp42, tmp12)
tmp44 = tl.load(in_ptr0 + (tmp43 + 4 * tmp13 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp45 = 1.25
tmp46 = tmp29 * tmp45
tmp47 = 2.25
tmp48 = tmp46 - tmp47
tmp49 = tmp48 * tmp29
tmp50 = tmp49 * tmp29
tmp51 = tmp50 + tmp28
tmp52 = tmp44 * tmp51
tmp53 = tmp20 + tmp8
tmp54 = triton_helpers.maximum(tmp53, tmp10)
tmp55 = triton_helpers.minimum(tmp54, tmp12)
tmp56 = tl.load(in_ptr0 + (tmp55 + 4 * tmp13 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp57 = tmp28 - tmp29
tmp58 = tmp57 * tmp45
tmp59 = tmp58 - tmp47
tmp60 = tmp59 * tmp57
tmp61 = tmp60 * tmp57
tmp62 = tmp61 + tmp28
tmp63 = tmp56 * tmp62
tmp64 = tl.full([1], 2, tl.int64)
tmp65 = tmp20 + tmp64
tmp66 = triton_helpers.maximum(tmp65, tmp10)
tmp67 = triton_helpers.minimum(tmp66, tmp12)
tmp68 = tl.load(in_ptr0 + (tmp67 + 4 * tmp13 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp69 = 2.0
tmp70 = tmp69 - tmp29
tmp71 = tmp70 * tmp31
tmp72 = tmp71 - tmp33
tmp73 = tmp72 * tmp70
tmp74 = tmp73 + tmp36
tmp75 = tmp74 * tmp70
tmp76 = tmp75 - tmp39
tmp77 = tmp68 * tmp76
tmp78 = tmp41 + tmp52
tmp79 = tmp78 + tmp63
tmp80 = tmp79 + tmp77
tmp81 = tmp5 - tmp6
tmp82 = triton_helpers.maximum(tmp81, tmp26)
tmp83 = triton_helpers.minimum(tmp82, tmp28)
tmp84 = tmp83 + tmp28
tmp85 = tmp84 * tmp31
tmp86 = tmp85 - tmp33
tmp87 = tmp86 * tmp84
tmp88 = tmp87 + tmp36
tmp89 = tmp88 * tmp84
tmp90 = tmp89 - tmp39
tmp91 = tmp80 * tmp90
tmp92 = triton_helpers.maximum(tmp7, tmp10)
tmp93 = triton_helpers.minimum(tmp92, tmp12)
tmp94 = tl.load(in_ptr0 + (tmp23 + 4 * tmp93 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp95 = tmp94 * tmp40
tmp96 = tl.load(in_ptr0 + (tmp43 + 4 * tmp93 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp97 = tmp96 * tmp51
tmp98 = tl.load(in_ptr0 + (tmp55 + 4 * tmp93 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp99 = tmp98 * tmp62
tmp100 = tl.load(in_ptr0 + (tmp67 + 4 * tmp93 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp101 = tmp100 * tmp76
tmp102 = tmp7 + tmp8
tmp103 = triton_helpers.maximum(tmp102, tmp10)
tmp104 = triton_helpers.minimum(tmp103, tmp12)
tmp105 = tl.load(in_ptr0 + (tmp23 + 4 * tmp104 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp106 = tmp105 * tmp40
tmp107 = tl.load(in_ptr0 + (tmp43 + 4 * tmp104 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp108 = tmp107 * tmp51
tmp109 = tl.load(in_ptr0 + (tmp55 + 4 * tmp104 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp110 = tmp109 * tmp62
tmp111 = tl.load(in_ptr0 + (tmp67 + 4 * tmp104 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp112 = tmp111 * tmp76
tmp113 = tmp95 + tmp97
tmp114 = tmp113 + tmp99
tmp115 = tmp114 + tmp101
tmp116 = tmp83 * tmp45
tmp117 = tmp116 - tmp47
tmp118 = tmp117 * tmp83
tmp119 = tmp118 * tmp83
tmp120 = tmp119 + tmp28
tmp121 = tmp115 * tmp120
tmp122 = tmp91 + tmp121
tmp123 = tmp106 + tmp108
tmp124 = tmp123 + tmp110
tmp125 = tmp124 + tmp112
tmp126 = tmp28 - tmp83
tmp127 = tmp126 * tmp45
tmp128 = tmp127 - tmp47
tmp129 = tmp128 * tmp126
tmp130 = tmp129 * tmp126
tmp131 = tmp130 + tmp28
tmp132 = tmp125 * tmp131
tmp133 = tmp122 + tmp132
tmp134 = tmp7 + tmp64
tmp135 = triton_helpers.maximum(tmp134, tmp10)
tmp136 = triton_helpers.minimum(tmp135, tmp12)
tmp137 = tl.load(in_ptr0 + (tmp23 + 4 * tmp136 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp138 = tmp137 * tmp40
tmp139 = tl.load(in_ptr0 + (tmp43 + 4 * tmp136 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp140 = tmp139 * tmp51
tmp141 = tl.load(in_ptr0 + (tmp55 + 4 * tmp136 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp142 = tmp141 * tmp62
tmp143 = tl.load(in_ptr0 + (tmp67 + 4 * tmp136 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp144 = tmp143 * tmp76
tmp145 = tmp138 + tmp140
tmp146 = tmp145 + tmp142
tmp147 = tmp146 + tmp144
tmp148 = tmp69 - tmp83
tmp149 = tmp148 * tmp31
tmp150 = tmp149 - tmp33
tmp151 = tmp150 * tmp148
tmp152 = tmp151 + tmp36
tmp153 = tmp152 * tmp148
tmp154 = tmp153 - tmp39
tmp155 = tmp147 * tmp154
tl.store(in_out_ptr1 + x4, tmp133, xmask)
tl.store(in_out_ptr2 + x4, tmp155, xmask)
@triton.jit
def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_1(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 16 % 16
x0 = xindex % 16
x2 = xindex // 256
x4 = xindex
tmp0 = x1
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = libdevice.floor(tmp5)
tmp7 = tmp6.to(tl.int32)
tmp8 = tl.full([1], 1, tl.int64)
tmp9 = tmp7 - tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full([1], 7, tl.int64)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tmp14 = x0
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp15 + tmp2
tmp17 = tmp16 * tmp2
tmp18 = tmp17 - tmp2
tmp19 = libdevice.floor(tmp18)
tmp20 = tmp19.to(tl.int32)
tmp21 = tmp20 - tmp8
tmp22 = triton_helpers.maximum(tmp21, tmp10)
tmp23 = triton_helpers.minimum(tmp22, tmp12)
tmp24 = tl.load(in_ptr0 + (tmp23 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp25 = tl.load(in_ptr1 + (tmp23 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp26 = tmp24 + tmp25
tmp27 = tmp18 - tmp19
tmp28 = 0.0
tmp29 = triton_helpers.maximum(tmp27, tmp28)
tmp30 = 1.0
tmp31 = triton_helpers.minimum(tmp29, tmp30)
tmp32 = tmp31 + tmp30
tmp33 = -0.75
tmp34 = tmp32 * tmp33
tmp35 = -3.75
tmp36 = tmp34 - tmp35
tmp37 = tmp36 * tmp32
tmp38 = -6.0
tmp39 = tmp37 + tmp38
tmp40 = tmp39 * tmp32
tmp41 = -3.0
tmp42 = tmp40 - tmp41
tmp43 = tmp26 * tmp42
tmp44 = triton_helpers.maximum(tmp20, tmp10)
tmp45 = triton_helpers.minimum(tmp44, tmp12)
tmp46 = tl.load(in_ptr0 + (tmp45 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp47 = tl.load(in_ptr1 + (tmp45 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp48 = tmp46 + tmp47
tmp49 = 1.25
tmp50 = tmp31 * tmp49
tmp51 = 2.25
tmp52 = tmp50 - tmp51
tmp53 = tmp52 * tmp31
tmp54 = tmp53 * tmp31
tmp55 = tmp54 + tmp30
tmp56 = tmp48 * tmp55
tmp57 = tmp20 + tmp8
tmp58 = triton_helpers.maximum(tmp57, tmp10)
tmp59 = triton_helpers.minimum(tmp58, tmp12)
tmp60 = tl.load(in_ptr0 + (tmp59 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp61 = tl.load(in_ptr1 + (tmp59 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp62 = tmp60 + tmp61
tmp63 = tmp30 - tmp31
tmp64 = tmp63 * tmp49
tmp65 = tmp64 - tmp51
tmp66 = tmp65 * tmp63
tmp67 = tmp66 * tmp63
tmp68 = tmp67 + tmp30
tmp69 = tmp62 * tmp68
tmp70 = tl.full([1], 2, tl.int64)
tmp71 = tmp20 + tmp70
tmp72 = triton_helpers.maximum(tmp71, tmp10)
tmp73 = triton_helpers.minimum(tmp72, tmp12)
tmp74 = tl.load(in_ptr0 + (tmp73 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp75 = tl.load(in_ptr1 + (tmp73 + 8 * tmp13 + 64 * x2), None,
eviction_policy='evict_last')
tmp76 = tmp74 + tmp75
tmp77 = 2.0
tmp78 = tmp77 - tmp31
tmp79 = tmp78 * tmp33
tmp80 = tmp79 - tmp35
tmp81 = tmp80 * tmp78
tmp82 = tmp81 + tmp38
tmp83 = tmp82 * tmp78
tmp84 = tmp83 - tmp41
tmp85 = tmp76 * tmp84
tmp86 = tmp43 + tmp56
tmp87 = tmp86 + tmp69
tmp88 = tmp87 + tmp85
tmp89 = tmp5 - tmp6
tmp90 = triton_helpers.maximum(tmp89, tmp28)
tmp91 = triton_helpers.minimum(tmp90, tmp30)
tmp92 = tmp91 + tmp30
tmp93 = tmp92 * tmp33
tmp94 = tmp93 - tmp35
tmp95 = tmp94 * tmp92
tmp96 = tmp95 + tmp38
tmp97 = tmp96 * tmp92
tmp98 = tmp97 - tmp41
tmp99 = tmp88 * tmp98
tmp100 = triton_helpers.maximum(tmp7, tmp10)
tmp101 = triton_helpers.minimum(tmp100, tmp12)
tmp102 = tl.load(in_ptr0 + (tmp23 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp103 = tl.load(in_ptr1 + (tmp23 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp104 = tmp102 + tmp103
tmp105 = tmp104 * tmp42
tmp106 = tl.load(in_ptr0 + (tmp45 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp107 = tl.load(in_ptr1 + (tmp45 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp108 = tmp106 + tmp107
tmp109 = tmp108 * tmp55
tmp110 = tl.load(in_ptr0 + (tmp59 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp111 = tl.load(in_ptr1 + (tmp59 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp112 = tmp110 + tmp111
tmp113 = tmp112 * tmp68
tmp114 = tl.load(in_ptr0 + (tmp73 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp115 = tl.load(in_ptr1 + (tmp73 + 8 * tmp101 + 64 * x2), None,
eviction_policy='evict_last')
tmp116 = tmp114 + tmp115
tmp117 = tmp116 * tmp84
tmp118 = tmp7 + tmp8
tmp119 = triton_helpers.maximum(tmp118, tmp10)
tmp120 = triton_helpers.minimum(tmp119, tmp12)
tmp121 = tl.load(in_ptr0 + (tmp23 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp122 = tl.load(in_ptr1 + (tmp23 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp123 = tmp121 + tmp122
tmp124 = tmp123 * tmp42
tmp125 = tl.load(in_ptr0 + (tmp45 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp126 = tl.load(in_ptr1 + (tmp45 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp127 = tmp125 + tmp126
tmp128 = tmp127 * tmp55
tmp129 = tl.load(in_ptr0 + (tmp59 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp130 = tl.load(in_ptr1 + (tmp59 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp131 = tmp129 + tmp130
tmp132 = tmp131 * tmp68
tmp133 = tl.load(in_ptr0 + (tmp73 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp134 = tl.load(in_ptr1 + (tmp73 + 8 * tmp120 + 64 * x2), None,
eviction_policy='evict_last')
tmp135 = tmp133 + tmp134
tmp136 = tmp135 * tmp84
tmp137 = tmp105 + tmp109
tmp138 = tmp137 + tmp113
tmp139 = tmp138 + tmp117
tmp140 = tmp91 * tmp49
tmp141 = tmp140 - tmp51
tmp142 = tmp141 * tmp91
tmp143 = tmp142 * tmp91
tmp144 = tmp143 + tmp30
tmp145 = tmp139 * tmp144
tmp146 = tmp99 + tmp145
tmp147 = tmp124 + tmp128
tmp148 = tmp147 + tmp132
tmp149 = tmp148 + tmp136
tmp150 = tmp30 - tmp91
tmp151 = tmp150 * tmp49
tmp152 = tmp151 - tmp51
tmp153 = tmp152 * tmp150
tmp154 = tmp153 * tmp150
tmp155 = tmp154 + tmp30
tmp156 = tmp149 * tmp155
tmp157 = tmp146 + tmp156
tmp158 = tmp7 + tmp70
tmp159 = triton_helpers.maximum(tmp158, tmp10)
tmp160 = triton_helpers.minimum(tmp159, tmp12)
tmp161 = tl.load(in_ptr0 + (tmp23 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp162 = tl.load(in_ptr1 + (tmp23 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp163 = tmp161 + tmp162
tmp164 = tmp163 * tmp42
tmp165 = tl.load(in_ptr0 + (tmp45 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp166 = tl.load(in_ptr1 + (tmp45 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp167 = tmp165 + tmp166
tmp168 = tmp167 * tmp55
tmp169 = tl.load(in_ptr0 + (tmp59 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp170 = tl.load(in_ptr1 + (tmp59 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp171 = tmp169 + tmp170
tmp172 = tmp171 * tmp68
tmp173 = tl.load(in_ptr0 + (tmp73 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp174 = tl.load(in_ptr1 + (tmp73 + 8 * tmp160 + 64 * x2), None,
eviction_policy='evict_last')
tmp175 = tmp173 + tmp174
tmp176 = tmp175 * tmp84
tmp177 = tmp164 + tmp168
tmp178 = tmp177 + tmp172
tmp179 = tmp178 + tmp176
tmp180 = tmp77 - tmp91
tmp181 = tmp180 * tmp33
tmp182 = tmp181 - tmp35
tmp183 = tmp182 * tmp180
tmp184 = tmp183 + tmp38
tmp185 = tmp184 * tmp180
tmp186 = tmp185 - tmp41
tmp187 = tmp179 * tmp186
tl.store(in_out_ptr0 + x4, tmp157, None)
tl.store(in_out_ptr1 + x4, tmp187, None)
@triton.jit
def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_2(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 32 % 32
x0 = xindex % 32
x2 = xindex // 1024
x4 = xindex
tmp0 = x1
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = libdevice.floor(tmp5)
tmp7 = tmp6.to(tl.int32)
tmp8 = tl.full([1], 1, tl.int64)
tmp9 = tmp7 - tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full([1], 15, tl.int64)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tmp14 = x0
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp15 + tmp2
tmp17 = tmp16 * tmp2
tmp18 = tmp17 - tmp2
tmp19 = libdevice.floor(tmp18)
tmp20 = tmp19.to(tl.int32)
tmp21 = tmp20 - tmp8
tmp22 = triton_helpers.maximum(tmp21, tmp10)
tmp23 = triton_helpers.minimum(tmp22, tmp12)
tmp24 = tl.load(in_ptr0 + (tmp23 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp25 = tl.load(in_ptr1 + (tmp23 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp26 = tmp24 + tmp25
tmp27 = tmp18 - tmp19
tmp28 = 0.0
tmp29 = triton_helpers.maximum(tmp27, tmp28)
tmp30 = 1.0
tmp31 = triton_helpers.minimum(tmp29, tmp30)
tmp32 = tmp31 + tmp30
tmp33 = -0.75
tmp34 = tmp32 * tmp33
tmp35 = -3.75
tmp36 = tmp34 - tmp35
tmp37 = tmp36 * tmp32
tmp38 = -6.0
tmp39 = tmp37 + tmp38
tmp40 = tmp39 * tmp32
tmp41 = -3.0
tmp42 = tmp40 - tmp41
tmp43 = tmp26 * tmp42
tmp44 = triton_helpers.maximum(tmp20, tmp10)
tmp45 = triton_helpers.minimum(tmp44, tmp12)
tmp46 = tl.load(in_ptr0 + (tmp45 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp47 = tl.load(in_ptr1 + (tmp45 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp48 = tmp46 + tmp47
tmp49 = 1.25
tmp50 = tmp31 * tmp49
tmp51 = 2.25
tmp52 = tmp50 - tmp51
tmp53 = tmp52 * tmp31
tmp54 = tmp53 * tmp31
tmp55 = tmp54 + tmp30
tmp56 = tmp48 * tmp55
tmp57 = tmp20 + tmp8
tmp58 = triton_helpers.maximum(tmp57, tmp10)
tmp59 = triton_helpers.minimum(tmp58, tmp12)
tmp60 = tl.load(in_ptr0 + (tmp59 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp61 = tl.load(in_ptr1 + (tmp59 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp62 = tmp60 + tmp61
tmp63 = tmp30 - tmp31
tmp64 = tmp63 * tmp49
tmp65 = tmp64 - tmp51
tmp66 = tmp65 * tmp63
tmp67 = tmp66 * tmp63
tmp68 = tmp67 + tmp30
tmp69 = tmp62 * tmp68
tmp70 = tl.full([1], 2, tl.int64)
tmp71 = tmp20 + tmp70
tmp72 = triton_helpers.maximum(tmp71, tmp10)
tmp73 = triton_helpers.minimum(tmp72, tmp12)
tmp74 = tl.load(in_ptr0 + (tmp73 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp75 = tl.load(in_ptr1 + (tmp73 + 16 * tmp13 + 256 * x2), None,
eviction_policy='evict_last')
tmp76 = tmp74 + tmp75
tmp77 = 2.0
tmp78 = tmp77 - tmp31
tmp79 = tmp78 * tmp33
tmp80 = tmp79 - tmp35
tmp81 = tmp80 * tmp78
tmp82 = tmp81 + tmp38
tmp83 = tmp82 * tmp78
tmp84 = tmp83 - tmp41
tmp85 = tmp76 * tmp84
tmp86 = tmp43 + tmp56
tmp87 = tmp86 + tmp69
tmp88 = tmp87 + tmp85
tmp89 = tmp5 - tmp6
tmp90 = triton_helpers.maximum(tmp89, tmp28)
tmp91 = triton_helpers.minimum(tmp90, tmp30)
tmp92 = tmp91 + tmp30
tmp93 = tmp92 * tmp33
tmp94 = tmp93 - tmp35
tmp95 = tmp94 * tmp92
tmp96 = tmp95 + tmp38
tmp97 = tmp96 * tmp92
tmp98 = tmp97 - tmp41
tmp99 = tmp88 * tmp98
tmp100 = triton_helpers.maximum(tmp7, tmp10)
tmp101 = triton_helpers.minimum(tmp100, tmp12)
tmp102 = tl.load(in_ptr0 + (tmp23 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp103 = tl.load(in_ptr1 + (tmp23 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp104 = tmp102 + tmp103
tmp105 = tmp104 * tmp42
tmp106 = tl.load(in_ptr0 + (tmp45 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp107 = tl.load(in_ptr1 + (tmp45 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp108 = tmp106 + tmp107
tmp109 = tmp108 * tmp55
tmp110 = tl.load(in_ptr0 + (tmp59 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp111 = tl.load(in_ptr1 + (tmp59 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp112 = tmp110 + tmp111
tmp113 = tmp112 * tmp68
tmp114 = tl.load(in_ptr0 + (tmp73 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp115 = tl.load(in_ptr1 + (tmp73 + 16 * tmp101 + 256 * x2), None,
eviction_policy='evict_last')
tmp116 = tmp114 + tmp115
tmp117 = tmp116 * tmp84
tmp118 = tmp7 + tmp8
tmp119 = triton_helpers.maximum(tmp118, tmp10)
tmp120 = triton_helpers.minimum(tmp119, tmp12)
tmp121 = tl.load(in_ptr0 + (tmp23 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp122 = tl.load(in_ptr1 + (tmp23 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp123 = tmp121 + tmp122
tmp124 = tmp123 * tmp42
tmp125 = tl.load(in_ptr0 + (tmp45 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp126 = tl.load(in_ptr1 + (tmp45 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp127 = tmp125 + tmp126
tmp128 = tmp127 * tmp55
tmp129 = tl.load(in_ptr0 + (tmp59 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp130 = tl.load(in_ptr1 + (tmp59 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp131 = tmp129 + tmp130
tmp132 = tmp131 * tmp68
tmp133 = tl.load(in_ptr0 + (tmp73 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp134 = tl.load(in_ptr1 + (tmp73 + 16 * tmp120 + 256 * x2), None,
eviction_policy='evict_last')
tmp135 = tmp133 + tmp134
tmp136 = tmp135 * tmp84
tmp137 = tmp105 + tmp109
tmp138 = tmp137 + tmp113
tmp139 = tmp138 + tmp117
tmp140 = tmp91 * tmp49
tmp141 = tmp140 - tmp51
tmp142 = tmp141 * tmp91
tmp143 = tmp142 * tmp91
tmp144 = tmp143 + tmp30
tmp145 = tmp139 * tmp144
tmp146 = tmp99 + tmp145
tmp147 = tmp124 + tmp128
tmp148 = tmp147 + tmp132
tmp149 = tmp148 + tmp136
tmp150 = tmp30 - tmp91
tmp151 = tmp150 * tmp49
tmp152 = tmp151 - tmp51
tmp153 = tmp152 * tmp150
tmp154 = tmp153 * tmp150
tmp155 = tmp154 + tmp30
tmp156 = tmp149 * tmp155
tmp157 = tmp146 + tmp156
tmp158 = tmp7 + tmp70
tmp159 = triton_helpers.maximum(tmp158, tmp10)
tmp160 = triton_helpers.minimum(tmp159, tmp12)
tmp161 = tl.load(in_ptr0 + (tmp23 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp162 = tl.load(in_ptr1 + (tmp23 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp163 = tmp161 + tmp162
tmp164 = tmp163 * tmp42
tmp165 = tl.load(in_ptr0 + (tmp45 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp166 = tl.load(in_ptr1 + (tmp45 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp167 = tmp165 + tmp166
tmp168 = tmp167 * tmp55
tmp169 = tl.load(in_ptr0 + (tmp59 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp170 = tl.load(in_ptr1 + (tmp59 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp171 = tmp169 + tmp170
tmp172 = tmp171 * tmp68
tmp173 = tl.load(in_ptr0 + (tmp73 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp174 = tl.load(in_ptr1 + (tmp73 + 16 * tmp160 + 256 * x2), None,
eviction_policy='evict_last')
tmp175 = tmp173 + tmp174
tmp176 = tmp175 * tmp84
tmp177 = tmp164 + tmp168
tmp178 = tmp177 + tmp172
tmp179 = tmp178 + tmp176
tmp180 = tmp77 - tmp91
tmp181 = tmp180 * tmp33
tmp182 = tmp181 - tmp35
tmp183 = tmp182 * tmp180
tmp184 = tmp183 + tmp38
tmp185 = tmp184 * tmp180
tmp186 = tmp185 - tmp41
tmp187 = tmp179 * tmp186
tl.store(in_out_ptr0 + x4, tmp157, None)
tl.store(in_out_ptr1 + x4, tmp187, None)
@triton.jit
def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_3(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 64 % 64
x0 = xindex % 64
x2 = xindex // 4096
x3 = xindex
tmp0 = x1
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = libdevice.floor(tmp5)
tmp7 = tmp6.to(tl.int32)
tmp8 = tl.full([1], 1, tl.int64)
tmp9 = tmp7 - tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full([1], 31, tl.int64)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tmp14 = x0
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp15 + tmp2
tmp17 = tmp16 * tmp2
tmp18 = tmp17 - tmp2
tmp19 = libdevice.floor(tmp18)
tmp20 = tmp19.to(tl.int32)
tmp21 = tmp20 - tmp8
tmp22 = triton_helpers.maximum(tmp21, tmp10)
tmp23 = triton_helpers.minimum(tmp22, tmp12)
tmp24 = tl.load(in_ptr0 + (tmp23 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp25 = tl.load(in_ptr1 + (tmp23 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp26 = tmp24 + tmp25
tmp27 = tmp18 - tmp19
tmp28 = 0.0
tmp29 = triton_helpers.maximum(tmp27, tmp28)
tmp30 = 1.0
tmp31 = triton_helpers.minimum(tmp29, tmp30)
tmp32 = tmp31 + tmp30
tmp33 = -0.75
tmp34 = tmp32 * tmp33
tmp35 = -3.75
tmp36 = tmp34 - tmp35
tmp37 = tmp36 * tmp32
tmp38 = -6.0
tmp39 = tmp37 + tmp38
tmp40 = tmp39 * tmp32
tmp41 = -3.0
tmp42 = tmp40 - tmp41
tmp43 = tmp26 * tmp42
tmp44 = triton_helpers.maximum(tmp20, tmp10)
tmp45 = triton_helpers.minimum(tmp44, tmp12)
tmp46 = tl.load(in_ptr0 + (tmp45 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp47 = tl.load(in_ptr1 + (tmp45 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp48 = tmp46 + tmp47
tmp49 = 1.25
tmp50 = tmp31 * tmp49
tmp51 = 2.25
tmp52 = tmp50 - tmp51
tmp53 = tmp52 * tmp31
tmp54 = tmp53 * tmp31
tmp55 = tmp54 + tmp30
tmp56 = tmp48 * tmp55
tmp57 = tmp20 + tmp8
tmp58 = triton_helpers.maximum(tmp57, tmp10)
tmp59 = triton_helpers.minimum(tmp58, tmp12)
tmp60 = tl.load(in_ptr0 + (tmp59 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp61 = tl.load(in_ptr1 + (tmp59 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp62 = tmp60 + tmp61
tmp63 = tmp30 - tmp31
tmp64 = tmp63 * tmp49
tmp65 = tmp64 - tmp51
tmp66 = tmp65 * tmp63
tmp67 = tmp66 * tmp63
tmp68 = tmp67 + tmp30
tmp69 = tmp62 * tmp68
tmp70 = tl.full([1], 2, tl.int64)
tmp71 = tmp20 + tmp70
tmp72 = triton_helpers.maximum(tmp71, tmp10)
tmp73 = triton_helpers.minimum(tmp72, tmp12)
tmp74 = tl.load(in_ptr0 + (tmp73 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp75 = tl.load(in_ptr1 + (tmp73 + 32 * tmp13 + 1024 * x2), None,
eviction_policy='evict_last')
tmp76 = tmp74 + tmp75
tmp77 = 2.0
tmp78 = tmp77 - tmp31
tmp79 = tmp78 * tmp33
tmp80 = tmp79 - tmp35
tmp81 = tmp80 * tmp78
tmp82 = tmp81 + tmp38
tmp83 = tmp82 * tmp78
tmp84 = tmp83 - tmp41
tmp85 = tmp76 * tmp84
tmp86 = tmp43 + tmp56
tmp87 = tmp86 + tmp69
tmp88 = tmp87 + tmp85
tmp89 = tmp5 - tmp6
tmp90 = triton_helpers.maximum(tmp89, tmp28)
tmp91 = triton_helpers.minimum(tmp90, tmp30)
tmp92 = tmp91 + tmp30
tmp93 = tmp92 * tmp33
tmp94 = tmp93 - tmp35
tmp95 = tmp94 * tmp92
tmp96 = tmp95 + tmp38
tmp97 = tmp96 * tmp92
tmp98 = tmp97 - tmp41
tmp99 = tmp88 * tmp98
tmp100 = triton_helpers.maximum(tmp7, tmp10)
tmp101 = triton_helpers.minimum(tmp100, tmp12)
tmp102 = tl.load(in_ptr0 + (tmp23 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp103 = tl.load(in_ptr1 + (tmp23 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp104 = tmp102 + tmp103
tmp105 = tmp104 * tmp42
tmp106 = tl.load(in_ptr0 + (tmp45 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp107 = tl.load(in_ptr1 + (tmp45 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp108 = tmp106 + tmp107
tmp109 = tmp108 * tmp55
tmp110 = tl.load(in_ptr0 + (tmp59 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp111 = tl.load(in_ptr1 + (tmp59 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp112 = tmp110 + tmp111
tmp113 = tmp112 * tmp68
tmp114 = tl.load(in_ptr0 + (tmp73 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp115 = tl.load(in_ptr1 + (tmp73 + 32 * tmp101 + 1024 * x2), None,
eviction_policy='evict_last')
tmp116 = tmp114 + tmp115
tmp117 = tmp116 * tmp84
tmp118 = tmp7 + tmp8
tmp119 = triton_helpers.maximum(tmp118, tmp10)
tmp120 = triton_helpers.minimum(tmp119, tmp12)
tmp121 = tl.load(in_ptr0 + (tmp23 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp122 = tl.load(in_ptr1 + (tmp23 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp123 = tmp121 + tmp122
tmp124 = tmp123 * tmp42
tmp125 = tl.load(in_ptr0 + (tmp45 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp126 = tl.load(in_ptr1 + (tmp45 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp127 = tmp125 + tmp126
tmp128 = tmp127 * tmp55
tmp129 = tl.load(in_ptr0 + (tmp59 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp130 = tl.load(in_ptr1 + (tmp59 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp131 = tmp129 + tmp130
tmp132 = tmp131 * tmp68
tmp133 = tl.load(in_ptr0 + (tmp73 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp134 = tl.load(in_ptr1 + (tmp73 + 32 * tmp120 + 1024 * x2), None,
eviction_policy='evict_last')
tmp135 = tmp133 + tmp134
tmp136 = tmp135 * tmp84
tmp137 = tmp105 + tmp109
tmp138 = tmp137 + tmp113
tmp139 = tmp138 + tmp117
tmp140 = tmp91 * tmp49
tmp141 = tmp140 - tmp51
tmp142 = tmp141 * tmp91
tmp143 = tmp142 * tmp91
tmp144 = tmp143 + tmp30
tmp145 = tmp139 * tmp144
tmp146 = tmp99 + tmp145
tmp147 = tmp124 + tmp128
tmp148 = tmp147 + tmp132
tmp149 = tmp148 + tmp136
tmp150 = tmp30 - tmp91
tmp151 = tmp150 * tmp49
tmp152 = tmp151 - tmp51
tmp153 = tmp152 * tmp150
tmp154 = tmp153 * tmp150
tmp155 = tmp154 + tmp30
tmp156 = tmp149 * tmp155
tmp157 = tmp146 + tmp156
tmp158 = tmp7 + tmp70
tmp159 = triton_helpers.maximum(tmp158, tmp10)
tmp160 = triton_helpers.minimum(tmp159, tmp12)
tmp161 = tl.load(in_ptr0 + (tmp23 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp162 = tl.load(in_ptr1 + (tmp23 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp163 = tmp161 + tmp162
tmp164 = tmp163 * tmp42
tmp165 = tl.load(in_ptr0 + (tmp45 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp166 = tl.load(in_ptr1 + (tmp45 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp167 = tmp165 + tmp166
tmp168 = tmp167 * tmp55
tmp169 = tl.load(in_ptr0 + (tmp59 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp170 = tl.load(in_ptr1 + (tmp59 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp171 = tmp169 + tmp170
tmp172 = tmp171 * tmp68
tmp173 = tl.load(in_ptr0 + (tmp73 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp174 = tl.load(in_ptr1 + (tmp73 + 32 * tmp160 + 1024 * x2), None,
eviction_policy='evict_last')
tmp175 = tmp173 + tmp174
tmp176 = tmp175 * tmp84
tmp177 = tmp164 + tmp168
tmp178 = tmp177 + tmp172
tmp179 = tmp178 + tmp176
tmp180 = tmp77 - tmp91
tmp181 = tmp180 * tmp33
tmp182 = tmp181 - tmp35
tmp183 = tmp182 * tmp180
tmp184 = tmp183 + tmp38
tmp185 = tmp184 * tmp180
tmp186 = tmp185 - tmp41
tmp187 = tmp179 * tmp186
tmp188 = tmp157 + tmp187
tl.store(in_out_ptr0 + x3, tmp188, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf10 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32
)
buf13 = buf10
del buf10
buf14 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32
)
buf18 = buf14
del buf14
get_raw_stream(0)
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_0[
grid(1024)](buf13, buf18, arg0_1, 1024, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
buf19 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1),
torch.float32)
buf23 = buf19
del buf19
buf32 = buf23
del buf23
buf33 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1),
torch.float32)
buf37 = buf33
del buf33
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_1[
grid(4096)](buf32, buf37, buf13, buf18, 4096, XBLOCK=128,
num_warps=4, num_stages=1)
del buf13
del buf18
buf38 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1),
torch.float32)
buf42 = buf38
del buf38
buf51 = buf42
del buf42
buf52 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1),
torch.float32)
buf56 = buf52
del buf52
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_2[
grid(16384)](buf51, buf56, buf32, buf37, 16384, XBLOCK=128,
num_warps=4, num_stages=1)
del buf32
del buf37
buf57 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.float32)
buf61 = buf57
del buf57
buf70 = buf61
del buf61
buf76 = buf70
del buf70
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_3[
grid(65536)](buf76, buf51, buf56, 65536, XBLOCK=256, num_warps=
4, num_stages=1)
del buf51
del buf56
return buf76,
class UpsampleNew(nn.Module):
def __init__(self, n_iter):
super(UpsampleNew, self).__init__()
self.n_iter = n_iter
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
AyushExel/GANSketching
|
Upsample
| false
| 13,442
|
[
"MIT"
] | 598
|
c72524ac4425de898087af7a4c554b777a4e2218
|
https://github.com/AyushExel/GANSketching/tree/c72524ac4425de898087af7a4c554b777a4e2218
|
MLP
|
import torch
import torch.nn as nn
class SharedDropout(nn.Module):
def __init__(self, p=0.5, batch_first=True):
super(SharedDropout, self).__init__()
self.p = p
self.batch_first = batch_first
def extra_repr(self):
info = f'p={self.p}'
if self.batch_first:
info += f', batch_first={self.batch_first}'
return info
def forward(self, x):
if self.training:
if self.batch_first:
mask = self.get_mask(x[:, 0], self.p)
else:
mask = self.get_mask(x[0], self.p)
x *= mask.unsqueeze(1) if self.batch_first else mask
return x
@staticmethod
def get_mask(x, p):
mask = x.new_full(x.shape, 1 - p)
mask = torch.bernoulli(mask) / (1 - p)
return mask
class MLP(nn.Module):
def __init__(self, n_in, n_hidden, dropout):
super(MLP, self).__init__()
self.linear = nn.Linear(n_in, n_hidden)
self.activation = nn.LeakyReLU(negative_slope=0.1)
self.dropout = SharedDropout(dropout)
self.reset_parameters()
def reset_parameters(self):
nn.init.orthogonal_(self.linear.weight)
nn.init.zeros_(self.linear.bias)
def forward(self, x):
x = self.linear(x)
x = self.activation(x)
x = self.dropout(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 4, 'n_hidden': 4, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(256)](buf0, primals_2, buf1,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf1
class SharedDropout(nn.Module):
def __init__(self, p=0.5, batch_first=True):
super(SharedDropout, self).__init__()
self.p = p
self.batch_first = batch_first
def extra_repr(self):
info = f'p={self.p}'
if self.batch_first:
info += f', batch_first={self.batch_first}'
return info
def forward(self, x):
if self.training:
if self.batch_first:
mask = self.get_mask(x[:, 0], self.p)
else:
mask = self.get_mask(x[0], self.p)
x *= mask.unsqueeze(1) if self.batch_first else mask
return x
@staticmethod
def get_mask(x, p):
mask = x.new_full(x.shape, 1 - p)
mask = torch.bernoulli(mask) / (1 - p)
return mask
class MLPNew(nn.Module):
def __init__(self, n_in, n_hidden, dropout):
super(MLPNew, self).__init__()
self.linear = nn.Linear(n_in, n_hidden)
self.activation = nn.LeakyReLU(negative_slope=0.1)
self.dropout = SharedDropout(dropout)
self.reset_parameters()
def reset_parameters(self):
nn.init.orthogonal_(self.linear.weight)
nn.init.zeros_(self.linear.bias)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
CNLPT/lightNLP
|
MLP
| false
| 13,443
|
[
"Apache-2.0"
] | 889
|
c7f128422ba5b16f514bb294145cb3b562e95829
|
https://github.com/CNLPT/lightNLP/tree/c7f128422ba5b16f514bb294145cb3b562e95829
|
AttentionModule
|
import torch
from torch import nn
import torch.nn.functional as F
class AttentionModule(nn.Module):
def __init__(self, d_model, d_k=None, device='cpu', dropout=None):
super().__init__()
if not d_k:
d_k = d_model
self.W = nn.Parameter(torch.randn(d_model, d_model, device=device))
self.bias = nn.Parameter(torch.randn(1, device=device))
self.dropout = dropout
self.norm = nn.LayerNorm(d_model)
def forward(self, key, query, value):
key = self.norm(key)
query = self.norm(query)
value = self.norm(value)
query_W_key = torch.bmm(torch.matmul(query, self.W), key.transpose(
-2, -1))
if self.dropout:
query_W_key = self.dropout(query_W_key)
weights = F.softmax(torch.tanh(query_W_key + self.bias), dim=-1)
return weights, torch.bmm(weights, value)
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}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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
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, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10,
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
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')
tmp9 = tl.load(in_ptr5 + x2, xmask)
tmp10 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr7 + x1, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr8 + x2, xmask)
tmp17 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr10 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp11 = tmp9 - tmp10
tmp13 = tmp11 * tmp12
tmp14 = tmp13 * tmp5
tmp15 = tmp14 + tmp7
tmp18 = tmp16 - tmp17
tmp20 = tmp18 * tmp19
tmp21 = tmp20 * tmp5
tmp22 = tmp21 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp22, xmask)
@triton.jit
def triton_poi_fused__softmax_add_tanh_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 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp0 + tmp2
tmp4 = libdevice.tanh(tmp3)
tmp6 = tmp5 + tmp2
tmp7 = libdevice.tanh(tmp6)
tmp8 = triton_helpers.maximum(tmp4, tmp7)
tmp10 = tmp9 + tmp2
tmp11 = libdevice.tanh(tmp10)
tmp12 = triton_helpers.maximum(tmp8, tmp11)
tmp14 = tmp13 + tmp2
tmp15 = libdevice.tanh(tmp14)
tmp16 = triton_helpers.maximum(tmp12, tmp15)
tmp17 = tmp4 - tmp16
tmp18 = tl_math.exp(tmp17)
tmp19 = tmp7 - tmp16
tmp20 = tl_math.exp(tmp19)
tmp21 = tmp18 + tmp20
tmp22 = tmp11 - tmp16
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp21 + tmp23
tmp25 = tmp15 - tmp16
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp24 + tmp26
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp27, xmask)
@triton.jit
def triton_poi_fused__softmax_add_tanh_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp5 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp0 + tmp2
tmp4 = libdevice.tanh(tmp3)
tmp6 = tmp4 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp9 = tmp7 / tmp8
tl.store(out_ptr0 + x2, tmp9, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_3, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf3 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_4, buf2,
buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_5, buf4,
buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf9 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](primals_5, buf4,
buf5, primals_1, primals_2, primals_4, buf2, buf3, primals_3,
buf0, buf1, buf6, buf7, buf9, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf0
del buf1
del buf2
del buf3
del primals_1
del primals_2
buf8 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (16, 4), (4, 1), 0),
primals_6, out=buf8)
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf8, (4, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (4, 4, 4), (16, 1, 4), 0), out=buf10)
buf11 = buf5
del buf5
buf12 = buf4
del buf4
triton_poi_fused__softmax_add_tanh_2[grid(16)](buf10, primals_7,
buf11, buf12, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_add_tanh_3[grid(64)](buf10, primals_7,
buf11, buf12, buf13, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf11
del buf12
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf13, buf6, out=buf14)
return (buf13, buf14, primals_3, primals_4, primals_5, primals_7, buf10,
buf13, reinterpret_tensor(buf6, (4, 4, 4), (16, 1, 4), 0),
reinterpret_tensor(buf8, (4, 4, 4), (16, 1, 4), 0), buf9,
reinterpret_tensor(buf7, (4, 16), (1, 4), 0), reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0))
class AttentionModuleNew(nn.Module):
def __init__(self, d_model, d_k=None, device='cpu', dropout=None):
super().__init__()
if not d_k:
d_k = d_model
self.W = nn.Parameter(torch.randn(d_model, d_model, device=device))
self.bias = nn.Parameter(torch.randn(1, device=device))
self.dropout = dropout
self.norm = nn.LayerNorm(d_model)
def forward(self, input_0, input_1, input_2):
primals_6 = self.W
primals_7 = self.bias
primals_1 = self.norm.weight
primals_2 = self.norm.bias
primals_3 = input_0
primals_4 = input_1
primals_5 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
BruceWen120/medical-abbreviation-pretraining
|
AttentionModule
| false
| 13,444
|
[
"Apache-2.0",
"MIT"
] | 125
|
333e49461f7463e97515f949f441c7ac8af7d980
|
https://github.com/BruceWen120/medical-abbreviation-pretraining/tree/333e49461f7463e97515f949f441c7ac8af7d980
|
Resv1Block
|
import torch
import torch.nn as nn
def conv3x3(in_channels, out_channels, stride=1, padding=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_channels, out_channels, 3, stride, padding, bias=True)
class Resv1Block(nn.Module):
"""ResNet v1 block without bn"""
def __init__(self, inplanes, planes, stride=1):
super(Resv1Block, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.relu1 = nn.ReLU()
self.conv2 = conv3x3(planes, planes, stride)
self.relu2 = nn.ReLU()
def forward(self, x):
out = self.conv1(x)
out = self.relu1(out)
out = self.conv2(out)
out += x
out = self.relu2(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_convolution_relu_threshold_backward_1(in_out_ptr0,
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + 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 + x3, tmp6, xmask)
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, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_convolution_relu_threshold_backward_1[grid(256)](
buf3, primals_5, primals_3, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1, buf4
def conv3x3(in_channels, out_channels, stride=1, padding=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_channels, out_channels, 3, stride, padding, bias=True)
class Resv1BlockNew(nn.Module):
"""ResNet v1 block without bn"""
def __init__(self, inplanes, planes, stride=1):
super(Resv1BlockNew, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.relu1 = nn.ReLU()
self.conv2 = conv3x3(planes, planes, stride)
self.relu2 = nn.ReLU()
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
CNN-NISER/lffd-pytorch
|
Resv1Block
| false
| 13,445
|
[
"MIT"
] | 220
|
7d6476ece79cf75c6265c89346ddac48929ce8f6
|
https://github.com/CNN-NISER/lffd-pytorch/tree/7d6476ece79cf75c6265c89346ddac48929ce8f6
|
Conv
|
import torch
import torch.utils.data
from torch import nn
class Conv(nn.Module):
def __init__(self, inp_dim, out_dim, kernel_size=3, stride=1, bn=False,
relu=True):
super(Conv, self).__init__()
self.inp_dim = inp_dim
self.conv = nn.Conv2d(inp_dim, out_dim, kernel_size, stride,
padding=(kernel_size - 1) // 2, bias=True)
self.relu = None
self.bn = None
if relu:
self.relu = nn.ReLU()
if bn:
self.bn = nn.BatchNorm2d(out_dim)
def forward(self, x):
assert x.size()[1] == self.inp_dim, '{} {}'.format(x.size()[1],
self.inp_dim)
x = self.conv(x)
if self.relu is not None:
x = self.relu(x)
if self.bn is not None:
x = self.bn(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inp_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
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_0(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_convolution_relu_threshold_backward_0[grid(256)](buf1,
primals_3, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
return buf1, primals_1, primals_2, buf2
class ConvNew(nn.Module):
def __init__(self, inp_dim, out_dim, kernel_size=3, stride=1, bn=False,
relu=True):
super(ConvNew, self).__init__()
self.inp_dim = inp_dim
self.conv = nn.Conv2d(inp_dim, out_dim, kernel_size, stride,
padding=(kernel_size - 1) // 2, bias=True)
self.relu = None
self.bn = None
if relu:
self.relu = nn.ReLU()
if bn:
self.bn = nn.BatchNorm2d(out_dim)
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]
|
CenIII/pose-ae-train
|
Conv
| false
| 13,446
|
[
"BSD-3-Clause"
] | 250
|
8780ba9f3d80ca3a724bbee7b815073adc3d3e6e
|
https://github.com/CenIII/pose-ae-train/tree/8780ba9f3d80ca3a724bbee7b815073adc3d3e6e
|
L2Norm
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class L2Norm(nn.Module):
"""L2Norm layer across all channels."""
def __init__(self, in_features, scale):
super(L2Norm, self).__init__()
self.weight = nn.Parameter(torch.Tensor(in_features))
self.reset_parameters(scale)
def reset_parameters(self, scale):
nn.init.constant(self.weight, scale)
def forward(self, x):
x = F.normalize(x, dim=1)
scale = self.weight[None, :, None, None]
return scale * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'scale': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 4
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), 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 = libdevice.sqrt(tmp12)
tmp14 = 1e-12
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp16 = tmp1 / tmp15
tmp17 = tmp0 * tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_mul_0[grid(256)](primals_2, primals_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf0, primals_1
class L2NormNew(nn.Module):
"""L2Norm layer across all channels."""
def __init__(self, in_features, scale):
super(L2NormNew, self).__init__()
self.weight = nn.Parameter(torch.Tensor(in_features))
self.reset_parameters(scale)
def reset_parameters(self, scale):
nn.init.constant(self.weight, scale)
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
CVHj/torchcv
|
L2Norm
| false
| 13,447
|
[
"MIT"
] | 433
|
6291f3e1e4bbf6467fd6b1e79001d34a59481bb6
|
https://github.com/CVHj/torchcv/tree/6291f3e1e4bbf6467fd6b1e79001d34a59481bb6
|
BranchNet
|
import torch
import torch.nn as nn
def conv1x1(in_channels, out_channels):
"""1x1 convolution"""
return nn.Conv2d(in_channels, out_channels, 1, bias=True)
class BranchNet(nn.Module):
"""
The branch of NaiveNet is the network output and
only consists of conv 1×1 and ReLU.
"""
def __init__(self, inplanes, planes):
super(BranchNet, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.conv2_score = conv1x1(planes, planes)
self.conv3_score = conv1x1(planes, 2)
self.conv2_bbox = conv1x1(planes, planes)
self.conv3_bbox = conv1x1(planes, 4)
self.relu = nn.ReLU()
def forward(self, x):
out = self.conv1(x)
out = self.relu(out)
out_score = self.conv2_score(out)
out_score = self.relu(out_score)
out_score = self.conv3_score(out_score)
out_bbox = self.conv2_bbox(out)
out_bbox = self.relu(out_bbox)
out_bbox = self.conv3_bbox(out_bbox)
return out_score, out_bbox
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_1(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_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)
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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (2,), (1,))
assert_size_stride(primals_8, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(256)](buf3, primals_5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 2, 4, 4), (32, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_1[grid(128)](buf5, primals_7, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf1, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_0[grid(256)](buf7, primals_9, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf8 = extern_kernels.convolution(buf7, primals_10, 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_11, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_11
return (buf5, buf9, primals_1, primals_3, primals_4, primals_6,
primals_8, primals_10, buf1, buf3, buf7)
def conv1x1(in_channels, out_channels):
"""1x1 convolution"""
return nn.Conv2d(in_channels, out_channels, 1, bias=True)
class BranchNetNew(nn.Module):
"""
The branch of NaiveNet is the network output and
only consists of conv 1×1 and ReLU.
"""
def __init__(self, inplanes, planes):
super(BranchNetNew, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.conv2_score = conv1x1(planes, planes)
self.conv3_score = conv1x1(planes, 2)
self.conv2_bbox = conv1x1(planes, planes)
self.conv3_bbox = conv1x1(planes, 4)
self.relu = nn.ReLU()
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2_score.weight
primals_5 = self.conv2_score.bias
primals_6 = self.conv3_score.weight
primals_7 = self.conv3_score.bias
primals_8 = self.conv2_bbox.weight
primals_9 = self.conv2_bbox.bias
primals_10 = self.conv3_bbox.weight
primals_11 = self.conv3_bbox.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], output[1]
|
CNN-NISER/lffd-pytorch
|
BranchNet
| false
| 13,448
|
[
"MIT"
] | 220
|
7d6476ece79cf75c6265c89346ddac48929ce8f6
|
https://github.com/CNN-NISER/lffd-pytorch/tree/7d6476ece79cf75c6265c89346ddac48929ce8f6
|
Downsample
|
import torch
import torch.nn as nn
class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(in_channels, in_channels,
kernel_size=3, stride=2, padding=0)
def forward(self, x):
if self.with_conv:
pad = 0, 1, 0, 1
x = torch.nn.functional.pad(x, pad, mode='constant', value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'with_conv': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import 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_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 5 % 5
x0 = xindex % 5
x2 = xindex // 25
x3 = xindex
tmp0 = x1
tmp1 = tl.full([1], 4, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = x0
tmp4 = tmp3 < tmp1
tmp5 = tmp2 & tmp4
tmp6 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp5 & xmask, other=0.0)
tl.store(out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(400)](primals_1, buf0, 400,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 2, 2), (16, 4, 2, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_2, buf0
class DownsampleNew(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(in_channels, in_channels,
kernel_size=3, stride=2, padding=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]
|
CasualGANPapers/Make-A-Scene
|
Downsample
| false
| 13,449
|
[
"MIT"
] | 47
|
4457ef91ccf4a345f3178cf821f12b49df616b6d
|
https://github.com/CasualGANPapers/Make-A-Scene/tree/4457ef91ccf4a345f3178cf821f12b49df616b6d
|
backWarp
|
import torch
import numpy as np
import torch.nn as nn
class backWarp(nn.Module):
"""
A class for creating a backwarping object.
This is used for backwarping to an image:
Given optical flow from frame I0 to I1 --> F_0_1 and frame I1,
it generates I0 <-- backwarp(F_0_1, I1).
...
Methods
-------
forward(x)
Returns output tensor after passing input `img` and `flow` to the backwarping
block.
"""
def __init__(self, H, W):
"""
Parameters
----------
W : int
width of the image.
H : int
height of the image.
device : device
computation device (cpu/cuda).
"""
super(backWarp, self).__init__()
gridX, gridY = np.meshgrid(np.arange(W), np.arange(H))
self.W = W
self.H = H
self.gridX = torch.nn.Parameter(torch.tensor(gridX), requires_grad=
False)
self.gridY = torch.nn.Parameter(torch.tensor(gridY), requires_grad=
False)
def forward(self, img, flow):
"""
Returns output tensor after passing input `img` and `flow` to the backwarping
block.
I0 = backwarp(I1, F_0_1)
Parameters
----------
img : tensor
frame I1.
flow : tensor
optical flow from I0 and I1: F_0_1.
Returns
-------
tensor
frame I0.
"""
u = flow[:, 0, :, :]
v = flow[:, 1, :, :]
x = self.gridX.unsqueeze(0).expand_as(u).float() + u
y = self.gridY.unsqueeze(0).expand_as(v).float() + v
x = 2 * (x / self.W - 0.5)
y = 2 * (y / self.H - 0.5)
grid = torch.stack((x, y), dim=3)
imgOut = torch.nn.functional.grid_sample(img, grid, padding_mode=
'border')
return imgOut
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'H': 4, 'W': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_grid_sampler_2d_0(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
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
x4 = xindex // 16
tmp0 = tl.full([1], 0, tl.int64)
tmp2 = tl.full([1], 1, tl.int64)
tmp3 = tmp0 < tmp2
tmp4 = tl.load(in_ptr0 + x0, tmp3 & xmask, eviction_policy='evict_last',
other=0.0)
tmp5 = tmp4.to(tl.float32)
tmp6 = tl.load(in_ptr1 + (x0 + 64 * x2), tmp3 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = 0.25
tmp9 = tmp7 * tmp8
tmp10 = 0.5
tmp11 = tmp9 - tmp10
tmp12 = 2.0
tmp13 = tmp11 * tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp3, tmp13, tmp14)
tmp16 = tmp0 >= tmp2
tl.full([1], 2, tl.int64)
tmp19 = tl.load(in_ptr2 + x0, tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tmp19.to(tl.float32)
tmp21 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tmp20 + tmp21
tmp23 = tmp22 * tmp8
tmp24 = tmp23 - tmp10
tmp25 = tmp24 * tmp12
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp16, tmp25, tmp26)
tmp28 = tl.where(tmp3, tmp15, tmp27)
tmp29 = tmp28 * tmp12
tmp30 = 1.5
tmp31 = tmp29 + tmp30
tmp33 = tmp2 < tmp2
tmp34 = tl.load(in_ptr0 + x0, tmp33 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp35 = tmp34.to(tl.float32)
tmp36 = tl.load(in_ptr1 + (x0 + 64 * x2), tmp33 & xmask,
eviction_policy='evict_last', other=0.0)
tmp37 = tmp35 + tmp36
tmp38 = tmp37 * tmp8
tmp39 = tmp38 - tmp10
tmp40 = tmp39 * tmp12
tmp41 = tl.full(tmp40.shape, 0.0, tmp40.dtype)
tmp42 = tl.where(tmp33, tmp40, tmp41)
tmp43 = tmp2 >= tmp2
tmp45 = tl.load(in_ptr2 + x0, tmp43 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp46 = tmp45.to(tl.float32)
tmp47 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), tmp43 & xmask,
eviction_policy='evict_last', other=0.0)
tmp48 = tmp46 + tmp47
tmp49 = tmp48 * tmp8
tmp50 = tmp49 - tmp10
tmp51 = tmp50 * tmp12
tmp52 = tl.full(tmp51.shape, 0.0, tmp51.dtype)
tmp53 = tl.where(tmp43, tmp51, tmp52)
tmp54 = tl.where(tmp33, tmp42, tmp53)
tmp55 = tmp54 * tmp12
tmp56 = tmp55 + tmp30
tmp57 = 0.0
tmp58 = triton_helpers.maximum(tmp31, tmp57)
tmp59 = 3.0
tmp60 = triton_helpers.minimum(tmp58, tmp59)
tmp61 = libdevice.floor(tmp60)
tmp62 = tmp61 >= tmp57
tmp63 = 4.0
tmp64 = tmp61 < tmp63
tmp65 = triton_helpers.maximum(tmp56, tmp57)
tmp66 = triton_helpers.minimum(tmp65, tmp59)
tmp67 = libdevice.floor(tmp66)
tmp68 = tmp67 >= tmp57
tmp69 = tmp67 < tmp63
tmp70 = tmp68 & tmp69
tmp71 = tmp64 & tmp70
tmp72 = tmp62 & tmp71
tmp73 = tmp67.to(tl.int64)
tmp74 = tl.where(tmp72, tmp73, tmp0)
tmp75 = tl.full([XBLOCK], 4, tl.int32)
tmp76 = tmp74 + tmp75
tmp77 = tmp74 < 0
tmp78 = tl.where(tmp77, tmp76, tmp74)
tl.device_assert((0 <= tmp78) & (tmp78 < 4) | ~xmask,
'index out of bounds: 0 <= tmp78 < 4')
tmp80 = tmp61.to(tl.int64)
tmp81 = tl.where(tmp72, tmp80, tmp0)
tmp82 = tmp81 + tmp75
tmp83 = tmp81 < 0
tmp84 = tl.where(tmp83, tmp82, tmp81)
tl.device_assert((0 <= tmp84) & (tmp84 < 4) | ~xmask,
'index out of bounds: 0 <= tmp84 < 4')
tmp86 = tl.load(in_ptr3 + (tmp84 + 4 * tmp78 + 16 * x4), xmask,
eviction_policy='evict_last')
tmp87 = 1.0
tmp88 = tmp61 + tmp87
tmp89 = tmp88 - tmp60
tmp90 = tmp67 + tmp87
tmp91 = tmp90 - tmp66
tmp92 = tmp89 * tmp91
tmp93 = tl.where(tmp72, tmp92, tmp57)
tmp94 = tmp86 * tmp93
tmp95 = tmp88 >= tmp57
tmp96 = tmp88 < tmp63
tmp97 = tmp96 & tmp70
tmp98 = tmp95 & tmp97
tmp99 = tl.where(tmp98, tmp73, tmp0)
tmp100 = tmp99 + tmp75
tmp101 = tmp99 < 0
tmp102 = tl.where(tmp101, tmp100, tmp99)
tl.device_assert((0 <= tmp102) & (tmp102 < 4) | ~xmask,
'index out of bounds: 0 <= tmp102 < 4')
tmp104 = tmp88.to(tl.int64)
tmp105 = tl.where(tmp98, tmp104, tmp0)
tmp106 = tmp105 + tmp75
tmp107 = tmp105 < 0
tmp108 = tl.where(tmp107, tmp106, tmp105)
tl.device_assert((0 <= tmp108) & (tmp108 < 4) | ~xmask,
'index out of bounds: 0 <= tmp108 < 4')
tmp110 = tl.load(in_ptr3 + (tmp108 + 4 * tmp102 + 16 * x4), xmask,
eviction_policy='evict_last')
tmp111 = tmp60 - tmp61
tmp112 = tmp111 * tmp91
tmp113 = tl.where(tmp98, tmp112, tmp57)
tmp114 = tmp110 * tmp113
tmp115 = tmp90 >= tmp57
tmp116 = tmp90 < tmp63
tmp117 = tmp115 & tmp116
tmp118 = tmp64 & tmp117
tmp119 = tmp62 & tmp118
tmp120 = tmp90.to(tl.int64)
tmp121 = tl.where(tmp119, tmp120, tmp0)
tmp122 = tmp121 + tmp75
tmp123 = tmp121 < 0
tmp124 = tl.where(tmp123, tmp122, tmp121)
tl.device_assert((0 <= tmp124) & (tmp124 < 4) | ~xmask,
'index out of bounds: 0 <= tmp124 < 4')
tmp126 = tl.where(tmp119, tmp80, tmp0)
tmp127 = tmp126 + tmp75
tmp128 = tmp126 < 0
tmp129 = tl.where(tmp128, tmp127, tmp126)
tl.device_assert((0 <= tmp129) & (tmp129 < 4) | ~xmask,
'index out of bounds: 0 <= tmp129 < 4')
tmp131 = tl.load(in_ptr3 + (tmp129 + 4 * tmp124 + 16 * x4), xmask,
eviction_policy='evict_last')
tmp132 = tmp66 - tmp67
tmp133 = tmp89 * tmp132
tmp134 = tl.where(tmp119, tmp133, tmp57)
tmp135 = tmp131 * tmp134
tmp136 = tmp96 & tmp117
tmp137 = tmp95 & tmp136
tmp138 = tl.where(tmp137, tmp120, tmp0)
tmp139 = tmp138 + tmp75
tmp140 = tmp138 < 0
tmp141 = tl.where(tmp140, tmp139, tmp138)
tl.device_assert((0 <= tmp141) & (tmp141 < 4) | ~xmask,
'index out of bounds: 0 <= tmp141 < 4')
tmp143 = tl.where(tmp137, tmp104, tmp0)
tmp144 = tmp143 + tmp75
tmp145 = tmp143 < 0
tmp146 = tl.where(tmp145, tmp144, tmp143)
tl.device_assert((0 <= tmp146) & (tmp146 < 4) | ~xmask,
'index out of bounds: 0 <= tmp146 < 4')
tmp148 = tl.load(in_ptr3 + (tmp146 + 4 * tmp141 + 16 * x4), xmask,
eviction_policy='evict_last')
tmp149 = tmp111 * tmp132
tmp150 = tl.where(tmp137, tmp149, tmp57)
tmp151 = tmp148 * tmp150
tmp152 = tmp94 + tmp114
tmp153 = tmp152 + tmp135
tmp154 = tmp153 + tmp151
tl.store(in_out_ptr0 + x3, tmp154, 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, 1))
assert_size_stride(arg2_1, (4, 4), (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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf6 = buf2
del buf2
get_raw_stream(0)
triton_poi_fused_grid_sampler_2d_0[grid(256)](buf6, arg1_1, arg0_1,
arg2_1, arg3_1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
return buf6,
class backWarpNew(nn.Module):
"""
A class for creating a backwarping object.
This is used for backwarping to an image:
Given optical flow from frame I0 to I1 --> F_0_1 and frame I1,
it generates I0 <-- backwarp(F_0_1, I1).
...
Methods
-------
forward(x)
Returns output tensor after passing input `img` and `flow` to the backwarping
block.
"""
def __init__(self, H, W):
"""
Parameters
----------
W : int
width of the image.
H : int
height of the image.
device : device
computation device (cpu/cuda).
"""
super(backWarpNew, self).__init__()
gridX, gridY = np.meshgrid(np.arange(W), np.arange(H))
self.W = W
self.H = H
self.gridX = torch.nn.Parameter(torch.tensor(gridX), requires_grad=
False)
self.gridY = torch.nn.Parameter(torch.tensor(gridY), requires_grad=
False)
def forward(self, input_0, input_1):
arg1_1 = self.gridX
arg2_1 = self.gridY
arg0_1 = input_0
arg3_1 = input_1
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0]
|
CM-BF/FeatureFlow
|
backWarp
| false
| 13,450
|
[
"MIT"
] | 161
|
06642697922f17211e5faa353e24b1a0946885b1
|
https://github.com/CM-BF/FeatureFlow/tree/06642697922f17211e5faa353e24b1a0946885b1
|
Biaffine
|
import torch
import torch.nn as nn
class Biaffine(nn.Module):
def __init__(self, n_in, n_out=1, bias_x=True, bias_y=True):
super(Biaffine, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.bias_x = bias_x
self.bias_y = bias_y
self.weight = nn.Parameter(torch.Tensor(n_out, n_in + bias_x, n_in +
bias_y))
self.reset_parameters()
def extra_repr(self):
info = f'n_in={self.n_in}, n_out={self.n_out}'
if self.bias_x:
info += f', bias_x={self.bias_x}'
if self.bias_y:
info += f', bias_y={self.bias_y}'
return info
def reset_parameters(self):
nn.init.zeros_(self.weight)
def forward(self, x, y):
if self.bias_x:
x = torch.cat([x, x.new_ones(x.shape[:-1]).unsqueeze(-1)], -1)
if self.bias_y:
y = torch.cat([y, y.new_ones(y.shape[:-1]).unsqueeze(-1)], -1)
x = x.unsqueeze(1)
y = y.unsqueeze(1)
s = x @ self.weight @ torch.transpose(y, -1, -2)
s = s.squeeze(1)
return s
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp9 = 1.0
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp6, tmp9, tmp10)
tmp12 = tl.where(tmp4, tmp5, tmp11)
tl.store(out_ptr0 + x2, tmp12, xmask)
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, 5, 5), (25, 5, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 5), (80, 20, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(320)](primals_1, buf0, 320, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4, 5), (20, 5, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 5), (20, 5, 1),
0), reinterpret_tensor(primals_3, (16, 5, 5), (0, 5, 1), 0),
out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4, 4, 5), (80, 20, 5, 1), torch.float32)
triton_poi_fused_cat_0[grid(320)](primals_2, buf2, 320, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf1, reinterpret_tensor(buf2, (16, 5, 4), (20,
1, 5), 0), out=buf3)
del buf1
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf2, (16, 4, 5), (20, 5, 1), 0
), reinterpret_tensor(buf0, (16, 5, 4), (20, 1, 5), 0)
class BiaffineNew(nn.Module):
def __init__(self, n_in, n_out=1, bias_x=True, bias_y=True):
super(BiaffineNew, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.bias_x = bias_x
self.bias_y = bias_y
self.weight = nn.Parameter(torch.Tensor(n_out, n_in + bias_x, n_in +
bias_y))
self.reset_parameters()
def extra_repr(self):
info = f'n_in={self.n_in}, n_out={self.n_out}'
if self.bias_x:
info += f', bias_x={self.bias_x}'
if self.bias_y:
info += f', bias_y={self.bias_y}'
return info
def reset_parameters(self):
nn.init.zeros_(self.weight)
def forward(self, input_0, input_1):
primals_3 = self.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
CNLPT/lightNLP
|
Biaffine
| false
| 13,451
|
[
"Apache-2.0"
] | 889
|
c7f128422ba5b16f514bb294145cb3b562e95829
|
https://github.com/CNLPT/lightNLP/tree/c7f128422ba5b16f514bb294145cb3b562e95829
|
MaxPoolStride1
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class MaxPoolStride1(nn.Module):
def __init__(self):
super(MaxPoolStride1, self).__init__()
def forward(self, x):
x_pad = F.pad(x, (0, 1, 0, 1), mode='replicate')
x = F.max_pool2d(x_pad, 2, stride=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime 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_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (4 * (3 * (3 <= x1) + x1 * (x1 < 3)) + 16 * x2 +
(3 * (3 <= x0) + x0 * (x0 < 3))), xmask)
tmp1 = tl.load(in_ptr0 + (4 * (3 * (3 <= x1) + x1 * (x1 < 3)) + 16 * x2 +
(3 * (3 <= 1 + x0) + (1 + x0) * (1 + x0 < 3))), xmask)
tmp3 = tl.load(in_ptr0 + (4 * (3 * (3 <= 1 + x1) + (1 + x1) * (1 + x1 <
3)) + 16 * x2 + (3 * (3 <= x0) + x0 * (x0 < 3))), xmask)
tmp5 = tl.load(in_ptr0 + (4 * (3 * (3 <= 1 + x1) + (1 + x1) * (1 + x1 <
3)) + 16 * x2 + (3 * (3 <= 1 + x0) + (1 + x0) * (1 + x0 < 3))), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(256)](arg0_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class MaxPoolStride1New(nn.Module):
def __init__(self):
super(MaxPoolStride1New, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CharlesPikachu/YOLO
|
MaxPoolStride1
| false
| 13,452
|
[
"MIT"
] | 57
|
950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
https://github.com/CharlesPikachu/YOLO/tree/950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
Merge
|
import torch
import torch.utils.data
from torch import nn
class Conv(nn.Module):
def __init__(self, inp_dim, out_dim, kernel_size=3, stride=1, bn=False,
relu=True):
super(Conv, self).__init__()
self.inp_dim = inp_dim
self.conv = nn.Conv2d(inp_dim, out_dim, kernel_size, stride,
padding=(kernel_size - 1) // 2, bias=True)
self.relu = None
self.bn = None
if relu:
self.relu = nn.ReLU()
if bn:
self.bn = nn.BatchNorm2d(out_dim)
def forward(self, x):
assert x.size()[1] == self.inp_dim, '{} {}'.format(x.size()[1],
self.inp_dim)
x = self.conv(x)
if self.relu is not None:
x = self.relu(x)
if self.bn is not None:
x = self.bn(x)
return x
class Merge(nn.Module):
def __init__(self, x_dim, y_dim):
super(Merge, self).__init__()
self.conv = Conv(x_dim, y_dim, 1, relu=False, bn=False)
def forward(self, x):
return self.conv(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'x_dim': 4, 'y_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(256)](buf1, primals_3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
return buf1, primals_1, primals_2
class Conv(nn.Module):
def __init__(self, inp_dim, out_dim, kernel_size=3, stride=1, bn=False,
relu=True):
super(Conv, self).__init__()
self.inp_dim = inp_dim
self.conv = nn.Conv2d(inp_dim, out_dim, kernel_size, stride,
padding=(kernel_size - 1) // 2, bias=True)
self.relu = None
self.bn = None
if relu:
self.relu = nn.ReLU()
if bn:
self.bn = nn.BatchNorm2d(out_dim)
def forward(self, x):
assert x.size()[1] == self.inp_dim, '{} {}'.format(x.size()[1],
self.inp_dim)
x = self.conv(x)
if self.relu is not None:
x = self.relu(x)
if self.bn is not None:
x = self.bn(x)
return x
class MergeNew(nn.Module):
def __init__(self, x_dim, y_dim):
super(MergeNew, self).__init__()
self.conv = Conv(x_dim, y_dim, 1, relu=False, bn=False)
def forward(self, input_0):
primals_2 = self.conv.conv.weight
primals_3 = self.conv.conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
CenIII/pose-ae-train
|
Merge
| false
| 13,453
|
[
"BSD-3-Clause"
] | 250
|
8780ba9f3d80ca3a724bbee7b815073adc3d3e6e
|
https://github.com/CenIII/pose-ae-train/tree/8780ba9f3d80ca3a724bbee7b815073adc3d3e6e
|
MultiHeadSelfAttention
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.init
import torch.nn.parallel
class MultiHeadSelfAttention(nn.Module):
"""Self-attention module by Lin, Zhouhan, et al. ICLR 2017"""
def __init__(self, n_head, d_in, d_hidden):
super(MultiHeadSelfAttention, self).__init__()
self.n_head = n_head
self.w_1 = nn.Linear(d_in, d_hidden, bias=False)
self.w_2 = nn.Linear(d_hidden, n_head, bias=False)
self.tanh = nn.Tanh()
self.softmax = nn.Softmax(dim=1)
self.init_weights()
def init_weights(self):
nn.init.xavier_uniform_(self.w_1.weight)
nn.init.xavier_uniform_(self.w_2.weight)
def forward(self, x, mask=None):
attn = self.w_2(self.tanh(self.w_1(x)))
if mask is not None:
mask = mask.repeat(self.n_head, 1, 1).permute(1, 2, 0)
attn.masked_fill_(mask, -np.inf)
attn = self.softmax(attn)
output = torch.bmm(attn.transpose(1, 2), x)
if output.shape[1] == 1:
output = output.squeeze(1)
return output, attn
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_head': 4, 'd_in': 4, 'd_hidden': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.init
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_tanh_0(in_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_out_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
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), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (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_tanh_0[grid(64)](buf1, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
del buf2
triton_poi_fused__softmax_2[grid(64)](buf3, buf4, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf5 = buf3
del buf3
extern_kernels.bmm(reinterpret_tensor(buf4, (4, 4, 4), (16, 1, 4),
0), primals_2, out=buf5)
return buf5, buf4, primals_2, buf1, buf4, primals_3
class MultiHeadSelfAttentionNew(nn.Module):
"""Self-attention module by Lin, Zhouhan, et al. ICLR 2017"""
def __init__(self, n_head, d_in, d_hidden):
super(MultiHeadSelfAttentionNew, self).__init__()
self.n_head = n_head
self.w_1 = nn.Linear(d_in, d_hidden, bias=False)
self.w_2 = nn.Linear(d_hidden, n_head, bias=False)
self.tanh = nn.Tanh()
self.softmax = nn.Softmax(dim=1)
self.init_weights()
def init_weights(self):
nn.init.xavier_uniform_(self.w_1.weight)
nn.init.xavier_uniform_(self.w_2.weight)
def forward(self, input_0):
primals_1 = self.w_1.weight
primals_3 = self.w_2.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
CLT29/pvse
|
MultiHeadSelfAttention
| false
| 13,454
|
[
"MIT"
] | 119
|
bf5232148396ee5051564ef68a48538de0ddbc84
|
https://github.com/CLT29/pvse/tree/bf5232148396ee5051564ef68a48538de0ddbc84
|
LogSTFTMagnitudeLoss
|
import torch
import torch.utils.data
import torch.nn.functional as F
class LogSTFTMagnitudeLoss(torch.nn.Module):
"""Log STFT magnitude loss module."""
def __init__(self):
"""Initilize los STFT magnitude loss module."""
super(LogSTFTMagnitudeLoss, self).__init__()
def forward(self, x_mag, y_mag):
"""Calculate forward propagation.
Args:
x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
Returns:
Tensor: Log STFT magnitude loss value.
"""
return F.l1_loss(torch.log(y_mag), torch.log(x_mag))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_log_mean_sub_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_math.log(tmp0)
tmp3 = tl_math.log(tmp2)
tmp4 = tmp1 - tmp3
tmp5 = tl_math.abs(tmp4)
tmp6 = tl.broadcast_to(tmp5, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = 256.0
tmp10 = tmp8 / tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp10, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_log_mean_sub_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 LogSTFTMagnitudeLossNew(torch.nn.Module):
"""Log STFT magnitude loss module."""
def __init__(self):
"""Initilize los STFT magnitude loss module."""
super(LogSTFTMagnitudeLossNew, self).__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ChanganVR/hifigan-denoiser
|
LogSTFTMagnitudeLoss
| false
| 13,455
|
[
"Apache-2.0"
] | 100
|
9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
https://github.com/ChanganVR/hifigan-denoiser/tree/9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
GlobalAvgPool2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GlobalAvgPool2d(nn.Module):
def __init__(self):
super(GlobalAvgPool2d, self).__init__()
def forward(self, x):
N = x.data.size(0)
C = x.data.size(1)
H = x.data.size(2)
W = x.data.size(3)
x = F.avg_pool2d(x, (H, W))
x = x.view(N, C)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_avg_pool2d_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 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp8 = tmp7 + tmp6
tmp10 = tmp9 + tmp8
tmp12 = tmp11 + tmp10
tmp14 = tmp13 + tmp12
tmp16 = tmp15 + tmp14
tmp18 = tmp17 + tmp16
tmp20 = tmp19 + tmp18
tmp22 = tmp21 + tmp20
tmp24 = tmp23 + tmp22
tmp26 = tmp25 + tmp24
tmp28 = tmp27 + tmp26
tmp30 = tmp29 + tmp28
tmp31 = 0.0625
tmp32 = tmp30 * tmp31
tl.store(out_ptr0 + x0, tmp32, 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, 1, 1), (4, 1, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4), (4, 1), 0),
class GlobalAvgPool2dNew(nn.Module):
def __init__(self):
super(GlobalAvgPool2dNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CharlesPikachu/YOLO
|
GlobalAvgPool2d
| false
| 13,456
|
[
"MIT"
] | 57
|
950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
https://github.com/CharlesPikachu/YOLO/tree/950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
MatrixTree
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class MatrixTree(nn.Module):
"""Implementation of the matrix-tree theorem for computing marginals
of non-projective dependency parsing. This attention layer is used
in the paper "Learning Structured Text Representations"
:cite:`DBLP:journals/corr/LiuL17d`.
"""
def __init__(self, eps=1e-05):
self.eps = eps
super(MatrixTree, self).__init__()
def forward(self, input):
laplacian = input.exp() + self.eps
output = input.clone()
for b in range(input.size(0)):
lap = laplacian[b].masked_fill(torch.eye(input.size(1), device=
input.device).ne(0), 0)
lap = -lap + torch.diag(lap.sum(0))
lap[0] = input[b].diag().exp()
inv_laplacian = lap.inverse()
factor = inv_laplacian.diag().unsqueeze(1).expand_as(input[b]
).transpose(0, 1)
term1 = input[b].exp().mul(factor).clone()
term2 = input[b].exp().mul(inv_laplacian.transpose(0, 1)).clone()
term1[:, 0] = 0
term2[0] = 0
output[b] = term1 - term2
roots_output = input[b].diag().exp().mul(inv_laplacian.
transpose(0, 1)[0])
output[b] = output[b] + torch.diag(roots_output)
return output
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.cuda
import torch.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_eye_masked_fill_ne_sum_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
tmp7 = tl.load(in_ptr0 + x0, xmask)
tmp16 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (12 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_1(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + x2, xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_2(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp7 = tl.load(in_ptr0 + (16 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (20 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (24 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (28 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_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
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (16 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_4(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
x2 = xindex
x1 = xindex // 4
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp6 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + x2, xmask)
tmp18 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 0, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tmp2 == tmp0
tmp5 = tl_math.exp(tmp4)
tmp7 = tmp5 * tmp6
tmp8 = 0.0
tmp9 = tl.where(tmp3, tmp8, tmp7)
tmp10 = x1
tmp11 = tmp10 == tmp0
tmp13 = tmp5 * tmp12
tmp14 = tl.where(tmp11, tmp8, tmp13)
tmp15 = tmp9 - tmp14
tmp16 = tl.where(tmp1, tmp15, tmp4)
tmp17 = tmp2 == tmp10
tmp19 = tl_math.exp(tmp18)
tmp21 = tmp19 * tmp20
tmp22 = tl.where(tmp17, tmp21, tmp8)
tmp23 = tmp16 + tmp22
tl.store(out_ptr0 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_5(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr1 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tmp4 == tmp1
tmp7 = tl_math.exp(tmp6)
tmp9 = tmp7 * tmp8
tmp10 = 0.0
tmp11 = tl.where(tmp5, tmp10, tmp9)
tmp12 = x1
tmp13 = tmp12 == tmp1
tmp15 = tmp7 * tmp14
tmp16 = tl.where(tmp13, tmp10, tmp15)
tmp17 = tmp11 - tmp16
tmp19 = tl.where(tmp2, tmp17, tmp18)
tmp20 = tl.where(tmp2, tmp3, tmp19)
tl.store(out_ptr0 + x5, tmp20, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_6(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
tmp7 = tl.load(in_ptr0 + (32 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (36 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (40 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (44 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_7(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (32 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_8(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
tmp5 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (16 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (16 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 1, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_9(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (16 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_10(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
tmp7 = tl.load(in_ptr0 + (48 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (52 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (56 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (60 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_11(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (48 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_12(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
tmp5 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (32 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (32 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 2, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_13(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 // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (32 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_14(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
tmp5 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (48 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (48 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 3, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_15(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 // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (48 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_eye_masked_fill_ne_sum_0[grid(4)](arg0_1, buf0, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_1[
grid(16)](arg0_1, buf0, buf1, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf2 = torch.ops.aten.linalg_inv_ex.default(buf1)
buf3 = buf2[0]
del buf2
buf5 = buf0
del buf0
triton_poi_fused_eye_masked_fill_ne_sum_2[grid(4)](arg0_1, buf5, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf6 = buf1
del buf1
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_3[
grid(16)](arg0_1, buf5, buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = torch.ops.aten.linalg_inv_ex.default(buf6)
buf8 = buf7[0]
del buf7
buf10 = buf6
del buf6
triton_poi_fused_add_diag_embed_4[grid(16)](arg0_1, buf3, buf10, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_5[grid(64)
](buf10, arg0_1, buf3, buf11, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf10
buf12 = buf5
del buf5
triton_poi_fused_eye_masked_fill_ne_sum_6[grid(4)](arg0_1, buf12, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf13 = reinterpret_tensor(buf3, (4, 4), (4, 1), 0)
del buf3
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_7[
grid(16)](arg0_1, buf12, buf13, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf14 = torch.ops.aten.linalg_inv_ex.default(buf13)
buf15 = buf14[0]
del buf14
buf17 = buf13
del buf13
triton_poi_fused_add_diag_embed_8[grid(16)](arg0_1, buf8, buf11,
buf17, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf18 = buf11
del buf11
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_9[grid(64)
](buf18, buf17, arg0_1, buf8, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf17
buf19 = buf12
del buf12
triton_poi_fused_eye_masked_fill_ne_sum_10[grid(4)](arg0_1, buf19,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf20 = reinterpret_tensor(buf8, (4, 4), (4, 1), 0)
del buf8
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_11[
grid(16)](arg0_1, buf19, buf20, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf19
buf21 = torch.ops.aten.linalg_inv_ex.default(buf20)
buf22 = buf21[0]
del buf21
buf24 = buf20
del buf20
triton_poi_fused_add_diag_embed_12[grid(16)](arg0_1, buf15, buf18,
buf24, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf25 = buf18
del buf18
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_13[grid(64)
](buf25, buf24, arg0_1, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf15
buf26 = buf24
del buf24
triton_poi_fused_add_diag_embed_14[grid(16)](arg0_1, buf22, buf25,
buf26, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf27 = buf25
del buf25
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_15[grid(64)
](buf27, buf26, arg0_1, buf22, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del arg0_1
del buf22
del buf26
return buf27,
class MatrixTreeNew(nn.Module):
"""Implementation of the matrix-tree theorem for computing marginals
of non-projective dependency parsing. This attention layer is used
in the paper "Learning Structured Text Representations"
:cite:`DBLP:journals/corr/LiuL17d`.
"""
def __init__(self, eps=1e-05):
self.eps = eps
super(MatrixTreeNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
BradLin0819/kg2text
|
MatrixTree
| false
| 13,457
|
[
"Apache-2.0"
] | 86
|
e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
https://github.com/BradLin0819/kg2text/tree/e586eb2027c0d85db9826cbe1d9e14f2d26fc93f
|
ResolutionScalingLayer
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResolutionScalingLayer(nn.Module):
"""Implements the resolution scaling layer.
Basically, this layer can be used to upsample or downsample feature maps from
spatial domain with nearest neighbor interpolation.
"""
def __init__(self, scale_factor=2):
super().__init__()
self.scale_factor = scale_factor
def forward(self, x):
return F.interpolate(x, scale_factor=self.scale_factor, mode='nearest')
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__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)
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, 8, 8), (256, 64, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__unsafe_index_0[grid(1024)](arg0_1, buf0, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ResolutionScalingLayerNew(nn.Module):
"""Implements the resolution scaling layer.
Basically, this layer can be used to upsample or downsample feature maps from
spatial domain with nearest neighbor interpolation.
"""
def __init__(self, scale_factor=2):
super().__init__()
self.scale_factor = scale_factor
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CV-IP/interfacegan
|
ResolutionScalingLayer
| false
| 13,458
|
[
"MIT"
] | 855
|
5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
https://github.com/CV-IP/interfacegan/tree/5a556b8e693f6e1888f769f653aaafaaccca5dc2
|
SpectralConvergengeLoss
|
import torch
import torch.utils.data
class SpectralConvergengeLoss(torch.nn.Module):
"""Spectral convergence loss module."""
def __init__(self):
"""Initilize spectral convergence loss module."""
super(SpectralConvergengeLoss, self).__init__()
def forward(self, x_mag, y_mag):
"""Calculate forward propagation.
Args:
x_mag (Tensor): Magnitude spectrogram of predicted signal (B, #frames, #freq_bins).
y_mag (Tensor): Magnitude spectrogram of groundtruth signal (B, #frames, #freq_bins).
Returns:
Tensor: Spectral convergence loss value.
"""
return torch.norm(y_mag - x_mag, p='fro') / torch.norm(y_mag, p='fro')
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_div_linalg_vector_norm_sub_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 = tmp0 * tmp0
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = libdevice.sqrt(tmp6)
tmp12 = libdevice.sqrt(tmp10)
tmp13 = tmp11 / tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_div_linalg_vector_norm_sub_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 SpectralConvergengeLossNew(torch.nn.Module):
"""Spectral convergence loss module."""
def __init__(self):
"""Initilize spectral convergence loss module."""
super(SpectralConvergengeLossNew, self).__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ChanganVR/hifigan-denoiser
|
SpectralConvergengeLoss
| false
| 13,459
|
[
"Apache-2.0"
] | 100
|
9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
https://github.com/ChanganVR/hifigan-denoiser/tree/9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
Reorg
|
import torch
import torch.nn as nn
class Reorg(nn.Module):
def __init__(self, stride=2):
super(Reorg, self).__init__()
self.stride = stride
def forward(self, x):
assert x.data.dim() == 4
B = x.data.size(0)
C = x.data.size(1)
H = x.data.size(2)
W = x.data.size(3)
assert H % self.stride == 0
assert W % self.stride == 0
w_stride = self.stride
h_stride = self.stride
x = x.view(B, C, H // h_stride, h_stride, W // w_stride, w_stride
).transpose(3, 4).contiguous()
x = x.view(B, C, H // h_stride * (W // w_stride), h_stride * w_stride
).transpose(2, 3).contiguous()
x = x.view(B, C, h_stride * w_stride, H // h_stride, W // w_stride
).transpose(1, 2).contiguous()
x = x.view(B, h_stride * w_stride * C, H // h_stride, W // w_stride)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 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 % 2
x3 = xindex // 2
y0 = yindex % 4
y1 = yindex // 4
x5 = xindex
y4 = yindex
tmp0 = tl.load(in_ptr0 + (2 * x2 + 4 * (y0 // 2) + 8 * x3 + 64 * y1 +
y0 % 2), xmask & ymask)
tl.store(out_ptr0 + (x5 + 16 * y4), tmp0, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 2, 2), (64, 16, 4, 2, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 16)](arg0_1, buf0, 16, 16, XBLOCK
=16, YBLOCK=16, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 16, 2, 2), (64, 4, 2, 1), 0),
class ReorgNew(nn.Module):
def __init__(self, stride=2):
super(ReorgNew, self).__init__()
self.stride = stride
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
CharlesPikachu/YOLO
|
Reorg
| false
| 13,460
|
[
"MIT"
] | 57
|
950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
https://github.com/CharlesPikachu/YOLO/tree/950b11c35517c1c3d7d7856b5768c4023c1f89eb
|
LayerNorm
|
import torch
import torch.nn as nn
class LayerNorm(nn.LayerNorm):
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True):
"""Layer Norm."""
super(LayerNorm, self).__init__(normalized_shape, eps=eps,
elementwise_affine=elementwise_affine)
def forward(self, x):
x = x.permute(0, 2, 1)
y = super(LayerNorm, self).forward(x)
y = y.permute(0, 2, 1)
return y
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'normalized_shape': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_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 % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = 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 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y3, ymask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + y3, ymask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + (x2 + 4 * y3), tmp8, xmask & ymask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (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(16, 4)](primals_1, buf0,
buf1, primals_2, primals_3, buf2, 16, 4, XBLOCK=4, YBLOCK=16,
num_warps=1, num_stages=1)
del buf0
del buf1
del primals_2
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), primals_1
class LayerNormNew(nn.LayerNorm):
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True):
"""Layer Norm."""
super(LayerNormNew, self).__init__(normalized_shape, eps=eps,
elementwise_affine=elementwise_affine)
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]
|
ChavesLiu/pytorch-dc-tts
|
LayerNorm
| false
| 13,461
|
[
"MIT"
] | 145
|
29a1ab11f69b2c4316ae0a8766e995b96385a29f
|
https://github.com/ChavesLiu/pytorch-dc-tts/tree/29a1ab11f69b2c4316ae0a8766e995b96385a29f
|
LayerNormConv2d
|
import torch
import torch.nn as nn
import torch.nn.functional
class LayerNormConv2d(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super().__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
y = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
y = self.gamma.view(*shape) * y + self.beta.view(*shape)
return y
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
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_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)
tmp26 = 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-05
tmp25 = tmp23 + tmp24
tmp27 = tmp0 - tmp20
tmp28 = tmp27 / tmp25
tmp29 = tmp26 * 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 LayerNormConv2dNew(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super().__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.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]
|
ChenFengYe/relightable-nr
|
LayerNormConv2d
| false
| 13,462
|
[
"MIT"
] | 105
|
239a97406f4df01cf5786dcdde58e464395a682d
|
https://github.com/ChenFengYe/relightable-nr/tree/239a97406f4df01cf5786dcdde58e464395a682d
|
maxout
|
import torch
import torch.nn as nn
import torch.utils.data
class maxout(nn.Module):
"""
maxout network
"""
def __init__(self, in_feature, out_feature, pool_size):
super(maxout, self).__init__()
self.in_feature = in_feature
self.out_feature = out_feature
self.pool_size = pool_size
self.linear = nn.Linear(in_feature, out_feature * pool_size)
def forward(self, x):
output = self.linear(x)
output = output.view(-1, self.out_feature, self.pool_size)
output = output.max(2)[0]
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_feature': 4, 'out_feature': 4, 'pool_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
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_max_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = tmp0 > tmp1
tmp8 = tmp0 == tmp1
tmp9 = tmp0 != tmp0
tmp10 = tmp1 != tmp1
tmp11 = tmp9 > tmp10
tmp12 = tmp7 | tmp11
tmp13 = tmp9 & tmp10
tmp14 = tmp8 | tmp13
tmp15 = tl.full([1], 0, tl.int64)
tmp16 = tl.full([1], 1, tl.int64)
tmp17 = tmp15 < tmp16
tmp18 = tmp14 & tmp17
tmp19 = tmp12 | tmp18
tmp20 = tl.where(tmp19, tmp0, tmp1)
tmp21 = tl.where(tmp19, tmp15, tmp16)
tmp22 = tmp20 > tmp3
tmp23 = tmp20 == tmp3
tmp24 = tmp20 != tmp20
tmp25 = tmp3 != tmp3
tmp26 = tmp24 > tmp25
tmp27 = tmp22 | tmp26
tmp28 = tmp24 & tmp25
tmp29 = tmp23 | tmp28
tmp30 = tl.full([1], 2, tl.int64)
tmp31 = tmp21 < tmp30
tmp32 = tmp29 & tmp31
tmp33 = tmp27 | tmp32
tmp34 = tl.where(tmp33, tmp20, tmp3)
tmp35 = tl.where(tmp33, tmp21, tmp30)
tmp36 = tmp34 > tmp5
tmp37 = tmp34 == tmp5
tmp38 = tmp34 != tmp34
tmp39 = tmp5 != tmp5
tmp40 = tmp38 > tmp39
tmp41 = tmp36 | tmp40
tmp42 = tmp38 & tmp39
tmp43 = tmp37 | tmp42
tmp44 = tl.full([1], 3, tl.int64)
tmp45 = tmp35 < tmp44
tmp46 = tmp43 & tmp45
tmp47 = tmp41 | tmp46
tl.where(tmp47, tmp34, tmp5)
tmp49 = tl.where(tmp47, tmp35, tmp44)
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp49, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (16, 4), (4, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 16), (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)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused_max_0[grid(256)](buf0, buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf0
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (64, 4, 1), (4, 1, 1), 0)
class maxoutNew(nn.Module):
"""
maxout network
"""
def __init__(self, in_feature, out_feature, pool_size):
super(maxoutNew, self).__init__()
self.in_feature = in_feature
self.out_feature = out_feature
self.pool_size = pool_size
self.linear = nn.Linear(in_feature, out_feature * pool_size)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ChenZhongFu/KOBE
|
maxout
| false
| 13,463
|
[
"MIT"
] | 176
|
710d7556516bdbd9ad971e6ff8b8f625a1a55e5a
|
https://github.com/ChenZhongFu/KOBE/tree/710d7556516bdbd9ad971e6ff8b8f625a1a55e5a
|
Down2d
|
import torch
import torch.utils.data
import torch.nn as nn
class Down2d(nn.Module):
"""docstring for Down2d."""
def __init__(self, in_channel, out_channel, kernel, stride, padding):
super(Down2d, self).__init__()
self.c1 = nn.Conv2d(in_channel, out_channel, kernel_size=kernel,
stride=stride, padding=padding)
self.n1 = nn.InstanceNorm2d(out_channel)
self.c2 = nn.Conv2d(in_channel, out_channel, kernel_size=kernel,
stride=stride, padding=padding)
self.n2 = nn.InstanceNorm2d(out_channel)
def forward(self, x):
x1 = self.c1(x)
x1 = self.n1(x1)
x2 = self.c2(x)
x2 = self.n2(x2)
x3 = x1 * torch.sigmoid(x2)
return x3
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel': 4, 'stride':
1, 'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_mul_sigmoid_0(
in_out_ptr0, in_out_ptr1, in_out_ptr2, in_out_ptr3, in_ptr0, in_ptr1,
out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
rnumel = 81
RBLOCK: tl.constexpr = 128
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
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 81 * x3), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_out_ptr2 + (r2 + 81 * x3), rmask & xmask, other=0.0)
tmp25 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(rmask & xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 81, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(rmask & xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 81.0
tmp20 = tmp18 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tmp26 = tmp24 + tmp25
tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK])
tl.where(rmask & xmask, tmp27, 0)
tmp30 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK])
tmp32 = tl.where(rmask & xmask, tmp30, 0)
tmp33 = tl.sum(tmp32, 1)[:, None]
tmp34 = tmp33 / tmp11
tmp35 = tmp27 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
tmp39 = tl.where(rmask & xmask, tmp37, 0)
tmp40 = tl.sum(tmp39, 1)[:, None]
tmp41 = tmp40 / tmp19
tmp42 = tmp41 + tmp21
tmp43 = libdevice.rsqrt(tmp42)
tmp44 = tmp2 - tmp12
tmp45 = tmp44 * tmp23
tmp46 = tmp26 - tmp34
tmp47 = tmp46 * tmp43
tmp48 = tl.sigmoid(tmp47)
tmp49 = tmp45 * tmp48
tl.store(in_out_ptr0 + (r2 + 81 * x3), tmp2, rmask & xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp23, xmask)
tl.store(in_out_ptr2 + (r2 + 81 * x3), tmp26, rmask & xmask)
tl.debug_barrier()
tl.store(in_out_ptr3 + x3, tmp43, xmask)
tl.store(out_ptr2 + (r2 + 81 * x3), tmp49, rmask & xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
tl.store(out_ptr1 + x3, tmp34, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 9, 9), (324, 81, 9, 1))
buf6 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 9, 9), (324, 81, 9, 1))
buf1 = buf0
del buf0
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
buf7 = buf6
del buf6
buf8 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf9 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf11 = reinterpret_tensor(buf9, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf9
buf12 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32
)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_convolution_mul_sigmoid_0[
grid(16)](buf1, buf5, buf7, buf11, primals_2, primals_5, buf2,
buf8, buf12, 16, 81, XBLOCK=1, num_warps=2, num_stages=1)
del primals_2
del primals_5
return (buf12, primals_1, primals_3, primals_4, buf1, buf2, buf5, buf7,
buf8, buf11)
class Down2dNew(nn.Module):
"""docstring for Down2d."""
def __init__(self, in_channel, out_channel, kernel, stride, padding):
super(Down2dNew, self).__init__()
self.c1 = nn.Conv2d(in_channel, out_channel, kernel_size=kernel,
stride=stride, padding=padding)
self.n1 = nn.InstanceNorm2d(out_channel)
self.c2 = nn.Conv2d(in_channel, out_channel, kernel_size=kernel,
stride=stride, padding=padding)
self.n2 = nn.InstanceNorm2d(out_channel)
def forward(self, input_0):
primals_1 = self.c1.weight
primals_2 = self.c1.bias
primals_3 = self.c2.weight
primals_5 = self.c2.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
ChanganVR/hifigan-denoiser
|
Down2d
| false
| 13,464
|
[
"Apache-2.0"
] | 100
|
9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
https://github.com/ChanganVR/hifigan-denoiser/tree/9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
Conv2dSame
|
import torch
import torch.nn as nn
import torch.nn.functional
class Conv2dSame(torch.nn.Module):
"""2D convolution that pads to keep spatial dimensions equal.
Cannot deal with stride. Only quadratic kernels (=scalar kernel_size).
"""
def __init__(self, in_channels, out_channels, kernel_size, bias=True,
padding_layer=nn.ReflectionPad2d):
"""
:param in_channels: Number of input channels
:param out_channels: Number of output channels
:param kernel_size: Scalar. Spatial dimensions of kernel (only quadratic kernels supported).
:param bias: Whether or not to use bias.
:param padding_layer: Which padding to use. Default is reflection padding.
"""
super().__init__()
ka = kernel_size // 2
kb = ka - 1 if kernel_size % 2 == 0 else ka
self.net = nn.Sequential(padding_layer((ka, kb, ka, kb)), nn.Conv2d
(in_channels, out_channels, kernel_size, bias=bias, stride=1))
self.weight = self.net[1].weight
self.bias = self.net[1].bias
def forward(self, x):
return self.net(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
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_reflection_pad2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 784
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 7
x1 = xindex // 7 % 7
x2 = xindex // 49
x3 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-2 +
x0)) + -4 * tl_math.abs(-3 + tl_math.abs(-2 + x1)) + 16 * x2),
xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 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, 7, 7), (196, 49, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_reflection_pad2d_0[grid(784)](primals_1, buf0, 784,
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, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(256)](buf2, primals_3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf2, primals_2, buf0
class Conv2dSameNew(torch.nn.Module):
"""2D convolution that pads to keep spatial dimensions equal.
Cannot deal with stride. Only quadratic kernels (=scalar kernel_size).
"""
def __init__(self, in_channels, out_channels, kernel_size, bias=True,
padding_layer=nn.ReflectionPad2d):
"""
:param in_channels: Number of input channels
:param out_channels: Number of output channels
:param kernel_size: Scalar. Spatial dimensions of kernel (only quadratic kernels supported).
:param bias: Whether or not to use bias.
:param padding_layer: Which padding to use. Default is reflection padding.
"""
super().__init__()
ka = kernel_size // 2
kb = ka - 1 if kernel_size % 2 == 0 else ka
self.net = nn.Sequential(padding_layer((ka, kb, ka, kb)), nn.Conv2d
(in_channels, out_channels, kernel_size, bias=bias, stride=1))
self.weight = self.net[1].weight
self.bias = self.net[1].bias
def forward(self, input_0):
primals_1 = self.weight
primals_3 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ChenFengYe/relightable-nr
|
Conv2dSame
| false
| 13,465
|
[
"MIT"
] | 105
|
239a97406f4df01cf5786dcdde58e464395a682d
|
https://github.com/ChenFengYe/relightable-nr/tree/239a97406f4df01cf5786dcdde58e464395a682d
|
ResidualConv1dGLU
|
import math
import torch
import torch.utils.data
import torch.nn.functional as F
import torch.nn as nn
class ResidualConv1dGLU(nn.Module):
"""Residual dilated conv1d + Gated linear unit
Args:
residual_channels (int): Residual input / output channels
gate_channels (int): Gated activation channels.
kernel_size (int): Kernel size of convolution layers.
skip_out_channels (int): Skip connection channels. If None, set to same
as ``residual_channels``.
cin_channels (int): Local conditioning channels. If negative value is
set, local conditioning is disabled.
gin_channels (int): Global conditioning channels. If negative value is
set, global conditioning is disabled.
dropout (float): Dropout probability.
padding (int): Padding for convolution layers. If None, proper padding
is computed depends on dilation and kernel_size.
dilation (int): Dilation factor.
"""
def __init__(self, residual_channels, gate_channels, kernel_size,
skip_out_channels=None, cin_channels=-1, gin_channels=-1, dropout=1 -
0.95, padding=None, dilation=1, bias=True, *args, **kwargs):
super(ResidualConv1dGLU, self).__init__()
self.dropout = dropout
if skip_out_channels is None:
skip_out_channels = residual_channels
if padding is None:
padding = (kernel_size - 1) // 2 * dilation
self.conv = nn.Conv1d(residual_channels, gate_channels, kernel_size,
*args, padding=padding, dilation=dilation, bias=bias, **kwargs)
gate_out_channels = gate_channels // 2
self.conv1x1_out = nn.Conv1d(gate_out_channels, residual_channels,
1, bias=bias)
self.conv1x1_skip = nn.Conv1d(gate_out_channels, skip_out_channels,
1, bias=bias)
def forward(self, x):
"""Forward
Args:
x (Tensor): B x C x T
c (Tensor): B x C x T, Local conditioning features
g (Tensor): B x C x T, Expanded global conditioning features
Returns:
Tensor: output
"""
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
splitdim = 1
x = self.conv(x)
a, b = x.split(x.size(splitdim) // 2, dim=splitdim)
x = torch.tanh(a) * torch.sigmoid(b)
s = self.conv1x1_skip(x)
x = self.conv1x1_out(x)
x = (x + residual) * math.sqrt(0.5)
return x, s
def get_inputs():
return [torch.rand([4, 4, 2])]
def get_init_inputs():
return [[], {'residual_channels': 4, 'gate_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.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
@triton.jit
def triton_poi_fused_mul_sigmoid_tanh_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
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_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + x0 + 4 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (2 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tmp6 = tmp4 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp8 = tmp3 * tmp7
tl.store(out_ptr0 + x2, tmp3, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
tl.store(out_ptr2 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_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)
@triton.jit
def triton_poi_fused_add_convolution_mul_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 2
x1 = xindex // 2 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = 0.7071067811865476
tmp6 = tmp4 * tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 2, 1), (2, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 2, 1), (2, 1, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
padding=(1,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1), (4, 1, 1))
buf1 = empty_strided_cuda((4, 2, 1), (2, 1, 1), torch.float32)
buf2 = empty_strided_cuda((4, 2, 1), (2, 1, 1), torch.float32)
buf3 = empty_strided_cuda((4, 2, 1), (2, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_tanh_0[grid(8)](buf0, primals_3, buf1,
buf2, buf3, 8, XBLOCK=8, num_warps=1, num_stages=1)
del buf0
del primals_3
buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 1), (4, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_1[grid(16)](buf5, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf6 = extern_kernels.convolution(buf3, primals_6, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 1), (4, 1, 1))
buf7 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
triton_poi_fused_add_convolution_mul_2[grid(32)](buf6, primals_7,
primals_1, buf7, 32, XBLOCK=32, num_warps=1, num_stages=1)
del buf6
del primals_7
return (buf7, buf5, primals_1, primals_2, primals_4, primals_6, buf1,
buf2, buf3)
class ResidualConv1dGLUNew(nn.Module):
"""Residual dilated conv1d + Gated linear unit
Args:
residual_channels (int): Residual input / output channels
gate_channels (int): Gated activation channels.
kernel_size (int): Kernel size of convolution layers.
skip_out_channels (int): Skip connection channels. If None, set to same
as ``residual_channels``.
cin_channels (int): Local conditioning channels. If negative value is
set, local conditioning is disabled.
gin_channels (int): Global conditioning channels. If negative value is
set, global conditioning is disabled.
dropout (float): Dropout probability.
padding (int): Padding for convolution layers. If None, proper padding
is computed depends on dilation and kernel_size.
dilation (int): Dilation factor.
"""
def __init__(self, residual_channels, gate_channels, kernel_size,
skip_out_channels=None, cin_channels=-1, gin_channels=-1, dropout=1 -
0.95, padding=None, dilation=1, bias=True, *args, **kwargs):
super(ResidualConv1dGLUNew, self).__init__()
self.dropout = dropout
if skip_out_channels is None:
skip_out_channels = residual_channels
if padding is None:
padding = (kernel_size - 1) // 2 * dilation
self.conv = nn.Conv1d(residual_channels, gate_channels, kernel_size,
*args, padding=padding, dilation=dilation, bias=bias, **kwargs)
gate_out_channels = gate_channels // 2
self.conv1x1_out = nn.Conv1d(gate_out_channels, residual_channels,
1, bias=bias)
self.conv1x1_skip = nn.Conv1d(gate_out_channels, skip_out_channels,
1, bias=bias)
def forward(self, input_0):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_4 = self.conv1x1_out.weight
primals_5 = self.conv1x1_out.bias
primals_6 = self.conv1x1_skip.weight
primals_7 = self.conv1x1_skip.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
ChanganVR/hifigan-denoiser
|
ResidualConv1dGLU
| false
| 13,466
|
[
"Apache-2.0"
] | 100
|
9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
https://github.com/ChanganVR/hifigan-denoiser/tree/9bd77c53556e1372b4bbff8dce8b120297cc4e5c
|
ShapeConv2d
|
from torch.nn import Module
import math
import torch
import numpy as np
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn import init
from torch._jit_internal import Optional
from torch.nn.modules.module import Module
class ShapeConv2d(Module):
"""
ShapeConv2d can be used as an alternative for torch.nn.Conv2d.
"""
__constants__ = ['stride', 'padding', 'dilation', 'groups',
'padding_mode', 'output_padding', 'in_channels', 'out_channels',
'kernel_size', 'D_mul']
__annotations__ = {'bias': Optional[torch.Tensor]}
def __init__(self, in_channels, out_channels, kernel_size, D_mul=None,
stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode=
'zeros'):
super(ShapeConv2d, self).__init__()
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
if in_channels % groups != 0:
raise ValueError('in_channels must be divisible by groups')
if out_channels % groups != 0:
raise ValueError('out_channels must be divisible by groups')
valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
if padding_mode not in valid_padding_modes:
raise ValueError(
"padding_mode must be one of {}, but got padding_mode='{}'"
.format(valid_padding_modes, padding_mode))
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.padding_mode = padding_mode
self.testing = not self.training
self._padding_repeated_twice = tuple(x for x in self.padding for _ in
range(2))
M = self.kernel_size[0]
N = self.kernel_size[1]
self.D_mul = M * N if D_mul is None or M * N <= 1 else D_mul
self.weight = Parameter(torch.Tensor(out_channels, in_channels //
groups, M, N))
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if M * N > 1:
self.Shape = Parameter(torch.Tensor(in_channels, M * N, self.D_mul)
)
self.Base = Parameter(torch.Tensor(1))
init_zero = np.zeros([in_channels, M * N, self.D_mul], dtype=np
.float32)
init_one = np.ones([1], dtype=np.float32)
self.Shape.data = torch.from_numpy(init_zero)
self.Base.data = torch.from_numpy(init_one)
eye = torch.reshape(torch.eye(M * N, dtype=torch.float32), (1,
M * N, M * N))
D_diag = eye.repeat((in_channels, 1, self.D_mul // (M * N)))
if self.D_mul % (M * N) != 0:
zeros = torch.zeros([1, M * N, self.D_mul % (M * N)])
self.D_diag = Parameter(torch.cat([D_diag, zeros], dim=2),
requires_grad=False)
else:
self.D_diag = Parameter(D_diag, requires_grad=False)
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
else:
self.register_parameter('bias', None)
def extra_repr(self):
s = (
'{in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}'
)
if self.padding != (0,) * len(self.padding):
s += ', padding={padding}'
if self.dilation != (1,) * len(self.dilation):
s += ', dilation={dilation}'
if self.groups != 1:
s += ', groups={groups}'
if self.bias is None:
s += ', bias=False'
if self.padding_mode != 'zeros':
s += ', padding_mode={padding_mode}'
return s.format(**self.__dict__)
def __setstate__(self, state):
super(ShapeConv2d, self).__setstate__(state)
if not hasattr(self, 'padding_mode'):
self.padding_mode = 'zeros'
def _conv_forward(self, input, weight):
if self.padding_mode != 'zeros':
return F.conv2d(F.pad(input, self._padding_repeated_twice, mode
=self.padding_mode), weight, self.bias, self.stride, _pair(
0), self.dilation, self.groups)
return F.conv2d(input, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
def compute_shape_w(self):
Shape = self.Shape + self.D_diag
Base = self.Base
W = torch.reshape(self.weight, (self.out_channels // self.groups,
self.in_channels, self.D_mul))
W_base = torch.mean(W, [2], keepdims=True)
W_shape = W - W_base
D_shape = torch.reshape(torch.einsum('ims,ois->oim', Shape, W_shape
), self.weight.shape)
D_base = torch.reshape(W_base * Base, (self.out_channels, self.
in_channels // self.groups, 1, 1))
DW = D_shape + D_base
return DW
def forward(self, input):
M = self.kernel_size[0]
N = self.kernel_size[1]
if M * N > 1 and not self.testing:
DW = self.compute_shape_w()
else:
DW = self.weight
return self._conv_forward(input, DW)
def _load_from_state_dict(self, state_dict, prefix, local_metadata,
strict, missing_keys, unexpected_keys, error_msgs):
self.testing = not self.training
super(ShapeConv2d, self)._load_from_state_dict(state_dict, prefix,
local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
if self.kernel_size[0] * self.kernel_size[1] > 1 and not self.training:
self.weight.data = self.compute_shape_w()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.nn import Module
import math
import numpy as np
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn import init
from torch._jit_internal import Optional
from torch.nn.modules.module import Module
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_sub_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tmp7 = tmp0 - tmp6
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp7, xmask)
@triton.jit
def triton_poi_fused_add_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
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tl.load(in_ptr1 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 * tmp3
tmp5 = tmp0 + tmp4
tl.store(in_out_ptr0 + x3, tmp5, xmask)
@triton.jit
def triton_poi_fused_convolution_3(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
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
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (x1 + 64 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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, 16, 16), (256, 16, 1))
assert_size_stride(primals_2, (4, 16, 16), (256, 16, 1))
assert_size_stride(primals_3, (1,), (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, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_mean_sub_0[grid(16)](buf1, primals_4, buf3, 16, 16,
XBLOCK=8, num_warps=2, num_stages=1)
del primals_4
buf2 = empty_strided_cuda((4, 16, 16), (256, 16, 1), torch.float32)
triton_poi_fused_add_1[grid(1024)](primals_1, primals_2, buf2, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(buf2, reinterpret_tensor(buf3, (4, 16, 4), (16,
1, 64), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (1, 64, 16, 4), 0)
del buf4
triton_poi_fused_add_2[grid(256)](buf5, buf1, primals_3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_convolution_3[grid(4, 64)](buf5, buf6, 4, 64,
XBLOCK=32, YBLOCK=4, num_warps=4, num_stages=1)
buf7 = extern_kernels.convolution(primals_6, buf6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 4, 1, 1), (4, 1, 1, 1))
del buf6
buf8 = buf7
del buf7
triton_poi_fused_convolution_4[grid(16)](buf8, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf8, primals_3, primals_6, buf1, buf5, reinterpret_tensor(buf2,
(4, 16, 16), (256, 1, 16), 0), reinterpret_tensor(buf3, (4, 4, 16),
(16, 64, 1), 0)
class ShapeConv2dNew(Module):
"""
ShapeConv2d can be used as an alternative for torch.nn.Conv2d.
"""
__constants__ = ['stride', 'padding', 'dilation', 'groups',
'padding_mode', 'output_padding', 'in_channels', 'out_channels',
'kernel_size', 'D_mul']
__annotations__ = {'bias': Optional[torch.Tensor]}
def __init__(self, in_channels, out_channels, kernel_size, D_mul=None,
stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode=
'zeros'):
super(ShapeConv2dNew, self).__init__()
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
if in_channels % groups != 0:
raise ValueError('in_channels must be divisible by groups')
if out_channels % groups != 0:
raise ValueError('out_channels must be divisible by groups')
valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
if padding_mode not in valid_padding_modes:
raise ValueError(
"padding_mode must be one of {}, but got padding_mode='{}'"
.format(valid_padding_modes, padding_mode))
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.padding_mode = padding_mode
self.testing = not self.training
self._padding_repeated_twice = tuple(x for x in self.padding for _ in
range(2))
M = self.kernel_size[0]
N = self.kernel_size[1]
self.D_mul = M * N if D_mul is None or M * N <= 1 else D_mul
self.weight = Parameter(torch.Tensor(out_channels, in_channels //
groups, M, N))
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if M * N > 1:
self.Shape = Parameter(torch.Tensor(in_channels, M * N, self.D_mul)
)
self.Base = Parameter(torch.Tensor(1))
init_zero = np.zeros([in_channels, M * N, self.D_mul], dtype=np
.float32)
init_one = np.ones([1], dtype=np.float32)
self.Shape.data = torch.from_numpy(init_zero)
self.Base.data = torch.from_numpy(init_one)
eye = torch.reshape(torch.eye(M * N, dtype=torch.float32), (1,
M * N, M * N))
D_diag = eye.repeat((in_channels, 1, self.D_mul // (M * N)))
if self.D_mul % (M * N) != 0:
zeros = torch.zeros([1, M * N, self.D_mul % (M * N)])
self.D_diag = Parameter(torch.cat([D_diag, zeros], dim=2),
requires_grad=False)
else:
self.D_diag = Parameter(D_diag, requires_grad=False)
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
else:
self.register_parameter('bias', None)
def extra_repr(self):
s = (
'{in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}'
)
if self.padding != (0,) * len(self.padding):
s += ', padding={padding}'
if self.dilation != (1,) * len(self.dilation):
s += ', dilation={dilation}'
if self.groups != 1:
s += ', groups={groups}'
if self.bias is None:
s += ', bias=False'
if self.padding_mode != 'zeros':
s += ', padding_mode={padding_mode}'
return s.format(**self.__dict__)
def __setstate__(self, state):
super(ShapeConv2dNew, self).__setstate__(state)
if not hasattr(self, 'padding_mode'):
self.padding_mode = 'zeros'
def _conv_forward(self, input, weight):
if self.padding_mode != 'zeros':
return F.conv2d(F.pad(input, self._padding_repeated_twice, mode
=self.padding_mode), weight, self.bias, self.stride, _pair(
0), self.dilation, self.groups)
return F.conv2d(input, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
def compute_shape_w(self):
Shape = self.Shape + self.D_diag
Base = self.Base
W = torch.reshape(self.weight, (self.out_channels // self.groups,
self.in_channels, self.D_mul))
W_base = torch.mean(W, [2], keepdims=True)
W_shape = W - W_base
D_shape = torch.reshape(torch.einsum('ims,ois->oim', Shape, W_shape
), self.weight.shape)
D_base = torch.reshape(W_base * Base, (self.out_channels, self.
in_channels // self.groups, 1, 1))
DW = D_shape + D_base
return DW
def _load_from_state_dict(self, state_dict, prefix, local_metadata,
strict, missing_keys, unexpected_keys, error_msgs):
self.testing = not self.training
super(ShapeConv2dNew, self)._load_from_state_dict(state_dict,
prefix, local_metadata, strict, missing_keys, unexpected_keys,
error_msgs)
if self.kernel_size[0] * self.kernel_size[1] > 1 and not self.training:
self.weight.data = self.compute_shape_w()
def forward(self, input_0):
primals_4 = self.weight
primals_1 = self.Shape
primals_3 = self.Base
primals_2 = self.D_diag
primals_5 = self.bias
primals_6 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
COATZ/ShapeConv
|
ShapeConv2d
| false
| 13,467
|
[
"Apache-2.0"
] | 57
|
f34f4e95ee2b69ac645fd5ba608e3c11cfadfded
|
https://github.com/COATZ/ShapeConv/tree/f34f4e95ee2b69ac645fd5ba608e3c11cfadfded
|
Actor
|
import torch
import numpy as np
import torch.nn as nn
def fanin_init(size, fanin=None):
fanin = fanin or size[0]
v = 1.0 / np.sqrt(fanin)
return torch.Tensor(size).uniform_(-v, v)
class Actor(nn.Module):
def __init__(self, nb_states, nb_actions, hidden1=256, hidden2=128,
init_w=0.003):
super(Actor, self).__init__()
self.fc1 = nn.Linear(nb_states, hidden1)
self.fc2 = nn.Linear(hidden1, hidden2)
self.fc3 = nn.Linear(hidden2, nb_actions)
self.relu = nn.ReLU()
self.softsign = nn.Softsign()
self.init_weights(init_w)
def init_weights(self, init_w):
self.fc1.weight.data = fanin_init(self.fc1.weight.data.size())
self.fc2.weight.data = fanin_init(self.fc2.weight.data.size())
self.fc3.weight.data.uniform_(-init_w, init_w)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
out = self.relu(out)
out = self.fc3(out)
out = self.softsign(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nb_states': 4, 'nb_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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_abs_add_div_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl_math.abs(tmp0)
tmp2 = 1.0
tmp3 = tmp1 + tmp2
tmp4 = tmp0 / tmp3
tl.store(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, (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, (128, 256), (256, 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, 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
buf7 = 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, buf7, 16384, 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, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 128), (1, 256), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf3,
primals_5, buf6, 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
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_abs_add_div_2[grid(256)](buf4, buf5, 256, XBLOCK=
256, num_warps=4, num_stages=1)
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), reinterpret_tensor(buf3, (64, 128), (128, 1), 0
), buf4, primals_6, buf6, primals_4, buf7
def fanin_init(size, fanin=None):
fanin = fanin or size[0]
v = 1.0 / np.sqrt(fanin)
return torch.Tensor(size).uniform_(-v, v)
class ActorNew(nn.Module):
def __init__(self, nb_states, nb_actions, hidden1=256, hidden2=128,
init_w=0.003):
super(ActorNew, self).__init__()
self.fc1 = nn.Linear(nb_states, hidden1)
self.fc2 = nn.Linear(hidden1, hidden2)
self.fc3 = nn.Linear(hidden2, nb_actions)
self.relu = nn.ReLU()
self.softsign = nn.Softsign()
self.init_weights(init_w)
def init_weights(self, init_w):
self.fc1.weight.data = fanin_init(self.fc1.weight.data.size())
self.fc2.weight.data = fanin_init(self.fc2.weight.data.size())
self.fc3.weight.data.uniform_(-init_w, init_w)
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]
|
ChangyWen/wolpertinger_ddpg
|
Actor
| false
| 13,468
|
[
"MIT"
] | 46
|
23e1dcf19dd4bed3cc48f898122c3d57cfc296d3
|
https://github.com/ChangyWen/wolpertinger_ddpg/tree/23e1dcf19dd4bed3cc48f898122c3d57cfc296d3
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor, self).__init__()
self.l1 = nn.Linear(state_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, action_dim)
self.max_action = max_action
def forward(self, state):
a = F.relu(self.l1(state))
a = F.relu(self.l2(a))
a = torch.tanh(self.l3(a)) * self.max_action
return a
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4, 'action_dim': 4, 'max_action': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 25600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 400
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 300
x2 = xindex // 1200
x3 = xindex % 1200
tmp0 = tl.load(in_ptr0 + x4, 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 + (x3 + 1216 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 1280 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 300
x1 = xindex // 300
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 300 * (x1 % 4) + 1216 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_mul_tanh_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = 4.0
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (400, 4), (4, 1))
assert_size_stride(primals_2, (400,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (300, 400), (400, 1))
assert_size_stride(primals_5, (300,), (1,))
assert_size_stride(primals_6, (4, 300), (300, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 400), (6400, 1600, 400, 1), 0
)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 400), (6656, 1664, 400, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(25600)](buf1,
primals_2, buf8, 25600, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 400), (400, 1), 0),
reinterpret_tensor(primals_4, (400, 300), (1, 400), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 300), (4864, 1216, 300, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf2,
primals_5, buf3, buf7, 19200, XBLOCK=128, num_warps=4, num_stages=1
)
del primals_5
buf4 = buf2
del buf2
triton_poi_fused_relu_view_2[grid(19200)](buf3, buf4, 19200, XBLOCK
=256, num_warps=4, num_stages=1)
del buf3
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, buf4, reinterpret_tensor(primals_6,
(300, 4), (1, 300), 0), alpha=1, beta=1, out=buf5)
del primals_7
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_tanh_3[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 400), (400, 1), 0
), buf4, buf5, primals_6, buf7, primals_4, buf8
class ActorNew(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(ActorNew, self).__init__()
self.l1 = nn.Linear(state_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, action_dim)
self.max_action = max_action
def forward(self, input_0):
primals_1 = self.l1.weight
primals_2 = self.l1.bias
primals_4 = self.l2.weight
primals_5 = self.l2.bias
primals_6 = self.l3.weight
primals_7 = self.l3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
ChenShawn/Adapted_TD3_Robustness_Certification
|
Actor
| false
| 13,469
|
[
"MIT"
] | 91
|
6b28b031b098a2f0a49f2945f8a669205f09c4fe
|
https://github.com/ChenShawn/Adapted_TD3_Robustness_Certification/tree/6b28b031b098a2f0a49f2945f8a669205f09c4fe
|
Critic
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, state_dim, action_dim):
super(Critic, self).__init__()
self.l1 = nn.Linear(state_dim + action_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, 1)
def forward(self, state, action):
state_action = torch.cat([state, action], 1)
q = F.relu(self.l1(state_action))
q = F.relu(self.l2(q))
q = self.l3(q)
return q
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4, 'action_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 400
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_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 300
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) = 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, (400, 8), (8, 1))
assert_size_stride(primals_4, (400,), (1,))
assert_size_stride(primals_5, (300, 400), (400, 1))
assert_size_stride(primals_6, (300,), (1,))
assert_size_stride(primals_7, (1, 300), (300, 1))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 400), (400, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 400), (1,
8), 0), out=buf1)
del primals_3
buf2 = buf1
del buf1
triton_poi_fused_relu_1[grid(1600)](buf2, primals_4, 1600, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 300), (300, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (400, 300), (
1, 400), 0), out=buf3)
buf4 = buf3
del buf3
triton_poi_fused_relu_2[grid(1200)](buf4, primals_6, 1200, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_6
buf6 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_8, buf4, reinterpret_tensor(primals_7,
(300, 1), (1, 300), 0), alpha=1, beta=1, out=buf6)
del primals_8
return buf6, buf0, buf2, buf4, primals_7, primals_5
class CriticNew(nn.Module):
def __init__(self, state_dim, action_dim):
super(CriticNew, self).__init__()
self.l1 = nn.Linear(state_dim + action_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, 1)
def forward(self, input_0, input_1):
primals_3 = self.l1.weight
primals_4 = self.l1.bias
primals_5 = self.l2.weight
primals_6 = self.l2.bias
primals_7 = self.l3.weight
primals_8 = self.l3.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
ChenShawn/Adapted_TD3_Robustness_Certification
|
Critic
| false
| 13,470
|
[
"MIT"
] | 91
|
6b28b031b098a2f0a49f2945f8a669205f09c4fe
|
https://github.com/ChenShawn/Adapted_TD3_Robustness_Certification/tree/6b28b031b098a2f0a49f2945f8a669205f09c4fe
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.