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
|
|---|---|---|---|---|---|---|---|---|---|---|
SoftmaxAffineLayer
|
import torch
import torch.nn.functional as F
import torch.nn
def to_device(device_object, tensor):
"""
Select device for non-parameters tensor w.r.t model or tensor which has been specified a device.
"""
if isinstance(device_object, torch.nn.Module):
next(device_object.parameters()).device
elif isinstance(device_object, torch.Tensor):
pass
return tensor
class TdnnAffine(torch.nn.Module):
""" An implemented tdnn affine component by conv1d
y = splice(w * x, context) + b
@input_dim: number of dims of frame <=> inputs channels of conv
@output_dim: number of layer nodes <=> outputs channels of conv
@context: a list of context
e.g. [-2,0,2]
If context is [0], then the TdnnAffine is equal to linear layer.
"""
def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=
True, stride=1, groups=1, norm_w=False, norm_f=False):
super(TdnnAffine, self).__init__()
assert input_dim % groups == 0
for index in range(0, len(context) - 1):
if context[index] >= context[index + 1]:
raise ValueError(
'Context tuple {} is invalid, such as the order.'.
format(context))
self.input_dim = input_dim
self.output_dim = output_dim
self.context = context
self.bool_bias = bias
self.pad = pad
self.groups = groups
self.norm_w = norm_w
self.norm_f = norm_f
self.stride = stride
self.left_context = context[0] if context[0] < 0 else 0
self.right_context = context[-1] if context[-1] > 0 else 0
self.tot_context = self.right_context - self.left_context + 1
if self.tot_context > 1 and self.norm_f:
self.norm_f = False
None
kernel_size = self.tot_context,
self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim //
groups, *kernel_size))
if self.bool_bias:
self.bias = torch.nn.Parameter(torch.randn(output_dim))
else:
self.register_parameter('bias', None)
self.init_weight()
if len(context) != self.tot_context:
self.mask = torch.tensor([[[(1 if index in context else 0) for
index in range(self.left_context, self.right_context + 1)]]])
else:
self.mask = None
self.selected_device = False
def init_weight(self):
torch.nn.init.normal_(self.weight, 0.0, 0.01)
if self.bias is not None:
torch.nn.init.constant_(self.bias, 0.0)
def forward(self, inputs):
"""
@inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
assert len(inputs.shape) == 3
assert inputs.shape[1] == self.input_dim
if self.pad:
inputs = F.pad(inputs, (-self.left_context, self.right_context),
mode='constant', value=0)
assert inputs.shape[2] >= self.tot_context
if not self.selected_device and self.mask is not None:
self.mask = to_device(self, self.mask)
self.selected_device = True
filters = (self.weight * self.mask if self.mask is not None else
self.weight)
if self.norm_w:
filters = F.normalize(filters, dim=1)
if self.norm_f:
inputs = F.normalize(inputs, dim=1)
outputs = F.conv1d(inputs, filters, self.bias, stride=self.stride,
padding=0, dilation=1, groups=self.groups)
return outputs
def extra_repr(self):
return (
'{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, groups={groups}, norm_w={norm_w}, norm_f={norm_f}'
.format(**self.__dict__))
@classmethod
def thop_count(self, m, x, y):
x = x[0]
kernel_ops = torch.zeros(m.weight.size()[2:]).numel()
bias_ops = 1 if m.bias is not None else 0
total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops)
m.total_ops += torch.DoubleTensor([int(total_ops)])
class SoftmaxAffineLayer(torch.nn.Module):
""" An usual 2-fold softmax layer with an affine transform.
@dim: which dim to apply softmax on
"""
def __init__(self, input_dim, output_dim, context=[0], dim=1, log=True,
bias=True, groups=1, t=1.0, special_init=False):
super(SoftmaxAffineLayer, self).__init__()
self.affine = TdnnAffine(input_dim, output_dim, context=context,
bias=bias, groups=groups)
self.t = t
if log:
self.softmax = torch.nn.LogSoftmax(dim=dim)
else:
self.softmax = torch.nn.Softmax(dim=dim)
if special_init:
torch.nn.init.xavier_uniform_(self.affine.weight, gain=torch.nn
.init.calculate_gain('sigmoid'))
def forward(self, inputs):
"""
@inputs: any, such as a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
return self.softmax(self.affine(inputs) / self.t)
def get_inputs():
return [torch.rand([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._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
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_convolution_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
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp6 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr1 + 1)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp12 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp13 = tl.load(in_ptr1 + 2)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp18 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp19 = tl.load(in_ptr1 + 3)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp9 = tmp6 + tmp8
tmp10 = tmp9 * tmp4
tmp11 = triton_helpers.maximum(tmp5, tmp10)
tmp15 = tmp12 + tmp14
tmp16 = tmp15 * tmp4
tmp17 = triton_helpers.maximum(tmp11, tmp16)
tmp21 = tmp18 + tmp20
tmp22 = tmp21 * tmp4
tmp23 = triton_helpers.maximum(tmp17, tmp22)
tmp24 = tmp5 - tmp23
tmp25 = tmp24 * tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp10 - tmp23
tmp28 = tmp27 * tmp4
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp26 + tmp29
tmp31 = tmp16 - tmp23
tmp32 = tmp31 * tmp4
tmp33 = tl_math.exp(tmp32)
tmp34 = tmp30 + tmp33
tmp35 = tmp22 - tmp23
tmp36 = tmp35 * tmp4
tmp37 = tl_math.exp(tmp36)
tmp38 = tmp34 + tmp37
tl.store(out_ptr0 + x2, tmp23, xmask)
tl.store(out_ptr1 + x2, tmp38, xmask)
@triton.jit
def triton_poi_fused__log_softmax_convolution_1(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
x3 = xindex
x1 = xindex // 4 % 4
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp8 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp3
tmp9 = tl_math.log(tmp8)
tmp10 = tmp7 - tmp9
tl.store(in_out_ptr0 + x3, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4), (16, 4, 1))
buf1 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
buf2 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_convolution_0[grid(16)](buf0,
primals_3, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf3 = buf0
del buf0
triton_poi_fused__log_softmax_convolution_1[grid(64)](buf3,
primals_3, buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf1
del buf2
del primals_3
return buf3, primals_1, primals_2, buf3
def to_device(device_object, tensor):
"""
Select device for non-parameters tensor w.r.t model or tensor which has been specified a device.
"""
if isinstance(device_object, torch.nn.Module):
next(device_object.parameters()).device
elif isinstance(device_object, torch.Tensor):
pass
return tensor
class TdnnAffine(torch.nn.Module):
""" An implemented tdnn affine component by conv1d
y = splice(w * x, context) + b
@input_dim: number of dims of frame <=> inputs channels of conv
@output_dim: number of layer nodes <=> outputs channels of conv
@context: a list of context
e.g. [-2,0,2]
If context is [0], then the TdnnAffine is equal to linear layer.
"""
def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=
True, stride=1, groups=1, norm_w=False, norm_f=False):
super(TdnnAffine, self).__init__()
assert input_dim % groups == 0
for index in range(0, len(context) - 1):
if context[index] >= context[index + 1]:
raise ValueError(
'Context tuple {} is invalid, such as the order.'.
format(context))
self.input_dim = input_dim
self.output_dim = output_dim
self.context = context
self.bool_bias = bias
self.pad = pad
self.groups = groups
self.norm_w = norm_w
self.norm_f = norm_f
self.stride = stride
self.left_context = context[0] if context[0] < 0 else 0
self.right_context = context[-1] if context[-1] > 0 else 0
self.tot_context = self.right_context - self.left_context + 1
if self.tot_context > 1 and self.norm_f:
self.norm_f = False
None
kernel_size = self.tot_context,
self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim //
groups, *kernel_size))
if self.bool_bias:
self.bias = torch.nn.Parameter(torch.randn(output_dim))
else:
self.register_parameter('bias', None)
self.init_weight()
if len(context) != self.tot_context:
self.mask = torch.tensor([[[(1 if index in context else 0) for
index in range(self.left_context, self.right_context + 1)]]])
else:
self.mask = None
self.selected_device = False
def init_weight(self):
torch.nn.init.normal_(self.weight, 0.0, 0.01)
if self.bias is not None:
torch.nn.init.constant_(self.bias, 0.0)
def forward(self, inputs):
"""
@inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
assert len(inputs.shape) == 3
assert inputs.shape[1] == self.input_dim
if self.pad:
inputs = F.pad(inputs, (-self.left_context, self.right_context),
mode='constant', value=0)
assert inputs.shape[2] >= self.tot_context
if not self.selected_device and self.mask is not None:
self.mask = to_device(self, self.mask)
self.selected_device = True
filters = (self.weight * self.mask if self.mask is not None else
self.weight)
if self.norm_w:
filters = F.normalize(filters, dim=1)
if self.norm_f:
inputs = F.normalize(inputs, dim=1)
outputs = F.conv1d(inputs, filters, self.bias, stride=self.stride,
padding=0, dilation=1, groups=self.groups)
return outputs
def extra_repr(self):
return (
'{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, groups={groups}, norm_w={norm_w}, norm_f={norm_f}'
.format(**self.__dict__))
@classmethod
def thop_count(self, m, x, y):
x = x[0]
kernel_ops = torch.zeros(m.weight.size()[2:]).numel()
bias_ops = 1 if m.bias is not None else 0
total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops)
m.total_ops += torch.DoubleTensor([int(total_ops)])
class SoftmaxAffineLayerNew(torch.nn.Module):
""" An usual 2-fold softmax layer with an affine transform.
@dim: which dim to apply softmax on
"""
def __init__(self, input_dim, output_dim, context=[0], dim=1, log=True,
bias=True, groups=1, t=1.0, special_init=False):
super(SoftmaxAffineLayerNew, self).__init__()
self.affine = TdnnAffine(input_dim, output_dim, context=context,
bias=bias, groups=groups)
self.t = t
if log:
self.softmax = torch.nn.LogSoftmax(dim=dim)
else:
self.softmax = torch.nn.Softmax(dim=dim)
if special_init:
torch.nn.init.xavier_uniform_(self.affine.weight, gain=torch.nn
.init.calculate_gain('sigmoid'))
def forward(self, input_0):
primals_2 = self.affine.weight
primals_3 = self.affine.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
qlindazm/asv-subtools
|
SoftmaxAffineLayer
| false
| 4,235
|
[
"Apache-2.0"
] | 0
|
fe1d31db9f3268622016babe944201f6ff81ed56
|
https://github.com/qlindazm/asv-subtools/tree/fe1d31db9f3268622016babe944201f6ff81ed56
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self, Cin, Cout):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(Cin, Cout, (3, 3))
def forward(self, x):
x0 = self.conv1(x)
x1 = self.conv1(x)
z = torch.cat([x0, x1])
output = F.log_softmax(z, dim=1)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'Cin': 4, 'Cout': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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_cat_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp6 = tl.load(in_ptr1 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK])
tmp20 = tl.load(in_ptr1 + 1)
tmp21 = tl.broadcast_to(tmp20, [XBLOCK])
tmp32 = tl.load(in_ptr1 + 2)
tmp33 = tl.broadcast_to(tmp32, [XBLOCK])
tmp44 = tl.load(in_ptr1 + 3)
tmp45 = tl.broadcast_to(tmp44, [XBLOCK])
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1), tmp4 & xmask, other=0.0)
tmp8 = tmp5 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp4, tmp8, tmp9)
tmp11 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp14 = tl.load(in_ptr0 + (x0 + 16 * (-4 + x1)), tmp11 & xmask, other=0.0)
tmp15 = tmp14 + tmp7
tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
tmp17 = tl.where(tmp11, tmp15, tmp16)
tmp18 = tl.where(tmp4, tmp10, tmp17)
tmp19 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), tmp4 & xmask, other=0.0)
tmp22 = tmp19 + tmp21
tmp23 = tl.full(tmp22.shape, 0.0, tmp22.dtype)
tmp24 = tl.where(tmp4, tmp22, tmp23)
tmp25 = tl.load(in_ptr0 + (4 + x0 + 16 * (-4 + x1)), tmp11 & xmask,
other=0.0)
tmp26 = tmp25 + tmp21
tmp27 = tl.full(tmp26.shape, 0.0, tmp26.dtype)
tmp28 = tl.where(tmp11, tmp26, tmp27)
tmp29 = tl.where(tmp4, tmp24, tmp28)
tmp30 = triton_helpers.maximum(tmp18, tmp29)
tmp31 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), tmp4 & xmask, other=0.0)
tmp34 = tmp31 + tmp33
tmp35 = tl.full(tmp34.shape, 0.0, tmp34.dtype)
tmp36 = tl.where(tmp4, tmp34, tmp35)
tmp37 = tl.load(in_ptr0 + (8 + x0 + 16 * (-4 + x1)), tmp11 & xmask,
other=0.0)
tmp38 = tmp37 + tmp33
tmp39 = tl.full(tmp38.shape, 0.0, tmp38.dtype)
tmp40 = tl.where(tmp11, tmp38, tmp39)
tmp41 = tl.where(tmp4, tmp36, tmp40)
tmp42 = triton_helpers.maximum(tmp30, tmp41)
tmp43 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), tmp4 & xmask, other=0.0)
tmp46 = tmp43 + tmp45
tmp47 = tl.full(tmp46.shape, 0.0, tmp46.dtype)
tmp48 = tl.where(tmp4, tmp46, tmp47)
tmp49 = tl.load(in_ptr0 + (12 + x0 + 16 * (-4 + x1)), tmp11 & xmask,
other=0.0)
tmp50 = tmp49 + tmp45
tmp51 = tl.full(tmp50.shape, 0.0, tmp50.dtype)
tmp52 = tl.where(tmp11, tmp50, tmp51)
tmp53 = tl.where(tmp4, tmp48, tmp52)
tmp54 = triton_helpers.maximum(tmp42, tmp53)
tmp55 = tmp18 - tmp54
tmp56 = tl_math.exp(tmp55)
tmp57 = tmp29 - tmp54
tmp58 = tl_math.exp(tmp57)
tmp59 = tmp56 + tmp58
tmp60 = tmp41 - tmp54
tmp61 = tl_math.exp(tmp60)
tmp62 = tmp59 + tmp61
tmp63 = tmp53 - tmp54
tmp64 = tl_math.exp(tmp63)
tmp65 = tmp62 + tmp64
tl.store(out_ptr0 + x2, tmp54, xmask)
tl.store(out_ptr1 + x2, tmp65, xmask)
@triton.jit
def triton_poi_fused__log_softmax_cat_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x1 = xindex // 4 % 4
x0 = xindex % 4
x4 = xindex
tmp19 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr3 + (x0 + 4 * x2), xmask, eviction_policy=
'evict_last')
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x3 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp13 = tl.load(in_ptr0 + (x3 + 16 * (-4 + x2)), tmp10 & xmask, other=0.0)
tmp14 = tl.load(in_ptr1 + x1, tmp10 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tmp13 + tmp14
tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
tmp17 = tl.where(tmp10, tmp15, tmp16)
tmp18 = tl.where(tmp4, tmp9, tmp17)
tmp20 = tmp18 - tmp19
tmp22 = tl_math.log(tmp21)
tmp23 = tmp20 - tmp22
tl.store(out_ptr0 + x4, tmp23, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1))
buf1 = empty_strided_cuda((8, 1, 2, 2), (4, 32, 2, 1), torch.float32)
buf2 = empty_strided_cuda((8, 1, 2, 2), (4, 32, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_cat_0[grid(32)](buf0, primals_2, buf1,
buf2, 32, XBLOCK=32, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((8, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused__log_softmax_cat_1[grid(128)](buf0, primals_2,
buf1, buf2, buf3, 128, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del buf1
del buf2
del primals_2
return buf3, primals_1, primals_3, buf3
class NetNew(nn.Module):
def __init__(self, Cin, Cout):
super(NetNew, self).__init__()
self.conv1 = nn.Conv2d(Cin, Cout, (3, 3))
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
saeta/mlir-npcomp
|
Net
| false
| 4,236
|
[
"Apache-2.0"
] | 0
|
85898aaf10ea30237ee1d66c977b966cf7fcf6d0
|
https://github.com/saeta/mlir-npcomp/tree/85898aaf10ea30237ee1d66c977b966cf7fcf6d0
|
ChunkSeparationAffine
|
import torch
import torch.nn.functional as F
import torch.nn
def to_device(device_object, tensor):
"""
Select device for non-parameters tensor w.r.t model or tensor which has been specified a device.
"""
if isinstance(device_object, torch.nn.Module):
next(device_object.parameters()).device
elif isinstance(device_object, torch.Tensor):
pass
return tensor
class TdnnAffine(torch.nn.Module):
""" An implemented tdnn affine component by conv1d
y = splice(w * x, context) + b
@input_dim: number of dims of frame <=> inputs channels of conv
@output_dim: number of layer nodes <=> outputs channels of conv
@context: a list of context
e.g. [-2,0,2]
If context is [0], then the TdnnAffine is equal to linear layer.
"""
def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=
True, stride=1, groups=1, norm_w=False, norm_f=False):
super(TdnnAffine, self).__init__()
assert input_dim % groups == 0
for index in range(0, len(context) - 1):
if context[index] >= context[index + 1]:
raise ValueError(
'Context tuple {} is invalid, such as the order.'.
format(context))
self.input_dim = input_dim
self.output_dim = output_dim
self.context = context
self.bool_bias = bias
self.pad = pad
self.groups = groups
self.norm_w = norm_w
self.norm_f = norm_f
self.stride = stride
self.left_context = context[0] if context[0] < 0 else 0
self.right_context = context[-1] if context[-1] > 0 else 0
self.tot_context = self.right_context - self.left_context + 1
if self.tot_context > 1 and self.norm_f:
self.norm_f = False
None
kernel_size = self.tot_context,
self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim //
groups, *kernel_size))
if self.bool_bias:
self.bias = torch.nn.Parameter(torch.randn(output_dim))
else:
self.register_parameter('bias', None)
self.init_weight()
if len(context) != self.tot_context:
self.mask = torch.tensor([[[(1 if index in context else 0) for
index in range(self.left_context, self.right_context + 1)]]])
else:
self.mask = None
self.selected_device = False
def init_weight(self):
torch.nn.init.normal_(self.weight, 0.0, 0.01)
if self.bias is not None:
torch.nn.init.constant_(self.bias, 0.0)
def forward(self, inputs):
"""
@inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
assert len(inputs.shape) == 3
assert inputs.shape[1] == self.input_dim
if self.pad:
inputs = F.pad(inputs, (-self.left_context, self.right_context),
mode='constant', value=0)
assert inputs.shape[2] >= self.tot_context
if not self.selected_device and self.mask is not None:
self.mask = to_device(self, self.mask)
self.selected_device = True
filters = (self.weight * self.mask if self.mask is not None else
self.weight)
if self.norm_w:
filters = F.normalize(filters, dim=1)
if self.norm_f:
inputs = F.normalize(inputs, dim=1)
outputs = F.conv1d(inputs, filters, self.bias, stride=self.stride,
padding=0, dilation=1, groups=self.groups)
return outputs
def extra_repr(self):
return (
'{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, groups={groups}, norm_w={norm_w}, norm_f={norm_f}'
.format(**self.__dict__))
@classmethod
def thop_count(self, m, x, y):
x = x[0]
kernel_ops = torch.zeros(m.weight.size()[2:]).numel()
bias_ops = 1 if m.bias is not None else 0
total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops)
m.total_ops += torch.DoubleTensor([int(total_ops)])
class ChunkSeparationAffine(torch.nn.Module):
"""By this component, the chunk will be grouped to two parts, odd and even.
"""
def __init__(self, input_dim, output_dim, **options):
super(ChunkSeparationAffine, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.odd = TdnnAffine(input_dim, output_dim // 2, stride=2, **options)
self.even = TdnnAffine(input_dim, output_dim // 2, stride=2, **options)
def forward(self, inputs):
"""
@inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
assert len(inputs.shape) == 3
assert inputs.shape[1] == self.input_dim
if inputs.shape[2] % 2 != 0:
inputs = F.pad(inputs, (0, 1), mode='constant', value=0)
return torch.cat((self.odd(inputs), self.even(inputs[:, :, 1:])), dim=1
)
def get_inputs():
return [torch.rand([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
import torch.nn.functional as F
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x1 = xindex // 3
x2 = xindex
tmp0 = tl.load(in_ptr0 + (1 + x0 + 4 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 2 % 4
x0 = xindex % 2
x2 = xindex // 8
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 2 * x1 + 4 * x2), tmp4 & xmask, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp13 = tl.load(in_ptr2 + (x0 + 2 * (-2 + x1) + 4 * x2), tmp10 & xmask,
other=0.0)
tmp14 = tl.load(in_ptr3 + (-2 + x1), tmp10 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tmp13 + tmp14
tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
tmp17 = tl.where(tmp10, tmp15, tmp16)
tmp18 = tl.where(tmp4, tmp9, tmp17)
tl.store(out_ptr0 + x3, tmp18, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (2, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (2, 4, 1), (4, 1, 1))
assert_size_stride(primals_5, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(2,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 2, 2), (4, 2, 1))
buf1 = empty_strided_cuda((4, 4, 3), (12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(48)](primals_1, buf1, 48,
XBLOCK=64, num_warps=1, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 2), (4, 2, 1))
buf3 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](buf0, primals_3, buf2, primals_5,
buf3, 32, XBLOCK=32, num_warps=1, num_stages=1)
del buf0
del buf2
del primals_3
del primals_5
return buf3, primals_1, primals_2, primals_4, buf1
def to_device(device_object, tensor):
"""
Select device for non-parameters tensor w.r.t model or tensor which has been specified a device.
"""
if isinstance(device_object, torch.nn.Module):
next(device_object.parameters()).device
elif isinstance(device_object, torch.Tensor):
pass
return tensor
class TdnnAffine(torch.nn.Module):
""" An implemented tdnn affine component by conv1d
y = splice(w * x, context) + b
@input_dim: number of dims of frame <=> inputs channels of conv
@output_dim: number of layer nodes <=> outputs channels of conv
@context: a list of context
e.g. [-2,0,2]
If context is [0], then the TdnnAffine is equal to linear layer.
"""
def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=
True, stride=1, groups=1, norm_w=False, norm_f=False):
super(TdnnAffine, self).__init__()
assert input_dim % groups == 0
for index in range(0, len(context) - 1):
if context[index] >= context[index + 1]:
raise ValueError(
'Context tuple {} is invalid, such as the order.'.
format(context))
self.input_dim = input_dim
self.output_dim = output_dim
self.context = context
self.bool_bias = bias
self.pad = pad
self.groups = groups
self.norm_w = norm_w
self.norm_f = norm_f
self.stride = stride
self.left_context = context[0] if context[0] < 0 else 0
self.right_context = context[-1] if context[-1] > 0 else 0
self.tot_context = self.right_context - self.left_context + 1
if self.tot_context > 1 and self.norm_f:
self.norm_f = False
None
kernel_size = self.tot_context,
self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim //
groups, *kernel_size))
if self.bool_bias:
self.bias = torch.nn.Parameter(torch.randn(output_dim))
else:
self.register_parameter('bias', None)
self.init_weight()
if len(context) != self.tot_context:
self.mask = torch.tensor([[[(1 if index in context else 0) for
index in range(self.left_context, self.right_context + 1)]]])
else:
self.mask = None
self.selected_device = False
def init_weight(self):
torch.nn.init.normal_(self.weight, 0.0, 0.01)
if self.bias is not None:
torch.nn.init.constant_(self.bias, 0.0)
def forward(self, inputs):
"""
@inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
"""
assert len(inputs.shape) == 3
assert inputs.shape[1] == self.input_dim
if self.pad:
inputs = F.pad(inputs, (-self.left_context, self.right_context),
mode='constant', value=0)
assert inputs.shape[2] >= self.tot_context
if not self.selected_device and self.mask is not None:
self.mask = to_device(self, self.mask)
self.selected_device = True
filters = (self.weight * self.mask if self.mask is not None else
self.weight)
if self.norm_w:
filters = F.normalize(filters, dim=1)
if self.norm_f:
inputs = F.normalize(inputs, dim=1)
outputs = F.conv1d(inputs, filters, self.bias, stride=self.stride,
padding=0, dilation=1, groups=self.groups)
return outputs
def extra_repr(self):
return (
'{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, groups={groups}, norm_w={norm_w}, norm_f={norm_f}'
.format(**self.__dict__))
@classmethod
def thop_count(self, m, x, y):
x = x[0]
kernel_ops = torch.zeros(m.weight.size()[2:]).numel()
bias_ops = 1 if m.bias is not None else 0
total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops)
m.total_ops += torch.DoubleTensor([int(total_ops)])
class ChunkSeparationAffineNew(torch.nn.Module):
"""By this component, the chunk will be grouped to two parts, odd and even.
"""
def __init__(self, input_dim, output_dim, **options):
super(ChunkSeparationAffineNew, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.odd = TdnnAffine(input_dim, output_dim // 2, stride=2, **options)
self.even = TdnnAffine(input_dim, output_dim // 2, stride=2, **options)
def forward(self, input_0):
primals_2 = self.odd.weight
primals_3 = self.odd.bias
primals_4 = self.even.weight
primals_5 = self.even.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
qlindazm/asv-subtools
|
ChunkSeparationAffine
| false
| 4,237
|
[
"Apache-2.0"
] | 0
|
fe1d31db9f3268622016babe944201f6ff81ed56
|
https://github.com/qlindazm/asv-subtools/tree/fe1d31db9f3268622016babe944201f6ff81ed56
|
BartClassificationHead
|
import torch
from torch import nn
import torch.utils.checkpoint
class BartClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, input_dim: 'int', inner_dim: 'int', pooler_dropout:
'float'):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
self.dropout = nn.Dropout(p=pooler_dropout)
self.out_proj = nn.Linear(inner_dim, 1, bias=True)
self.sigmoid = nn.Sigmoid()
def forward(self, hidden_states: 'torch.Tensor', mask: 'torch.Tensor'):
hidden_states = self.dropout(hidden_states)
hidden_states = self.dense(hidden_states)
hidden_states = torch.tanh(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.out_proj(hidden_states)
sent_scores = self.sigmoid(hidden_states)
sent_scores = sent_scores.squeeze(-1) * mask.float()
return sent_scores
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'inner_dim': 4, 'pooler_dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (1, 4), (4, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_1[grid(256)](buf3, primals_6, buf4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
return buf4, primals_6, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1, buf3, primals_4
class BartClassificationHeadNew(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, input_dim: 'int', inner_dim: 'int', pooler_dropout:
'float'):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
self.dropout = nn.Dropout(p=pooler_dropout)
self.out_proj = nn.Linear(inner_dim, 1, bias=True)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0, input_1):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_4 = self.out_proj.weight
primals_5 = self.out_proj.bias
primals_1 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
sajastu/transformers-sent-curr
|
BartClassificationHead
| false
| 4,238
|
[
"Apache-2.0"
] | 0
|
6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
https://github.com/sajastu/transformers-sent-curr/tree/6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
GroupedLinearLayer
|
import torch
from torch import nn
import torch.utils.checkpoint
class GroupedLinearLayer(nn.Module):
def __init__(self, input_size, output_size, num_groups):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self.output_size // self.num_groups
self.weight = nn.Parameter(torch.empty(self.num_groups, self.
group_in_dim, self.group_out_dim))
self.bias = nn.Parameter(torch.empty(output_size))
def forward(self, hidden_states):
batch_size = list(hidden_states.size())[0]
x = torch.reshape(hidden_states, [-1, self.num_groups, self.
group_in_dim])
x = x.permute(1, 0, 2)
x = torch.matmul(x, self.weight)
x = x.permute(1, 0, 2)
x = torch.reshape(x, [batch_size, -1, self.output_size])
x = x + self.bias
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4, 'num_groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (1, 64, 4), (4, 4,
1), 0), primals_2, out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 16, 4), (64, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
return buf1, reinterpret_tensor(primals_1, (1, 4, 64), (4, 1, 4), 0)
class GroupedLinearLayerNew(nn.Module):
def __init__(self, input_size, output_size, num_groups):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self.output_size // self.num_groups
self.weight = nn.Parameter(torch.empty(self.num_groups, self.
group_in_dim, self.group_out_dim))
self.bias = nn.Parameter(torch.empty(output_size))
def forward(self, input_0):
primals_2 = self.weight
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
sajastu/transformers-sent-curr
|
GroupedLinearLayer
| false
| 4,239
|
[
"Apache-2.0"
] | 0
|
6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
https://github.com/sajastu/transformers-sent-curr/tree/6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
HubertFeatureProjection
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.utils.checkpoint
class HubertFeatureProjection(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.
layer_norm_eps)
self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
self.dropout = nn.Dropout(config.feat_proj_dropout)
def forward(self, hidden_states):
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.projection(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(conv_dim=[4, 4], layer_norm_eps=1,
hidden_size=4, feat_proj_dropout=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1.0
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(64)](primals_3, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(256)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf0
del buf1
del primals_1
del primals_2
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_3, reinterpret_tensor(buf2, (64, 4), (4, 1), 0), primals_4
class HubertFeatureProjectionNew(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.
layer_norm_eps)
self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
self.dropout = nn.Dropout(config.feat_proj_dropout)
def forward(self, input_0):
primals_1 = self.layer_norm.weight
primals_2 = self.layer_norm.bias
primals_4 = self.projection.weight
primals_5 = self.projection.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
sajastu/transformers-sent-curr
|
HubertFeatureProjection
| false
| 4,240
|
[
"Apache-2.0"
] | 0
|
6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
https://github.com/sajastu/transformers-sent-curr/tree/6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
Actor
|
import torch
import torch.nn as nn
from torch.distributions import Categorical
from torch.distributions import Normal
from torch.distributions import Independent
class Actor(nn.Module):
def __init__(self, obs_dim: 'int', ac_lim: 'float', ac_dim: 'int',
discrete: 'bool'=True):
super().__init__()
self.ac_dim = ac_dim
self.ac_lim = ac_lim
self.obs_dim = obs_dim
self.discrete = discrete
self.fc1 = nn.Linear(obs_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, ac_dim)
if not self.discrete:
self.log_scale = nn.Parameter(0.3 * torch.ones(self.ac_dim),
requires_grad=True)
def forward(self, x):
x = torch.tanh(self.fc1(x))
x = torch.tanh(self.fc2(x))
if self.discrete:
x = torch.softmax(self.fc3(x), dim=1)
else:
x = torch.tanh(self.fc3(x))
return x
def act(self, obs, deterministic=False):
if self.discrete:
action_prob = self.forward(obs)
dist = Categorical(action_prob)
if deterministic:
action = torch.argmax(action_prob, dim=1)
else:
action = dist.sample()
else:
action_mean = self.forward(obs)
action_mean = action_mean * self.ac_lim
normal = Normal(action_mean, torch.exp(self.log_scale))
dist = Independent(normal, 1)
if deterministic:
action = action_mean.detach()
else:
action = dist.sample()
action_logprobs = dist.log_prob(torch.squeeze(action))
return action, action_logprobs
def get_actions_dist(self, obs):
if self.discrete:
action_prob = self.forward(obs)
dist = Categorical(action_prob)
else:
action_mean = self.forward(obs)
action_mean = action_mean * self.ac_lim
normal = Normal(action_mean, torch.exp(self.log_scale))
dist = Independent(normal, 1)
return dist
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_dim': 4, 'ac_lim': 4, 'ac_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
from torch.distributions import Categorical
from torch.distributions import Normal
from torch.distributions import Independent
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (4, 64), (64, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(4096)](buf1, primals_2, 4096, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(4096)](buf3, primals_5, 4096, XBLOCK=
256, 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, 64),
(64, 1), 0), reinterpret_tensor(primals_6, (64, 4), (1, 64), 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__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, buf6, primals_6, primals_4
class ActorNew(nn.Module):
def __init__(self, obs_dim: 'int', ac_lim: 'float', ac_dim: 'int',
discrete: 'bool'=True):
super().__init__()
self.ac_dim = ac_dim
self.ac_lim = ac_lim
self.obs_dim = obs_dim
self.discrete = discrete
self.fc1 = nn.Linear(obs_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, ac_dim)
if not self.discrete:
self.log_scale = nn.Parameter(0.3 * torch.ones(self.ac_dim),
requires_grad=True)
def act(self, obs, deterministic=False):
if self.discrete:
action_prob = self.forward(obs)
dist = Categorical(action_prob)
if deterministic:
action = torch.argmax(action_prob, dim=1)
else:
action = dist.sample()
else:
action_mean = self.forward(obs)
action_mean = action_mean * self.ac_lim
normal = Normal(action_mean, torch.exp(self.log_scale))
dist = Independent(normal, 1)
if deterministic:
action = action_mean.detach()
else:
action = dist.sample()
action_logprobs = dist.log_prob(torch.squeeze(action))
return action, action_logprobs
def get_actions_dist(self, obs):
if self.discrete:
action_prob = self.forward(obs)
dist = Categorical(action_prob)
else:
action_mean = self.forward(obs)
action_mean = action_mean * self.ac_lim
normal = Normal(action_mean, torch.exp(self.log_scale))
dist = Independent(normal, 1)
return dist
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]
|
raznem/rlex
|
Actor
| false
| 4,242
|
[
"MIT"
] | 0
|
d24b964d80067becc81d86f6ce87e5be413b7049
|
https://github.com/raznem/rlex/tree/d24b964d80067becc81d86f6ce87e5be413b7049
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceLoss, self).__init__()
def forward(self, inputs, targets, smooth=1):
inputs = torch.sigmoid(inputs)
inputs = inputs.view(-1)
targets = targets.view(-1)
intersection = (inputs * targets).sum()
dice = (2.0 * intersection + smooth) / (inputs.sum() + targets.sum(
) + smooth)
return 1 - dice
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mul_rsub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tl.broadcast_to(tmp1, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = tl.broadcast_to(tmp2, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = 2.0
tmp14 = tmp6 * tmp13
tmp15 = 1.0
tmp16 = tmp14 + tmp15
tmp17 = tmp9 + tmp12
tmp18 = tmp17 + tmp15
tmp19 = tmp16 / tmp18
tmp20 = tmp15 - tmp19
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp20, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mul_rsub_sum_0[grid(1)](buf3, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf3,
class DiceLossNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceLossNew, 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]
|
salem-devloper/COVID-Lung-Segment
|
DiceLoss
| false
| 4,243
|
[
"MIT"
] | 0
|
6896f6b0c56dac6d32e005afd4a94d59b1917b44
|
https://github.com/salem-devloper/COVID-Lung-Segment/tree/6896f6b0c56dac6d32e005afd4a94d59b1917b44
|
ImageTransformationNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResidualBlock(nn.Module):
"""
Vanilla convolutional residual block from seminal paper by He et al.
Use of instance normalization suggested by Ulyanov et al. in
https://arxiv.org/pdf/1607.08022.pdf%C2%A0%C2%A0%C2%A0%C2%A0.
"""
def __init__(self, filters=128):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(filters, filters, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm1 = nn.InstanceNorm2d(filters, affine=True)
self.conv2 = nn.Conv2d(filters, filters, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm2 = nn.InstanceNorm2d(filters, affine=True)
def forward(self, x):
a = self.conv1(x)
b = self.in_norm1(a)
c = F.relu(b)
d = self.conv2(c)
e = self.in_norm2(d)
return F.relu(e + x)
class ImageTransformationNet(nn.Module):
"""
The image transformation network described in the paper by Johnson et al.,
with instance normalization as suggested by Ulyanov et al.
"""
def __init__(self, vangoh=False):
super(ImageTransformationNet, self).__init__()
self.conv1 = nn.Conv2d(3, 32, (9, 9), padding=(4, 4), padding_mode=
'reflect')
self.in_norm1 = nn.InstanceNorm2d(32, affine=True)
self.conv2 = nn.Conv2d(32, 64, (3, 3), padding=(1, 1), padding_mode
='reflect', stride=2)
self.in_norm2 = nn.InstanceNorm2d(64, affine=True)
self.conv3 = nn.Conv2d(64, 128, (3, 3), padding=(1, 1),
padding_mode='reflect', stride=2)
self.in_norm3 = nn.InstanceNorm2d(128, affine=True)
self.block1 = ResidualBlock()
self.block2 = ResidualBlock()
self.block3 = ResidualBlock()
self.block4 = ResidualBlock()
self.block5 = ResidualBlock()
self.conv4 = nn.Conv2d(128, 64, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm4 = nn.InstanceNorm2d(64, affine=True)
if vangoh:
self.conv5 = nn.ConvTranspose2d(64, 32, (3, 3), padding=(1, 1))
else:
self.conv5 = nn.Conv2d(64, 32, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm5 = nn.InstanceNorm2d(32, affine=True)
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
self.conv6 = nn.Conv2d(32, 3, (9, 9), padding=(4, 4), padding_mode=
'reflect')
def forward(self, x):
x = self.conv1(x)
x = self.in_norm1(x)
x = F.relu(x)
x = self.conv2(x)
x = self.in_norm2(x)
x = F.relu(x)
x = self.conv3(x)
x = self.in_norm3(x)
x = F.relu(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.upsample(x)
x = self.conv4(x)
x = self.in_norm4(x)
x = F.relu(x)
x = self.upsample(x)
x = self.conv5(x)
x = self.in_norm5(x)
x = F.relu(x)
x = self.conv6(x)
return x
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_reflection_pad2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 62208
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 72
x1 = xindex // 72 % 72
x2 = xindex // 5184
x3 = xindex
tmp0 = tl.load(in_ptr0 + (4095 + -1 * tl_math.abs(-63 + tl_math.abs(-4 +
x0)) + -64 * tl_math.abs(-63 + tl_math.abs(-4 + x1)) + 4096 * x2),
xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_red_fused__native_batch_norm_legit_convolution_1(in_out_ptr0,
in_out_ptr1, in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr,
RBLOCK: tl.constexpr):
xnumel = 128
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x3 = xindex
x0 = xindex % 32
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
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
r2 = rindex
tmp0 = tl.load(in_out_ptr0 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', 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)
tl.store(in_out_ptr0 + (r2 + 4096 * x3), tmp2, rmask & xmask)
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 + x3, tmp4, xmask)
tmp7 = 4096.0
tmp8 = tmp5 / tmp7
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = libdevice.rsqrt(tmp10)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp11, xmask)
@triton.jit
def triton_poi_fused_repeat_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0 % 32, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_reflection_pad2d_relu_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 557568
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 66
x1 = xindex // 66 % 66
x2 = xindex // 4356
x3 = xindex
tmp0 = tl.load(in_ptr0 + (4095 + -1 * tl_math.abs(-63 + tl_math.abs(-1 +
x0)) + -64 * tl_math.abs(-63 + tl_math.abs(-1 + x1)) + 4096 * x2),
xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, xmask, 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
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_4(in_out_ptr0,
in_out_ptr1, in_ptr0, out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + (r2 + 1024 * x3), None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = tl.broadcast_to(tmp3, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tl.full([1], 1024, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp3 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 1024.0
tmp17 = tmp15 / tmp16
tmp18 = 1e-05
tmp19 = tmp17 + tmp18
tmp20 = libdevice.rsqrt(tmp19)
tl.store(in_out_ptr0 + (r2 + 1024 * x3), tmp2, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp20, None)
tl.store(out_ptr0 + x3, tmp10, None)
@triton.jit
def triton_poi_fused_repeat_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0 % 64, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_reflection_pad2d_relu_6(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 295936
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 34
x1 = xindex // 34 % 34
x2 = xindex // 1156
x3 = xindex
tmp0 = tl.load(in_ptr0 + (1023 + -1 * tl_math.abs(-31 + tl_math.abs(-1 +
x0)) + -32 * tl_math.abs(-31 + tl_math.abs(-1 + x1)) + 1024 * x2),
xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, xmask, 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
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_relu_repeat_7(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1,
out_ptr2, out_ptr3, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 128
tmp0 = tl.load(in_ptr0 + x0 % 128, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x0 % 128, None, eviction_policy='evict_last')
tmp2 = tl.load(in_out_ptr0 + (r3 + 256 * x0), None)
tmp3 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = tl.broadcast_to(tmp5, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = tl.full([1], 256, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp5 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [RBLOCK])
tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0))
tmp18 = 256.0
tmp19 = tmp17 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp4 - tmp12
tmp24 = tmp23 * tmp22
tmp25 = tmp24 * tmp0
tmp26 = tmp25 + tmp1
tmp27 = tl.full([1], 0, tl.int32)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tl.store(out_ptr0 + x0, tmp0, None)
tl.store(out_ptr1 + x0, tmp1, None)
tl.store(in_out_ptr0 + (r3 + 256 * x0), tmp4, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp22, None)
tl.store(out_ptr3 + (r3 + 256 * x0), tmp28, None)
tl.store(out_ptr2 + x0, tmp12, None)
@triton.jit
def triton_poi_fused_reflection_pad2d_8(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 % 18
x1 = xindex // 18 % 18
x2 = xindex // 324
x3 = xindex
tmp0 = tl.load(in_ptr0 + (255 + -1 * tl_math.abs(-15 + tl_math.abs(-1 +
x0)) + -16 * tl_math.abs(-15 + tl_math.abs(-1 + x1)) + 256 * x2),
None, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, None)
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_9(in_out_ptr0,
in_out_ptr1, in_ptr0, out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + (r2 + 256 * x3), None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = tl.broadcast_to(tmp3, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tl.full([1], 256, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp3 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tmp18 = 1e-05
tmp19 = tmp17 + tmp18
tmp20 = libdevice.rsqrt(tmp19)
tl.store(in_out_ptr0 + (r2 + 256 * x3), tmp2, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp20, None)
tl.store(out_ptr0 + x3, tmp10, None)
@triton.jit
def triton_poi_fused_repeat_10(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0 % 128, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_reflection_pad2d_relu_11(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, 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 % 18
x1 = xindex // 18 % 18
x2 = xindex // 324
x3 = xindex
tmp0 = tl.load(in_ptr0 + (255 + -1 * tl_math.abs(-15 + tl_math.abs(-1 +
x0)) + -16 * tl_math.abs(-15 + tl_math.abs(-1 + x1)) + 256 * x2),
None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tl.store(out_ptr0 + x3, tmp10, None)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_12(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1,
out_ptr3, out_ptr4, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 128
tmp0 = tl.load(in_ptr0 + x0 % 128, None, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 256 * x0), None)
tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp27 = tl.load(in_out_ptr1 + (r3 + 256 * x0), None)
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = tl.broadcast_to(tmp4, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.full([1], 256, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp4 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = tmp3 - tmp11
tmp18 = 256.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp24 = tmp23 * tmp0
tmp26 = tmp24 + tmp25
tmp28 = tmp26 + tmp27
tmp29 = tl.full([1], 0, tl.int32)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tmp31 = 0.0
tmp32 = tmp30 <= tmp31
tl.store(out_ptr0 + x0, tmp0, None)
tl.store(in_out_ptr0 + (r3 + 256 * x0), tmp3, None)
tl.store(in_out_ptr1 + (r3 + 256 * x0), tmp30, None)
tl.store(out_ptr3 + (r3 + 256 * x0), tmp32, None)
tl.store(out_ptr4 + x0, tmp22, None)
tl.store(out_ptr1 + x0, tmp11, None)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_13(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1,
out_ptr3, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 128
tmp0 = tl.load(in_ptr0 + x0 % 128, None, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 256 * x0), None)
tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp27 = tl.load(in_out_ptr1 + (r3 + 256 * x0), None)
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = tl.broadcast_to(tmp4, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.full([1], 256, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp4 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = tmp3 - tmp11
tmp18 = 256.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp24 = tmp23 * tmp0
tmp26 = tmp24 + tmp25
tmp28 = tmp26 + tmp27
tmp29 = tl.full([1], 0, tl.int32)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tl.store(out_ptr0 + x0, tmp0, None)
tl.store(in_out_ptr0 + (r3 + 256 * x0), tmp3, None)
tl.store(in_out_ptr1 + (r3 + 256 * x0), tmp30, None)
tl.store(out_ptr3 + x0, tmp22, None)
tl.store(out_ptr1 + x0, tmp11, None)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_14(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1,
out_ptr3, out_ptr4, out_ptr5, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 128
tmp0 = tl.load(in_ptr0 + x0 % 128, None, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 256 * x0), None)
tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr3 + (r3 + 256 * x0), None)
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = tl.broadcast_to(tmp4, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.full([1], 256, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp4 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = tmp3 - tmp11
tmp18 = 256.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp24 = tmp23 * tmp0
tmp26 = tmp24 + tmp25
tmp28 = tmp26 + tmp27
tmp29 = tl.full([1], 0, tl.int32)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tmp31 = 0.0
tmp32 = tmp27 <= tmp31
tl.store(out_ptr0 + x0, tmp0, None)
tl.store(in_out_ptr0 + (r3 + 256 * x0), tmp3, None)
tl.store(out_ptr3 + (r3 + 256 * x0), tmp30, None)
tl.store(out_ptr4 + (r3 + 256 * x0), tmp32, None)
tl.store(out_ptr5 + x0, tmp22, None)
tl.store(out_ptr1 + x0, tmp11, None)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_15(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1,
out_ptr3, out_ptr4, out_ptr5, out_ptr6, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 128
tmp0 = tl.load(in_ptr0 + x0 % 128, None, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 256 * x0), None)
tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr3 + (r3 + 256 * x0), None)
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = tl.broadcast_to(tmp4, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.full([1], 256, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp4 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = tmp3 - tmp11
tmp18 = 256.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp24 = tmp23 * tmp0
tmp26 = tmp24 + tmp25
tmp28 = tmp26 + tmp27
tmp29 = tl.full([1], 0, tl.int32)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tmp31 = 0.0
tmp32 = tmp30 <= tmp31
tmp33 = tmp27 <= tmp31
tl.store(out_ptr0 + x0, tmp0, None)
tl.store(in_out_ptr0 + (r3 + 256 * x0), tmp3, None)
tl.store(out_ptr3 + (r3 + 256 * x0), tmp30, None)
tl.store(out_ptr4 + (r3 + 256 * x0), tmp32, None)
tl.store(out_ptr5 + (r3 + 256 * x0), tmp33, None)
tl.store(out_ptr6 + x0, tmp22, None)
tl.store(out_ptr1 + x0, tmp11, None)
@triton.jit
def triton_poi_fused_arange_16(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_mul_17(out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tmp3.to(tl.int32)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_reflection_pad2d_18(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 34 % 34
x0 = xindex % 34
x2 = xindex // 1156
x5 = xindex
tmp0 = tl.load(in_ptr0 + (31 + -1 * tl_math.abs(-31 + tl_math.abs(-1 +
x1))), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (31 + -1 * tl_math.abs(-31 + tl_math.abs(-1 +
x0))), None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 16, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr1 + (tmp8 + 16 * tmp4 + 256 * x2), None,
eviction_policy='evict_last')
tl.store(out_ptr0 + x5, tmp9, None)
@triton.jit
def triton_poi_fused_arange_19(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_mul_20(out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tmp3.to(tl.int32)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_reflection_pad2d_relu_21(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1115136
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 66 % 66
x0 = xindex % 66
x2 = xindex // 4356
x5 = xindex
tmp0 = tl.load(in_ptr0 + (63 + -1 * tl_math.abs(-63 + tl_math.abs(-1 +
x1))), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (63 + -1 * tl_math.abs(-63 + tl_math.abs(-1 +
x0))), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 32, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr1 + (tmp8 + 32 * tmp4 + 1024 * x2), xmask,
eviction_policy='evict_last')
tmp11 = tmp9 - tmp10
tmp13 = tmp11 * tmp12
tmp15 = tmp13 * tmp14
tmp17 = tmp15 + tmp16
tmp18 = tl.full([1], 0, tl.int32)
tmp19 = triton_helpers.maximum(tmp18, tmp17)
tl.store(out_ptr0 + x5, tmp19, xmask)
@triton.jit
def triton_poi_fused_reflection_pad2d_relu_22(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, 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 % 72
x1 = xindex // 72 % 72
x2 = xindex // 5184
x3 = xindex
tmp0 = tl.load(in_ptr0 + (4095 + -1 * tl_math.abs(-63 + tl_math.abs(-4 +
x0)) + -64 * tl_math.abs(-63 + tl_math.abs(-4 + x1)) + 4096 * x2),
None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tl.store(out_ptr0 + x3, tmp10, None)
@triton.jit
def triton_poi_fused_convolution_23(in_out_ptr0, in_ptr0, xnumel, XBLOCK:
tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51, primals_52,
primals_53, primals_54, primals_55, primals_56, primals_57,
primals_58, primals_59, primals_60, primals_61, primals_62, primals_63
) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 9, 9), (243, 81, 9, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (32,), (1,))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64,), (1,))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (128,), (1,))
assert_size_stride(primals_13, (128,), (1,))
assert_size_stride(primals_14, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_15, (128,), (1,))
assert_size_stride(primals_16, (128,), (1,))
assert_size_stride(primals_17, (128,), (1,))
assert_size_stride(primals_18, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_19, (128,), (1,))
assert_size_stride(primals_20, (128,), (1,))
assert_size_stride(primals_21, (128,), (1,))
assert_size_stride(primals_22, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_23, (128,), (1,))
assert_size_stride(primals_24, (128,), (1,))
assert_size_stride(primals_25, (128,), (1,))
assert_size_stride(primals_26, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_27, (128,), (1,))
assert_size_stride(primals_28, (128,), (1,))
assert_size_stride(primals_29, (128,), (1,))
assert_size_stride(primals_30, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_31, (128,), (1,))
assert_size_stride(primals_32, (128,), (1,))
assert_size_stride(primals_33, (128,), (1,))
assert_size_stride(primals_34, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_35, (128,), (1,))
assert_size_stride(primals_36, (128,), (1,))
assert_size_stride(primals_37, (128,), (1,))
assert_size_stride(primals_38, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_39, (128,), (1,))
assert_size_stride(primals_40, (128,), (1,))
assert_size_stride(primals_41, (128,), (1,))
assert_size_stride(primals_42, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_43, (128,), (1,))
assert_size_stride(primals_44, (128,), (1,))
assert_size_stride(primals_45, (128,), (1,))
assert_size_stride(primals_46, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_47, (128,), (1,))
assert_size_stride(primals_48, (128,), (1,))
assert_size_stride(primals_49, (128,), (1,))
assert_size_stride(primals_50, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_51, (128,), (1,))
assert_size_stride(primals_52, (128,), (1,))
assert_size_stride(primals_53, (128,), (1,))
assert_size_stride(primals_54, (64, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_55, (64,), (1,))
assert_size_stride(primals_56, (64,), (1,))
assert_size_stride(primals_57, (64,), (1,))
assert_size_stride(primals_58, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_59, (32,), (1,))
assert_size_stride(primals_60, (32,), (1,))
assert_size_stride(primals_61, (32,), (1,))
assert_size_stride(primals_62, (3, 32, 9, 9), (2592, 81, 9, 1))
assert_size_stride(primals_63, (3,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 72, 72), (15552, 5184, 72, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_reflection_pad2d_0[grid(62208)](primals_3, buf0,
62208, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf2 = buf1
del buf1
buf5 = empty_strided_cuda((1, 128, 1, 1), (128, 1, 1, 1), torch.float32
)
buf6 = empty_strided_cuda((1, 128, 1, 1), (128, 1, 128, 128), torch
.float32)
buf8 = reinterpret_tensor(buf6, (1, 128, 1, 1), (128, 1, 1, 1), 0)
del buf6
triton_red_fused__native_batch_norm_legit_convolution_1[grid(128)](buf2
, buf8, primals_2, buf5, 128, 4096, XBLOCK=1, RBLOCK=2048,
num_warps=16, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((128,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(128)](primals_4, buf3, 128, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_4
buf4 = empty_strided_cuda((128,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(128)](primals_5, buf4, 128, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_5
buf9 = empty_strided_cuda((4, 32, 66, 66), (139392, 4356, 66, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_3[grid(557568)](buf2, buf5,
buf8, buf3, buf4, buf9, 557568, XBLOCK=512, num_warps=8,
num_stages=1)
buf10 = extern_kernels.convolution(buf9, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf11 = buf10
del buf10
buf14 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 1, 1), torch.
float32)
buf15 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256),
torch.float32)
buf17 = reinterpret_tensor(buf15, (1, 256, 1, 1), (256, 1, 1, 1), 0)
del buf15
triton_per_fused__native_batch_norm_legit_convolution_4[grid(256)](
buf11, buf17, primals_7, buf14, 256, 1024, num_warps=8,
num_stages=1)
del primals_7
buf12 = empty_strided_cuda((256,), (1,), torch.float32)
triton_poi_fused_repeat_5[grid(256)](primals_8, buf12, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_8
buf13 = empty_strided_cuda((256,), (1,), torch.float32)
triton_poi_fused_repeat_5[grid(256)](primals_9, buf13, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_9
buf18 = empty_strided_cuda((4, 64, 34, 34), (73984, 1156, 34, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_6[grid(295936)](buf11, buf14,
buf17, buf12, buf13, buf18, 295936, XBLOCK=1024, num_warps=4,
num_stages=1)
buf19 = extern_kernels.convolution(buf18, primals_10, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 128, 16, 16), (32768, 256, 16, 1))
buf21 = empty_strided_cuda((512,), (1,), torch.float32)
buf22 = empty_strided_cuda((512,), (1,), torch.float32)
buf20 = buf19
del buf19
buf23 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf24 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf26 = reinterpret_tensor(buf24, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf24
buf27 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
triton_per_fused__native_batch_norm_legit_convolution_relu_repeat_7[
grid(512)](buf20, buf26, primals_12, primals_13, primals_11,
buf21, buf22, buf23, buf27, 512, 256, num_warps=2, num_stages=1)
del primals_11
del primals_12
del primals_13
buf28 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_8[grid(165888)](buf27, buf28,
165888, XBLOCK=512, num_warps=8, num_stages=1)
buf29 = extern_kernels.convolution(buf28, primals_14, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf29, (4, 128, 16, 16), (32768, 256, 16, 1))
buf30 = buf29
del buf29
buf33 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf34 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf36 = reinterpret_tensor(buf34, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf34
triton_per_fused__native_batch_norm_legit_convolution_9[grid(512)](
buf30, buf36, primals_15, buf33, 512, 256, num_warps=2,
num_stages=1)
del primals_15
buf31 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_16, buf31, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_16
buf32 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_17, buf32, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_17
buf37 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_11[grid(165888)](buf30,
buf33, buf36, buf31, buf32, buf37, 165888, XBLOCK=1024,
num_warps=4, num_stages=1)
buf38 = extern_kernels.convolution(buf37, primals_18, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 128, 16, 16), (32768, 256, 16, 1))
buf40 = empty_strided_cuda((512,), (1,), torch.float32)
buf39 = buf38
del buf38
buf41 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf45 = buf27
del buf27
buf147 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf44 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_12[
grid(512)](buf39, buf45, primals_20, primals_19, primals_21,
buf40, buf41, buf147, buf44, 512, 256, num_warps=2, num_stages=1)
del primals_19
del primals_20
del primals_21
buf46 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_8[grid(165888)](buf45, buf46,
165888, XBLOCK=512, num_warps=8, num_stages=1)
buf47 = extern_kernels.convolution(buf46, primals_22, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf47, (4, 128, 16, 16), (32768, 256, 16, 1))
buf48 = buf47
del buf47
buf51 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf52 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf54 = reinterpret_tensor(buf52, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf52
triton_per_fused__native_batch_norm_legit_convolution_9[grid(512)](
buf48, buf54, primals_23, buf51, 512, 256, num_warps=2,
num_stages=1)
del primals_23
buf49 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_24, buf49, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_24
buf50 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_25, buf50, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_25
buf55 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_11[grid(165888)](buf48,
buf51, buf54, buf49, buf50, buf55, 165888, XBLOCK=1024,
num_warps=4, num_stages=1)
buf56 = extern_kernels.convolution(buf55, primals_26, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 128, 16, 16), (32768, 256, 16, 1))
buf58 = empty_strided_cuda((512,), (1,), torch.float32)
buf57 = buf56
del buf56
buf59 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf63 = buf45
del buf45
buf62 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_13[
grid(512)](buf57, buf63, primals_28, primals_27, primals_29,
buf58, buf59, buf62, 512, 256, num_warps=2, num_stages=1)
del primals_27
del primals_28
del primals_29
buf64 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_8[grid(165888)](buf63, buf64,
165888, XBLOCK=512, num_warps=8, num_stages=1)
buf65 = extern_kernels.convolution(buf64, primals_30, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf65, (4, 128, 16, 16), (32768, 256, 16, 1))
buf66 = buf65
del buf65
buf69 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf70 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf72 = reinterpret_tensor(buf70, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf70
triton_per_fused__native_batch_norm_legit_convolution_9[grid(512)](
buf66, buf72, primals_31, buf69, 512, 256, num_warps=2,
num_stages=1)
del primals_31
buf67 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_32, buf67, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_32
buf68 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_33, buf68, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_33
buf73 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_11[grid(165888)](buf66,
buf69, buf72, buf67, buf68, buf73, 165888, XBLOCK=1024,
num_warps=4, num_stages=1)
buf74 = extern_kernels.convolution(buf73, primals_34, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf74, (4, 128, 16, 16), (32768, 256, 16, 1))
buf76 = empty_strided_cuda((512,), (1,), torch.float32)
buf75 = buf74
del buf74
buf77 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf81 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
buf146 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf80 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_14[
grid(512)](buf75, primals_36, primals_35, primals_37, buf63,
buf76, buf77, buf81, buf146, buf80, 512, 256, num_warps=2,
num_stages=1)
del primals_35
del primals_36
del primals_37
buf82 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_8[grid(165888)](buf81, buf82,
165888, XBLOCK=512, num_warps=8, num_stages=1)
buf83 = extern_kernels.convolution(buf82, primals_38, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf83, (4, 128, 16, 16), (32768, 256, 16, 1))
buf84 = buf83
del buf83
buf87 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf88 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf90 = reinterpret_tensor(buf88, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf88
triton_per_fused__native_batch_norm_legit_convolution_9[grid(512)](
buf84, buf90, primals_39, buf87, 512, 256, num_warps=2,
num_stages=1)
del primals_39
buf85 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_40, buf85, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_40
buf86 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_41, buf86, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_41
buf91 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_11[grid(165888)](buf84,
buf87, buf90, buf85, buf86, buf91, 165888, XBLOCK=1024,
num_warps=4, num_stages=1)
buf92 = extern_kernels.convolution(buf91, primals_42, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf92, (4, 128, 16, 16), (32768, 256, 16, 1))
buf94 = empty_strided_cuda((512,), (1,), torch.float32)
buf93 = buf92
del buf92
buf95 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf99 = buf63
del buf63
buf145 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf98 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_14[
grid(512)](buf93, primals_44, primals_43, primals_45, buf81,
buf94, buf95, buf99, buf145, buf98, 512, 256, num_warps=2,
num_stages=1)
del primals_43
del primals_44
del primals_45
buf100 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_8[grid(165888)](buf99, buf100,
165888, XBLOCK=512, num_warps=8, num_stages=1)
buf101 = extern_kernels.convolution(buf100, primals_46, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf101, (4, 128, 16, 16), (32768, 256, 16, 1))
buf102 = buf101
del buf101
buf105 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 1, 1), torch.
float32)
buf106 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf108 = reinterpret_tensor(buf106, (1, 512, 1, 1), (512, 1, 1, 1), 0)
del buf106
triton_per_fused__native_batch_norm_legit_convolution_9[grid(512)](
buf102, buf108, primals_47, buf105, 512, 256, num_warps=2,
num_stages=1)
del primals_47
buf103 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_48, buf103, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_48
buf104 = empty_strided_cuda((512,), (1,), torch.float32)
triton_poi_fused_repeat_10[grid(512)](primals_49, buf104, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_49
buf109 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_11[grid(165888)](buf102,
buf105, buf108, buf103, buf104, buf109, 165888, XBLOCK=1024,
num_warps=4, num_stages=1)
buf110 = extern_kernels.convolution(buf109, primals_50, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf110, (4, 128, 16, 16), (32768, 256, 16, 1))
buf112 = empty_strided_cuda((512,), (1,), torch.float32)
buf111 = buf110
del buf110
buf113 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf117 = buf81
del buf81
buf143 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf144 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf116 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_15[
grid(512)](buf111, primals_52, primals_51, primals_53, buf99,
buf112, buf113, buf117, buf143, buf144, buf116, 512, 256,
num_warps=2, num_stages=1)
del buf99
del primals_51
del primals_52
del primals_53
buf118 = empty_strided_cuda((32,), (1,), torch.int64)
triton_poi_fused_arange_16[grid(32)](buf118, 32, XBLOCK=32,
num_warps=1, num_stages=1)
buf119 = empty_strided_cuda((32,), (1,), torch.int64)
triton_poi_fused__to_copy_add_arange_mul_17[grid(32)](buf119, 32,
XBLOCK=32, num_warps=1, num_stages=1)
buf120 = empty_strided_cuda((4, 128, 34, 34), (147968, 1156, 34, 1),
torch.float32)
triton_poi_fused__unsafe_index_reflection_pad2d_18[grid(591872)](buf119
, buf117, buf120, 591872, XBLOCK=1024, num_warps=4, num_stages=1)
del buf117
buf121 = extern_kernels.convolution(buf120, primals_54, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf121, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf122 = buf121
del buf121
buf125 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 1, 1), torch.
float32)
buf126 = empty_strided_cuda((1, 256, 1, 1), (256, 1, 256, 256),
torch.float32)
buf128 = reinterpret_tensor(buf126, (1, 256, 1, 1), (256, 1, 1, 1), 0)
del buf126
triton_per_fused__native_batch_norm_legit_convolution_4[grid(256)](
buf122, buf128, primals_55, buf125, 256, 1024, num_warps=8,
num_stages=1)
del primals_55
buf123 = empty_strided_cuda((256,), (1,), torch.float32)
triton_poi_fused_repeat_5[grid(256)](primals_56, buf123, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_56
buf124 = empty_strided_cuda((256,), (1,), torch.float32)
triton_poi_fused_repeat_5[grid(256)](primals_57, buf124, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_57
buf129 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused_arange_19[grid(64)](buf129, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf130 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused__to_copy_add_arange_mul_20[grid(64)](buf130, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf131 = empty_strided_cuda((4, 64, 66, 66), (278784, 4356, 66, 1),
torch.float32)
triton_poi_fused__unsafe_index_reflection_pad2d_relu_21[grid(1115136)](
buf130, buf122, buf125, buf128, buf123, buf124, buf131, 1115136,
XBLOCK=512, num_warps=8, num_stages=1)
buf132 = extern_kernels.convolution(buf131, primals_58, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf132, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf133 = buf132
del buf132
buf136 = empty_strided_cuda((1, 128, 1, 1), (128, 1, 1, 1), torch.
float32)
buf137 = empty_strided_cuda((1, 128, 1, 1), (128, 1, 128, 128),
torch.float32)
buf139 = reinterpret_tensor(buf137, (1, 128, 1, 1), (128, 1, 1, 1), 0)
del buf137
triton_red_fused__native_batch_norm_legit_convolution_1[grid(128)](
buf133, buf139, primals_59, buf136, 128, 4096, XBLOCK=1, RBLOCK
=2048, num_warps=16, num_stages=1)
del primals_59
buf134 = empty_strided_cuda((128,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(128)](primals_60, buf134, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_60
buf135 = empty_strided_cuda((128,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(128)](primals_61, buf135, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_61
buf140 = empty_strided_cuda((4, 32, 72, 72), (165888, 5184, 72, 1),
torch.float32)
triton_poi_fused_reflection_pad2d_relu_22[grid(663552)](buf133,
buf136, buf139, buf134, buf135, buf140, 663552, XBLOCK=512,
num_warps=8, num_stages=1)
buf141 = extern_kernels.convolution(buf140, primals_62, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf141, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf142 = buf141
del buf141
triton_poi_fused_convolution_23[grid(49152)](buf142, primals_63,
49152, XBLOCK=256, num_warps=4, num_stages=1)
del primals_63
return (buf142, primals_1, primals_6, primals_10, primals_14,
primals_18, primals_22, primals_26, primals_30, primals_34,
primals_38, primals_42, primals_46, primals_50, primals_54,
primals_58, primals_62, buf0, buf2, buf3, buf4, buf5, buf8, buf9,
buf11, buf12, buf13, buf14, buf17, buf18, buf20, buf21, buf22,
buf23, buf26, buf28, buf30, buf31, buf32, buf33, buf36, buf37,
buf39, buf40, reinterpret_tensor(buf44, (512,), (1,), 0), buf46,
buf48, buf49, buf50, buf51, buf54, buf55, buf57, buf58,
reinterpret_tensor(buf62, (512,), (1,), 0), buf64, buf66, buf67,
buf68, buf69, buf72, buf73, buf75, buf76, reinterpret_tensor(buf80,
(512,), (1,), 0), buf82, buf84, buf85, buf86, buf87, buf90, buf91,
buf93, buf94, reinterpret_tensor(buf98, (512,), (1,), 0), buf100,
buf102, buf103, buf104, buf105, buf108, buf109, buf111, buf112,
reinterpret_tensor(buf116, (512,), (1,), 0), buf118, buf119, buf120,
buf122, buf123, buf124, buf125, buf128, buf129, buf130, buf131,
buf133, buf134, buf135, buf136, buf139, buf140, buf143,
reinterpret_tensor(buf113, (1, 512, 1, 1), (512, 1, 1, 1), 0),
buf144, reinterpret_tensor(buf95, (1, 512, 1, 1), (512, 1, 1, 1), 0
), buf145, reinterpret_tensor(buf77, (1, 512, 1, 1), (512, 1, 1, 1),
0), buf146, reinterpret_tensor(buf59, (1, 512, 1, 1), (512, 1, 1, 1
), 0), buf147, reinterpret_tensor(buf41, (1, 512, 1, 1), (512, 1, 1,
1), 0))
class ResidualBlock(nn.Module):
"""
Vanilla convolutional residual block from seminal paper by He et al.
Use of instance normalization suggested by Ulyanov et al. in
https://arxiv.org/pdf/1607.08022.pdf%C2%A0%C2%A0%C2%A0%C2%A0.
"""
def __init__(self, filters=128):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(filters, filters, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm1 = nn.InstanceNorm2d(filters, affine=True)
self.conv2 = nn.Conv2d(filters, filters, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm2 = nn.InstanceNorm2d(filters, affine=True)
def forward(self, x):
a = self.conv1(x)
b = self.in_norm1(a)
c = F.relu(b)
d = self.conv2(c)
e = self.in_norm2(d)
return F.relu(e + x)
class ImageTransformationNetNew(nn.Module):
"""
The image transformation network described in the paper by Johnson et al.,
with instance normalization as suggested by Ulyanov et al.
"""
def __init__(self, vangoh=False):
super(ImageTransformationNetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 32, (9, 9), padding=(4, 4), padding_mode=
'reflect')
self.in_norm1 = nn.InstanceNorm2d(32, affine=True)
self.conv2 = nn.Conv2d(32, 64, (3, 3), padding=(1, 1), padding_mode
='reflect', stride=2)
self.in_norm2 = nn.InstanceNorm2d(64, affine=True)
self.conv3 = nn.Conv2d(64, 128, (3, 3), padding=(1, 1),
padding_mode='reflect', stride=2)
self.in_norm3 = nn.InstanceNorm2d(128, affine=True)
self.block1 = ResidualBlock()
self.block2 = ResidualBlock()
self.block3 = ResidualBlock()
self.block4 = ResidualBlock()
self.block5 = ResidualBlock()
self.conv4 = nn.Conv2d(128, 64, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm4 = nn.InstanceNorm2d(64, affine=True)
if vangoh:
self.conv5 = nn.ConvTranspose2d(64, 32, (3, 3), padding=(1, 1))
else:
self.conv5 = nn.Conv2d(64, 32, (3, 3), padding=(1, 1),
padding_mode='reflect')
self.in_norm5 = nn.InstanceNorm2d(32, affine=True)
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
self.conv6 = nn.Conv2d(32, 3, (9, 9), padding=(4, 4), padding_mode=
'reflect')
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.in_norm1.weight
primals_5 = self.in_norm1.bias
primals_6 = self.conv2.weight
primals_7 = self.conv2.bias
primals_8 = self.in_norm2.weight
primals_9 = self.in_norm2.bias
primals_10 = self.conv3.weight
primals_11 = self.conv3.bias
primals_12 = self.in_norm3.weight
primals_13 = self.in_norm3.bias
primals_14 = self.block1.conv1.weight
primals_15 = self.block1.conv1.bias
primals_16 = self.block1.in_norm1.weight
primals_17 = self.block1.in_norm1.bias
primals_18 = self.block1.conv2.weight
primals_19 = self.block1.conv2.bias
primals_20 = self.block1.in_norm2.weight
primals_21 = self.block1.in_norm2.bias
primals_22 = self.block2.conv1.weight
primals_23 = self.block2.conv1.bias
primals_24 = self.block2.in_norm1.weight
primals_25 = self.block2.in_norm1.bias
primals_26 = self.block2.conv2.weight
primals_27 = self.block2.conv2.bias
primals_28 = self.block2.in_norm2.weight
primals_29 = self.block2.in_norm2.bias
primals_30 = self.block3.conv1.weight
primals_31 = self.block3.conv1.bias
primals_32 = self.block3.in_norm1.weight
primals_33 = self.block3.in_norm1.bias
primals_34 = self.block3.conv2.weight
primals_35 = self.block3.conv2.bias
primals_36 = self.block3.in_norm2.weight
primals_37 = self.block3.in_norm2.bias
primals_38 = self.block4.conv1.weight
primals_39 = self.block4.conv1.bias
primals_40 = self.block4.in_norm1.weight
primals_41 = self.block4.in_norm1.bias
primals_42 = self.block4.conv2.weight
primals_43 = self.block4.conv2.bias
primals_44 = self.block4.in_norm2.weight
primals_45 = self.block4.in_norm2.bias
primals_46 = self.block5.conv1.weight
primals_47 = self.block5.conv1.bias
primals_48 = self.block5.in_norm1.weight
primals_49 = self.block5.in_norm1.bias
primals_50 = self.block5.conv2.weight
primals_51 = self.block5.conv2.bias
primals_52 = self.block5.in_norm2.weight
primals_53 = self.block5.in_norm2.bias
primals_54 = self.conv4.weight
primals_55 = self.conv4.bias
primals_56 = self.in_norm4.weight
primals_57 = self.in_norm4.bias
primals_58 = self.conv5.weight
primals_59 = self.conv5.bias
primals_60 = self.in_norm5.weight
primals_61 = self.in_norm5.bias
primals_62 = self.conv6.weight
primals_63 = self.conv6.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40, primals_41, primals_42, primals_43, primals_44,
primals_45, primals_46, primals_47, primals_48, primals_49,
primals_50, primals_51, primals_52, primals_53, primals_54,
primals_55, primals_56, primals_57, primals_58, primals_59,
primals_60, primals_61, primals_62, primals_63])
return output[0]
|
rileypsmith/Fast-Style-Transfer
|
ImageTransformationNet
| false
| 4,244
|
[
"MIT"
] | 0
|
8b2164f8bc6d63530f914610b6c5c5c1b0f4ffd5
|
https://github.com/rileypsmith/Fast-Style-Transfer/tree/8b2164f8bc6d63530f914610b6c5c5c1b0f4ffd5
|
LayerNormCustom
|
import torch
import torch.nn as nn
class LayerNormCustom(nn.Module):
"""A layernorm module in the TF style (epsilon inside the square root)."""
def __init__(self, n_hidden, variance_epsilon=1e-12):
super().__init__()
self.gamma = nn.Parameter(torch.ones(n_hidden))
self.beta = nn.Parameter(torch.zeros(n_hidden))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_hidden': 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_mean_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1e-12
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_sub_0[grid(256)](primals_1, buf0, 256, XBLOCK
=128, num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_1[grid(256)](primals_2,
buf0, primals_3, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_2
del primals_3
return buf1, primals_1
class LayerNormCustomNew(nn.Module):
"""A layernorm module in the TF style (epsilon inside the square root)."""
def __init__(self, n_hidden, variance_epsilon=1e-12):
super().__init__()
self.gamma = nn.Parameter(torch.ones(n_hidden))
self.beta = nn.Parameter(torch.zeros(n_hidden))
self.variance_epsilon = variance_epsilon
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]
|
renebidart/pytorch-cifar
|
LayerNormCustom
| false
| 4,245
|
[
"MIT"
] | 0
|
8f623299c25f7f219bab34bc7df41fe24232b1af
|
https://github.com/renebidart/pytorch-cifar/tree/8f623299c25f7f219bab34bc7df41fe24232b1af
|
IBertLMHead
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
import torch.utils.checkpoint
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class IBertLMHead(nn.Module):
"""I-BERT Head for masked language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size,
bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
self.decoder.bias = self.bias
def forward(self, features, **kwargs):
x = self.dense(features)
x = gelu(x)
x = self.layer_norm(x)
x = self.decoder(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, layer_norm_eps=1,
vocab_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
from torch import nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mul_native_layer_norm_pow_tanh_0(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tmp15 = tmp14 * tmp1
tmp16 = tmp14 * tmp14
tmp17 = tmp16 * tmp14
tmp18 = tmp17 * tmp5
tmp19 = tmp14 + tmp18
tmp20 = tmp19 * tmp8
tmp21 = libdevice.tanh(tmp20)
tmp22 = tmp21 + tmp11
tmp23 = tmp15 * tmp22
tmp24 = tmp13 + tmp23
tmp26 = tmp25 * tmp1
tmp27 = tmp25 * tmp25
tmp28 = tmp27 * tmp25
tmp29 = tmp28 * tmp5
tmp30 = tmp25 + tmp29
tmp31 = tmp30 * tmp8
tmp32 = libdevice.tanh(tmp31)
tmp33 = tmp32 + tmp11
tmp34 = tmp26 * tmp33
tmp35 = tmp24 + tmp34
tmp37 = tmp36 * tmp1
tmp38 = tmp36 * tmp36
tmp39 = tmp38 * tmp36
tmp40 = tmp39 * tmp5
tmp41 = tmp36 + tmp40
tmp42 = tmp41 * tmp8
tmp43 = libdevice.tanh(tmp42)
tmp44 = tmp43 + tmp11
tmp45 = tmp37 * tmp44
tmp46 = tmp35 + tmp45
tmp47 = 4.0
tmp48 = tmp46 / tmp47
tmp49 = tmp13 - tmp48
tmp50 = tmp49 * tmp49
tmp51 = tmp23 - tmp48
tmp52 = tmp51 * tmp51
tmp53 = tmp50 + tmp52
tmp54 = tmp34 - tmp48
tmp55 = tmp54 * tmp54
tmp56 = tmp53 + tmp55
tmp57 = tmp45 - tmp48
tmp58 = tmp57 * tmp57
tmp59 = tmp56 + tmp58
tmp60 = tmp59 / tmp47
tl.store(out_ptr0 + x0, tmp48, xmask)
tl.store(out_ptr1 + x0, tmp60, xmask)
@triton.jit
def triton_poi_fused_add_mul_native_layer_norm_pow_tanh_1(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp14 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tmp15 = tmp13 - tmp14
tmp17 = tmp16 + tmp11
tmp18 = libdevice.rsqrt(tmp17)
tmp19 = tmp15 * tmp18
tmp21 = tmp19 * tmp20
tmp23 = tmp21 + tmp22
tl.store(out_ptr0 + x2, tmp23, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_native_layer_norm_pow_tanh_0[grid(64)](buf0,
buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_native_layer_norm_pow_tanh_1[grid(256)](buf0,
buf1, buf2, primals_4, primals_5, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
del buf2
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf3, (64, 4), (4, 1), 0), primals_6
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class IBertLMHeadNew(nn.Module):
"""I-BERT Head for masked language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size,
bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
self.decoder.bias = self.bias
def forward(self, input_0):
primals_2 = self.bias
primals_1 = self.dense.weight
primals_4 = self.dense.bias
primals_5 = self.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_6 = self.decoder.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
sajastu/transformers-sent-curr
|
IBertLMHead
| false
| 4,246
|
[
"Apache-2.0"
] | 0
|
6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
https://github.com/sajastu/transformers-sent-curr/tree/6dc41545c4ac298a010090fbca4b454c2eaf3dbb
|
PatchSequential
|
import math
import torch
import warnings
from typing import Dict
from typing import Optional
from typing import Tuple
import torch.nn as nn
import torch.nn.functional as F
from typing import cast
from typing import List
from typing import Union
from torch.distributions import Bernoulli
from itertools import zip_longest
from collections import OrderedDict
from typing import Any
from typing import Iterator
from typing import NamedTuple
from torch.nn.modules.utils import _pair
from math import pi
def _adapted_sampling(shape: 'Union[Tuple, torch.Size]', dist:
'torch.distributions.Distribution', same_on_batch=False) ->torch.Tensor:
"""The uniform sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
By default, same_on_batch is set to False.
"""
if same_on_batch:
return dist.sample((1, *shape[1:])).repeat(shape[0], *([1] * (len(
shape) - 1)))
return dist.sample(shape)
def _transform_output_shape(output:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', shape: 'Tuple'
) ->Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: torch.Tensor
shape: List/tuple of int
Returns:
torch.Tensor
"""
is_tuple = isinstance(output, tuple)
out_tensor: 'torch.Tensor'
trans_matrix: 'Optional[torch.Tensor]'
if is_tuple:
out_tensor, trans_matrix = cast(Tuple[torch.Tensor, torch.Tensor],
output)
else:
out_tensor = cast(torch.Tensor, output)
trans_matrix = None
if trans_matrix is not None:
if len(out_tensor.shape) > len(shape):
assert trans_matrix.shape[0
] == 1, f'Dimension 0 of transformation matrix is expected to be 1, got {trans_matrix.shape[0]}'
trans_matrix = trans_matrix.squeeze(0)
for dim in range(len(out_tensor.shape) - len(shape)):
assert out_tensor.shape[0
] == 1, f'Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}'
out_tensor = out_tensor.squeeze(0)
return (out_tensor, trans_matrix) if is_tuple else out_tensor
def _transform_input(input: 'torch.Tensor') ->torch.Tensor:
"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
Args:
input: torch.Tensor
Returns:
torch.Tensor
"""
if not torch.is_tensor(input):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if len(input.shape) not in [2, 3, 4]:
raise ValueError(
f'Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}'
)
if len(input.shape) == 2:
input = input.unsqueeze(0)
if len(input.shape) == 3:
input = input.unsqueeze(0)
return input
def _validate_input_dtype(input: 'torch.Tensor', accepted_dtypes: 'List'
) ->None:
"""Check if the dtype of the input tensor is in the range of accepted_dtypes
Args:
input: torch.Tensor
accepted_dtypes: List. e.g. [torch.float32, torch.float64]
"""
if input.dtype not in accepted_dtypes:
raise TypeError(
f'Expected input of {accepted_dtypes}. Got {input.dtype}')
def _extract_device_dtype(tensor_list: 'List[Optional[Any]]') ->Tuple[torch
.device, torch.dtype]:
"""Check if all the input are in the same device (only if when they are torch.Tensor).
If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
Returns:
[torch.device, torch.dtype]
"""
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
if not isinstance(tensor, (torch.Tensor,)):
continue
_device = tensor.device
_dtype = tensor.dtype
if device is None and dtype is None:
device = _device
dtype = _dtype
elif device != _device or dtype != _dtype:
raise ValueError(
f'Passed values are not in the same device and dtype.Got ({device}, {dtype}) and ({_device}, {_dtype}).'
)
if device is None:
device = torch.device('cpu')
if dtype is None:
dtype = torch.get_default_dtype()
return device, dtype
def _joint_range_check(ranged_factor: 'torch.Tensor', name: 'str', bounds:
'Optional[Tuple[float, float]]'=None) ->None:
"""check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]"""
if bounds is None:
bounds = float('-inf'), float('inf')
if ranged_factor.dim() == 1 and len(ranged_factor) == 2:
if not bounds[0] <= ranged_factor[0] or not bounds[1] >= ranged_factor[
1]:
raise ValueError(
f'{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.'
)
if not bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]:
raise ValueError(
f'{name}[0] should be smaller than {name}[1] got {ranged_factor}'
)
else:
raise TypeError(
f'{name} should be a tensor with length 2 whose values between {bounds}. Got {ranged_factor}.'
)
def _singular_range_check(ranged_factor: 'torch.Tensor', name: 'str',
bounds: 'Optional[Tuple[float, float]]'=None, skip_none: 'bool'=False,
mode: 'str'='2d') ->None:
"""check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
if mode == '2d':
dim_size = 2
elif mode == '3d':
dim_size = 3
else:
raise ValueError(f"'mode' shall be either 2d or 3d. Got {mode}")
if skip_none and ranged_factor is None:
return
if bounds is None:
bounds = float('-inf'), float('inf')
if ranged_factor.dim() == 1 and len(ranged_factor) == dim_size:
for f in ranged_factor:
if not bounds[0] <= f <= bounds[1]:
raise ValueError(
f'{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.'
)
else:
raise TypeError(
f'{name} should be a float number or a tuple with length {dim_size} whose values between {bounds}.Got {ranged_factor}'
)
def _range_bound(factor:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]', name:
'str', center: 'float'=0.0, bounds: 'Tuple[float, float]'=(0, float(
'inf')), check: 'Optional[str]'='joint', device: 'torch.device'=torch.
device('cpu'), dtype: 'torch.dtype'=torch.get_default_dtype()
) ->torch.Tensor:
"""Check inputs and compute the corresponding factor bounds"""
if not isinstance(factor, torch.Tensor):
factor = torch.tensor(factor, device=device, dtype=dtype)
factor_bound: 'torch.Tensor'
if factor.dim() == 0:
if factor < 0:
raise ValueError(
f'If {name} is a single number number, it must be non negative. Got {factor}'
)
factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=
factor.device, dtype=factor.dtype) + center
factor_bound = factor_bound.clamp(bounds[0], bounds[1])
else:
factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
if check is not None:
if check == 'joint':
_joint_range_check(factor_bound, name, bounds)
elif check == 'singular':
_singular_range_check(factor_bound, name, bounds)
else:
raise NotImplementedError(f"methods '{check}' not implemented.")
return factor_bound
def adjust_brightness(input: 'torch.Tensor', brightness_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust Brightness of an image.
.. image:: _static/img/adjust_brightness.png
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
input: image to be adjusted in the shape of :math:`(*, N)`.
brightness_factor: Brightness adjust factor per element
in the batch. 0 does not modify the input image while any other number modify the
brightness.
Return:
Adjusted image in the shape of :math:`(*, N)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
>>> adjust_brightness(x, 1.)
tensor([[[[1., 1.],
[1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3)
>>> y = torch.tensor([0.25, 0.50])
>>> adjust_brightness(x, y).shape
torch.Size([2, 5, 3, 3])
"""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(brightness_factor, (float, torch.Tensor)):
raise TypeError(
f'The factor should be either a float or torch.Tensor. Got {type(brightness_factor)}'
)
if isinstance(brightness_factor, float):
brightness_factor = torch.tensor([brightness_factor])
brightness_factor = brightness_factor.to(input.device)
for _ in input.shape[1:]:
brightness_factor = torch.unsqueeze(brightness_factor, dim=-1)
x_adjust: 'torch.Tensor' = input + brightness_factor
out: 'torch.Tensor' = torch.clamp(x_adjust, 0.0, 1.0)
return out
def adjust_contrast(input: 'torch.Tensor', contrast_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust Contrast of an image.
.. image:: _static/img/adjust_contrast.png
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
input: Image to be adjusted in the shape of :math:`(*, N)`.
contrast_factor: Contrast adjust factor per element
in the batch. 0 generates a completely black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
Return:
Adjusted image in the shape of :math:`(*, N)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
>>> adjust_contrast(x, 0.5)
tensor([[[[0.5000, 0.5000],
[0.5000, 0.5000]]]])
>>> x = torch.ones(2, 5, 3, 3)
>>> y = torch.tensor([0.65, 0.50])
>>> adjust_contrast(x, y).shape
torch.Size([2, 5, 3, 3])
"""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(contrast_factor, (float, torch.Tensor)):
raise TypeError(
f'The factor should be either a float or torch.Tensor. Got {type(contrast_factor)}'
)
if isinstance(contrast_factor, float):
contrast_factor = torch.tensor([contrast_factor])
contrast_factor = contrast_factor.to(input.device)
if (contrast_factor < 0).any():
raise ValueError(
f'Contrast factor must be non-negative. Got {contrast_factor}')
for _ in input.shape[1:]:
contrast_factor = torch.unsqueeze(contrast_factor, dim=-1)
x_adjust: 'torch.Tensor' = input * contrast_factor
out: 'torch.Tensor' = torch.clamp(x_adjust, 0.0, 1.0)
return out
def adjust_hue_raw(input: 'torch.Tensor', hue_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust hue of an image. Expecting input to be in hsv format already."""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(hue_factor, (float, torch.Tensor)):
raise TypeError(
f'The hue_factor should be a float number or torch.Tensor in the range between [-PI, PI]. Got {type(hue_factor)}'
)
if isinstance(hue_factor, float):
hue_factor = torch.as_tensor(hue_factor)
hue_factor = hue_factor
for _ in input.shape[1:]:
hue_factor = torch.unsqueeze(hue_factor, dim=-1)
h, s, v = torch.chunk(input, chunks=3, dim=-3)
divisor: 'float' = 2 * pi
h_out: 'torch.Tensor' = torch.fmod(h + hue_factor, divisor)
out: 'torch.Tensor' = torch.cat([h_out, s, v], dim=-3)
return out
def hsv_to_rgb(image: 'torch.Tensor') ->torch.Tensor:
"""Convert an image from HSV to RGB.
The H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.
Args:
image: HSV Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.
Returns:
RGB version of the image with shape of :math:`(*, 3, H, W)`.
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = hsv_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError('Input size must have a shape of (*, 3, H, W). Got {}'
.format(image.shape))
h: 'torch.Tensor' = image[..., 0, :, :] / (2 * math.pi)
s: 'torch.Tensor' = image[..., 1, :, :]
v: 'torch.Tensor' = image[..., 2, :, :]
hi: 'torch.Tensor' = torch.floor(h * 6) % 6
f: 'torch.Tensor' = h * 6 % 6 - hi
one: 'torch.Tensor' = torch.tensor(1.0).to(image.device)
p: 'torch.Tensor' = v * (one - s)
q: 'torch.Tensor' = v * (one - f * s)
t: 'torch.Tensor' = v * (one - (one - f) * s)
hi = hi.long()
indices: 'torch.Tensor' = torch.stack([hi, hi + 6, hi + 12], dim=-3)
out = torch.stack((v, q, p, p, t, v, t, v, v, q, p, p, p, p, t, v, v, q
), dim=-3)
out = torch.gather(out, -3, indices)
return out
def rgb_to_hsv(image: 'torch.Tensor', eps: 'float'=1e-06) ->torch.Tensor:
"""Convert an image from RGB to HSV.
.. image:: _static/img/rgb_to_hsv.png
The image data is assumed to be in the range of (0, 1).
Args:
image: RGB Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.
eps: scalar to enforce numarical stability.
Returns:
HSV version of the image with shape of :math:`(*, 3, H, W)`.
The H channel values are in the range 0..2pi. S and V are in the range 0..1.
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_hsv(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError('Input size must have a shape of (*, 3, H, W). Got {}'
.format(image.shape))
maxc, _ = image.max(-3)
maxc_mask = image == maxc.unsqueeze(-3)
_, max_indices = ((maxc_mask.cumsum(-3) == 1) & maxc_mask).max(-3)
minc: 'torch.Tensor' = image.min(-3)[0]
v: 'torch.Tensor' = maxc
deltac: 'torch.Tensor' = maxc - minc
s: 'torch.Tensor' = deltac / (v + eps)
deltac = torch.where(deltac == 0, torch.ones_like(deltac, device=deltac
.device, dtype=deltac.dtype), deltac)
maxc_tmp = maxc.unsqueeze(-3) - image
rc: 'torch.Tensor' = maxc_tmp[..., 0, :, :]
gc: 'torch.Tensor' = maxc_tmp[..., 1, :, :]
bc: 'torch.Tensor' = maxc_tmp[..., 2, :, :]
h = torch.stack([bc - gc, 2.0 * deltac + rc - bc, 4.0 * deltac + gc -
rc], dim=-3)
h = torch.gather(h, dim=-3, index=max_indices[..., None, :, :])
h = h.squeeze(-3)
h = h / deltac
h = h / 6.0 % 1.0
h = 2 * math.pi * h
return torch.stack([h, s, v], dim=-3)
def adjust_hue(input: 'torch.Tensor', hue_factor: 'Union[float, torch.Tensor]'
) ->torch.Tensor:
"""Adjust hue of an image.
.. image:: _static/img/adjust_hue.png
The input image is expected to be an RGB image in the range of [0, 1].
Args:
input: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
and -PI give complete reversal of hue channel in HSV space in positive and negative
direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
image with complementary colors while 0 gives the original image.
Return:
Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
>>> x = torch.ones(1, 3, 2, 2)
>>> adjust_hue(x, 3.141516).shape
torch.Size([1, 3, 2, 2])
>>> x = torch.ones(2, 3, 3, 3)
>>> y = torch.ones(2) * 3.141516
>>> adjust_hue(x, y).shape
torch.Size([2, 3, 3, 3])
"""
x_hsv: 'torch.Tensor' = rgb_to_hsv(input)
x_adjusted: 'torch.Tensor' = adjust_hue_raw(x_hsv, hue_factor)
out: 'torch.Tensor' = hsv_to_rgb(x_adjusted)
return out
def adjust_saturation_raw(input: 'torch.Tensor', saturation_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust color saturation of an image. Expecting input to be in hsv format already."""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(saturation_factor, (float, torch.Tensor)):
raise TypeError(
f'The saturation_factor should be a float number or torch.Tensor.Got {type(saturation_factor)}'
)
if isinstance(saturation_factor, float):
saturation_factor = torch.as_tensor(saturation_factor)
saturation_factor = saturation_factor.to(input.device)
for _ in input.shape[1:]:
saturation_factor = torch.unsqueeze(saturation_factor, dim=-1)
h, s, v = torch.chunk(input, chunks=3, dim=-3)
s_out: 'torch.Tensor' = torch.clamp(s * saturation_factor, min=0, max=1)
out: 'torch.Tensor' = torch.cat([h, s_out, v], dim=-3)
return out
def adjust_saturation(input: 'torch.Tensor', saturation_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust color saturation of an image.
.. image:: _static/img/adjust_saturation.png
The input image is expected to be an RGB image in the range of [0, 1].
Args:
input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
saturation_factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
Return:
Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
>>> x = torch.ones(1, 3, 3, 3)
>>> adjust_saturation(x, 2.).shape
torch.Size([1, 3, 3, 3])
>>> x = torch.ones(2, 3, 3, 3)
>>> y = torch.tensor([1., 2.])
>>> adjust_saturation(x, y).shape
torch.Size([2, 3, 3, 3])
"""
x_hsv: 'torch.Tensor' = rgb_to_hsv(input)
x_adjusted: 'torch.Tensor' = adjust_saturation_raw(x_hsv, saturation_factor
)
out: 'torch.Tensor' = hsv_to_rgb(x_adjusted)
return out
def _extract_tensor_patchesnd(input: 'torch.Tensor', window_sizes:
'Tuple[int, ...]', strides: 'Tuple[int, ...]') ->torch.Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
input = input.unfold(dim, patch_size, stride)
input = input.permute(0, *dims, 1, *[(dim + len(dims)) for dim in dims]
).contiguous()
return input.view(batch_size, -1, num_channels, *window_sizes)
def extract_tensor_patches(input: 'torch.Tensor', window_size:
'Union[int, Tuple[int, int]]', stride: 'Union[int, Tuple[int, int]]'=1,
padding: 'Union[int, Tuple[int, int]]'=0) ->torch.Tensor:
"""Function that extract patches from tensors and stack them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
"""
if not torch.is_tensor(input):
raise TypeError('Input input type is not a torch.Tensor. Got {}'.
format(type(input)))
if not len(input.shape) == 4:
raise ValueError('Invalid input shape, we expect BxCxHxW. Got: {}'.
format(input.shape))
if padding:
pad_vert, pad_horz = _pair(padding)
input = F.pad(input, [pad_horz, pad_horz, pad_vert, pad_vert])
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
class _BasicAugmentationBase(nn.Module):
"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
To change this behaviour, please use ``set_rng_device_and_dtype``.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation
probabilities element-wisely.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __init__(self, p: 'float'=0.5, p_batch: 'float'=1.0, same_on_batch:
'bool'=False, keepdim: 'bool'=False) ->None:
super(_BasicAugmentationBase, self).__init__()
self.p = p
self.p_batch = p_batch
self.same_on_batch = same_on_batch
self.keepdim = keepdim
self._params: 'Dict[str, torch.Tensor]' = {}
if p != 0.0 or p != 1.0:
self._p_gen = Bernoulli(self.p)
if p_batch != 0.0 or p_batch != 1.0:
self._p_batch_gen = Bernoulli(self.p_batch)
self.set_rng_device_and_dtype(torch.device('cpu'), torch.
get_default_dtype())
def __repr__(self) ->str:
return (
f'p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}'
)
def __unpack_input__(self, input: 'torch.Tensor') ->torch.Tensor:
return input
def __check_batching__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]'):
"""Check if a transformation matrix is returned,
it has to be in the same batching mode as output."""
raise NotImplementedError
def transform_tensor(self, input: 'torch.Tensor') ->torch.Tensor:
"""Standardize input tensors."""
raise NotImplementedError
def generate_parameters(self, batch_shape: 'torch.Size') ->Dict[str,
torch.Tensor]:
return {}
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
raise NotImplementedError
def set_rng_device_and_dtype(self, device: 'torch.device', dtype:
'torch.dtype') ->None:
"""Change the random generation device and dtype.
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
self.device = device
self.dtype = dtype
def __batch_prob_generator__(self, batch_shape: 'torch.Size', p:
'float', p_batch: 'float', same_on_batch: 'bool') ->torch.Tensor:
batch_prob: 'torch.Tensor'
if p_batch == 1:
batch_prob = torch.tensor([True])
elif p_batch == 0:
batch_prob = torch.tensor([False])
else:
batch_prob = _adapted_sampling((1,), self._p_batch_gen,
same_on_batch).bool()
if batch_prob.sum().item() == 1:
elem_prob: 'torch.Tensor'
if p == 1:
elem_prob = torch.tensor([True] * batch_shape[0])
elif p == 0:
elem_prob = torch.tensor([False] * batch_shape[0])
else:
elem_prob = _adapted_sampling((batch_shape[0],), self.
_p_gen, same_on_batch).bool()
batch_prob = batch_prob * elem_prob
else:
batch_prob = batch_prob.repeat(batch_shape[0])
return batch_prob
def forward_parameters(self, batch_shape):
to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.
p_batch, self.same_on_batch)
_params = self.generate_parameters(torch.Size((int(to_apply.sum().
item()), *batch_shape[1:])))
if _params is None:
_params = {}
_params['batch_prob'] = to_apply
return _params
def apply_func(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->Union[torch.Tensor, Tuple[torch.Tensor,
torch.Tensor]]:
input = self.transform_tensor(input)
return self.apply_transform(input, params)
def forward(self, input: 'torch.Tensor', params:
'Optional[Dict[str, torch.Tensor]]'=None) ->Union[torch.Tensor,
Tuple[torch.Tensor, torch.Tensor]]:
in_tensor = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
if params is None:
params = self.forward_parameters(batch_shape)
self._params = params
output = self.apply_func(input, self._params)
return _transform_output_shape(output, ori_shape
) if self.keepdim else output
class _AugmentationBase(_BasicAugmentationBase):
"""_AugmentationBase base class for customized augmentation implementations.
Advanced augmentation base class with the functionality of transformation matrix calculations.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __init__(self, return_transform: 'bool'=None, same_on_batch: 'bool'
=False, p: 'float'=0.5, p_batch: 'float'=1.0, keepdim: 'bool'=False
) ->None:
super(_AugmentationBase, self).__init__(p, p_batch=p_batch,
same_on_batch=same_on_batch, keepdim=keepdim)
self.p = p
self.p_batch = p_batch
self.return_transform = return_transform
def __repr__(self) ->str:
return super().__repr__(
) + f', return_transform={self.return_transform}'
def identity_matrix(self, input: 'torch.Tensor') ->torch.Tensor:
raise NotImplementedError
def compute_transformation(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
raise NotImplementedError
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]', transform: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
raise NotImplementedError
def __unpack_input__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]') ->Tuple[
torch.Tensor, Optional[torch.Tensor]]:
if isinstance(input, tuple):
in_tensor = input[0]
in_transformation = input[1]
return in_tensor, in_transformation
in_tensor = input
return in_tensor, None
def apply_func(self, in_tensor: 'torch.Tensor', in_transform:
'Optional[torch.Tensor]', params: 'Dict[str, torch.Tensor]',
return_transform: 'bool'=False) ->Union[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
to_apply = params['batch_prob']
if torch.sum(to_apply) == 0:
output = in_tensor
trans_matrix = self.identity_matrix(in_tensor)
elif torch.sum(to_apply) == len(to_apply):
trans_matrix = self.compute_transformation(in_tensor, params)
output = self.apply_transform(in_tensor, params, trans_matrix)
else:
output = in_tensor.clone()
trans_matrix = self.identity_matrix(in_tensor)
trans_matrix[to_apply] = self.compute_transformation(in_tensor[
to_apply], params)
output[to_apply] = self.apply_transform(in_tensor[to_apply],
params, trans_matrix[to_apply])
self._transform_matrix = trans_matrix
if return_transform:
out_transformation = (trans_matrix if in_transform is None else
trans_matrix @ in_transform)
return output, out_transformation
if in_transform is not None:
return output, in_transform
return output
def forward(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', params:
'Optional[Dict[str, torch.Tensor]]'=None, return_transform:
'Optional[bool]'=None) ->Union[torch.Tensor, Tuple[torch.Tensor,
torch.Tensor]]:
in_tensor, in_transform = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
if return_transform is None:
return_transform = self.return_transform
return_transform = cast(bool, return_transform)
if params is None:
params = self.forward_parameters(batch_shape)
if 'batch_prob' not in params:
params['batch_prob'] = torch.tensor([True] * batch_shape[0])
warnings.warn(
'`batch_prob` is not found in params. Will assume applying on all data.'
)
self._params = params
output = self.apply_func(in_tensor, in_transform, self._params,
return_transform)
return _transform_output_shape(output, ori_shape
) if self.keepdim else output
class AugmentationBase2D(_AugmentationBase):
"""AugmentationBase2D base class for customized augmentation implementations.
For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
"compute_transformation" is only required when passing "return_transform" as True.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __check_batching__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]'):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
assert len(mat.shape
) == 3, 'Input tensor is in batch mode but transformation matrix is not'
assert mat.shape[0] == inp.shape[0
], f'In batch dimension, input has {inp.shape[0]}but transformation matrix has {mat.shape[0]}'
elif len(inp.shape) == 3 or len(inp.shape) == 2:
assert len(mat.shape
) == 2, 'Input tensor is in non-batch mode but transformation matrix is not'
else:
raise ValueError(
f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}'
)
def transform_tensor(self, input: 'torch.Tensor') ->torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.
float32, torch.float64])
return _transform_input(input)
def identity_matrix(self, input) ->torch.Tensor:
"""Return 3x3 identity matrix."""
return kornia.eye_like(3, input)
class IntensityAugmentationBase2D(AugmentationBase2D):
"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
"compute_transformation" is only required when passing "return_transform" as True.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def compute_transformation(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
return self.identity_matrix(input)
class ParamItem(NamedTuple):
name: 'str'
data: 'Union[dict, list]'
class ImageSequential(nn.Sequential):
"""Sequential for creating kornia image processing pipeline.
Args:
*args : a list of kornia augmentation and image operation modules.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
return_transform: if ``True`` return the matrix describing the transformation
applied to each. If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
random_apply: randomly select a sublist (order agnostic) of args to
apply transformation.
If int, a fixed number of transformations will be selected.
If (a,), x number of transformations (a <= x <= len(args)) will be selected.
If (a, b), x number of transformations (a <= x <= b) will be selected.
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
Returns:
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: the tensor (, and the transformation matrix)
has been sequentially modified by the args.
Examples:
>>> import kornia
>>> input = torch.randn(2, 3, 5, 6)
>>> aug_list = ImageSequential(
... kornia.color.BgrToRgb(),
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.filters.MedianBlur((3, 3)),
... kornia.augmentation.RandomAffine(360, p=1.0),
... kornia.enhance.Invert(),
... return_transform=True,
... same_on_batch=True,
... random_apply=10,
... )
>>> out = aug_list(input)
>>> out[0].shape, out[1].shape
(torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 3]))
Reproduce with provided params.
>>> out2 = aug_list(input, params=aug_list._params)
>>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1])
(True, True)
Note:
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
Those transformations in ``kornia.geometry`` will not be taken into account.
"""
def __init__(self, *args: nn.Module, same_on_batch: Optional[bool]=None,
return_transform: Optional[bool]=None, keepdim: Optional[bool]=None,
random_apply: Union[int, bool, Tuple[int, int]]=False) ->None:
self.same_on_batch = same_on_batch
self.return_transform = return_transform
self.keepdim = keepdim
_args = OrderedDict()
for idx, arg in enumerate(args):
if not isinstance(arg, nn.Module):
raise NotImplementedError(
f'Only nn.Module are supported at this moment. Got {arg}.')
if isinstance(arg, _AugmentationBase):
if same_on_batch is not None:
arg.same_on_batch = same_on_batch
if return_transform is not None:
arg.return_transform = return_transform
if keepdim is not None:
arg.keepdim = keepdim
_args.update({f'{arg.__class__.__name__}_{idx}': arg})
super(ImageSequential, self).__init__(_args)
self._params: 'List[Any]' = []
self.random_apply: 'Union[Tuple[int, int], bool]'
if random_apply:
if isinstance(random_apply, (bool,)) and random_apply is True:
self.random_apply = len(args), len(args) + 1
elif isinstance(random_apply, (int,)):
self.random_apply = random_apply, random_apply + 1
elif isinstance(random_apply, (tuple,)) and len(random_apply
) == 2 and isinstance(random_apply[0], (int,)) and isinstance(
random_apply[1], (int,)):
self.random_apply = random_apply[0], random_apply[1] + 1
elif isinstance(random_apply, (tuple,)) and len(random_apply
) == 1 and isinstance(random_apply[0], (int,)):
self.random_apply = random_apply[0], len(args) + 1
else:
raise ValueError(
f'Non-readable random_apply. Got {random_apply}.')
assert isinstance(self.random_apply, (tuple,)) and len(self.
random_apply) == 2 and isinstance(self.random_apply[0], (int,)
) and isinstance(self.random_apply[0], (int,)
), f'Expect a tuple of (int, int). Got {self.random_apply}.'
else:
self.random_apply = False
def _get_child_sequence(self) ->Iterator[Tuple[str, nn.Module]]:
if self.random_apply:
num_samples = int(torch.randint(*self.random_apply, (1,)).item())
indices = torch.multinomial(torch.ones((len(self),)),
num_samples, replacement=True if num_samples > len(self) else
False)
return self._get_children_by_indices(indices)
return self.named_children()
def _get_children_by_indices(self, indices: 'torch.Tensor') ->Iterator[
Tuple[str, nn.Module]]:
modules = list(self.named_children())
for idx in indices:
yield modules[idx]
def _get_children_by_module_names(self, names: 'List[str]') ->Iterator[
Tuple[str, nn.Module]]:
modules = list(self.named_children())
for name in names:
yield modules[list(dict(self.named_children()).keys()).index(name)]
def get_forward_sequence(self, params: 'Optional[List[ParamItem]]'=None
) ->Iterator[Tuple[str, nn.Module]]:
if params is None:
named_modules = self._get_child_sequence()
else:
named_modules = self._get_children_by_module_names([p.name for
p in params])
return named_modules
def apply_to_input(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]',
module_name: 'str', module: 'Optional[nn.Module]'=None, param:
'Optional[ParamItem]'=None) ->Union[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
if module is None:
module = self.get_submodule(module_name)
if param is not None:
assert module_name == param.name
_param = param.data
else:
_param = None
if isinstance(module, (_AugmentationBase, ImageSequential)
) and _param is None:
input = module(input)
self._params.append(ParamItem(module_name, module._params))
elif isinstance(module, (_AugmentationBase, ImageSequential)
) and _param is not None:
input = module(input, params=_param)
self._params.append(ParamItem(module_name, _param))
else:
assert _param == {
} or _param is None, f'Non-augmentaion operation {module_name} require empty parameters. Got {module}.'
if isinstance(input, (tuple, list)):
input = module(input[0]), input[1]
else:
input = module(input)
self._params.append(ParamItem(module_name, {}))
return input
def forward(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', params:
'Optional[List[ParamItem]]'=None) ->Union[torch.Tensor, Tuple[torch
.Tensor, torch.Tensor]]:
self._params = []
named_modules = self.get_forward_sequence(params)
params = [] if params is None else params
for (name, module), param in zip_longest(named_modules, params):
input = self.apply_to_input(input, name, module, param=param)
return input
class ColorJitter(IntensityAugmentationBase2D):
"""Applies a random transformation to the brightness, contrast, saturation and hue of a tensor image.
.. image:: _static/img/ColorJitter.png
Args:
p: probability of applying the transformation.
brightness: The brightness factor to apply.
contrast: The contrast factor to apply.
saturation: The saturation factor to apply.
hue: The hue factor to apply.
return_transform: if ``True`` return the matrix describing the transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
Examples:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.ones(1, 3, 3, 3)
>>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
>>> aug(inputs)
tensor([[[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]],
<BLANKLINE>
[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]],
<BLANKLINE>
[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]]]])
"""
def __init__(self, brightness:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
contrast:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
saturation:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
hue: 'Union[torch.Tensor, float, Tuple[float, float], List[float]]'
=0.0, return_transform: 'bool'=False, same_on_batch: 'bool'=False,
p: 'float'=1.0, keepdim: 'bool'=False) ->None:
super(ColorJitter, self).__init__(p=p, return_transform=
return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([brightness,
contrast, hue, saturation])
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def __repr__(self) ->str:
repr = (
f'brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}'
)
return self.__class__.__name__ + f'({repr}, {super().__repr__()})'
def generate_parameters(self, batch_shape: 'torch.Size') ->Dict[str,
torch.Tensor]:
brightness: 'torch.Tensor' = _range_bound(self.brightness,
'brightness', center=1.0, bounds=(0, 2), device=self._device,
dtype=self._dtype)
contrast: 'torch.Tensor' = _range_bound(self.contrast, 'contrast',
center=1.0, device=self._device, dtype=self._dtype)
saturation: 'torch.Tensor' = _range_bound(self.saturation,
'saturation', center=1.0, device=self._device, dtype=self._dtype)
hue: 'torch.Tensor' = _range_bound(self.hue, 'hue', bounds=(-0.5,
0.5), device=self._device, dtype=self._dtype)
return rg.random_color_jitter_generator(batch_shape[0], brightness,
contrast, saturation, hue, self.same_on_batch, self.device,
self.dtype)
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]', transform: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
transforms = [lambda img: adjust_brightness(img, params[
'brightness_factor'] - 1), lambda img: adjust_contrast(img,
params['contrast_factor']), lambda img: adjust_saturation(img,
params['saturation_factor']), lambda img: adjust_hue(img,
params['hue_factor'] * 2 * pi)]
jittered = input
for idx in params['order'].tolist():
t = transforms[idx]
jittered = t(jittered)
return jittered
class PatchSequential(ImageSequential):
"""Container for performing patch-level image processing.
.. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_patch_sequential_5_1.png
PatchSequential breaks input images into patches by a given grid size, which will be resembled back
afterwards. Different image processing and augmentation methods will be performed on each patch region.
Args:
*args: a list of processing modules.
grid_size: controls the grid board seperation.
padding: same or valid padding. If same padding, it will pad to include all pixels if the input
tensor cannot be divisible by grid_size. If valid padding, the redundent border will be removed.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
patchwise_apply: apply image processing args will be applied patch-wisely.
if ``True``, the number of args must be equal to grid number.
if ``False``, the image processing args will be applied as a sequence to all patches. Default: False.
random_apply: randomly select a sublist (order agnostic) of args to
apply transformation.
If ``int`` (batchwise mode only), a fixed number of transformations will be selected.
If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected.
If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected.
If ``True``, the whole list of args will be processed in a random order.
If ``False``, the whole list of args will be processed in original order.
Return:
List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)
has been sequentially modified by the args.
Examples:
>>> import kornia.augmentation as K
>>> input = torch.randn(2, 3, 224, 224)
>>> seq = PatchSequential(
... ImageSequential(
... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
... K.RandomPerspective(0.2, p=0.5),
... K.RandomSolarize(0.1, 0.1, p=0.5),
... ),
... K.RandomAffine(360, p=1.0),
... ImageSequential(
... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
... K.RandomPerspective(0.2, p=0.5),
... K.RandomSolarize(0.1, 0.1, p=0.5),
... ),
... K.RandomSolarize(0.1, 0.1, p=0.1),
... grid_size=(2,2),
... patchwise_apply=False,
... same_on_batch=True,
... random_apply=True,
... )
>>> out = seq(input)
>>> out.shape
torch.Size([2, 3, 224, 224])
>>> out1 = seq(input, seq._params)
>>> torch.equal(out, out1)
True
"""
def __init__(self, *args: nn.Module, grid_size: Tuple[int, int]=(4, 4),
padding: str='same', same_on_batch: Optional[bool]=None, keepdim:
Optional[bool]=None, patchwise_apply: bool=False, random_apply:
Union[int, bool, Tuple[int, int]]=False) ->None:
_random_apply: 'Optional[Union[int, Tuple[int, int]]]'
if patchwise_apply and random_apply is True:
_random_apply = grid_size[0] * grid_size[1], grid_size[0
] * grid_size[1]
elif patchwise_apply and random_apply is False:
assert len(args) == grid_size[0] * grid_size[1
], f'The number of processing modules must be equal with grid size.Got {len(args)} and {grid_size[0] * grid_size[1]}.'
_random_apply = random_apply
elif patchwise_apply and isinstance(random_apply, (int, tuple)):
raise ValueError(
f'Only boolean value allowed when `patchwise_apply` is set to True. Got {random_apply}.'
)
else:
_random_apply = random_apply
super(PatchSequential, self).__init__(*args, same_on_batch=
same_on_batch, return_transform=False, keepdim=keepdim,
random_apply=_random_apply)
assert padding in ['same', 'valid'
], f'`padding` must be either `same` or `valid`. Got {padding}.'
self.grid_size = grid_size
self.padding = padding
self.patchwise_apply = patchwise_apply
def is_intensity_only(self) ->bool:
"""Check if all transformations are intensity-based.
Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks).
"""
for arg in self.children():
if isinstance(arg, (ImageSequential,)):
for _arg in arg.children():
if not isinstance(_arg, IntensityAugmentationBase2D):
return False
elif not isinstance(_arg, IntensityAugmentationBase2D):
return False
return True
def __repeat_param_across_patches__(self, param: 'torch.Tensor',
patch_num: 'int') ->torch.Tensor:
"""Repeat parameters across patches.
The input is shaped as (B, ...), while to output (B * patch_num, ...), which
to guarentee that the same transformation would happen for each patch index.
(B1, B2, ..., Bn) => (B1, ... Bn, B1, ..., Bn, ..., B1, ..., Bn)
| pt_size | | pt_size | ..., | pt_size |
"""
repeated = torch.cat([param] * patch_num, dim=0)
return repeated
def compute_padding(self, input: 'torch.Tensor', padding: 'str',
grid_size: 'Optional[Tuple[int, int]]'=None) ->Tuple[int, int, int, int
]:
if grid_size is None:
grid_size = self.grid_size
if padding == 'valid':
ph, pw = input.size(-2) // grid_size[0], input.size(-1
) // grid_size[1]
return -pw // 2, pw // 2 - pw, -ph // 2, ph // 2 - ph
elif padding == 'same':
ph = input.size(-2) - input.size(-2) // grid_size[0] * grid_size[0]
pw = input.size(-1) - input.size(-1) // grid_size[1] * grid_size[1]
return pw // 2, pw - pw // 2, ph // 2, ph - ph // 2
else:
raise NotImplementedError(
f"Expect `padding` as either 'valid' or 'same'. Got {padding}."
)
def extract_patches(self, input: 'torch.Tensor', grid_size:
'Optional[Tuple[int, int]]'=None, pad:
'Optional[Tuple[int, int, int, int]]'=None) ->torch.Tensor:
"""Extract patches from tensor.
Example:
>>> import kornia.augmentation as K
>>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
>>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
tensor([[[[[ 0, 1],
[ 4, 5]]],
<BLANKLINE>
<BLANKLINE>
[[[ 2, 3],
[ 6, 7]]],
<BLANKLINE>
<BLANKLINE>
[[[ 8, 9],
[12, 13]]],
<BLANKLINE>
<BLANKLINE>
[[[10, 11],
[14, 15]]]]])
>>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -1, -2, -2))
tensor([[[[[19, 20, 21]]],
<BLANKLINE>
<BLANKLINE>
[[[22, 23, 24]]],
<BLANKLINE>
<BLANKLINE>
[[[28, 29, 30]]],
<BLANKLINE>
<BLANKLINE>
[[[31, 32, 33]]]]])
"""
if pad is not None:
input = torch.nn.functional.pad(input, list(pad))
if grid_size is None:
grid_size = self.grid_size
window_size = input.size(-2) // grid_size[-2], input.size(-1
) // grid_size[-1]
stride = window_size
return extract_tensor_patches(input, window_size, stride)
def restore_from_patches(self, patches: 'torch.Tensor', grid_size:
'Tuple[int, int]'=(4, 4), pad:
'Optional[Tuple[int, int, int, int]]'=None) ->torch.Tensor:
"""Restore input from patches.
Example:
>>> import kornia.augmentation as K
>>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
>>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
>>> pas.restore_from_patches(out, grid_size=(2, 2))
tensor([[[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]]])
"""
if grid_size is None:
grid_size = self.grid_size
patches_tensor = patches.view(-1, grid_size[0], grid_size[1], *
patches.shape[-3:])
restored_tensor = torch.cat(torch.chunk(patches_tensor, grid_size[0
], dim=1), -2).squeeze(1)
restored_tensor = torch.cat(torch.chunk(restored_tensor, grid_size[
1], dim=1), -1).squeeze(1)
if pad is not None:
restored_tensor = torch.nn.functional.pad(restored_tensor, [(-i
) for i in pad])
return restored_tensor
def forward_patchwise(self, input: 'torch.Tensor', params:
'Optional[List[List[ParamItem]]]'=None) ->torch.Tensor:
if params is None:
params = [[]] * input.size(1)
auglist = [self.get_forward_sequence() for _ in range(input.
size(1))]
else:
auglist = [self.get_forward_sequence(p) for p in params]
assert input.size(0) == len(auglist) == len(params)
out = []
self._params = []
for inp, proc, param in zip(input, auglist, params):
o = []
p = []
for inp_pat, (proc_name, proc_pat), _param in zip_longest(inp,
proc, param):
if isinstance(proc_pat, (_AugmentationBase, ImageSequential)):
o.append(proc_pat(inp_pat[None], _param.data if _param
is not None else None))
p.append(ParamItem(proc_name, proc_pat._params))
else:
o.append(proc_pat(inp_pat[None]))
p.append(ParamItem(proc_name, {}))
out.append(torch.cat(o, dim=0))
self._params.append(p)
input = torch.stack(out, dim=0)
return input
def forward_batchwise(self, input: 'torch.Tensor', params:
'Optional[List[ParamItem]]'=None) ->torch.Tensor:
if self.same_on_batch:
batch_shape = input.size(1), *input.shape[-3:]
patch_num = input.size(0)
else:
batch_shape = input.size(0) * input.size(1), *input.shape[-3:]
if params is None:
params = []
for name, aug in self.get_forward_sequence():
if isinstance(aug, _AugmentationBase):
aug.same_on_batch = False
param = aug.forward_parameters(batch_shape)
if self.same_on_batch:
for k, v in param.items():
if not (k == 'order' and isinstance(aug,
ColorJitter)):
param.update({k: self.
__repeat_param_across_patches__(v,
patch_num)})
aug.same_on_batch = True
else:
param = None
params.append(ParamItem(name, param))
input = super().forward(input.view(-1, *input.shape[-3:]), params)
return input
def forward(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', params:
'Optional[Union[List[ParamItem], List[List[ParamItem]]]]'=None
) ->Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Input transformation will be returned if input is a tuple."""
if isinstance(input, (tuple,)):
pad = self.compute_padding(input[0], self.padding)
input = self.extract_patches(input[0], self.grid_size, pad), input[
1]
else:
pad = self.compute_padding(input, self.padding)
input = self.extract_patches(input, self.grid_size, pad)
if not self.patchwise_apply:
params = cast(List[ParamItem], params)
if isinstance(input, (tuple,)):
input = self.forward_batchwise(input[0], params), input[1]
else:
input = self.forward_batchwise(input, params)
else:
params = cast(List[List[ParamItem]], params)
if isinstance(input, (tuple,)):
input = self.forward_patchwise(input[0], params), input[1]
else:
input = self.forward_patchwise(input, params)
if isinstance(input, (tuple,)):
input = self.restore_from_patches(input[0], self.grid_size, pad=pad
), input[1]
else:
input = self.restore_from_patches(input, self.grid_size, pad=pad)
return input
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 math
import warnings
from typing import Dict
from typing import Optional
from typing import Tuple
import torch.nn as nn
import torch.nn.functional as F
from typing import cast
from typing import List
from typing import Union
from torch.distributions import Bernoulli
from itertools import zip_longest
from collections import OrderedDict
from typing import Any
from typing import Iterator
from typing import NamedTuple
from torch.nn.modules.utils import _pair
from math import pi
assert_size_stride = torch._C._dynamo.guards.assert_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 = 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
x5 = xindex // 16
x6 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = x1
tmp7 = tmp5 < tmp3
tmp8 = tmp7 & tmp4
tmp9 = tl.load(in_ptr0 + (16 * x2 + 64 * x3 + 16 * x3 % 16), tmp8 &
xmask, eviction_policy='evict_last', other=0.0)
tmp10 = tmp5 >= tmp3
tmp11 = tl.full([1], 2, tl.int64)
tmp12 = tmp5 < tmp11
tmp13 = tmp10 & tmp12
tmp14 = tmp13 & tmp4
tmp15 = tl.load(in_ptr0 + (4 + 16 * x5), tmp14 & xmask, eviction_policy
='evict_last', other=0.0)
tmp16 = tmp5 >= tmp11
tmp17 = tl.full([1], 3, tl.int64)
tmp18 = tmp5 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tmp19 & tmp4
tmp21 = tl.load(in_ptr0 + (8 + 16 * x5), tmp20 & xmask, eviction_policy
='evict_last', other=0.0)
tmp22 = tmp5 >= tmp17
tl.full([1], 4, tl.int64)
tmp25 = tmp22 & tmp4
tmp26 = tl.load(in_ptr0 + (12 + 16 * x5), tmp25 & xmask,
eviction_policy='evict_last', other=0.0)
tmp27 = tl.where(tmp19, tmp21, tmp26)
tmp28 = tl.where(tmp13, tmp15, tmp27)
tmp29 = tl.where(tmp7, tmp9, tmp28)
tmp30 = tl.full(tmp29.shape, 0.0, tmp29.dtype)
tmp31 = tl.where(tmp4, tmp29, tmp30)
tmp32 = tmp0 >= tmp3
tmp33 = tmp0 < tmp11
tmp34 = tmp32 & tmp33
tmp35 = tmp7 & tmp34
tmp36 = tl.load(in_ptr0 + (1 + 16 * x5), tmp35 & xmask, eviction_policy
='evict_last', other=0.0)
tmp37 = tmp13 & tmp34
tmp38 = tl.load(in_ptr0 + (5 + 16 * x5), tmp37 & xmask, eviction_policy
='evict_last', other=0.0)
tmp39 = tmp19 & tmp34
tmp40 = tl.load(in_ptr0 + (9 + 16 * x5), tmp39 & xmask, eviction_policy
='evict_last', other=0.0)
tmp41 = tmp22 & tmp34
tmp42 = tl.load(in_ptr0 + (13 + 16 * x5), tmp41 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tl.where(tmp19, tmp40, tmp42)
tmp44 = tl.where(tmp13, tmp38, tmp43)
tmp45 = tl.where(tmp7, tmp36, tmp44)
tmp46 = tl.full(tmp45.shape, 0.0, tmp45.dtype)
tmp47 = tl.where(tmp34, tmp45, tmp46)
tmp48 = tmp0 >= tmp11
tmp49 = tmp0 < tmp17
tmp50 = tmp48 & tmp49
tmp51 = tmp7 & tmp50
tmp52 = tl.load(in_ptr0 + (2 + 16 * x5), tmp51 & xmask, eviction_policy
='evict_last', other=0.0)
tmp53 = tmp13 & tmp50
tmp54 = tl.load(in_ptr0 + (6 + 16 * x5), tmp53 & xmask, eviction_policy
='evict_last', other=0.0)
tmp55 = tmp19 & tmp50
tmp56 = tl.load(in_ptr0 + (10 + 16 * x5), tmp55 & xmask,
eviction_policy='evict_last', other=0.0)
tmp57 = tmp22 & tmp50
tmp58 = tl.load(in_ptr0 + (14 + 16 * x5), tmp57 & xmask,
eviction_policy='evict_last', other=0.0)
tmp59 = tl.where(tmp19, tmp56, tmp58)
tmp60 = tl.where(tmp13, tmp54, tmp59)
tmp61 = tl.where(tmp7, tmp52, tmp60)
tmp62 = tl.full(tmp61.shape, 0.0, tmp61.dtype)
tmp63 = tl.where(tmp50, tmp61, tmp62)
tmp64 = tmp0 >= tmp17
tmp66 = tmp7 & tmp64
tmp67 = tl.load(in_ptr0 + (3 + 16 * x5), tmp66 & xmask, eviction_policy
='evict_last', other=0.0)
tmp68 = tmp13 & tmp64
tmp69 = tl.load(in_ptr0 + (7 + 16 * x5), tmp68 & xmask, eviction_policy
='evict_last', other=0.0)
tmp70 = tmp19 & tmp64
tmp71 = tl.load(in_ptr0 + (11 + 16 * x5), tmp70 & xmask,
eviction_policy='evict_last', other=0.0)
tmp72 = tmp22 & tmp64
tmp73 = tl.load(in_ptr0 + (15 + 16 * x5), tmp72 & xmask,
eviction_policy='evict_last', other=0.0)
tmp74 = tl.where(tmp19, tmp71, tmp73)
tmp75 = tl.where(tmp13, tmp69, tmp74)
tmp76 = tl.where(tmp7, tmp67, tmp75)
tmp77 = tl.full(tmp76.shape, 0.0, tmp76.dtype)
tmp78 = tl.where(tmp64, tmp76, tmp77)
tmp79 = tl.where(tmp50, tmp63, tmp78)
tmp80 = tl.where(tmp34, tmp47, tmp79)
tmp81 = tl.where(tmp4, tmp31, tmp80)
tl.store(out_ptr0 + x6, tmp81, 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, 4), (64, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0),
def _adapted_sampling(shape: 'Union[Tuple, torch.Size]', dist:
'torch.distributions.Distribution', same_on_batch=False) ->torch.Tensor:
"""The uniform sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
By default, same_on_batch is set to False.
"""
if same_on_batch:
return dist.sample((1, *shape[1:])).repeat(shape[0], *([1] * (len(
shape) - 1)))
return dist.sample(shape)
def _transform_output_shape(output:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', shape: 'Tuple'
) ->Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: torch.Tensor
shape: List/tuple of int
Returns:
torch.Tensor
"""
is_tuple = isinstance(output, tuple)
out_tensor: 'torch.Tensor'
trans_matrix: 'Optional[torch.Tensor]'
if is_tuple:
out_tensor, trans_matrix = cast(Tuple[torch.Tensor, torch.Tensor],
output)
else:
out_tensor = cast(torch.Tensor, output)
trans_matrix = None
if trans_matrix is not None:
if len(out_tensor.shape) > len(shape):
assert trans_matrix.shape[0
] == 1, f'Dimension 0 of transformation matrix is expected to be 1, got {trans_matrix.shape[0]}'
trans_matrix = trans_matrix.squeeze(0)
for dim in range(len(out_tensor.shape) - len(shape)):
assert out_tensor.shape[0
] == 1, f'Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}'
out_tensor = out_tensor.squeeze(0)
return (out_tensor, trans_matrix) if is_tuple else out_tensor
def _transform_input(input: 'torch.Tensor') ->torch.Tensor:
"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
Args:
input: torch.Tensor
Returns:
torch.Tensor
"""
if not torch.is_tensor(input):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if len(input.shape) not in [2, 3, 4]:
raise ValueError(
f'Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}'
)
if len(input.shape) == 2:
input = input.unsqueeze(0)
if len(input.shape) == 3:
input = input.unsqueeze(0)
return input
def _validate_input_dtype(input: 'torch.Tensor', accepted_dtypes: 'List'
) ->None:
"""Check if the dtype of the input tensor is in the range of accepted_dtypes
Args:
input: torch.Tensor
accepted_dtypes: List. e.g. [torch.float32, torch.float64]
"""
if input.dtype not in accepted_dtypes:
raise TypeError(
f'Expected input of {accepted_dtypes}. Got {input.dtype}')
def _extract_device_dtype(tensor_list: 'List[Optional[Any]]') ->Tuple[torch
.device, torch.dtype]:
"""Check if all the input are in the same device (only if when they are torch.Tensor).
If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
Returns:
[torch.device, torch.dtype]
"""
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
if not isinstance(tensor, (torch.Tensor,)):
continue
_device = tensor.device
_dtype = tensor.dtype
if device is None and dtype is None:
device = _device
dtype = _dtype
elif device != _device or dtype != _dtype:
raise ValueError(
f'Passed values are not in the same device and dtype.Got ({device}, {dtype}) and ({_device}, {_dtype}).'
)
if device is None:
device = torch.device('cpu')
if dtype is None:
dtype = torch.get_default_dtype()
return device, dtype
def _joint_range_check(ranged_factor: 'torch.Tensor', name: 'str', bounds:
'Optional[Tuple[float, float]]'=None) ->None:
"""check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]"""
if bounds is None:
bounds = float('-inf'), float('inf')
if ranged_factor.dim() == 1 and len(ranged_factor) == 2:
if not bounds[0] <= ranged_factor[0] or not bounds[1] >= ranged_factor[
1]:
raise ValueError(
f'{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.'
)
if not bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]:
raise ValueError(
f'{name}[0] should be smaller than {name}[1] got {ranged_factor}'
)
else:
raise TypeError(
f'{name} should be a tensor with length 2 whose values between {bounds}. Got {ranged_factor}.'
)
def _singular_range_check(ranged_factor: 'torch.Tensor', name: 'str',
bounds: 'Optional[Tuple[float, float]]'=None, skip_none: 'bool'=False,
mode: 'str'='2d') ->None:
"""check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
if mode == '2d':
dim_size = 2
elif mode == '3d':
dim_size = 3
else:
raise ValueError(f"'mode' shall be either 2d or 3d. Got {mode}")
if skip_none and ranged_factor is None:
return
if bounds is None:
bounds = float('-inf'), float('inf')
if ranged_factor.dim() == 1 and len(ranged_factor) == dim_size:
for f in ranged_factor:
if not bounds[0] <= f <= bounds[1]:
raise ValueError(
f'{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.'
)
else:
raise TypeError(
f'{name} should be a float number or a tuple with length {dim_size} whose values between {bounds}.Got {ranged_factor}'
)
def _range_bound(factor:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]', name:
'str', center: 'float'=0.0, bounds: 'Tuple[float, float]'=(0, float(
'inf')), check: 'Optional[str]'='joint', device: 'torch.device'=torch.
device('cpu'), dtype: 'torch.dtype'=torch.get_default_dtype()
) ->torch.Tensor:
"""Check inputs and compute the corresponding factor bounds"""
if not isinstance(factor, torch.Tensor):
factor = torch.tensor(factor, device=device, dtype=dtype)
factor_bound: 'torch.Tensor'
if factor.dim() == 0:
if factor < 0:
raise ValueError(
f'If {name} is a single number number, it must be non negative. Got {factor}'
)
factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=
factor.device, dtype=factor.dtype) + center
factor_bound = factor_bound.clamp(bounds[0], bounds[1])
else:
factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
if check is not None:
if check == 'joint':
_joint_range_check(factor_bound, name, bounds)
elif check == 'singular':
_singular_range_check(factor_bound, name, bounds)
else:
raise NotImplementedError(f"methods '{check}' not implemented.")
return factor_bound
def adjust_brightness(input: 'torch.Tensor', brightness_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust Brightness of an image.
.. image:: _static/img/adjust_brightness.png
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
input: image to be adjusted in the shape of :math:`(*, N)`.
brightness_factor: Brightness adjust factor per element
in the batch. 0 does not modify the input image while any other number modify the
brightness.
Return:
Adjusted image in the shape of :math:`(*, N)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
>>> adjust_brightness(x, 1.)
tensor([[[[1., 1.],
[1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3)
>>> y = torch.tensor([0.25, 0.50])
>>> adjust_brightness(x, y).shape
torch.Size([2, 5, 3, 3])
"""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(brightness_factor, (float, torch.Tensor)):
raise TypeError(
f'The factor should be either a float or torch.Tensor. Got {type(brightness_factor)}'
)
if isinstance(brightness_factor, float):
brightness_factor = torch.tensor([brightness_factor])
brightness_factor = brightness_factor.to(input.device)
for _ in input.shape[1:]:
brightness_factor = torch.unsqueeze(brightness_factor, dim=-1)
x_adjust: 'torch.Tensor' = input + brightness_factor
out: 'torch.Tensor' = torch.clamp(x_adjust, 0.0, 1.0)
return out
def adjust_contrast(input: 'torch.Tensor', contrast_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust Contrast of an image.
.. image:: _static/img/adjust_contrast.png
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
input: Image to be adjusted in the shape of :math:`(*, N)`.
contrast_factor: Contrast adjust factor per element
in the batch. 0 generates a completely black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
Return:
Adjusted image in the shape of :math:`(*, N)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
>>> adjust_contrast(x, 0.5)
tensor([[[[0.5000, 0.5000],
[0.5000, 0.5000]]]])
>>> x = torch.ones(2, 5, 3, 3)
>>> y = torch.tensor([0.65, 0.50])
>>> adjust_contrast(x, y).shape
torch.Size([2, 5, 3, 3])
"""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(contrast_factor, (float, torch.Tensor)):
raise TypeError(
f'The factor should be either a float or torch.Tensor. Got {type(contrast_factor)}'
)
if isinstance(contrast_factor, float):
contrast_factor = torch.tensor([contrast_factor])
contrast_factor = contrast_factor.to(input.device)
if (contrast_factor < 0).any():
raise ValueError(
f'Contrast factor must be non-negative. Got {contrast_factor}')
for _ in input.shape[1:]:
contrast_factor = torch.unsqueeze(contrast_factor, dim=-1)
x_adjust: 'torch.Tensor' = input * contrast_factor
out: 'torch.Tensor' = torch.clamp(x_adjust, 0.0, 1.0)
return out
def adjust_hue_raw(input: 'torch.Tensor', hue_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust hue of an image. Expecting input to be in hsv format already."""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(hue_factor, (float, torch.Tensor)):
raise TypeError(
f'The hue_factor should be a float number or torch.Tensor in the range between [-PI, PI]. Got {type(hue_factor)}'
)
if isinstance(hue_factor, float):
hue_factor = torch.as_tensor(hue_factor)
hue_factor = hue_factor
for _ in input.shape[1:]:
hue_factor = torch.unsqueeze(hue_factor, dim=-1)
h, s, v = torch.chunk(input, chunks=3, dim=-3)
divisor: 'float' = 2 * pi
h_out: 'torch.Tensor' = torch.fmod(h + hue_factor, divisor)
out: 'torch.Tensor' = torch.cat([h_out, s, v], dim=-3)
return out
def hsv_to_rgb(image: 'torch.Tensor') ->torch.Tensor:
"""Convert an image from HSV to RGB.
The H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.
Args:
image: HSV Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.
Returns:
RGB version of the image with shape of :math:`(*, 3, H, W)`.
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = hsv_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError('Input size must have a shape of (*, 3, H, W). Got {}'
.format(image.shape))
h: 'torch.Tensor' = image[..., 0, :, :] / (2 * math.pi)
s: 'torch.Tensor' = image[..., 1, :, :]
v: 'torch.Tensor' = image[..., 2, :, :]
hi: 'torch.Tensor' = torch.floor(h * 6) % 6
f: 'torch.Tensor' = h * 6 % 6 - hi
one: 'torch.Tensor' = torch.tensor(1.0).to(image.device)
p: 'torch.Tensor' = v * (one - s)
q: 'torch.Tensor' = v * (one - f * s)
t: 'torch.Tensor' = v * (one - (one - f) * s)
hi = hi.long()
indices: 'torch.Tensor' = torch.stack([hi, hi + 6, hi + 12], dim=-3)
out = torch.stack((v, q, p, p, t, v, t, v, v, q, p, p, p, p, t, v, v, q
), dim=-3)
out = torch.gather(out, -3, indices)
return out
def rgb_to_hsv(image: 'torch.Tensor', eps: 'float'=1e-06) ->torch.Tensor:
"""Convert an image from RGB to HSV.
.. image:: _static/img/rgb_to_hsv.png
The image data is assumed to be in the range of (0, 1).
Args:
image: RGB Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.
eps: scalar to enforce numarical stability.
Returns:
HSV version of the image with shape of :math:`(*, 3, H, W)`.
The H channel values are in the range 0..2pi. S and V are in the range 0..1.
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_hsv(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError('Input size must have a shape of (*, 3, H, W). Got {}'
.format(image.shape))
maxc, _ = image.max(-3)
maxc_mask = image == maxc.unsqueeze(-3)
_, max_indices = ((maxc_mask.cumsum(-3) == 1) & maxc_mask).max(-3)
minc: 'torch.Tensor' = image.min(-3)[0]
v: 'torch.Tensor' = maxc
deltac: 'torch.Tensor' = maxc - minc
s: 'torch.Tensor' = deltac / (v + eps)
deltac = torch.where(deltac == 0, torch.ones_like(deltac, device=deltac
.device, dtype=deltac.dtype), deltac)
maxc_tmp = maxc.unsqueeze(-3) - image
rc: 'torch.Tensor' = maxc_tmp[..., 0, :, :]
gc: 'torch.Tensor' = maxc_tmp[..., 1, :, :]
bc: 'torch.Tensor' = maxc_tmp[..., 2, :, :]
h = torch.stack([bc - gc, 2.0 * deltac + rc - bc, 4.0 * deltac + gc -
rc], dim=-3)
h = torch.gather(h, dim=-3, index=max_indices[..., None, :, :])
h = h.squeeze(-3)
h = h / deltac
h = h / 6.0 % 1.0
h = 2 * math.pi * h
return torch.stack([h, s, v], dim=-3)
def adjust_hue(input: 'torch.Tensor', hue_factor: 'Union[float, torch.Tensor]'
) ->torch.Tensor:
"""Adjust hue of an image.
.. image:: _static/img/adjust_hue.png
The input image is expected to be an RGB image in the range of [0, 1].
Args:
input: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
and -PI give complete reversal of hue channel in HSV space in positive and negative
direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
image with complementary colors while 0 gives the original image.
Return:
Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
>>> x = torch.ones(1, 3, 2, 2)
>>> adjust_hue(x, 3.141516).shape
torch.Size([1, 3, 2, 2])
>>> x = torch.ones(2, 3, 3, 3)
>>> y = torch.ones(2) * 3.141516
>>> adjust_hue(x, y).shape
torch.Size([2, 3, 3, 3])
"""
x_hsv: 'torch.Tensor' = rgb_to_hsv(input)
x_adjusted: 'torch.Tensor' = adjust_hue_raw(x_hsv, hue_factor)
out: 'torch.Tensor' = hsv_to_rgb(x_adjusted)
return out
def adjust_saturation_raw(input: 'torch.Tensor', saturation_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust color saturation of an image. Expecting input to be in hsv format already."""
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not isinstance(saturation_factor, (float, torch.Tensor)):
raise TypeError(
f'The saturation_factor should be a float number or torch.Tensor.Got {type(saturation_factor)}'
)
if isinstance(saturation_factor, float):
saturation_factor = torch.as_tensor(saturation_factor)
saturation_factor = saturation_factor.to(input.device)
for _ in input.shape[1:]:
saturation_factor = torch.unsqueeze(saturation_factor, dim=-1)
h, s, v = torch.chunk(input, chunks=3, dim=-3)
s_out: 'torch.Tensor' = torch.clamp(s * saturation_factor, min=0, max=1)
out: 'torch.Tensor' = torch.cat([h, s_out, v], dim=-3)
return out
def adjust_saturation(input: 'torch.Tensor', saturation_factor:
'Union[float, torch.Tensor]') ->torch.Tensor:
"""Adjust color saturation of an image.
.. image:: _static/img/adjust_saturation.png
The input image is expected to be an RGB image in the range of [0, 1].
Args:
input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
saturation_factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
Return:
Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
>>> x = torch.ones(1, 3, 3, 3)
>>> adjust_saturation(x, 2.).shape
torch.Size([1, 3, 3, 3])
>>> x = torch.ones(2, 3, 3, 3)
>>> y = torch.tensor([1., 2.])
>>> adjust_saturation(x, y).shape
torch.Size([2, 3, 3, 3])
"""
x_hsv: 'torch.Tensor' = rgb_to_hsv(input)
x_adjusted: 'torch.Tensor' = adjust_saturation_raw(x_hsv, saturation_factor
)
out: 'torch.Tensor' = hsv_to_rgb(x_adjusted)
return out
def _extract_tensor_patchesnd(input: 'torch.Tensor', window_sizes:
'Tuple[int, ...]', strides: 'Tuple[int, ...]') ->torch.Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
input = input.unfold(dim, patch_size, stride)
input = input.permute(0, *dims, 1, *[(dim + len(dims)) for dim in dims]
).contiguous()
return input.view(batch_size, -1, num_channels, *window_sizes)
def extract_tensor_patches(input: 'torch.Tensor', window_size:
'Union[int, Tuple[int, int]]', stride: 'Union[int, Tuple[int, int]]'=1,
padding: 'Union[int, Tuple[int, int]]'=0) ->torch.Tensor:
"""Function that extract patches from tensors and stack them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
"""
if not torch.is_tensor(input):
raise TypeError('Input input type is not a torch.Tensor. Got {}'.
format(type(input)))
if not len(input.shape) == 4:
raise ValueError('Invalid input shape, we expect BxCxHxW. Got: {}'.
format(input.shape))
if padding:
pad_vert, pad_horz = _pair(padding)
input = F.pad(input, [pad_horz, pad_horz, pad_vert, pad_vert])
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
class _BasicAugmentationBase(nn.Module):
"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
To change this behaviour, please use ``set_rng_device_and_dtype``.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation
probabilities element-wisely.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __init__(self, p: 'float'=0.5, p_batch: 'float'=1.0, same_on_batch:
'bool'=False, keepdim: 'bool'=False) ->None:
super(_BasicAugmentationBase, self).__init__()
self.p = p
self.p_batch = p_batch
self.same_on_batch = same_on_batch
self.keepdim = keepdim
self._params: 'Dict[str, torch.Tensor]' = {}
if p != 0.0 or p != 1.0:
self._p_gen = Bernoulli(self.p)
if p_batch != 0.0 or p_batch != 1.0:
self._p_batch_gen = Bernoulli(self.p_batch)
self.set_rng_device_and_dtype(torch.device('cpu'), torch.
get_default_dtype())
def __repr__(self) ->str:
return (
f'p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}'
)
def __unpack_input__(self, input: 'torch.Tensor') ->torch.Tensor:
return input
def __check_batching__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]'):
"""Check if a transformation matrix is returned,
it has to be in the same batching mode as output."""
raise NotImplementedError
def transform_tensor(self, input: 'torch.Tensor') ->torch.Tensor:
"""Standardize input tensors."""
raise NotImplementedError
def generate_parameters(self, batch_shape: 'torch.Size') ->Dict[str,
torch.Tensor]:
return {}
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
raise NotImplementedError
def set_rng_device_and_dtype(self, device: 'torch.device', dtype:
'torch.dtype') ->None:
"""Change the random generation device and dtype.
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
self.device = device
self.dtype = dtype
def __batch_prob_generator__(self, batch_shape: 'torch.Size', p:
'float', p_batch: 'float', same_on_batch: 'bool') ->torch.Tensor:
batch_prob: 'torch.Tensor'
if p_batch == 1:
batch_prob = torch.tensor([True])
elif p_batch == 0:
batch_prob = torch.tensor([False])
else:
batch_prob = _adapted_sampling((1,), self._p_batch_gen,
same_on_batch).bool()
if batch_prob.sum().item() == 1:
elem_prob: 'torch.Tensor'
if p == 1:
elem_prob = torch.tensor([True] * batch_shape[0])
elif p == 0:
elem_prob = torch.tensor([False] * batch_shape[0])
else:
elem_prob = _adapted_sampling((batch_shape[0],), self.
_p_gen, same_on_batch).bool()
batch_prob = batch_prob * elem_prob
else:
batch_prob = batch_prob.repeat(batch_shape[0])
return batch_prob
def forward_parameters(self, batch_shape):
to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.
p_batch, self.same_on_batch)
_params = self.generate_parameters(torch.Size((int(to_apply.sum().
item()), *batch_shape[1:])))
if _params is None:
_params = {}
_params['batch_prob'] = to_apply
return _params
def apply_func(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->Union[torch.Tensor, Tuple[torch.Tensor,
torch.Tensor]]:
input = self.transform_tensor(input)
return self.apply_transform(input, params)
def forward(self, input: 'torch.Tensor', params:
'Optional[Dict[str, torch.Tensor]]'=None) ->Union[torch.Tensor,
Tuple[torch.Tensor, torch.Tensor]]:
in_tensor = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
if params is None:
params = self.forward_parameters(batch_shape)
self._params = params
output = self.apply_func(input, self._params)
return _transform_output_shape(output, ori_shape
) if self.keepdim else output
class _AugmentationBase(_BasicAugmentationBase):
"""_AugmentationBase base class for customized augmentation implementations.
Advanced augmentation base class with the functionality of transformation matrix calculations.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __init__(self, return_transform: 'bool'=None, same_on_batch: 'bool'
=False, p: 'float'=0.5, p_batch: 'float'=1.0, keepdim: 'bool'=False
) ->None:
super(_AugmentationBase, self).__init__(p, p_batch=p_batch,
same_on_batch=same_on_batch, keepdim=keepdim)
self.p = p
self.p_batch = p_batch
self.return_transform = return_transform
def __repr__(self) ->str:
return super().__repr__(
) + f', return_transform={self.return_transform}'
def identity_matrix(self, input: 'torch.Tensor') ->torch.Tensor:
raise NotImplementedError
def compute_transformation(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
raise NotImplementedError
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]', transform: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
raise NotImplementedError
def __unpack_input__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]') ->Tuple[
torch.Tensor, Optional[torch.Tensor]]:
if isinstance(input, tuple):
in_tensor = input[0]
in_transformation = input[1]
return in_tensor, in_transformation
in_tensor = input
return in_tensor, None
def apply_func(self, in_tensor: 'torch.Tensor', in_transform:
'Optional[torch.Tensor]', params: 'Dict[str, torch.Tensor]',
return_transform: 'bool'=False) ->Union[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
to_apply = params['batch_prob']
if torch.sum(to_apply) == 0:
output = in_tensor
trans_matrix = self.identity_matrix(in_tensor)
elif torch.sum(to_apply) == len(to_apply):
trans_matrix = self.compute_transformation(in_tensor, params)
output = self.apply_transform(in_tensor, params, trans_matrix)
else:
output = in_tensor.clone()
trans_matrix = self.identity_matrix(in_tensor)
trans_matrix[to_apply] = self.compute_transformation(in_tensor[
to_apply], params)
output[to_apply] = self.apply_transform(in_tensor[to_apply],
params, trans_matrix[to_apply])
self._transform_matrix = trans_matrix
if return_transform:
out_transformation = (trans_matrix if in_transform is None else
trans_matrix @ in_transform)
return output, out_transformation
if in_transform is not None:
return output, in_transform
return output
def forward(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', params:
'Optional[Dict[str, torch.Tensor]]'=None, return_transform:
'Optional[bool]'=None) ->Union[torch.Tensor, Tuple[torch.Tensor,
torch.Tensor]]:
in_tensor, in_transform = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
if return_transform is None:
return_transform = self.return_transform
return_transform = cast(bool, return_transform)
if params is None:
params = self.forward_parameters(batch_shape)
if 'batch_prob' not in params:
params['batch_prob'] = torch.tensor([True] * batch_shape[0])
warnings.warn(
'`batch_prob` is not found in params. Will assume applying on all data.'
)
self._params = params
output = self.apply_func(in_tensor, in_transform, self._params,
return_transform)
return _transform_output_shape(output, ori_shape
) if self.keepdim else output
class AugmentationBase2D(_AugmentationBase):
"""AugmentationBase2D base class for customized augmentation implementations.
For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
"compute_transformation" is only required when passing "return_transform" as True.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def __check_batching__(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]'):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
assert len(mat.shape
) == 3, 'Input tensor is in batch mode but transformation matrix is not'
assert mat.shape[0] == inp.shape[0
], f'In batch dimension, input has {inp.shape[0]}but transformation matrix has {mat.shape[0]}'
elif len(inp.shape) == 3 or len(inp.shape) == 2:
assert len(mat.shape
) == 2, 'Input tensor is in non-batch mode but transformation matrix is not'
else:
raise ValueError(
f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}'
)
def transform_tensor(self, input: 'torch.Tensor') ->torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.
float32, torch.float64])
return _transform_input(input)
def identity_matrix(self, input) ->torch.Tensor:
"""Return 3x3 identity matrix."""
return kornia.eye_like(3, input)
class IntensityAugmentationBase2D(AugmentationBase2D):
"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
"compute_transformation" is only required when passing "return_transform" as True.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation probabilities
element-wisely for a batch.
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). Default: False.
"""
def compute_transformation(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]') ->torch.Tensor:
return self.identity_matrix(input)
class ParamItem(NamedTuple):
name: 'str'
data: 'Union[dict, list]'
class ImageSequential(nn.Sequential):
"""Sequential for creating kornia image processing pipeline.
Args:
*args : a list of kornia augmentation and image operation modules.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
return_transform: if ``True`` return the matrix describing the transformation
applied to each. If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
random_apply: randomly select a sublist (order agnostic) of args to
apply transformation.
If int, a fixed number of transformations will be selected.
If (a,), x number of transformations (a <= x <= len(args)) will be selected.
If (a, b), x number of transformations (a <= x <= b) will be selected.
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
Returns:
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: the tensor (, and the transformation matrix)
has been sequentially modified by the args.
Examples:
>>> import kornia
>>> input = torch.randn(2, 3, 5, 6)
>>> aug_list = ImageSequential(
... kornia.color.BgrToRgb(),
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.filters.MedianBlur((3, 3)),
... kornia.augmentation.RandomAffine(360, p=1.0),
... kornia.enhance.Invert(),
... return_transform=True,
... same_on_batch=True,
... random_apply=10,
... )
>>> out = aug_list(input)
>>> out[0].shape, out[1].shape
(torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 3]))
Reproduce with provided params.
>>> out2 = aug_list(input, params=aug_list._params)
>>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1])
(True, True)
Note:
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
Those transformations in ``kornia.geometry`` will not be taken into account.
"""
def __init__(self, *args: nn.Module, same_on_batch: Optional[bool]=None,
return_transform: Optional[bool]=None, keepdim: Optional[bool]=None,
random_apply: Union[int, bool, Tuple[int, int]]=False) ->None:
self.same_on_batch = same_on_batch
self.return_transform = return_transform
self.keepdim = keepdim
_args = OrderedDict()
for idx, arg in enumerate(args):
if not isinstance(arg, nn.Module):
raise NotImplementedError(
f'Only nn.Module are supported at this moment. Got {arg}.')
if isinstance(arg, _AugmentationBase):
if same_on_batch is not None:
arg.same_on_batch = same_on_batch
if return_transform is not None:
arg.return_transform = return_transform
if keepdim is not None:
arg.keepdim = keepdim
_args.update({f'{arg.__class__.__name__}_{idx}': arg})
super(ImageSequential, self).__init__(_args)
self._params: 'List[Any]' = []
self.random_apply: 'Union[Tuple[int, int], bool]'
if random_apply:
if isinstance(random_apply, (bool,)) and random_apply is True:
self.random_apply = len(args), len(args) + 1
elif isinstance(random_apply, (int,)):
self.random_apply = random_apply, random_apply + 1
elif isinstance(random_apply, (tuple,)) and len(random_apply
) == 2 and isinstance(random_apply[0], (int,)) and isinstance(
random_apply[1], (int,)):
self.random_apply = random_apply[0], random_apply[1] + 1
elif isinstance(random_apply, (tuple,)) and len(random_apply
) == 1 and isinstance(random_apply[0], (int,)):
self.random_apply = random_apply[0], len(args) + 1
else:
raise ValueError(
f'Non-readable random_apply. Got {random_apply}.')
assert isinstance(self.random_apply, (tuple,)) and len(self.
random_apply) == 2 and isinstance(self.random_apply[0], (int,)
) and isinstance(self.random_apply[0], (int,)
), f'Expect a tuple of (int, int). Got {self.random_apply}.'
else:
self.random_apply = False
def _get_child_sequence(self) ->Iterator[Tuple[str, nn.Module]]:
if self.random_apply:
num_samples = int(torch.randint(*self.random_apply, (1,)).item())
indices = torch.multinomial(torch.ones((len(self),)),
num_samples, replacement=True if num_samples > len(self) else
False)
return self._get_children_by_indices(indices)
return self.named_children()
def _get_children_by_indices(self, indices: 'torch.Tensor') ->Iterator[
Tuple[str, nn.Module]]:
modules = list(self.named_children())
for idx in indices:
yield modules[idx]
def _get_children_by_module_names(self, names: 'List[str]') ->Iterator[
Tuple[str, nn.Module]]:
modules = list(self.named_children())
for name in names:
yield modules[list(dict(self.named_children()).keys()).index(name)]
def get_forward_sequence(self, params: 'Optional[List[ParamItem]]'=None
) ->Iterator[Tuple[str, nn.Module]]:
if params is None:
named_modules = self._get_child_sequence()
else:
named_modules = self._get_children_by_module_names([p.name for
p in params])
return named_modules
def apply_to_input(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]',
module_name: 'str', module: 'Optional[nn.Module]'=None, param:
'Optional[ParamItem]'=None) ->Union[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
if module is None:
module = self.get_submodule(module_name)
if param is not None:
assert module_name == param.name
_param = param.data
else:
_param = None
if isinstance(module, (_AugmentationBase, ImageSequential)
) and _param is None:
input = module(input)
self._params.append(ParamItem(module_name, module._params))
elif isinstance(module, (_AugmentationBase, ImageSequential)
) and _param is not None:
input = module(input, params=_param)
self._params.append(ParamItem(module_name, _param))
else:
assert _param == {
} or _param is None, f'Non-augmentaion operation {module_name} require empty parameters. Got {module}.'
if isinstance(input, (tuple, list)):
input = module(input[0]), input[1]
else:
input = module(input)
self._params.append(ParamItem(module_name, {}))
return input
def forward(self, input:
'Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]', params:
'Optional[List[ParamItem]]'=None) ->Union[torch.Tensor, Tuple[torch
.Tensor, torch.Tensor]]:
self._params = []
named_modules = self.get_forward_sequence(params)
params = [] if params is None else params
for (name, module), param in zip_longest(named_modules, params):
input = self.apply_to_input(input, name, module, param=param)
return input
class ColorJitter(IntensityAugmentationBase2D):
"""Applies a random transformation to the brightness, contrast, saturation and hue of a tensor image.
.. image:: _static/img/ColorJitter.png
Args:
p: probability of applying the transformation.
brightness: The brightness factor to apply.
contrast: The contrast factor to apply.
saturation: The saturation factor to apply.
hue: The hue factor to apply.
return_transform: if ``True`` return the matrix describing the transformation applied to each
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
Examples:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.ones(1, 3, 3, 3)
>>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
>>> aug(inputs)
tensor([[[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]],
<BLANKLINE>
[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]],
<BLANKLINE>
[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]]]])
"""
def __init__(self, brightness:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
contrast:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
saturation:
'Union[torch.Tensor, float, Tuple[float, float], List[float]]'=0.0,
hue: 'Union[torch.Tensor, float, Tuple[float, float], List[float]]'
=0.0, return_transform: 'bool'=False, same_on_batch: 'bool'=False,
p: 'float'=1.0, keepdim: 'bool'=False) ->None:
super(ColorJitter, self).__init__(p=p, return_transform=
return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([brightness,
contrast, hue, saturation])
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def __repr__(self) ->str:
repr = (
f'brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}'
)
return self.__class__.__name__ + f'({repr}, {super().__repr__()})'
def generate_parameters(self, batch_shape: 'torch.Size') ->Dict[str,
torch.Tensor]:
brightness: 'torch.Tensor' = _range_bound(self.brightness,
'brightness', center=1.0, bounds=(0, 2), device=self._device,
dtype=self._dtype)
contrast: 'torch.Tensor' = _range_bound(self.contrast, 'contrast',
center=1.0, device=self._device, dtype=self._dtype)
saturation: 'torch.Tensor' = _range_bound(self.saturation,
'saturation', center=1.0, device=self._device, dtype=self._dtype)
hue: 'torch.Tensor' = _range_bound(self.hue, 'hue', bounds=(-0.5,
0.5), device=self._device, dtype=self._dtype)
return rg.random_color_jitter_generator(batch_shape[0], brightness,
contrast, saturation, hue, self.same_on_batch, self.device,
self.dtype)
def apply_transform(self, input: 'torch.Tensor', params:
'Dict[str, torch.Tensor]', transform: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
transforms = [lambda img: adjust_brightness(img, params[
'brightness_factor'] - 1), lambda img: adjust_contrast(img,
params['contrast_factor']), lambda img: adjust_saturation(img,
params['saturation_factor']), lambda img: adjust_hue(img,
params['hue_factor'] * 2 * pi)]
jittered = input
for idx in params['order'].tolist():
t = transforms[idx]
jittered = t(jittered)
return jittered
class PatchSequentialNew(ImageSequential):
"""Container for performing patch-level image processing.
.. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_patch_sequential_5_1.png
PatchSequential breaks input images into patches by a given grid size, which will be resembled back
afterwards. Different image processing and augmentation methods will be performed on each patch region.
Args:
*args: a list of processing modules.
grid_size: controls the grid board seperation.
padding: same or valid padding. If same padding, it will pad to include all pixels if the input
tensor cannot be divisible by grid_size. If valid padding, the redundent border will be removed.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
patchwise_apply: apply image processing args will be applied patch-wisely.
if ``True``, the number of args must be equal to grid number.
if ``False``, the image processing args will be applied as a sequence to all patches. Default: False.
random_apply: randomly select a sublist (order agnostic) of args to
apply transformation.
If ``int`` (batchwise mode only), a fixed number of transformations will be selected.
If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected.
If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected.
If ``True``, the whole list of args will be processed in a random order.
If ``False``, the whole list of args will be processed in original order.
Return:
List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)
has been sequentially modified by the args.
Examples:
>>> import kornia.augmentation as K
>>> input = torch.randn(2, 3, 224, 224)
>>> seq = PatchSequential(
... ImageSequential(
... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
... K.RandomPerspective(0.2, p=0.5),
... K.RandomSolarize(0.1, 0.1, p=0.5),
... ),
... K.RandomAffine(360, p=1.0),
... ImageSequential(
... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
... K.RandomPerspective(0.2, p=0.5),
... K.RandomSolarize(0.1, 0.1, p=0.5),
... ),
... K.RandomSolarize(0.1, 0.1, p=0.1),
... grid_size=(2,2),
... patchwise_apply=False,
... same_on_batch=True,
... random_apply=True,
... )
>>> out = seq(input)
>>> out.shape
torch.Size([2, 3, 224, 224])
>>> out1 = seq(input, seq._params)
>>> torch.equal(out, out1)
True
"""
def __init__(self, *args: nn.Module, grid_size: Tuple[int, int]=(4, 4),
padding: str='same', same_on_batch: Optional[bool]=None, keepdim:
Optional[bool]=None, patchwise_apply: bool=False, random_apply:
Union[int, bool, Tuple[int, int]]=False) ->None:
_random_apply: 'Optional[Union[int, Tuple[int, int]]]'
if patchwise_apply and random_apply is True:
_random_apply = grid_size[0] * grid_size[1], grid_size[0
] * grid_size[1]
elif patchwise_apply and random_apply is False:
assert len(args) == grid_size[0] * grid_size[1
], f'The number of processing modules must be equal with grid size.Got {len(args)} and {grid_size[0] * grid_size[1]}.'
_random_apply = random_apply
elif patchwise_apply and isinstance(random_apply, (int, tuple)):
raise ValueError(
f'Only boolean value allowed when `patchwise_apply` is set to True. Got {random_apply}.'
)
else:
_random_apply = random_apply
super(PatchSequentialNew, self).__init__(*args, same_on_batch=
same_on_batch, return_transform=False, keepdim=keepdim,
random_apply=_random_apply)
assert padding in ['same', 'valid'
], f'`padding` must be either `same` or `valid`. Got {padding}.'
self.grid_size = grid_size
self.padding = padding
self.patchwise_apply = patchwise_apply
def is_intensity_only(self) ->bool:
"""Check if all transformations are intensity-based.
Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks).
"""
for arg in self.children():
if isinstance(arg, (ImageSequential,)):
for _arg in arg.children():
if not isinstance(_arg, IntensityAugmentationBase2D):
return False
elif not isinstance(_arg, IntensityAugmentationBase2D):
return False
return True
def __repeat_param_across_patches__(self, param: 'torch.Tensor',
patch_num: 'int') ->torch.Tensor:
"""Repeat parameters across patches.
The input is shaped as (B, ...), while to output (B * patch_num, ...), which
to guarentee that the same transformation would happen for each patch index.
(B1, B2, ..., Bn) => (B1, ... Bn, B1, ..., Bn, ..., B1, ..., Bn)
| pt_size | | pt_size | ..., | pt_size |
"""
repeated = torch.cat([param] * patch_num, dim=0)
return repeated
def compute_padding(self, input: 'torch.Tensor', padding: 'str',
grid_size: 'Optional[Tuple[int, int]]'=None) ->Tuple[int, int, int, int
]:
if grid_size is None:
grid_size = self.grid_size
if padding == 'valid':
ph, pw = input.size(-2) // grid_size[0], input.size(-1
) // grid_size[1]
return -pw // 2, pw // 2 - pw, -ph // 2, ph // 2 - ph
elif padding == 'same':
ph = input.size(-2) - input.size(-2) // grid_size[0] * grid_size[0]
pw = input.size(-1) - input.size(-1) // grid_size[1] * grid_size[1]
return pw // 2, pw - pw // 2, ph // 2, ph - ph // 2
else:
raise NotImplementedError(
f"Expect `padding` as either 'valid' or 'same'. Got {padding}."
)
def extract_patches(self, input: 'torch.Tensor', grid_size:
'Optional[Tuple[int, int]]'=None, pad:
'Optional[Tuple[int, int, int, int]]'=None) ->torch.Tensor:
"""Extract patches from tensor.
Example:
>>> import kornia.augmentation as K
>>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
>>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
tensor([[[[[ 0, 1],
[ 4, 5]]],
<BLANKLINE>
<BLANKLINE>
[[[ 2, 3],
[ 6, 7]]],
<BLANKLINE>
<BLANKLINE>
[[[ 8, 9],
[12, 13]]],
<BLANKLINE>
<BLANKLINE>
[[[10, 11],
[14, 15]]]]])
>>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -1, -2, -2))
tensor([[[[[19, 20, 21]]],
<BLANKLINE>
<BLANKLINE>
[[[22, 23, 24]]],
<BLANKLINE>
<BLANKLINE>
[[[28, 29, 30]]],
<BLANKLINE>
<BLANKLINE>
[[[31, 32, 33]]]]])
"""
if pad is not None:
input = torch.nn.functional.pad(input, list(pad))
if grid_size is None:
grid_size = self.grid_size
window_size = input.size(-2) // grid_size[-2], input.size(-1
) // grid_size[-1]
stride = window_size
return extract_tensor_patches(input, window_size, stride)
def restore_from_patches(self, patches: 'torch.Tensor', grid_size:
'Tuple[int, int]'=(4, 4), pad:
'Optional[Tuple[int, int, int, int]]'=None) ->torch.Tensor:
"""Restore input from patches.
Example:
>>> import kornia.augmentation as K
>>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
>>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
>>> pas.restore_from_patches(out, grid_size=(2, 2))
tensor([[[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]]])
"""
if grid_size is None:
grid_size = self.grid_size
patches_tensor = patches.view(-1, grid_size[0], grid_size[1], *
patches.shape[-3:])
restored_tensor = torch.cat(torch.chunk(patches_tensor, grid_size[0
], dim=1), -2).squeeze(1)
restored_tensor = torch.cat(torch.chunk(restored_tensor, grid_size[
1], dim=1), -1).squeeze(1)
if pad is not None:
restored_tensor = torch.nn.functional.pad(restored_tensor, [(-i
) for i in pad])
return restored_tensor
def forward_patchwise(self, input: 'torch.Tensor', params:
'Optional[List[List[ParamItem]]]'=None) ->torch.Tensor:
if params is None:
params = [[]] * input.size(1)
auglist = [self.get_forward_sequence() for _ in range(input.
size(1))]
else:
auglist = [self.get_forward_sequence(p) for p in params]
assert input.size(0) == len(auglist) == len(params)
out = []
self._params = []
for inp, proc, param in zip(input, auglist, params):
o = []
p = []
for inp_pat, (proc_name, proc_pat), _param in zip_longest(inp,
proc, param):
if isinstance(proc_pat, (_AugmentationBase, ImageSequential)):
o.append(proc_pat(inp_pat[None], _param.data if _param
is not None else None))
p.append(ParamItem(proc_name, proc_pat._params))
else:
o.append(proc_pat(inp_pat[None]))
p.append(ParamItem(proc_name, {}))
out.append(torch.cat(o, dim=0))
self._params.append(p)
input = torch.stack(out, dim=0)
return input
def forward_batchwise(self, input: 'torch.Tensor', params:
'Optional[List[ParamItem]]'=None) ->torch.Tensor:
if self.same_on_batch:
batch_shape = input.size(1), *input.shape[-3:]
patch_num = input.size(0)
else:
batch_shape = input.size(0) * input.size(1), *input.shape[-3:]
if params is None:
params = []
for name, aug in self.get_forward_sequence():
if isinstance(aug, _AugmentationBase):
aug.same_on_batch = False
param = aug.forward_parameters(batch_shape)
if self.same_on_batch:
for k, v in param.items():
if not (k == 'order' and isinstance(aug,
ColorJitter)):
param.update({k: self.
__repeat_param_across_patches__(v,
patch_num)})
aug.same_on_batch = True
else:
param = None
params.append(ParamItem(name, param))
input = super().forward(input.view(-1, *input.shape[-3:]), params)
return input
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
rozumden/kornia
|
PatchSequential
| false
| 4,247
|
[
"ECL-2.0",
"Apache-2.0"
] | 0
|
f62f324b201eea50e1e50db3fbf3e968e0a337c5
|
https://github.com/rozumden/kornia/tree/f62f324b201eea50e1e50db3fbf3e968e0a337c5
|
DAModule
|
import torch
import numpy as np
from torch import nn
from torch.nn import init
class ScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=0.001)
if m.bias is not None:
init.constant_(m.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class PositionAttentionModule(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
padding=(kernel_size - 1) // 2)
self.pa = ScaledDotProductAttention(d_model, d_k=d_model, d_v=
d_model, h=1)
def forward(self, x):
bs, c, _h, _w = x.shape
y = self.cnn(x)
y = y.view(bs, c, -1).permute(0, 2, 1)
y = self.pa(y, y, y)
return y
class SimplifiedScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, h, dropout=0.1):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(SimplifiedScaledDotProductAttention, self).__init__()
self.d_model = d_model
self.d_k = d_model // h
self.d_v = d_model // h
self.h = h
self.fc_o = nn.Linear(h * self.d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=0.001)
if m.bias is not None:
init.constant_(m.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = queries.view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3)
k = keys.view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = values.view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class ChannelAttentionModule(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
padding=(kernel_size - 1) // 2)
self.pa = SimplifiedScaledDotProductAttention(H * W, h=1)
def forward(self, x):
bs, c, _h, _w = x.shape
y = self.cnn(x)
y = y.view(bs, c, -1)
y = self.pa(y, y, y)
return y
class DAModule(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.position_attention_module = PositionAttentionModule(d_model=
512, kernel_size=3, H=7, W=7)
self.channel_attention_module = ChannelAttentionModule(d_model=512,
kernel_size=3, H=7, W=7)
def forward(self, input):
bs, c, h, w = input.shape
p_out = self.position_attention_module(input)
c_out = self.channel_attention_module(input)
p_out = p_out.permute(0, 2, 1).view(bs, c, h, w)
c_out = c_out.view(bs, c, h, w)
return p_out + c_out
def get_inputs():
return [torch.rand([4, 512, 1, 49])]
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 numpy as np
from torch import nn
from torch.nn import 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 49
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 49 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 25088 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 512 * x2 + 4608 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, None)
@triton.jit
def triton_per_fused__softmax_sqrt_3(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 196
rnumel = 49
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
x2 = xindex % 49
x3 = xindex // 49
tmp0 = tl.load(in_ptr0 + (r1 + 49 * x0), rmask & xmask, other=0.0)
tmp1 = tl.full([1, 1], 22.62741699796952, tl.float64)
tmp2 = tl.full([1, 1], 0.0, tl.float64)
tmp3 = tmp1 >= tmp2
tmp4 = 1.0
tmp5 = -1.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.where(rmask & xmask, tmp8, float('-inf'))
tmp11 = triton_helpers.max2(tmp10, 1)[:, None]
tmp12 = tmp7 - tmp11
tmp13 = tmp6.to(tl.float64)
tmp14 = tmp13 * tmp1
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp12 / tmp15
tmp17 = tl_math.exp(tmp16)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
tmp20 = tl.where(rmask & xmask, tmp18, 0)
tmp21 = tl.sum(tmp20, 1)[:, None]
tmp22 = tmp17 / tmp21
tl.store(out_ptr2 + (r1 + 49 * x2 + 2432 * x3), tmp22, rmask & xmask)
@triton.jit
def triton_per_fused__softmax_sqrt_4(in_ptr0, out_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 512 * x0), None)
tmp1 = tl.full([1], 7.0, tl.float64)
tmp2 = tl.full([1], 0.0, tl.float64)
tmp3 = tmp1 >= tmp2
tmp4 = 1.0
tmp5 = -1.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp8, 0))
tmp11 = tmp7 - tmp10
tmp12 = tmp6.to(tl.float64)
tmp13 = tmp12 * tmp1
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp11 / tmp14
tmp16 = tl_math.exp(tmp15)
tmp17 = tl.broadcast_to(tmp16, [RBLOCK])
tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0))
tmp20 = tmp16 / tmp19
tl.store(out_ptr2 + (r1 + 512 * x0), tmp20, None)
@triton.jit
def triton_poi_fused_add_5(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 196
xnumel = 512
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 49
y1 = yindex // 49
tmp0 = tl.load(in_out_ptr0 + (x2 + 512 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (y0 + 49 * x2 + 25088 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + (x2 + 512 * y3), tmp6, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15) = args
args.clear()
assert_size_stride(primals_1, (4, 512, 1, 49), (25088, 49, 49, 1))
assert_size_stride(primals_2, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_3, (512,), (1,))
assert_size_stride(primals_4, (512, 512), (512, 1))
assert_size_stride(primals_5, (512,), (1,))
assert_size_stride(primals_6, (512, 512), (512, 1))
assert_size_stride(primals_7, (512,), (1,))
assert_size_stride(primals_8, (512, 512), (512, 1))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (512, 512), (512, 1))
assert_size_stride(primals_11, (512,), (1,))
assert_size_stride(primals_12, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_13, (512,), (1,))
assert_size_stride(primals_14, (49, 49), (49, 1))
assert_size_stride(primals_15, (49,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 1, 49), (25088, 1, 25088, 512),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 49)](primals_1, buf0, 2048, 49,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_1[grid(262144, 9)](primals_2, buf1, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_1[grid(262144, 9)](primals_12, buf2, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_12
buf3 = extern_kernels.convolution(buf0, buf1, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 512, 1, 49), (25088, 1, 25088, 512))
buf4 = reinterpret_tensor(buf3, (4, 49, 512), (25088, 512, 1), 0)
del buf3
triton_poi_fused_clone_2[grid(100352)](buf4, primals_3, 100352,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_3
buf5 = empty_strided_cuda((196, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (196, 512), (512, 1), 0),
reinterpret_tensor(primals_4, (512, 512), (1, 512), 0), out=buf5)
buf6 = empty_strided_cuda((196, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (196, 512), (512, 1), 0),
reinterpret_tensor(primals_6, (512, 512), (1, 512), 0), out=buf6)
buf7 = empty_strided_cuda((196, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (196, 512), (512, 1), 0),
reinterpret_tensor(primals_8, (512, 512), (1, 512), 0), out=buf7)
buf8 = reinterpret_tensor(buf5, (4, 49, 512), (25088, 512, 1), 0)
del buf5
triton_poi_fused_clone_2[grid(100352)](buf8, primals_5, 100352,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf9 = reinterpret_tensor(buf6, (4, 49, 512), (25088, 512, 1), 0)
del buf6
triton_poi_fused_clone_2[grid(100352)](buf9, primals_7, 100352,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 49, 49), (2401, 49, 1), torch.float32)
extern_kernels.bmm(buf8, reinterpret_tensor(buf9, (4, 512, 49), (
25088, 1, 512), 0), out=buf10)
buf13 = empty_strided_cuda((4, 1, 49, 49), (2432, 49, 49, 1), torch
.float32)
triton_per_fused__softmax_sqrt_3[grid(196)](buf10, buf13, 196, 49,
XBLOCK=1, num_warps=2, num_stages=1)
del buf10
buf14 = reinterpret_tensor(buf7, (4, 49, 512), (25088, 512, 1), 0)
del buf7
triton_poi_fused_clone_2[grid(100352)](buf14, primals_9, 100352,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf15 = empty_strided_cuda((4, 49, 512), (25088, 512, 1), torch.float32
)
extern_kernels.bmm(reinterpret_tensor(buf13, (4, 49, 49), (2432, 49,
1), 0), buf14, out=buf15)
buf16 = empty_strided_cuda((196, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf15, (196, 512), (512, 1), 0
), reinterpret_tensor(primals_10, (512, 512), (1, 512), 0), out
=buf16)
buf17 = extern_kernels.convolution(buf0, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 512, 1, 49), (25088, 1, 25088, 512))
buf18 = buf17
del buf17
triton_poi_fused_clone_2[grid(100352)](buf18, primals_13, 100352,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf19 = empty_strided_cuda((4, 512, 512), (262144, 512, 1), torch.
float32)
extern_kernels.bmm(reinterpret_tensor(buf18, (4, 512, 49), (25088,
1, 512), 0), reinterpret_tensor(buf18, (4, 49, 512), (25088,
512, 1), 0), out=buf19)
buf22 = empty_strided_cuda((4, 1, 512, 512), (262144, 1, 512, 1),
torch.float32)
triton_per_fused__softmax_sqrt_4[grid(2048)](buf19, buf22, 2048,
512, num_warps=4, num_stages=1)
del buf19
buf23 = empty_strided_cuda((4, 512, 49), (25088, 49, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf22, (4, 512, 512), (262144,
512, 1), 0), reinterpret_tensor(buf18, (4, 512, 49), (25088, 1,
512), 0), out=buf23)
buf24 = empty_strided_cuda((2048, 49), (49, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf23, (2048, 49), (49, 1), 0),
reinterpret_tensor(primals_14, (49, 49), (1, 49), 0), out=buf24)
buf25 = reinterpret_tensor(buf16, (4, 512, 1, 49), (25088, 1, 25088,
512), 0)
del buf16
triton_poi_fused_add_5[grid(196, 512)](buf25, primals_11, buf24,
primals_15, 196, 512, XBLOCK=16, YBLOCK=256, num_warps=8,
num_stages=1)
del buf24
del primals_11
del primals_15
return buf25, buf0, buf1, buf2, reinterpret_tensor(buf4, (196, 512), (
512, 1), 0), buf13, reinterpret_tensor(buf15, (196, 512), (512, 1), 0
), buf18, buf22, reinterpret_tensor(buf23, (2048, 49), (49, 1), 0
), primals_14, primals_10, reinterpret_tensor(buf14, (4, 512, 49),
(25088, 1, 512), 0), reinterpret_tensor(buf8, (4, 512, 49), (25088,
1, 512), 0), buf9, primals_8, primals_6, primals_4
class ScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=0.001)
if m.bias is not None:
init.constant_(m.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class PositionAttentionModule(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
padding=(kernel_size - 1) // 2)
self.pa = ScaledDotProductAttention(d_model, d_k=d_model, d_v=
d_model, h=1)
def forward(self, x):
bs, c, _h, _w = x.shape
y = self.cnn(x)
y = y.view(bs, c, -1).permute(0, 2, 1)
y = self.pa(y, y, y)
return y
class SimplifiedScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, h, dropout=0.1):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(SimplifiedScaledDotProductAttention, self).__init__()
self.d_model = d_model
self.d_k = d_model // h
self.d_v = d_model // h
self.h = h
self.fc_o = nn.Linear(h * self.d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=0.001)
if m.bias is not None:
init.constant_(m.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = queries.view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3)
k = keys.view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = values.view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class ChannelAttentionModule(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
padding=(kernel_size - 1) // 2)
self.pa = SimplifiedScaledDotProductAttention(H * W, h=1)
def forward(self, x):
bs, c, _h, _w = x.shape
y = self.cnn(x)
y = y.view(bs, c, -1)
y = self.pa(y, y, y)
return y
class DAModuleNew(nn.Module):
def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
super().__init__()
self.position_attention_module = PositionAttentionModule(d_model=
512, kernel_size=3, H=7, W=7)
self.channel_attention_module = ChannelAttentionModule(d_model=512,
kernel_size=3, H=7, W=7)
def forward(self, input_0):
primals_2 = self.position_attention_module.cnn.weight
primals_3 = self.position_attention_module.cnn.bias
primals_4 = self.position_attention_module.pa.fc_q.weight
primals_5 = self.position_attention_module.pa.fc_q.bias
primals_6 = self.position_attention_module.pa.fc_k.weight
primals_7 = self.position_attention_module.pa.fc_k.bias
primals_8 = self.position_attention_module.pa.fc_v.weight
primals_9 = self.position_attention_module.pa.fc_v.bias
primals_10 = self.position_attention_module.pa.fc_o.weight
primals_11 = self.position_attention_module.pa.fc_o.bias
primals_12 = self.channel_attention_module.cnn.weight
primals_13 = self.channel_attention_module.cnn.bias
primals_14 = self.channel_attention_module.pa.fc_o.weight
primals_15 = self.channel_attention_module.pa.fc_o.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
rushirajsherlocked/External-Attention-pytorch
|
DAModule
| false
| 4,248
|
[
"MIT"
] | 0
|
7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
https://github.com/rushirajsherlocked/External-Attention-pytorch/tree/7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
MaskedWordPredictions
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
def gelu(x):
"""Gaussian Error Linear Unitという活性化関数です。
LeLUが0でカクっと不連続なので、そこを連続になるように滑らかにした形のLeLUです。
"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""LayerNormalization層です。
学習済みモデルをそのままロードするため、学習済みモデルの変数名に変えています。
オリジナルのGitHubの実装から変数名を変えています。
weight→gamma、bias→beta
"""
super(BertLayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class BertPredictionHeadTransform(nn.Module):
"""MaskedWordPredictionsにて、BERTからの特徴量を変換するモジュール(入出力のサイズは同じ)"""
def __init__(self, config):
super(BertPredictionHeadTransform, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.transform_act_fn = gelu
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
def forward(self, hidden_states):
"""hidden_statesはsequence_output:[minibatch, seq_len, hidden_size]"""
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class MaskedWordPredictions(nn.Module):
def __init__(self, config):
"""事前学習課題:Masked Language Model用のモジュール
元の[2]の実装では、BertLMPredictionHeadという名前です。
"""
super(MaskedWordPredictions, self).__init__()
self.transform = BertPredictionHeadTransform(config)
self.decoder = nn.Linear(in_features=config.hidden_size,
out_features=config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
"""
hidden_states:BERTからの出力[batch_size, seq_len, hidden_size]
"""
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states) + self.bias
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, vocab_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import 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_add_div_erf_mean_mul_pow_sub_0(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp23 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
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
tmp10 = tmp9 * tmp1
tmp11 = tmp9 * tmp3
tmp12 = libdevice.erf(tmp11)
tmp13 = tmp12 + tmp6
tmp14 = tmp10 * tmp13
tmp15 = tmp8 + tmp14
tmp17 = tmp16 * tmp1
tmp18 = tmp16 * tmp3
tmp19 = libdevice.erf(tmp18)
tmp20 = tmp19 + tmp6
tmp21 = tmp17 * tmp20
tmp22 = tmp15 + tmp21
tmp24 = tmp23 * tmp1
tmp25 = tmp23 * tmp3
tmp26 = libdevice.erf(tmp25)
tmp27 = tmp26 + tmp6
tmp28 = tmp24 * tmp27
tmp29 = tmp22 + tmp28
tmp30 = 4.0
tmp31 = tmp29 / tmp30
tmp32 = tmp8 - tmp31
tmp33 = tmp32 * tmp32
tmp34 = tmp14 - tmp31
tmp35 = tmp34 * tmp34
tmp36 = tmp33 + tmp35
tmp37 = tmp21 - tmp31
tmp38 = tmp37 * tmp37
tmp39 = tmp36 + tmp38
tmp40 = tmp28 - tmp31
tmp41 = tmp40 * tmp40
tmp42 = tmp39 + tmp41
tmp43 = tmp42 / tmp30
tl.store(out_ptr0 + x0, tmp31, xmask)
tl.store(out_ptr1 + x0, tmp43, xmask)
@triton.jit
def triton_poi_fused_add_div_erf_mul_sqrt_sub_1(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp10 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = 0.7071067811865475
tmp5 = tmp1 * tmp4
tmp6 = libdevice.erf(tmp5)
tmp7 = 1.0
tmp8 = tmp6 + tmp7
tmp9 = tmp3 * tmp8
tmp11 = tmp9 - tmp10
tmp13 = 1e-12
tmp14 = tmp12 + tmp13
tmp15 = libdevice.sqrt(tmp14)
tmp16 = tmp11 / tmp15
tmp17 = tmp0 * tmp16
tmp19 = tmp17 + tmp18
tl.store(out_ptr0 + x2, tmp19, xmask)
@triton.jit
def triton_poi_fused_add_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_erf_mean_mul_pow_sub_0[grid(64)](buf0,
buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_erf_mul_sqrt_sub_1[grid(256)](primals_4,
buf0, buf1, buf2, primals_5, buf3, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf1
del buf2
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_add_2[grid(256)](buf5, primals_7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
return buf5, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf3, (64, 4), (4, 1), 0), primals_6
def gelu(x):
"""Gaussian Error Linear Unitという活性化関数です。
LeLUが0でカクっと不連続なので、そこを連続になるように滑らかにした形のLeLUです。
"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""LayerNormalization層です。
学習済みモデルをそのままロードするため、学習済みモデルの変数名に変えています。
オリジナルのGitHubの実装から変数名を変えています。
weight→gamma、bias→beta
"""
super(BertLayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class BertPredictionHeadTransform(nn.Module):
"""MaskedWordPredictionsにて、BERTからの特徴量を変換するモジュール(入出力のサイズは同じ)"""
def __init__(self, config):
super(BertPredictionHeadTransform, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.transform_act_fn = gelu
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
def forward(self, hidden_states):
"""hidden_statesはsequence_output:[minibatch, seq_len, hidden_size]"""
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class MaskedWordPredictionsNew(nn.Module):
def __init__(self, config):
"""事前学習課題:Masked Language Model用のモジュール
元の[2]の実装では、BertLMPredictionHeadという名前です。
"""
super(MaskedWordPredictionsNew, self).__init__()
self.transform = BertPredictionHeadTransform(config)
self.decoder = nn.Linear(in_features=config.hidden_size,
out_features=config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, input_0):
primals_2 = self.bias
primals_1 = self.transform.dense.weight
primals_4 = self.transform.dense.bias
primals_5 = self.transform.LayerNorm.gamma
primals_7 = self.transform.LayerNorm.beta
primals_6 = self.decoder.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
kimihitosugiyama/text_analysis
|
MaskedWordPredictions
| false
| 4,249
|
[
"Apache-2.0"
] | 0
|
8f51022957928c31e52af1e0fd407daca3addb40
|
https://github.com/kimihitosugiyama/text_analysis/tree/8f51022957928c31e52af1e0fd407daca3addb40
|
Conv1dLinear
|
import torch
import torch.nn
class Conv1dLinear(torch.nn.Module):
"""Conv1D + Linear for Transformer block.
A variant of MultiLayeredConv1d, which replaces second conv-layer to linear.
"""
def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):
"""Initialize Conv1dLinear module.
Args:
in_chans (int): Number of input channels.
hidden_chans (int): Number of hidden channels.
kernel_size (int): Kernel size of conv1d.
dropout_rate (float): Dropout rate.
"""
super(Conv1dLinear, self).__init__()
self.w_1 = torch.nn.Conv1d(in_chans, hidden_chans, kernel_size,
stride=1, padding=(kernel_size - 1) // 2)
self.w_2 = torch.nn.Linear(hidden_chans, in_chans)
self.dropout = torch.nn.Dropout(dropout_rate)
def forward(self, x):
"""Calculate forward propagation.
Args:
x (Tensor): Batch of input tensors (B, *, in_chans).
Returns:
Tensor: Batch of output tensors (B, *, hidden_chans)
"""
x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)
return self.w_2(self.dropout(x))
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_chans': 4, 'hidden_chans': 4, 'kernel_size': 4,
'dropout_rate': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
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 % 3
y1 = yindex // 3
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 3 * x2 + 12 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_add_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
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_convolution_relu_threshold_backward_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(1,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 3), (12, 3, 1))
del buf0
buf2 = empty_strided_cuda((4, 3, 4), (12, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(12, 4)](buf1, primals_3, buf2, 12, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((12, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (12, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 3, 4), (12, 4, 1), 0)
del buf3
triton_poi_fused_add_2[grid(48)](buf4, primals_5, 48, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((4, 4, 3), (12, 3, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(48)](buf1,
primals_3, buf5, 48, XBLOCK=64, num_warps=1, num_stages=1)
del buf1
del primals_3
return buf4, primals_2, reinterpret_tensor(primals_1, (4, 4, 4), (16, 1,
4), 0), reinterpret_tensor(buf2, (12, 4), (4, 1), 0), primals_4, buf5
class Conv1dLinearNew(torch.nn.Module):
"""Conv1D + Linear for Transformer block.
A variant of MultiLayeredConv1d, which replaces second conv-layer to linear.
"""
def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):
"""Initialize Conv1dLinear module.
Args:
in_chans (int): Number of input channels.
hidden_chans (int): Number of hidden channels.
kernel_size (int): Kernel size of conv1d.
dropout_rate (float): Dropout rate.
"""
super(Conv1dLinearNew, self).__init__()
self.w_1 = torch.nn.Conv1d(in_chans, hidden_chans, kernel_size,
stride=1, padding=(kernel_size - 1) // 2)
self.w_2 = torch.nn.Linear(hidden_chans, in_chans)
self.dropout = torch.nn.Dropout(dropout_rate)
def forward(self, input_0):
primals_1 = self.w_1.weight
primals_3 = self.w_1.bias
primals_4 = self.w_2.weight
primals_5 = self.w_2.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
qlindazm/asv-subtools
|
Conv1dLinear
| false
| 4,250
|
[
"Apache-2.0"
] | 0
|
fe1d31db9f3268622016babe944201f6ff81ed56
|
https://github.com/qlindazm/asv-subtools/tree/fe1d31db9f3268622016babe944201f6ff81ed56
|
PositionWiseFeedForward
|
import math
import torch
import torch.nn as nn
def gelu(x):
"""Implementation of the gelu activation function by Hugging Face"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class PositionWiseFeedForward(nn.Module):
""" FeedForward Neural Networks for each position """
def __init__(self, n_hidden):
super().__init__()
self.fc1 = nn.Conv2d(n_hidden, n_hidden * 4, kernel_size=1, bias=True)
self.fc2 = nn.Conv2d(n_hidden * 4, n_hidden, kernel_size=1, bias=True)
def forward(self, x):
return self.fc2(gelu(self.fc1(x)))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_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.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_convolution_div_erf_mul_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = 0.7071067811865475
tmp6 = tmp2 * tmp5
tmp7 = libdevice.erf(tmp6)
tmp8 = 1.0
tmp9 = tmp7 + tmp8
tmp10 = tmp4 * tmp9
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp10, 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, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (16, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 16, 1, 1), (16, 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=1, bias=None)
assert_size_stride(buf0, (4, 16, 4, 4), (256, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 16, 4, 4), (256, 16, 4, 1), torch.float32
)
get_raw_stream(0)
triton_poi_fused_add_convolution_div_erf_mul_0[grid(1024)](buf1,
primals_2, buf2, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_1[grid(256)](buf4, primals_5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
return buf4, primals_1, primals_3, primals_4, buf1, buf2
def gelu(x):
"""Implementation of the gelu activation function by Hugging Face"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class PositionWiseFeedForwardNew(nn.Module):
""" FeedForward Neural Networks for each position """
def __init__(self, n_hidden):
super().__init__()
self.fc1 = nn.Conv2d(n_hidden, n_hidden * 4, kernel_size=1, bias=True)
self.fc2 = nn.Conv2d(n_hidden * 4, n_hidden, kernel_size=1, bias=True)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
renebidart/pytorch-cifar
|
PositionWiseFeedForward
| false
| 4,251
|
[
"MIT"
] | 0
|
8f623299c25f7f219bab34bc7df41fe24232b1af
|
https://github.com/renebidart/pytorch-cifar/tree/8f623299c25f7f219bab34bc7df41fe24232b1af
|
FC_Decoder
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class FC_Decoder(nn.Module):
def __init__(self, embedding_size):
super(FC_Decoder, self).__init__()
self.fc3 = nn.Linear(embedding_size, 1024)
self.fc4 = nn.Linear(1024, 784)
def forward(self, z):
h3 = F.relu(self.fc3(z))
return torch.sigmoid(self.fc4(h3))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'embedding_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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 % 1024
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 50176
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 784
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (1024, 4), (4, 1))
assert_size_stride(primals_2, (1024,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (784, 1024), (1024, 1))
assert_size_stride(primals_5, (784,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 1024), (1024, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 1024), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 1024), (16384, 4096, 1024,
1), 0)
del buf0
buf4 = empty_strided_cuda((4, 4, 4, 1024), (16384, 4096, 1024, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(65536)](buf1,
primals_2, buf4, 65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 784), (784, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 1024), (1024, 1), 0
), reinterpret_tensor(primals_4, (1024, 784), (1, 1024), 0),
out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 784), (12544, 3136, 784,
1), 0)
del buf2
triton_poi_fused_sigmoid_1[grid(50176)](buf3, primals_5, 50176,
XBLOCK=512, num_warps=4, num_stages=1)
del primals_5
return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 1024), (1024, 1), 0
), buf3, primals_4, buf4
class FC_DecoderNew(nn.Module):
def __init__(self, embedding_size):
super(FC_DecoderNew, self).__init__()
self.fc3 = nn.Linear(embedding_size, 1024)
self.fc4 = nn.Linear(1024, 784)
def forward(self, input_0):
primals_1 = self.fc3.weight
primals_2 = self.fc3.bias
primals_4 = self.fc4.weight
primals_5 = self.fc4.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
saksham36/LangGrounding
|
FC_Decoder
| false
| 4,252
|
[
"MIT"
] | 0
|
89ee9e5b8090e61e6bf7bf2b3e1dd45edf9664b7
|
https://github.com/saksham36/LangGrounding/tree/89ee9e5b8090e61e6bf7bf2b3e1dd45edf9664b7
|
Word2Vec
|
import torch
from torch import nn
class Word2Vec(nn.Module):
def __init__(self, features, embedding_size):
super().__init__()
0.5 / embedding_size
self.fc1 = nn.Linear(features, embedding_size)
self.fc2 = nn.Linear(embedding_size, features)
def forward(self, one_hot):
x = self.fc1(one_hot.float())
x = self.fc2(x)
log_softmax = torch.nn.functional.log_softmax(x, dim=1)
return log_softmax
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'features': 4, 'embedding_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_5
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](buf1, buf2, 256, XBLOCK=
128, num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused__log_softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del buf2
return buf3, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf0, buf3, primals_4
class Word2VecNew(nn.Module):
def __init__(self, features, embedding_size):
super().__init__()
0.5 / embedding_size
self.fc1 = nn.Linear(features, embedding_size)
self.fc2 = nn.Linear(embedding_size, features)
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]
|
salmanedhi/NNTI-WS2021-NLP-Project
|
Word2Vec
| false
| 4,253
|
[
"MIT"
] | 0
|
5b0a8f1258ef4e835a6e647082a8286078a0bdd6
|
https://github.com/salmanedhi/NNTI-WS2021-NLP-Project/tree/5b0a8f1258ef4e835a6e647082a8286078a0bdd6
|
Beta
|
import torch
import torch.nn as nn
import torch.functional as F
import torch.nn.functional as F
class BoundedBeta(torch.distributions.Beta):
def log_prob(self, x):
return super().log_prob((x + 1) / 2)
class Beta(nn.Module):
def __init__(self, action_dim):
super(Beta, self).__init__()
self.action_dim = action_dim
def forward(self, alpha_beta):
alpha = 1 + F.softplus(alpha_beta[:, :self.action_dim])
beta = 1 + F.softplus(alpha_beta[:, self.action_dim:])
return alpha, beta
def sample(self, x, deterministic):
if deterministic is False:
action = self.evaluate(x).sample()
else:
return self.evaluate(x).mean
return 2 * action - 1
def evaluate(self, x):
alpha, beta = self(x)
return BoundedBeta(alpha, beta)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'action_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, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_softplus_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 = 20.0
tmp2 = tmp0 > tmp1
tmp3 = tl_math.exp(tmp0)
tmp4 = libdevice.log1p(tmp3)
tmp5 = tl.where(tmp2, tmp0, tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_softplus_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 0, 4, 4), (0, 16, 4, 1), torch.float32)
return buf0, buf1
class BoundedBeta(torch.distributions.Beta):
def log_prob(self, x):
return super().log_prob((x + 1) / 2)
class BetaNew(nn.Module):
def __init__(self, action_dim):
super(BetaNew, self).__init__()
self.action_dim = action_dim
def sample(self, x, deterministic):
if deterministic is False:
action = self.evaluate(x).sample()
else:
return self.evaluate(x).mean
return 2 * action - 1
def evaluate(self, x):
alpha, beta = self(x)
return BoundedBeta(alpha, beta)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
samarth-robo/apex
|
Beta
| false
| 4,254
|
[
"MIT"
] | 0
|
db24044acacd0fcd006886eb1677eaa2f2beedad
|
https://github.com/samarth-robo/apex/tree/db24044acacd0fcd006886eb1677eaa2f2beedad
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
import torch.onnx
import torch.testing
class Actor(nn.Module):
def __init__(self, nb_states, nb_actions, hidden1=400, hidden2=300):
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.sigmoid = nn.Sigmoid()
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.sigmoid(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
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
import torch.onnx
import torch.testing
assert_size_stride = torch._C._dynamo.guards.assert_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_sigmoid_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = 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.mm(buf4, reinterpret_tensor(primals_6, (300, 4), (1,
300), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused_sigmoid_3[grid(256)](buf6, primals_7, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_7
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 400), (400, 1), 0
), buf4, buf6, primals_6, buf7, primals_4, buf8
class ActorNew(nn.Module):
def __init__(self, nb_states, nb_actions, hidden1=400, hidden2=300):
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.sigmoid = nn.Sigmoid()
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]
|
saman-aghazadeh/distiller
|
Actor
| false
| 4,255
|
[
"Apache-2.0"
] | 0
|
7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
https://github.com/saman-aghazadeh/distiller/tree/7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
Beta2
|
import torch
import numpy as np
import torch.nn as nn
class BoundedBeta(torch.distributions.Beta):
def log_prob(self, x):
return super().log_prob((x + 1) / 2)
class Beta2(nn.Module):
def __init__(self, action_dim, init_std=0.25, learn_std=False):
super(Beta2, self).__init__()
assert init_std < 0.5, 'Beta distribution has a max std dev of 0.5'
self.action_dim = action_dim
self.logstd = nn.Parameter(torch.ones(1, action_dim) * np.log(
init_std), requires_grad=learn_std)
self.learn_std = learn_std
def forward(self, x):
mean = torch.sigmoid(x)
var = self.logstd.exp().pow(2)
"""
alpha = ((1 - mu) / sigma^2 - 1 / mu) * mu^2
beta = alpha * (1 / mu - 1)
Implemented slightly differently for numerical stability.
"""
alpha = (1 - mean) / var * mean.pow(2) - mean
beta = (1 - mean) / var * mean - 1 - alpha
return alpha, beta
def sample(self, x, deterministic):
if deterministic is False:
action = self.evaluate(x).sample()
else:
return self.evaluate(x).mean
return 2 * action - 1
def evaluate(self, x):
alpha, beta = self(x)
return BoundedBeta(alpha, beta)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'action_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 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
@triton.jit
def triton_poi_fused_div_exp_mul_pow_rsub_sigmoid_sub_0(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp2 = 1.0
tmp3 = tmp2 - tmp1
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp5 * tmp5
tmp7 = tmp3 / tmp6
tmp8 = tmp1 * tmp1
tmp9 = tmp7 * tmp8
tmp10 = tmp9 - tmp1
tmp11 = tmp7 * tmp1
tmp12 = tmp11 - tmp2
tmp13 = tmp12 - tmp10
tl.store(out_ptr0 + x2, tmp10, xmask)
tl.store(out_ptr1 + x2, tmp13, 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, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_exp_mul_pow_rsub_sigmoid_sub_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
class BoundedBeta(torch.distributions.Beta):
def log_prob(self, x):
return super().log_prob((x + 1) / 2)
class Beta2New(nn.Module):
def __init__(self, action_dim, init_std=0.25, learn_std=False):
super(Beta2New, self).__init__()
assert init_std < 0.5, 'Beta distribution has a max std dev of 0.5'
self.action_dim = action_dim
self.logstd = nn.Parameter(torch.ones(1, action_dim) * np.log(
init_std), requires_grad=learn_std)
self.learn_std = learn_std
def sample(self, x, deterministic):
if deterministic is False:
action = self.evaluate(x).sample()
else:
return self.evaluate(x).mean
return 2 * action - 1
def evaluate(self, x):
alpha, beta = self(x)
return BoundedBeta(alpha, beta)
def forward(self, input_0):
arg1_1 = self.logstd
arg0_1 = input_0
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
samarth-robo/apex
|
Beta2
| false
| 4,256
|
[
"MIT"
] | 0
|
db24044acacd0fcd006886eb1677eaa2f2beedad
|
https://github.com/samarth-robo/apex/tree/db24044acacd0fcd006886eb1677eaa2f2beedad
|
BertPooler2
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.nn.parallel
import torch.optim
from torch.utils.data import *
import torch.nn.functional
class BertPooler2(nn.Module):
def __init__(self, config):
super(BertPooler2, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states):
first_token_tensor = hidden_states[:, 1]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.nn.parallel
import torch.optim
from torch.utils.data import *
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_add_tanh_1[grid(64)](buf2, primals_3, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf2
class BertPooler2New(nn.Module):
def __init__(self, config):
super(BertPooler2New, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
samuelyu2002/PACS
|
BertPooler2
| false
| 4,257
|
[
"MIT"
] | 0
|
5010b2f0d20933b0647e3d6230d673e1830249ec
|
https://github.com/samuelyu2002/PACS/tree/5010b2f0d20933b0647e3d6230d673e1830249ec
|
ModelWithDuplicates
|
import torch
from collections import OrderedDict
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
import torch.onnx
import torch.testing
class ModelWithDuplicates(nn.Module):
def __init__(self):
super(ModelWithDuplicates, self).__init__()
self.conv1 = nn.Conv2d(3, 10, 5)
self.post_conv1 = nn.ModuleList([nn.ReLU(), nn.Tanh()])
self.conv2 = nn.Conv2d(10, 20, 3)
self.post_conv2 = self.post_conv1
self.expected_mlist_to_dmlist = OrderedDict([('post_conv1', [
'post_conv1']), ('post_conv2', ['post_conv2'])])
self.expected_list_contents_name_changes = OrderedDict([(
'post_conv1.0', 'post_conv1_0'), ('post_conv1.1',
'post_conv1_1'), ('post_conv2.0', 'post_conv2_0'), (
'post_conv2.1', 'post_conv2_1')])
def forward(self, x):
x = self.conv1(x)
for m in self.post_conv1:
x = m(x)
x = self.conv2(x)
for m in self.post_conv2:
x = m(x)
return x
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from collections import OrderedDict
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
import torch.onnx
import torch.testing
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_tanh_threshold_backward_0(in_ptr0,
in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 144000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3600 % 10
x0 = 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 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = libdevice.tanh(tmp4)
tmp6 = 0.0
tmp7 = tmp4 <= tmp6
tl.store(out_ptr0 + x3, tmp5, xmask)
tl.store(out_ptr1 + (x0 + 3712 * x4), tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_tanh_threshold_backward_1(in_ptr0,
in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 269120
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3364 % 20
x0 = xindex % 3364
x4 = xindex // 3364
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = libdevice.tanh(tmp4)
tmp6 = 0.0
tmp7 = tmp4 <= tmp6
tl.store(out_ptr0 + x3, tmp5, xmask)
tl.store(out_ptr1 + (x0 + 3456 * x4), tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (10, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (10,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (20, 10, 3, 3), (90, 9, 3, 1))
assert_size_stride(primals_5, (20,), (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, 10, 60, 60), (36000, 3600, 60, 1))
buf1 = empty_strided_cuda((4, 10, 60, 60), (36000, 3600, 60, 1),
torch.float32)
buf5 = empty_strided_cuda((4, 10, 60, 60), (37120, 3712, 60, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_convolution_relu_tanh_threshold_backward_0[grid(
144000)](buf0, primals_2, buf1, buf5, 144000, XBLOCK=1024,
num_warps=4, num_stages=1)
del buf0
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, 20, 58, 58), (67280, 3364, 58, 1))
buf3 = empty_strided_cuda((4, 20, 58, 58), (67280, 3364, 58, 1),
torch.float32)
buf4 = empty_strided_cuda((4, 20, 58, 58), (69120, 3456, 58, 1),
torch.bool)
triton_poi_fused_convolution_relu_tanh_threshold_backward_1[grid(
269120)](buf2, primals_5, buf3, buf4, 269120, XBLOCK=512,
num_warps=8, num_stages=1)
del buf2
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1, buf3, buf4, buf5
class ModelWithDuplicatesNew(nn.Module):
def __init__(self):
super(ModelWithDuplicatesNew, self).__init__()
self.conv1 = nn.Conv2d(3, 10, 5)
self.post_conv1 = nn.ModuleList([nn.ReLU(), nn.Tanh()])
self.conv2 = nn.Conv2d(10, 20, 3)
self.post_conv2 = self.post_conv1
self.expected_mlist_to_dmlist = OrderedDict([('post_conv1', [
'post_conv1']), ('post_conv2', ['post_conv2'])])
self.expected_list_contents_name_changes = OrderedDict([(
'post_conv1.0', 'post_conv1_0'), ('post_conv1.1',
'post_conv1_1'), ('post_conv2.0', 'post_conv2_0'), (
'post_conv2.1', 'post_conv2_1')])
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
saman-aghazadeh/distiller
|
ModelWithDuplicates
| false
| 4,258
|
[
"Apache-2.0"
] | 0
|
7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
https://github.com/saman-aghazadeh/distiller/tree/7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
MySimpleNet
|
import torch
import torch.nn.functional as F
from torch import nn
class MySimpleNet(nn.Module):
"""
Very simple 2-layer net, slightly adapted from the docs:
https://skorch.readthedocs.io/en/stable/user/quickstart.html
"""
def __init__(self, num_in, num_feat, num_hidden=10, nonlin=F.relu):
super(MySimpleNet, self).__init__()
self.dense0 = nn.Linear(num_in, num_hidden)
self.nonlin = nonlin
self.dropout = nn.Dropout(0.5)
self.dense1 = nn.Linear(num_hidden, num_feat)
self.output = nn.Linear(num_feat, 2)
def forward(self, X, **kwargs):
X = self.nonlin(self.dense0(X))
X = self.dropout(X)
X = F.relu(self.dense1(X))
X = F.softmax(self.output(X))
return X
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_in': 4, 'num_feat': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 640
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 10
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 8
x2 = xindex // 32
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (8 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (16 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (24 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 8
x2 = xindex // 32
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (8 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (16 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (24 + x0 + 32 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (10, 4), (4, 1))
assert_size_stride(primals_2, (10,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 10), (10, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (2, 4), (4, 1))
assert_size_stride(primals_7, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 10), (10, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 10), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 10), (160, 40, 10, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 10), (160, 40, 10, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(640)](buf1,
primals_2, buf8, 640, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 10), (10, 1), 0),
reinterpret_tensor(primals_4, (10, 4), (1, 10), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256)](buf3,
primals_5, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 2), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
buf5 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.float32)
triton_poi_fused__softmax_2[grid(128)](buf4, buf5, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 2), (32, 8, 2, 1), 0)
del buf4
triton_poi_fused__softmax_3[grid(128)](buf5, buf6, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del buf5
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 10), (10, 1), 0), reinterpret_tensor(
buf3, (64, 4), (4, 1), 0), buf6, primals_6, buf7, primals_4, buf8
class MySimpleNetNew(nn.Module):
"""
Very simple 2-layer net, slightly adapted from the docs:
https://skorch.readthedocs.io/en/stable/user/quickstart.html
"""
def __init__(self, num_in, num_feat, num_hidden=10, nonlin=F.relu):
super(MySimpleNetNew, self).__init__()
self.dense0 = nn.Linear(num_in, num_hidden)
self.nonlin = nonlin
self.dropout = nn.Dropout(0.5)
self.dense1 = nn.Linear(num_hidden, num_feat)
self.output = nn.Linear(num_feat, 2)
def forward(self, input_0):
primals_1 = self.dense0.weight
primals_2 = self.dense0.bias
primals_4 = self.dense1.weight
primals_5 = self.dense1.bias
primals_6 = self.output.weight
primals_7 = self.output.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
samxu0823/anfis-pytorch
|
MySimpleNet
| false
| 4,259
|
[
"MIT"
] | 0
|
b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
https://github.com/samxu0823/anfis-pytorch/tree/b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
BahdanauAttention
|
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
from torch.nn.parameter import Parameter
import torch.onnx
import torch.testing
class EltwiseAdd(nn.Module):
def __init__(self, inplace=False):
"""Element-wise addition"""
super().__init__()
self.inplace = inplace
def forward(self, *input):
res = input[0]
if self.inplace:
for t in input[1:]:
res += t
else:
for t in input[1:]:
res = res + t
return res
class EltwiseMult(nn.Module):
def __init__(self, inplace=False):
"""Element-wise multiplication"""
super().__init__()
self.inplace = inplace
def forward(self, *input):
res = input[0]
if self.inplace:
for t in input[1:]:
res *= t
else:
for t in input[1:]:
res = res * t
return res
class Matmul(nn.Module):
"""
A wrapper module for matmul operation between 2 tensors.
"""
def __init__(self):
super(Matmul, self).__init__()
def forward(self, a: 'torch.Tensor', b: 'torch.Tensor'):
return a.matmul(b)
class BatchMatmul(nn.Module):
"""
A wrapper module for torch.bmm operation between 2 tensors.
"""
def __init__(self):
super(BatchMatmul, self).__init__()
def forward(self, a: 'torch.Tensor', b: 'torch.Tensor'):
return torch.bmm(a, b)
class BahdanauAttention(nn.Module):
"""
It should be very similar to tf.contrib.seq2seq.BahdanauAttention
"""
def __init__(self, query_size, key_size, num_units, normalize=False,
dropout=0, batch_first=False):
super(BahdanauAttention, self).__init__()
self.normalize = normalize
self.batch_first = batch_first
self.num_units = num_units
self.linear_q = nn.Linear(query_size, num_units, bias=False)
self.linear_k = nn.Linear(key_size, num_units, bias=False)
self.linear_att = Parameter(torch.Tensor(num_units))
self.dropout = nn.Dropout(dropout)
self.mask = None
self.eltwiseadd_qk = EltwiseAdd()
self.eltwiseadd_norm_bias = EltwiseAdd()
self.eltwisemul_norm_scaler = EltwiseMult()
self.tanh = nn.Tanh()
self.matmul_score = Matmul()
self.softmax_att = nn.Softmax(dim=-1)
self.context_matmul = BatchMatmul()
if self.normalize:
self.normalize_scalar = Parameter(torch.Tensor(1))
self.normalize_bias = Parameter(torch.Tensor(num_units))
else:
self.register_parameter('normalize_scalar', None)
self.register_parameter('normalize_bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.num_units)
self.linear_att.data.uniform_(-stdv, stdv)
if self.normalize:
self.normalize_scalar.data.fill_(stdv)
self.normalize_bias.data.zero_()
def set_mask(self, context_len, context):
"""
sets self.mask which is applied before softmax
ones for inactive context fields, zeros for active context fields
:param context_len: b
:param context: if batch_first: (b x t_k x n) else: (t_k x b x n)
self.mask: (b x t_k)
"""
if self.batch_first:
max_len = context.size(1)
else:
max_len = context.size(0)
indices = torch.arange(0, max_len, dtype=torch.int64, device=
context.device)
self.mask = indices >= context_len.unsqueeze(1)
def calc_score(self, att_query, att_keys):
"""
Calculate Bahdanau score
:param att_query: b x t_q x n
:param att_keys: b x t_k x n
return b x t_q x t_k scores
"""
b, t_k, n = att_keys.size()
t_q = att_query.size(1)
att_query = att_query.unsqueeze(2).expand(b, t_q, t_k, n)
att_keys = att_keys.unsqueeze(1).expand(b, t_q, t_k, n)
sum_qk = self.eltwiseadd_qk(att_query, att_keys)
if self.normalize:
sum_qk = self.eltwiseadd_norm_bias(sum_qk, self.normalize_bias)
tmp = self.linear_att
linear_att = tmp / tmp.norm()
linear_att = linear_att
linear_att = self.eltwisemul_norm_scaler(linear_att, self.
normalize_scalar)
else:
linear_att = self.linear_att
out = self.matmul_score(self.tanh(sum_qk), linear_att)
return out
def forward(self, query, keys):
"""
:param query: if batch_first: (b x t_q x n) else: (t_q x b x n)
:param keys: if batch_first: (b x t_k x n) else (t_k x b x n)
:returns: (context, scores_normalized)
context: if batch_first: (b x t_q x n) else (t_q x b x n)
scores_normalized: if batch_first (b x t_q x t_k) else (t_q x b x t_k)
"""
if not self.batch_first:
keys = keys.transpose(0, 1)
if query.dim() == 3:
query = query.transpose(0, 1)
if query.dim() == 2:
single_query = True
query = query.unsqueeze(1)
else:
single_query = False
b = query.size(0)
t_k = keys.size(1)
t_q = query.size(1)
processed_query = self.linear_q(query)
processed_key = self.linear_k(keys)
scores = self.calc_score(processed_query, processed_key)
if self.mask is not None:
mask = self.mask.unsqueeze(1).expand(b, t_q, t_k)
scores.data.masked_fill_(mask, -65504.0)
scores_normalized = self.softmax_att(scores)
scores_normalized = self.dropout(scores_normalized)
context = self.context_matmul(scores_normalized, keys)
if single_query:
context = context.squeeze(1)
scores_normalized = scores_normalized.squeeze(1)
elif not self.batch_first:
context = context.transpose(0, 1)
scores_normalized = scores_normalized.transpose(0, 1)
return context, scores_normalized
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'query_size': 4, 'key_size': 4, 'num_units': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.optim.lr_scheduler import *
import torch.optim.lr_scheduler
import torch.quantization
from torch.nn.parameter import Parameter
import torch.onnx
import torch.testing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_mv_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * (x0 // 4), xmask, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr1 + (4 * (x0 % 4) + 16 * (x0 // 16)), xmask,
eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr0 + (1 + 4 * (x0 // 4)), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr1 + (1 + 4 * (x0 % 4) + 16 * (x0 // 16)), xmask,
eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + 1)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK])
tmp15 = tl.load(in_ptr0 + (2 + 4 * (x0 // 4)), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + (2 + 4 * (x0 % 4) + 16 * (x0 // 16)), xmask,
eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + 2)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp23 = tl.load(in_ptr0 + (3 + 4 * (x0 // 4)), xmask, eviction_policy=
'evict_last')
tmp24 = tl.load(in_ptr1 + (3 + 4 * (x0 % 4) + 16 * (x0 // 16)), xmask,
eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + 3)
tmp28 = tl.broadcast_to(tmp27, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tmp6 = tmp3 * tmp5
tmp9 = tmp7 + tmp8
tmp10 = libdevice.tanh(tmp9)
tmp13 = tmp10 * tmp12
tmp14 = tmp6 + tmp13
tmp17 = tmp15 + tmp16
tmp18 = libdevice.tanh(tmp17)
tmp21 = tmp18 * tmp20
tmp22 = tmp14 + tmp21
tmp25 = tmp23 + tmp24
tmp26 = libdevice.tanh(tmp25)
tmp29 = tmp26 * tmp28
tmp30 = tmp22 + tmp29
tl.store(out_ptr0 + x0, tmp30, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_2, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(64)](primals_1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf3)
del primals_4
buf4 = empty_strided_cuda((64,), (1,), torch.float32)
triton_poi_fused_mv_1[grid(64)](buf1, buf3, primals_5, buf4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
triton_poi_fused__softmax_3[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = buf5
del buf5
extern_kernels.bmm(buf6, reinterpret_tensor(primals_1, (4, 4, 4), (
4, 16, 1), 0), out=buf7)
return reinterpret_tensor(buf7, (4, 4, 4), (4, 16, 1), 0
), reinterpret_tensor(buf6, (4, 4, 4), (4, 16, 1), 0
), primals_5, reinterpret_tensor(buf0, (16, 4), (4, 1), 0
), buf1, reinterpret_tensor(buf2, (16, 4), (4, 1), 0
), buf3, buf6, reinterpret_tensor(primals_1, (4, 4, 4), (4, 1, 16), 0)
class EltwiseAdd(nn.Module):
def __init__(self, inplace=False):
"""Element-wise addition"""
super().__init__()
self.inplace = inplace
def forward(self, *input):
res = input[0]
if self.inplace:
for t in input[1:]:
res += t
else:
for t in input[1:]:
res = res + t
return res
class EltwiseMult(nn.Module):
def __init__(self, inplace=False):
"""Element-wise multiplication"""
super().__init__()
self.inplace = inplace
def forward(self, *input):
res = input[0]
if self.inplace:
for t in input[1:]:
res *= t
else:
for t in input[1:]:
res = res * t
return res
class Matmul(nn.Module):
"""
A wrapper module for matmul operation between 2 tensors.
"""
def __init__(self):
super(Matmul, self).__init__()
def forward(self, a: 'torch.Tensor', b: 'torch.Tensor'):
return a.matmul(b)
class BatchMatmul(nn.Module):
"""
A wrapper module for torch.bmm operation between 2 tensors.
"""
def __init__(self):
super(BatchMatmul, self).__init__()
def forward(self, a: 'torch.Tensor', b: 'torch.Tensor'):
return torch.bmm(a, b)
class BahdanauAttentionNew(nn.Module):
"""
It should be very similar to tf.contrib.seq2seq.BahdanauAttention
"""
def __init__(self, query_size, key_size, num_units, normalize=False,
dropout=0, batch_first=False):
super(BahdanauAttentionNew, self).__init__()
self.normalize = normalize
self.batch_first = batch_first
self.num_units = num_units
self.linear_q = nn.Linear(query_size, num_units, bias=False)
self.linear_k = nn.Linear(key_size, num_units, bias=False)
self.linear_att = Parameter(torch.Tensor(num_units))
self.dropout = nn.Dropout(dropout)
self.mask = None
self.eltwiseadd_qk = EltwiseAdd()
self.eltwiseadd_norm_bias = EltwiseAdd()
self.eltwisemul_norm_scaler = EltwiseMult()
self.tanh = nn.Tanh()
self.matmul_score = Matmul()
self.softmax_att = nn.Softmax(dim=-1)
self.context_matmul = BatchMatmul()
if self.normalize:
self.normalize_scalar = Parameter(torch.Tensor(1))
self.normalize_bias = Parameter(torch.Tensor(num_units))
else:
self.register_parameter('normalize_scalar', None)
self.register_parameter('normalize_bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.num_units)
self.linear_att.data.uniform_(-stdv, stdv)
if self.normalize:
self.normalize_scalar.data.fill_(stdv)
self.normalize_bias.data.zero_()
def set_mask(self, context_len, context):
"""
sets self.mask which is applied before softmax
ones for inactive context fields, zeros for active context fields
:param context_len: b
:param context: if batch_first: (b x t_k x n) else: (t_k x b x n)
self.mask: (b x t_k)
"""
if self.batch_first:
max_len = context.size(1)
else:
max_len = context.size(0)
indices = torch.arange(0, max_len, dtype=torch.int64, device=
context.device)
self.mask = indices >= context_len.unsqueeze(1)
def calc_score(self, att_query, att_keys):
"""
Calculate Bahdanau score
:param att_query: b x t_q x n
:param att_keys: b x t_k x n
return b x t_q x t_k scores
"""
b, t_k, n = att_keys.size()
t_q = att_query.size(1)
att_query = att_query.unsqueeze(2).expand(b, t_q, t_k, n)
att_keys = att_keys.unsqueeze(1).expand(b, t_q, t_k, n)
sum_qk = self.eltwiseadd_qk(att_query, att_keys)
if self.normalize:
sum_qk = self.eltwiseadd_norm_bias(sum_qk, self.normalize_bias)
tmp = self.linear_att
linear_att = tmp / tmp.norm()
linear_att = linear_att
linear_att = self.eltwisemul_norm_scaler(linear_att, self.
normalize_scalar)
else:
linear_att = self.linear_att
out = self.matmul_score(self.tanh(sum_qk), linear_att)
return out
def forward(self, input_0, input_1):
primals_5 = self.linear_att
primals_3 = self.linear_q.weight
primals_4 = self.linear_k.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
saman-aghazadeh/distiller
|
BahdanauAttention
| false
| 4,260
|
[
"Apache-2.0"
] | 0
|
7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
https://github.com/saman-aghazadeh/distiller/tree/7e8d3e6193c807f7c55d8453f64e1bc3c02eee30
|
GaussMembFunc
|
import torch
def _mk_param(val):
"""Make a torch parameter from a scalar value"""
if isinstance(val, torch.Tensor):
val = val.item()
return torch.nn.Parameter(torch.tensor(val, dtype=torch.float))
class GaussMembFunc(torch.nn.Module):
"""
Gaussian membership functions, defined by two parameters:
mu, the mean (center)
sigma, the standard deviation.
"""
def __init__(self, mu, sigma):
super(GaussMembFunc, self).__init__()
self.register_parameter('mu', _mk_param(mu))
self.register_parameter('sigma', _mk_param(sigma))
def forward(self, x):
val = torch.exp(-torch.pow(x - self.mu, 2) / (2 * self.sigma ** 2))
return val
def pretty(self):
return 'GaussMembFunc {} {}'.format(self.mu, self.sigma)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'mu': 4, 'sigma': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
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_exp_mul_neg_pow_sub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp6 = tl.load(in_ptr2 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK])
tmp3 = tmp0 - tmp2
tmp4 = tmp3 * tmp3
tmp5 = -tmp4
tmp8 = tmp7 * tmp7
tmp9 = 2.0
tmp10 = tmp8 * tmp9
tmp11 = tmp5 / tmp10
tmp12 = tl_math.exp(tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (), ())
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (), ())
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_exp_mul_neg_pow_sub_0[grid(256)](primals_2,
primals_1, primals_3, buf0, 256, XBLOCK=128, num_warps=4,
num_stages=1)
return buf0, primals_1, primals_2, primals_3, buf0
def _mk_param(val):
"""Make a torch parameter from a scalar value"""
if isinstance(val, torch.Tensor):
val = val.item()
return torch.nn.Parameter(torch.tensor(val, dtype=torch.float))
class GaussMembFuncNew(torch.nn.Module):
"""
Gaussian membership functions, defined by two parameters:
mu, the mean (center)
sigma, the standard deviation.
"""
def __init__(self, mu, sigma):
super(GaussMembFuncNew, self).__init__()
self.register_parameter('mu', _mk_param(mu))
self.register_parameter('sigma', _mk_param(sigma))
def pretty(self):
return 'GaussMembFunc {} {}'.format(self.mu, self.sigma)
def forward(self, input_0):
primals_1 = self.mu
primals_3 = self.sigma
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
samxu0823/anfis-pytorch
|
GaussMembFunc
| false
| 4,261
|
[
"MIT"
] | 0
|
b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
https://github.com/samxu0823/anfis-pytorch/tree/b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
qy
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class qy(nn.Module):
def __init__(self, d_dim, x_dim, y_dim, z_dim):
super(qy, self).__init__()
self.fc1 = nn.Linear(z_dim, y_dim)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc1.bias.data.zero_()
def forward(self, zy):
h = F.relu(zy)
loc_y = self.fc1(h)
return loc_y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_dim': 4, 'x_dim': 4, 'y_dim': 4, 'z_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class qyNew(nn.Module):
def __init__(self, d_dim, x_dim, y_dim, z_dim):
super(qyNew, self).__init__()
self.fc1 = nn.Linear(z_dim, y_dim)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc1.bias.data.zero_()
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
sautami26/DIVA
|
qy
| false
| 4,262
|
[
"MIT"
] | 0
|
52af683db216cb6e2ac777597fd9ec744ce7c8f2
|
https://github.com/sautami26/DIVA/tree/52af683db216cb6e2ac777597fd9ec744ce7c8f2
|
BertAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.utils.checkpoint
class BertSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.position_embedding_type = getattr(config,
'position_embedding_type', 'absolute')
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.
max_position_embeddings - 1, self.attention_head_size)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, attention_mask=None, head_mask=None,
encoder_hidden_states=None, encoder_attention_mask=None,
output_attentions=False):
mixed_query_layer = self.query(hidden_states)
if encoder_hidden_states is not None:
mixed_key_layer = self.key(encoder_hidden_states)
mixed_value_layer = self.value(encoder_hidden_states)
attention_mask = encoder_attention_mask
else:
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
seq_length = hidden_states.size()[1]
position_ids_l = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.
max_position_embeddings - 1)
positional_embedding = positional_embedding
if self.position_embedding_type == 'relative_key':
relative_position_scores = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == 'relative_key_query':
relative_position_scores_query = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
relative_position_scores_key = torch.einsum('bhrd,lrd->bhlr',
key_layer, positional_embedding)
attention_scores = (attention_scores +
relative_position_scores_query +
relative_position_scores_key)
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (
context_layer,)
return outputs
class BertSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.self = BertSelfAttention(config)
self.output = BertSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.self.
num_attention_heads, self.self.attention_head_size, self.
pruned_heads)
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
self.self.num_attention_heads = self.self.num_attention_heads - len(
heads)
self.self.all_head_size = (self.self.attention_head_size * self.
self.num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, hidden_states, attention_mask=None, head_mask=None,
encoder_hidden_states=None, encoder_attention_mask=None,
output_attentions=False):
self_outputs = self.self(hidden_states, attention_mask, head_mask,
encoder_hidden_states, encoder_attention_mask, output_attentions)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:]
return outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5, position_embedding_type=4,
layer_norm_eps=1, hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
import torch.nn as nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_5(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_6(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_9, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_9
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](buf11, primals_3,
buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_6[grid(64)](buf11, primals_3,
buf12, buf13, primals_10, primals_11, buf14, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf12
del buf13
del primals_11
return buf14, primals_3, primals_10, buf7, reinterpret_tensor(buf8, (16,
1, 4), (4, 1, 1), 0), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0
), reinterpret_tensor(buf10, (16, 4), (4, 1), 0), buf11, primals_8
class BertSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.position_embedding_type = getattr(config,
'position_embedding_type', 'absolute')
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.
max_position_embeddings - 1, self.attention_head_size)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, attention_mask=None, head_mask=None,
encoder_hidden_states=None, encoder_attention_mask=None,
output_attentions=False):
mixed_query_layer = self.query(hidden_states)
if encoder_hidden_states is not None:
mixed_key_layer = self.key(encoder_hidden_states)
mixed_value_layer = self.value(encoder_hidden_states)
attention_mask = encoder_attention_mask
else:
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
seq_length = hidden_states.size()[1]
position_ids_l = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.
max_position_embeddings - 1)
positional_embedding = positional_embedding
if self.position_embedding_type == 'relative_key':
relative_position_scores = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == 'relative_key_query':
relative_position_scores_query = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
relative_position_scores_key = torch.einsum('bhrd,lrd->bhlr',
key_layer, positional_embedding)
attention_scores = (attention_scores +
relative_position_scores_query +
relative_position_scores_key)
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (
context_layer,)
return outputs
class BertSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertAttentionNew(nn.Module):
def __init__(self, config):
super().__init__()
self.self = BertSelfAttention(config)
self.output = BertSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.self.
num_attention_heads, self.self.attention_head_size, self.
pruned_heads)
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
self.self.num_attention_heads = self.self.num_attention_heads - len(
heads)
self.self.all_head_size = (self.self.attention_head_size * self.
self.num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, input_0):
primals_1 = self.self.query.weight
primals_2 = self.self.query.bias
primals_4 = self.self.key.weight
primals_5 = self.self.key.bias
primals_6 = self.self.value.weight
primals_7 = self.self.value.bias
primals_8 = self.output.dense.weight
primals_9 = self.output.dense.bias
primals_10 = self.output.LayerNorm.weight
primals_11 = self.output.LayerNorm.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
Hzfinfdu/Black-Box-Tuning
|
BertAttention
| false
| 4,263
|
[
"MIT"
] | 0
|
64eb5505875dc1b242c6f0a2a2f07e4000c24cb4
|
https://github.com/Hzfinfdu/Black-Box-Tuning/tree/64eb5505875dc1b242c6f0a2a2f07e4000c24cb4
|
down
|
import torch
from torch.functional import F
import torch.nn as nn
import torch.nn.functional as F
class down(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average Pooling --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels, filterSize):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used as input and output channels for the
second convolutional layer.
filterSize : int
filter size for the convolution filter. input N would create
a N x N filter.
"""
super(down, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, filterSize, stride=
1, padding=int((filterSize - 1) / 2))
self.conv2 = nn.Conv2d(outChannels, outChannels, filterSize, stride
=1, padding=int((filterSize - 1) / 2))
def forward(self, x):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.avg_pool2d(x, 2)
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(x), negative_slope=0.1)
return x
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]
|
samuelpietri/Super-SloMo
|
down
| false
| 4,264
|
[
"MIT"
] | 0
|
e20eaa5550c30737be42b61f8e82e731cfd17457
|
https://github.com/samuelpietri/Super-SloMo/tree/e20eaa5550c30737be42b61f8e82e731cfd17457
|
BellMembFunc
|
import torch
def _mk_param(val):
"""Make a torch parameter from a scalar value"""
if isinstance(val, torch.Tensor):
val = val.item()
return torch.nn.Parameter(torch.tensor(val, dtype=torch.float))
class BellMembFunc(torch.nn.Module):
"""
Generalised Bell membership function; defined by three parameters:
a, the half-width (at the crossover point)
b, controls the slope at the crossover point (which is -b/2a)
c, the center point
"""
def __init__(self, a, b, c):
super(BellMembFunc, self).__init__()
self.register_parameter('a', _mk_param(a))
self.register_parameter('b', _mk_param(b))
self.register_parameter('c', _mk_param(c))
self.b.register_hook(BellMembFunc.b_log_hook)
@staticmethod
def b_log_hook(grad):
"""
Possibility of a log(0) in the grad for b, giving a nan.
Fix this by replacing any nan in the grad with ~0.
"""
grad[torch.isnan(grad)] = 1e-09
return grad
def forward(self, x):
dist = torch.pow((x - self.c) / self.a, 2)
return torch.reciprocal(1 + torch.pow(dist, self.b))
def pretty(self):
return 'BellMembFunc {} {} {}'.format(self.a, self.b, self.c)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'a': 4, 'b': 4, 'c': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_pow_reciprocal_sub_0(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp8 = tl.load(in_ptr3 + 0)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp3 = tmp0 - tmp2
tmp6 = tmp3 / tmp5
tmp7 = tmp6 * tmp6
tmp10 = libdevice.pow(tmp7, tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tl.full([1], 1, tl.int32)
tmp14 = tmp13 / tmp12
tl.store(out_ptr0 + x0, tmp14, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (), ())
assert_size_stride(primals_4, (), ())
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_pow_reciprocal_sub_0[grid(256)](primals_2,
primals_1, primals_3, primals_4, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return buf0, primals_1, primals_2, primals_3, primals_4, buf0
def _mk_param(val):
"""Make a torch parameter from a scalar value"""
if isinstance(val, torch.Tensor):
val = val.item()
return torch.nn.Parameter(torch.tensor(val, dtype=torch.float))
class BellMembFuncNew(torch.nn.Module):
"""
Generalised Bell membership function; defined by three parameters:
a, the half-width (at the crossover point)
b, controls the slope at the crossover point (which is -b/2a)
c, the center point
"""
def __init__(self, a, b, c):
super(BellMembFuncNew, self).__init__()
self.register_parameter('a', _mk_param(a))
self.register_parameter('b', _mk_param(b))
self.register_parameter('c', _mk_param(c))
self.b.register_hook(BellMembFuncNew.b_log_hook)
@staticmethod
def b_log_hook(grad):
"""
Possibility of a log(0) in the grad for b, giving a nan.
Fix this by replacing any nan in the grad with ~0.
"""
grad[torch.isnan(grad)] = 1e-09
return grad
def pretty(self):
return 'BellMembFunc {} {} {}'.format(self.a, self.b, self.c)
def forward(self, input_0):
primals_1 = self.a
primals_3 = self.b
primals_4 = self.c
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
samxu0823/anfis-pytorch
|
BellMembFunc
| false
| 4,265
|
[
"MIT"
] | 0
|
b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
https://github.com/samxu0823/anfis-pytorch/tree/b4ec3f0e8259963800e9e0a2904a580d1e56cc1c
|
qd
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class qd(nn.Module):
def __init__(self, d_dim, x_dim, y_dim, z_dim):
super(qd, self).__init__()
self.fc1 = nn.Linear(z_dim, d_dim)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc1.bias.data.zero_()
def forward(self, zd):
h = F.relu(zd)
loc_d = self.fc1(h)
return loc_d
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_dim': 4, 'x_dim': 4, 'y_dim': 4, 'z_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class qdNew(nn.Module):
def __init__(self, d_dim, x_dim, y_dim, z_dim):
super(qdNew, self).__init__()
self.fc1 = nn.Linear(z_dim, d_dim)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc1.bias.data.zero_()
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
sautami26/DIVA
|
qd
| false
| 4,266
|
[
"MIT"
] | 0
|
52af683db216cb6e2ac777597fd9ec744ce7c8f2
|
https://github.com/sautami26/DIVA/tree/52af683db216cb6e2ac777597fd9ec744ce7c8f2
|
ConditionalBatchNorm2d
|
import torch
import torch.nn as nn
from torch.nn import Parameter
def l2normalize(v, eps=0.0001):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
_w = w.view(height, -1)
for _ in range(self.power_iterations):
v = l2normalize(torch.matmul(_w.t(), u))
u = l2normalize(torch.matmul(_w, v))
sigma = u.dot(_w.mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class ConditionalBatchNorm2d(nn.Module):
def __init__(self, num_features, num_classes, eps=0.0001, momentum=0.1):
super().__init__()
self.num_features = num_features
self.bn = nn.BatchNorm2d(num_features, affine=False, eps=eps,
momentum=momentum)
self.gamma_embed = SpectralNorm(nn.Linear(num_classes, num_features,
bias=False))
self.beta_embed = SpectralNorm(nn.Linear(num_classes, num_features,
bias=False))
def forward(self, x, y):
out = self.bn(x)
gamma = self.gamma_embed(y) + 1
beta = self.beta_embed(y)
out = gamma.view(-1, self.num_features, 1, 1) * out + beta.view(-1,
self.num_features, 1, 1)
return out
def get_inputs():
return [torch.rand([64, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_linalg_vector_norm_mv_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.load(in_ptr0 + (4 + r0), None)
tmp5 = tl.load(in_ptr1 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp9 = tl.load(in_ptr0 + (8 + r0), None)
tmp10 = tl.load(in_ptr1 + 2)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + (12 + r0), None)
tmp15 = tl.load(in_ptr1 + 3)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp18 * tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp22 = tl.sum(tmp20, 1)[:, None]
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp18, None)
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp22, None)
@triton.jit
def triton_per_fused_add_div_dot_linalg_vector_norm_mv_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp3 = tl.load(in_ptr2 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp10 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + 1)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp16 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr1 + 2)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
tmp22 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr1 + 3)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp5 = libdevice.sqrt(tmp4)
tmp6 = 0.0001
tmp7 = tmp5 + tmp6
tmp8 = tmp2 / tmp7
tmp9 = tmp0 * tmp8
tmp13 = tmp12 / tmp7
tmp14 = tmp10 * tmp13
tmp15 = tmp9 + tmp14
tmp19 = tmp18 / tmp7
tmp20 = tmp16 * tmp19
tmp21 = tmp15 + tmp20
tmp25 = tmp24 / tmp7
tmp26 = tmp22 * tmp25
tmp27 = tmp21 + tmp26
tmp28 = tmp27 * tmp27
tmp29 = tl.broadcast_to(tmp28, [XBLOCK, RBLOCK])
tmp31 = tl.sum(tmp29, 1)[:, None]
tmp32 = libdevice.sqrt(tmp31)
tmp33 = tmp32 + tmp6
tmp34 = tmp27 / tmp33
tmp35 = tmp34 * tmp27
tmp36 = tl.broadcast_to(tmp35, [XBLOCK, RBLOCK])
tmp38 = tl.sum(tmp36, 1)[:, None]
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp38, None)
@triton.jit
def triton_poi_fused_div_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 / tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused__native_batch_norm_legit_no_training_add_mul_3(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex // 16
x4 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x4, None)
tmp4 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x1, None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr4 + x3, None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp5 = tmp3 - tmp4
tmp7 = 0.0001
tmp8 = tmp6 + tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = tl.full([1], 1, tl.int32)
tmp11 = tmp10 / tmp9
tmp12 = tmp11 * tmp1
tmp13 = tmp5 * tmp12
tmp14 = tmp2 * tmp13
tmp16 = tmp14 + tmp15
tl.store(out_ptr0 + x4, tmp16, None)
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, (64, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_linalg_vector_norm_mv_0[grid(1)](primals_5,
primals_4, buf0, buf1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused_add_div_dot_linalg_vector_norm_mv_1[grid(1)](buf4,
primals_5, buf0, buf1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_div_2[grid(16)](primals_5, buf4, buf5, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(buf5, (4, 4), (1, 4), 0), out=buf6)
buf7 = buf0
del buf0
buf8 = buf4
del buf4
triton_per_fused_linalg_vector_norm_mv_0[grid(1)](primals_8,
primals_7, buf7, buf8, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf10 = buf1
del buf1
buf11 = buf10
del buf10
triton_per_fused_add_div_dot_linalg_vector_norm_mv_1[grid(1)](buf11,
primals_8, buf7, buf8, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf7
del buf8
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_div_2[grid(16)](primals_8, buf11, buf12, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf11
buf13 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(buf12, (4, 4), (1, 4), 0), out=buf13)
buf14 = empty_strided_cuda((64, 4, 4, 4), (64, 16, 4, 1), torch.float32
)
triton_poi_fused__native_batch_norm_legit_no_training_add_mul_3[grid
(4096)](buf6, primals_1, primals_2, primals_3, buf13, buf14,
4096, XBLOCK=256, num_warps=4, num_stages=1)
del buf13
del buf6
return (buf14, buf5, buf12, primals_1, primals_2, primals_3, primals_4,
primals_5, primals_7, primals_8, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0))
def l2normalize(v, eps=0.0001):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
_w = w.view(height, -1)
for _ in range(self.power_iterations):
v = l2normalize(torch.matmul(_w.t(), u))
u = l2normalize(torch.matmul(_w, v))
sigma = u.dot(_w.mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class ConditionalBatchNorm2dNew(nn.Module):
def __init__(self, num_features, num_classes, eps=0.0001, momentum=0.1):
super().__init__()
self.num_features = num_features
self.bn = nn.BatchNorm2d(num_features, affine=False, eps=eps,
momentum=momentum)
self.gamma_embed = SpectralNorm(nn.Linear(num_classes, num_features,
bias=False))
self.beta_embed = SpectralNorm(nn.Linear(num_classes, num_features,
bias=False))
def forward(self, input_0, input_1):
primals_2 = self.gamma_embed.module.weight_u
primals_3 = self.gamma_embed.module.weight_v
primals_5 = self.gamma_embed.module.weight_bar
primals_4 = self.beta_embed.module.weight_u
primals_7 = self.beta_embed.module.weight_v
primals_8 = self.beta_embed.module.weight_bar
primals_1 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
samuelemarro/anne
|
ConditionalBatchNorm2d
| false
| 4,267
|
[
"MIT"
] | 0
|
918022eb029a46fbfd1589369e9817f570d5651c
|
https://github.com/samuelemarro/anne/tree/918022eb029a46fbfd1589369e9817f570d5651c
|
GlobalAvgPool1d
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from abc import abstractmethod
from torch.nn import functional
class AvgPool(nn.Module):
"""
AvgPool Module.
"""
def __init__(self):
super().__init__()
@abstractmethod
def forward(self, input_tensor):
pass
class GlobalAvgPool1d(AvgPool):
"""
GlobalAvgPool1d Module.
"""
def forward(self, input_tensor):
return functional.avg_pool1d(input_tensor, input_tensor.size()[2:]
).view(input_tensor.size()[:2])
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
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from abc import abstractmethod
assert_size_stride = torch._C._dynamo.guards.assert_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 + 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 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_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 AvgPool(nn.Module):
"""
AvgPool Module.
"""
def __init__(self):
super().__init__()
@abstractmethod
def forward(self, input_tensor):
pass
class GlobalAvgPool1dNew(AvgPool):
"""
GlobalAvgPool1d Module.
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
savan77/nni
|
GlobalAvgPool1d
| false
| 4,268
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
DeepQNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class DeepQNetwork(nn.Module):
def __init__(self, imagesize, num_input_frames, num_actions, **kwargs):
super(DeepQNetwork, self).__init__()
self.conv1 = nn.Conv2d(in_channels=num_input_frames, out_channels=
32, kernel_size=9, stride=4, padding=4)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=5, stride=2, padding=2)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size
=3, stride=1, padding=1)
in_features = 64 * imagesize[0] * imagesize[1] // 64
self.fc1 = nn.Linear(in_features=in_features, out_features=512)
self.fc2 = nn.Linear(in_features=512, out_features=num_actions)
def forward(self, x):
batch_size = x.size(0)
x = F.relu(self.conv1(x), inplace=True)
x = F.relu(self.conv2(x), inplace=True)
x = F.relu(self.conv3(x), inplace=True)
x = x.view(batch_size, -1)
x = F.relu(self.fc1(x), inplace=True)
x = self.fc2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'imagesize': [4, 4], 'num_input_frames': 4, 'num_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (32, 4, 9, 9), (324, 81, 9, 1))
assert_size_stride(primals_3, (32,), (1,))
assert_size_stride(primals_4, (64, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (512, 16), (16, 1))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (4, 512), (512, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
4, 4, 4), (64, 16, 4, 1), 0), primals_2, stride=(4, 4), padding
=(4, 4), dilation=(1, 1), transposed=False, output_padding=(0,
0), groups=1, bias=None)
assert_size_stride(buf0, (1, 32, 1, 1), (32, 1, 1, 1))
buf1 = reinterpret_tensor(buf0, (32, 1, 1), (1, 1, 1), 0)
del buf0
buf11 = empty_strided_cuda((32, 1, 1), (1, 1, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(32)](buf1,
primals_3, buf11, 32, XBLOCK=32, num_warps=1, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 32,
1, 1), (0, 1, 0, 0), 0), primals_4, stride=(2, 2), padding=(2,
2), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf2, (1, 64, 1, 1), (64, 1, 1, 1))
buf3 = reinterpret_tensor(buf2, (64, 1, 1), (1, 1, 1), 0)
del buf2
buf10 = empty_strided_cuda((64, 1, 1), (1, 1, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf3,
primals_5, buf10, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(reinterpret_tensor(buf3, (1, 64,
1, 1), (0, 1, 0, 0), 0), primals_6, stride=(1, 1), padding=(1,
1), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf4, (1, 64, 1, 1), (64, 1, 1, 1))
buf5 = reinterpret_tensor(buf4, (64, 1, 1), (1, 1, 1), 0)
del buf4
buf9 = empty_strided_cuda((64, 1, 1), (1, 1, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf5,
primals_7, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (4, 16), (16, 1), 0),
reinterpret_tensor(primals_8, (16, 512), (1, 16), 0), out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_relu_2[grid(2048)](buf7, primals_9, 2048, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, buf7, reinterpret_tensor(
primals_10, (512, 4), (1, 512), 0), alpha=1, beta=1, out=buf8)
del primals_11
return buf8, primals_2, primals_4, primals_6, reinterpret_tensor(primals_1,
(1, 4, 4, 4), (64, 16, 4, 1), 0), reinterpret_tensor(buf1, (1, 32,
1, 1), (32, 1, 1, 1), 0), reinterpret_tensor(buf3, (1, 64, 1, 1), (
64, 1, 1, 1), 0), reinterpret_tensor(buf5, (4, 16), (16, 1), 0
), buf7, primals_10, primals_8, buf9, buf10, buf11
class DeepQNetworkNew(nn.Module):
def __init__(self, imagesize, num_input_frames, num_actions, **kwargs):
super(DeepQNetworkNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=num_input_frames, out_channels=
32, kernel_size=9, stride=4, padding=4)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=5, stride=2, padding=2)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size
=3, stride=1, padding=1)
in_features = 64 * imagesize[0] * imagesize[1] // 64
self.fc1 = nn.Linear(in_features=in_features, out_features=512)
self.fc2 = nn.Linear(in_features=512, out_features=num_actions)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
sanmusane/AIGames
|
DeepQNetwork
| false
| 4,269
|
[
"MIT"
] | 0
|
3f4eecdd02089911d1989e40e2b336e13b800e55
|
https://github.com/sanmusane/AIGames/tree/3f4eecdd02089911d1989e40e2b336e13b800e55
|
Mask
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class Mask(nn.Module):
def forward(self, seq, mask):
seq_mask = torch.unsqueeze(mask, 2)
seq_mask = torch.transpose(seq_mask.repeat(1, 1, seq.size()[1]), 1, 2)
return seq.where(torch.eq(seq_mask, 1), torch.zeros_like(seq))
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_eq_where_zeros_like_0(in_ptr0, in_ptr1, out_ptr0,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (x2 + 4 * y1), xmask & ymask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr1 + (x2 + 4 * y0), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 == tmp1
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + (y0 + 4 * x2 + 16 * y1), tmp5, xmask & ymask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_eq_where_zeros_like_0[grid(16, 4)](arg0_1, arg1_1,
buf0, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class MaskNew(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]
|
savan77/nni
|
Mask
| false
| 4,270
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
Pooling
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class ReLUConvBN(nn.Module):
"""
Parameters
---
C_in: int
the number of input channels
C_out: int
the number of output channels
stride: int
stride of the convolution
padding: int
zero-padding added to both sides of the input
dilation: int
spacing between kernel elements
bn_affine: bool
If set to ``True``, ``torch.nn.BatchNorm2d`` will have learnable affine parameters. Default: True
bn_momentun: float
the value used for the running_mean and running_var computation. Default: 0.1
bn_track_running_stats: bool
When set to ``True``, ``torch.nn.BatchNorm2d`` tracks the running mean and variance. Default: True
"""
def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation,
bn_affine=True, bn_momentum=0.1, bn_track_running_stats=True):
super(ReLUConvBN, self).__init__()
self.op = nn.Sequential(nn.ReLU(inplace=False), nn.Conv2d(C_in,
C_out, kernel_size, stride=stride, padding=padding, dilation=
dilation, bias=False), nn.BatchNorm2d(C_out, affine=bn_affine,
momentum=bn_momentum, track_running_stats=bn_track_running_stats))
def forward(self, x):
"""
Parameters
---
x: torch.Tensor
input tensor
"""
return self.op(x)
class Pooling(nn.Module):
"""
Parameters
---
C_in: int
the number of input channels
C_out: int
the number of output channels
stride: int
stride of the convolution
bn_affine: bool
If set to ``True``, ``torch.nn.BatchNorm2d`` will have learnable affine parameters. Default: True
bn_momentun: float
the value used for the running_mean and running_var computation. Default: 0.1
bn_track_running_stats: bool
When set to ``True``, ``torch.nn.BatchNorm2d`` tracks the running mean and variance. Default: True
"""
def __init__(self, C_in, C_out, stride, bn_affine=True, bn_momentum=0.1,
bn_track_running_stats=True):
super(Pooling, self).__init__()
if C_in == C_out:
self.preprocess = None
else:
self.preprocess = ReLUConvBN(C_in, C_out, 1, 1, 0, 0, bn_affine,
bn_momentum, bn_track_running_stats)
self.op = nn.AvgPool2d(3, stride=stride, padding=1,
count_include_pad=False)
def forward(self, x):
"""
Parameters
---
x: torch.Tensor
input tensor
"""
if self.preprocess:
x = self.preprocess(x)
return self.op(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'C_in': 4, 'C_out': 4, 'stride': 1}]
|
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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 4
x0 = xindex % 4
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-5 + x4), tmp10 & xmask, other=0.0)
tmp12 = x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-4 + x4), tmp16 & xmask, other=0.0)
tmp18 = tmp17 + tmp11
tmp19 = 1 + x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-3 + x4), tmp23 & xmask, other=0.0)
tmp25 = tmp24 + tmp18
tmp26 = x1
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-1 + x4), tmp30 & xmask, other=0.0)
tmp32 = tmp31 + tmp25
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + x4, tmp33 & xmask, other=0.0)
tmp35 = tmp34 + tmp32
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (1 + x4), tmp36 & xmask, other=0.0)
tmp38 = tmp37 + tmp35
tmp39 = 1 + x1
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (3 + x4), tmp43 & xmask, other=0.0)
tmp45 = tmp44 + tmp38
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (4 + x4), tmp46 & xmask, other=0.0)
tmp48 = tmp47 + tmp45
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (5 + x4), tmp49 & xmask, other=0.0)
tmp51 = tmp50 + tmp48
tmp52 = (0 * (0 >= -1 + x0) + (-1 + x0) * (-1 + x0 > 0)) * (0 * (0 >= -
1 + x1) + (-1 + x1) * (-1 + x1 > 0)) + (4 * (4 <= 2 + x0) + (2 + x0
) * (2 + x0 < 4)) * (4 * (4 <= 2 + x1) + (2 + x1) * (2 + x1 < 4)
) + -1 * (0 * (0 >= -1 + x0) + (-1 + x0) * (-1 + x0 > 0)) * (4 * (4 <=
2 + x1) + (2 + x1) * (2 + x1 < 4)) + -1 * (0 * (0 >= -1 + x1) + (-1 +
x1) * (-1 + x1 > 0)) * (4 * (4 <= 2 + x0) + (2 + x0) * (2 + x0 < 4))
tmp53 = tmp51 / tmp52
tl.store(out_ptr0 + x4, tmp53, 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_avg_pool2d_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ReLUConvBN(nn.Module):
"""
Parameters
---
C_in: int
the number of input channels
C_out: int
the number of output channels
stride: int
stride of the convolution
padding: int
zero-padding added to both sides of the input
dilation: int
spacing between kernel elements
bn_affine: bool
If set to ``True``, ``torch.nn.BatchNorm2d`` will have learnable affine parameters. Default: True
bn_momentun: float
the value used for the running_mean and running_var computation. Default: 0.1
bn_track_running_stats: bool
When set to ``True``, ``torch.nn.BatchNorm2d`` tracks the running mean and variance. Default: True
"""
def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation,
bn_affine=True, bn_momentum=0.1, bn_track_running_stats=True):
super(ReLUConvBN, self).__init__()
self.op = nn.Sequential(nn.ReLU(inplace=False), nn.Conv2d(C_in,
C_out, kernel_size, stride=stride, padding=padding, dilation=
dilation, bias=False), nn.BatchNorm2d(C_out, affine=bn_affine,
momentum=bn_momentum, track_running_stats=bn_track_running_stats))
def forward(self, x):
"""
Parameters
---
x: torch.Tensor
input tensor
"""
return self.op(x)
class PoolingNew(nn.Module):
"""
Parameters
---
C_in: int
the number of input channels
C_out: int
the number of output channels
stride: int
stride of the convolution
bn_affine: bool
If set to ``True``, ``torch.nn.BatchNorm2d`` will have learnable affine parameters. Default: True
bn_momentun: float
the value used for the running_mean and running_var computation. Default: 0.1
bn_track_running_stats: bool
When set to ``True``, ``torch.nn.BatchNorm2d`` tracks the running mean and variance. Default: True
"""
def __init__(self, C_in, C_out, stride, bn_affine=True, bn_momentum=0.1,
bn_track_running_stats=True):
super(PoolingNew, self).__init__()
if C_in == C_out:
self.preprocess = None
else:
self.preprocess = ReLUConvBN(C_in, C_out, 1, 1, 0, 0, bn_affine,
bn_momentum, bn_track_running_stats)
self.op = nn.AvgPool2d(3, stride=stride, padding=1,
count_include_pad=False)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
savan77/nni
|
Pooling
| false
| 4,271
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
BackboneModel1
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class BackboneModel1(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 1, 1, 1)
def forward(self, x):
return self.conv1(x)
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16384)](buf1, primals_2, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class BackboneModel1New(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 1, 1, 1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
savan77/nni
|
BackboneModel1
| false
| 4,272
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
InteractiveKLLoss
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.nn.functional as F
class InteractiveKLLoss(nn.Module):
def __init__(self, temperature):
super().__init__()
self.temperature = temperature
self.kl_loss = nn.KLDivLoss()
def forward(self, student, teacher):
return self.kl_loss(F.log_softmax(student / self.temperature, dim=1
), F.softmax(teacher / self.temperature, dim=1))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'temperature': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x3, tmp17, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tl.store(out_ptr0 + x3, tmp16, xmask)
@triton.jit
def triton_per_fused__log_softmax__softmax_mean_mul_sub_xlogy_2(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'
)
tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr1 + r3, None)
tmp18 = tl.load(in_ptr1 + (r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr1 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr1 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp26 = tl.load(in_ptr1 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp9 = libdevice.isnan(tmp8).to(tl.int1)
tmp10 = 0.0
tmp11 = tmp8 == tmp10
tmp12 = tl_math.log(tmp8)
tmp13 = tmp8 * tmp12
tmp14 = tl.where(tmp11, tmp10, tmp13)
tmp15 = float('nan')
tmp16 = tl.where(tmp9, tmp15, tmp14)
tmp19 = tl_math.exp(tmp18)
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp19 + tmp21
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp22 + tmp24
tmp27 = tl_math.exp(tmp26)
tmp28 = tmp25 + tmp27
tmp29 = tl_math.log(tmp28)
tmp30 = tmp17 - tmp29
tmp31 = tmp8 * tmp30
tmp32 = tmp16 - tmp31
tmp33 = tl.broadcast_to(tmp32, [RBLOCK])
tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0))
tmp36 = 256.0
tmp37 = tmp35 / tmp36
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp37, 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__softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](arg0_1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused__log_softmax__softmax_mean_mul_sub_xlogy_2[grid(1)](
buf4, buf0, buf2, 1, 256, num_warps=2, num_stages=1)
del buf0
del buf2
return buf4,
class InteractiveKLLossNew(nn.Module):
def __init__(self, temperature):
super().__init__()
self.temperature = temperature
self.kl_loss = nn.KLDivLoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
savan77/nni
|
InteractiveKLLoss
| false
| 4,273
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
GAT
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class GraphAttention(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttention, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
if torch.cuda.is_available():
param_type = torch.FloatTensor
else:
param_type = torch.FloatTensor
self.W = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
in_features, out_features).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.a1 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.a2 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.leaky_relu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj):
h = torch.mm(input, self.W)
h.size()[0]
f_1 = torch.mm(h, self.a1)
f_2 = torch.mm(h, self.a2)
e = self.leaky_relu(f_1 + f_2.transpose(0, 1))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GAT(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttention(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttention(nhid * nheads, nclass, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, x, adj):
x = F.dropout(x, self.dropout, training=self.training)
x = torch.cat([att(x, adj) for att in self.attentions], dim=1)
x = F.dropout(x, self.dropout, training=self.training)
x = F.elu(self.out_att(x, adj))
return F.log_softmax(x, dim=1)
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,
'alpha': 4, 'nheads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_leaky_relu_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
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_gt_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9,
in_ptr10, in_ptr11, in_ptr12, out_ptr0, out_ptr1, out_ptr2, out_ptr3,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tl.load(in_ptr3 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp13 = tl.load(in_ptr3 + 1)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp22 = tl.load(in_ptr3 + 2)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp29 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp30 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp31 = tl.load(in_ptr3 + 3)
tmp32 = tl.broadcast_to(tmp31, [XBLOCK])
tmp38 = tl.load(in_ptr4 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp39 = tl.load(in_ptr5 + x0, xmask)
tmp40 = tl.load(in_ptr6 + 0)
tmp41 = tl.broadcast_to(tmp40, [XBLOCK])
tmp46 = tl.load(in_ptr4 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp47 = tl.load(in_ptr6 + 1)
tmp48 = tl.broadcast_to(tmp47, [XBLOCK])
tmp54 = tl.load(in_ptr4 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp55 = tl.load(in_ptr6 + 2)
tmp56 = tl.broadcast_to(tmp55, [XBLOCK])
tmp62 = tl.load(in_ptr4 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp63 = tl.load(in_ptr6 + 3)
tmp64 = tl.broadcast_to(tmp63, [XBLOCK])
tmp70 = tl.load(in_ptr7 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp71 = tl.load(in_ptr8 + x0, xmask)
tmp72 = tl.load(in_ptr9 + 0)
tmp73 = tl.broadcast_to(tmp72, [XBLOCK])
tmp78 = tl.load(in_ptr7 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp79 = tl.load(in_ptr9 + 1)
tmp80 = tl.broadcast_to(tmp79, [XBLOCK])
tmp86 = tl.load(in_ptr7 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp87 = tl.load(in_ptr9 + 2)
tmp88 = tl.broadcast_to(tmp87, [XBLOCK])
tmp94 = tl.load(in_ptr7 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp95 = tl.load(in_ptr9 + 3)
tmp96 = tl.broadcast_to(tmp95, [XBLOCK])
tmp102 = tl.load(in_ptr10 + 4 * x0, xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp103 = tl.load(in_ptr11 + x0, xmask)
tmp104 = tl.load(in_ptr12 + 0)
tmp105 = tl.broadcast_to(tmp104, [XBLOCK])
tmp110 = tl.load(in_ptr10 + (1 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp111 = tl.load(in_ptr12 + 1)
tmp112 = tl.broadcast_to(tmp111, [XBLOCK])
tmp118 = tl.load(in_ptr10 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp119 = tl.load(in_ptr12 + 2)
tmp120 = tl.broadcast_to(tmp119, [XBLOCK])
tmp126 = tl.load(in_ptr10 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp127 = tl.load(in_ptr12 + 3)
tmp128 = tl.broadcast_to(tmp127, [XBLOCK])
tmp5 = tmp2 + tmp4
tmp6 = 4.0
tmp7 = tmp5 * tmp6
tmp8 = tl.where(tmp1, tmp5, tmp7)
tmp9 = -8999999815811072.0
tmp10 = tl.where(tmp0, tmp8, tmp9)
tmp15 = tmp2 + tmp14
tmp16 = tmp15 * tmp6
tmp17 = tl.where(tmp12, tmp15, tmp16)
tmp18 = tl.where(tmp11, tmp17, tmp9)
tmp19 = triton_helpers.maximum(tmp10, tmp18)
tmp24 = tmp2 + tmp23
tmp25 = tmp24 * tmp6
tmp26 = tl.where(tmp21, tmp24, tmp25)
tmp27 = tl.where(tmp20, tmp26, tmp9)
tmp28 = triton_helpers.maximum(tmp19, tmp27)
tmp33 = tmp2 + tmp32
tmp34 = tmp33 * tmp6
tmp35 = tl.where(tmp30, tmp33, tmp34)
tmp36 = tl.where(tmp29, tmp35, tmp9)
tmp37 = triton_helpers.maximum(tmp28, tmp36)
tmp42 = tmp39 + tmp41
tmp43 = tmp42 * tmp6
tmp44 = tl.where(tmp38, tmp42, tmp43)
tmp45 = tl.where(tmp0, tmp44, tmp9)
tmp49 = tmp39 + tmp48
tmp50 = tmp49 * tmp6
tmp51 = tl.where(tmp46, tmp49, tmp50)
tmp52 = tl.where(tmp11, tmp51, tmp9)
tmp53 = triton_helpers.maximum(tmp45, tmp52)
tmp57 = tmp39 + tmp56
tmp58 = tmp57 * tmp6
tmp59 = tl.where(tmp54, tmp57, tmp58)
tmp60 = tl.where(tmp20, tmp59, tmp9)
tmp61 = triton_helpers.maximum(tmp53, tmp60)
tmp65 = tmp39 + tmp64
tmp66 = tmp65 * tmp6
tmp67 = tl.where(tmp62, tmp65, tmp66)
tmp68 = tl.where(tmp29, tmp67, tmp9)
tmp69 = triton_helpers.maximum(tmp61, tmp68)
tmp74 = tmp71 + tmp73
tmp75 = tmp74 * tmp6
tmp76 = tl.where(tmp70, tmp74, tmp75)
tmp77 = tl.where(tmp0, tmp76, tmp9)
tmp81 = tmp71 + tmp80
tmp82 = tmp81 * tmp6
tmp83 = tl.where(tmp78, tmp81, tmp82)
tmp84 = tl.where(tmp11, tmp83, tmp9)
tmp85 = triton_helpers.maximum(tmp77, tmp84)
tmp89 = tmp71 + tmp88
tmp90 = tmp89 * tmp6
tmp91 = tl.where(tmp86, tmp89, tmp90)
tmp92 = tl.where(tmp20, tmp91, tmp9)
tmp93 = triton_helpers.maximum(tmp85, tmp92)
tmp97 = tmp71 + tmp96
tmp98 = tmp97 * tmp6
tmp99 = tl.where(tmp94, tmp97, tmp98)
tmp100 = tl.where(tmp29, tmp99, tmp9)
tmp101 = triton_helpers.maximum(tmp93, tmp100)
tmp106 = tmp103 + tmp105
tmp107 = tmp106 * tmp6
tmp108 = tl.where(tmp102, tmp106, tmp107)
tmp109 = tl.where(tmp0, tmp108, tmp9)
tmp113 = tmp103 + tmp112
tmp114 = tmp113 * tmp6
tmp115 = tl.where(tmp110, tmp113, tmp114)
tmp116 = tl.where(tmp11, tmp115, tmp9)
tmp117 = triton_helpers.maximum(tmp109, tmp116)
tmp121 = tmp103 + tmp120
tmp122 = tmp121 * tmp6
tmp123 = tl.where(tmp118, tmp121, tmp122)
tmp124 = tl.where(tmp20, tmp123, tmp9)
tmp125 = triton_helpers.maximum(tmp117, tmp124)
tmp129 = tmp103 + tmp128
tmp130 = tmp129 * tmp6
tmp131 = tl.where(tmp126, tmp129, tmp130)
tmp132 = tl.where(tmp29, tmp131, tmp9)
tmp133 = triton_helpers.maximum(tmp125, tmp132)
tl.store(out_ptr0 + x0, tmp37, xmask)
tl.store(out_ptr1 + x0, tmp69, xmask)
tl.store(out_ptr2 + x0, tmp101, xmask)
tl.store(out_ptr3 + x0, tmp133, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_3(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9,
in_ptr10, in_ptr11, in_ptr12, in_ptr13, in_ptr14, in_ptr15, in_ptr16,
out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr5 + x2, xmask).to(tl.int1)
tmp14 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr9 + x2, xmask).to(tl.int1)
tmp24 = tl.load(in_ptr10 + x1, xmask, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr11 + x0, xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp33 = tl.load(in_ptr13 + x2, xmask).to(tl.int1)
tmp34 = tl.load(in_ptr14 + x1, xmask, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr15 + x0, xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr16 + x1, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp5 = 4.0
tmp6 = tmp4 * tmp5
tmp7 = tl.where(tmp1, tmp4, tmp6)
tmp8 = -8999999815811072.0
tmp9 = tl.where(tmp0, tmp7, tmp8)
tmp11 = tmp9 - tmp10
tmp12 = tl_math.exp(tmp11)
tmp16 = tmp14 + tmp15
tmp17 = tmp16 * tmp5
tmp18 = tl.where(tmp13, tmp16, tmp17)
tmp19 = tl.where(tmp0, tmp18, tmp8)
tmp21 = tmp19 - tmp20
tmp22 = tl_math.exp(tmp21)
tmp26 = tmp24 + tmp25
tmp27 = tmp26 * tmp5
tmp28 = tl.where(tmp23, tmp26, tmp27)
tmp29 = tl.where(tmp0, tmp28, tmp8)
tmp31 = tmp29 - tmp30
tmp32 = tl_math.exp(tmp31)
tmp36 = tmp34 + tmp35
tmp37 = tmp36 * tmp5
tmp38 = tl.where(tmp33, tmp36, tmp37)
tmp39 = tl.where(tmp0, tmp38, tmp8)
tmp41 = tmp39 - tmp40
tmp42 = tl_math.exp(tmp41)
tl.store(out_ptr0 + x2, tmp12, xmask)
tl.store(out_ptr1 + x2, tmp22, xmask)
tl.store(out_ptr2 + x2, tmp32, xmask)
tl.store(out_ptr3 + x2, tmp42, xmask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 1.0
tmp9 = tmp5 * tmp8
tmp10 = libdevice.expm1(tmp9)
tmp11 = tmp10 * tmp8
tmp12 = tl.where(tmp7, tmp9, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tmp16 = tl.full([1], 8, tl.int64)
tmp17 = tmp0 < tmp16
tmp18 = tmp15 & tmp17
tmp19 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp18 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 > tmp6
tmp21 = tmp19 * tmp8
tmp22 = libdevice.expm1(tmp21)
tmp23 = tmp22 * tmp8
tmp24 = tl.where(tmp20, tmp21, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp18, tmp24, tmp25)
tmp27 = tmp0 >= tmp16
tmp28 = tl.full([1], 12, tl.int64)
tmp29 = tmp0 < tmp28
tmp30 = tmp27 & tmp29
tmp31 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp32 = tmp31 > tmp6
tmp33 = tmp31 * tmp8
tmp34 = libdevice.expm1(tmp33)
tmp35 = tmp34 * tmp8
tmp36 = tl.where(tmp32, tmp33, tmp35)
tmp37 = tl.full(tmp36.shape, 0.0, tmp36.dtype)
tmp38 = tl.where(tmp30, tmp36, tmp37)
tmp39 = tmp0 >= tmp28
tl.full([1], 16, tl.int64)
tmp42 = tl.load(in_ptr3 + (4 * x1 + (-12 + x0)), tmp39 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tmp42 > tmp6
tmp44 = tmp42 * tmp8
tmp45 = libdevice.expm1(tmp44)
tmp46 = tmp45 * tmp8
tmp47 = tl.where(tmp43, tmp44, tmp46)
tmp48 = tl.full(tmp47.shape, 0.0, tmp47.dtype)
tmp49 = tl.where(tmp39, tmp47, tmp48)
tmp50 = tl.where(tmp30, tmp38, tmp49)
tmp51 = tl.where(tmp18, tmp26, tmp50)
tmp52 = tl.where(tmp4, tmp14, tmp51)
tl.store(out_ptr0 + x2, tmp52, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_6(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tl.load(in_ptr3 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp13 = tl.load(in_ptr3 + 1)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp22 = tl.load(in_ptr3 + 2)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp29 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp30 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp31 = tl.load(in_ptr3 + 3)
tmp32 = tl.broadcast_to(tmp31, [XBLOCK])
tmp5 = tmp2 + tmp4
tmp6 = 4.0
tmp7 = tmp5 * tmp6
tmp8 = tl.where(tmp1, tmp5, tmp7)
tmp9 = -8999999815811072.0
tmp10 = tl.where(tmp0, tmp8, tmp9)
tmp15 = tmp2 + tmp14
tmp16 = tmp15 * tmp6
tmp17 = tl.where(tmp12, tmp15, tmp16)
tmp18 = tl.where(tmp11, tmp17, tmp9)
tmp19 = triton_helpers.maximum(tmp10, tmp18)
tmp24 = tmp2 + tmp23
tmp25 = tmp24 * tmp6
tmp26 = tl.where(tmp21, tmp24, tmp25)
tmp27 = tl.where(tmp20, tmp26, tmp9)
tmp28 = triton_helpers.maximum(tmp19, tmp27)
tmp33 = tmp2 + tmp32
tmp34 = tmp33 * tmp6
tmp35 = tl.where(tmp30, tmp33, tmp34)
tmp36 = tl.where(tmp29, tmp35, tmp9)
tmp37 = triton_helpers.maximum(tmp28, tmp36)
tl.store(out_ptr0 + x0, tmp37, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_7(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp5 = 4.0
tmp6 = tmp4 * tmp5
tmp7 = tl.where(tmp1, tmp4, tmp6)
tmp8 = -8999999815811072.0
tmp9 = tl.where(tmp0, tmp7, tmp8)
tmp11 = tmp9 - tmp10
tmp12 = tl_math.exp(tmp11)
tl.store(out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused__log_softmax_elu_8(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)
tmp8 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp28 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 1.0
tmp4 = tmp0 * tmp3
tmp5 = libdevice.expm1(tmp4)
tmp6 = tmp5 * tmp3
tmp7 = tl.where(tmp2, tmp4, tmp6)
tmp9 = tmp8 > tmp1
tmp10 = tmp8 * tmp3
tmp11 = libdevice.expm1(tmp10)
tmp12 = tmp11 * tmp3
tmp13 = tl.where(tmp9, tmp10, tmp12)
tmp15 = tmp14 > tmp1
tmp16 = tmp14 * tmp3
tmp17 = libdevice.expm1(tmp16)
tmp18 = tmp17 * tmp3
tmp19 = tl.where(tmp15, tmp16, tmp18)
tmp20 = triton_helpers.maximum(tmp13, tmp19)
tmp22 = tmp21 > tmp1
tmp23 = tmp21 * tmp3
tmp24 = libdevice.expm1(tmp23)
tmp25 = tmp24 * tmp3
tmp26 = tl.where(tmp22, tmp23, tmp25)
tmp27 = triton_helpers.maximum(tmp20, tmp26)
tmp29 = tmp28 > tmp1
tmp30 = tmp28 * tmp3
tmp31 = libdevice.expm1(tmp30)
tmp32 = tmp31 * tmp3
tmp33 = tl.where(tmp29, tmp30, tmp32)
tmp34 = triton_helpers.maximum(tmp27, tmp33)
tmp35 = tmp7 - tmp34
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused__log_softmax_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 1), (1, 1))
assert_size_stride(primals_4, (4, 1), (1, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4, 1), (1, 1))
assert_size_stride(primals_8, (4, 1), (1, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4, 1), (1, 1))
assert_size_stride(primals_11, (4, 1), (1, 1))
assert_size_stride(primals_12, (4, 4), (4, 1))
assert_size_stride(primals_13, (4, 1), (1, 1))
assert_size_stride(primals_14, (4, 1), (1, 1))
assert_size_stride(primals_15, (16, 4), (4, 1))
assert_size_stride(primals_16, (4, 1), (1, 1))
assert_size_stride(primals_17, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, primals_3, out=buf1)
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, primals_4, out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf1, buf2, buf3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_gt_1[grid(16)](primals_5, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_6, out=buf9)
del primals_6
buf10 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf9, primals_7, out=buf10)
buf11 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf9, primals_8, out=buf11)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf10, buf11, buf12, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_9, out=buf17)
del primals_9
buf18 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf17, primals_10, out=buf18)
buf19 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf17, primals_11, out=buf19)
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf18, buf19, buf20, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf25 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_12, out=buf25)
del primals_12
buf26 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf25, primals_13, out=buf26)
buf27 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf25, primals_14, out=buf27)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf26, buf27, buf28, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf13 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf21 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf29 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_2[grid(4)](buf4,
buf3, buf1, buf2, buf12, buf10, buf11, buf20, buf18, buf19,
buf28, buf26, buf27, buf5, buf13, buf21, buf29, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf22 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf30 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_3[grid(16)](buf4,
buf3, buf1, buf2, buf5, buf12, buf10, buf11, buf13, buf20,
buf18, buf19, buf21, buf28, buf26, buf27, buf29, buf6, buf14,
buf22, buf30, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf1
del buf10
del buf11
del buf13
del buf18
del buf19
del buf2
del buf21
del buf26
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf6, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf8 = buf6
del buf6
extern_kernels.mm(buf7, buf0, out=buf8)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf14, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf16 = buf14
del buf14
extern_kernels.mm(buf15, buf9, out=buf16)
buf23 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf22, buf23, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf24 = buf22
del buf22
extern_kernels.mm(buf23, buf17, out=buf24)
buf31 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf30, buf31, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf32 = buf30
del buf30
extern_kernels.mm(buf31, buf25, out=buf32)
buf33 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_cat_5[grid(64)](buf8, buf16, buf24, buf32, buf33,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf33, primals_15, out=buf34)
buf35 = reinterpret_tensor(buf5, (4, 1), (1, 1), 0)
del buf5
extern_kernels.mm(buf34, primals_16, out=buf35)
buf36 = reinterpret_tensor(buf29, (4, 1), (1, 1), 0)
del buf29
extern_kernels.mm(buf34, primals_17, out=buf36)
buf37 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf35, buf36, buf37, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf38 = reinterpret_tensor(buf27, (4, 1), (1, 4), 0)
del buf27
triton_poi_fused__softmax_add_leaky_relu_mul_where_6[grid(4)](buf4,
buf37, buf35, buf36, buf38, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf39 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_7[grid(16)](buf4,
buf37, buf35, buf36, buf38, buf39, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf35
del buf36
del buf38
buf40 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf39, buf40, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf41 = buf39
del buf39
extern_kernels.mm(buf40, buf34, out=buf41)
buf42 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_elu_8[grid(16)](buf41, buf42, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf43 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_9[grid(16)](buf42, buf43, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del buf42
return (buf43, buf3, buf4, buf7, buf8, buf12, buf15, buf16, buf20,
buf23, buf24, buf28, buf31, buf32, buf37, buf40, buf41, buf43,
reinterpret_tensor(buf34, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_17, (1, 4), (1, 1), 0), reinterpret_tensor(primals_16, (1,
4), (1, 1), 0), reinterpret_tensor(buf33, (16, 4), (1, 16), 0),
reinterpret_tensor(primals_15, (4, 16), (1, 4), 0),
reinterpret_tensor(buf25, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_14, (1, 4), (1, 1), 0), reinterpret_tensor(primals_13, (1,
4), (1, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0),
reinterpret_tensor(buf17, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_11, (1, 4), (1, 1), 0), reinterpret_tensor(primals_10, (1,
4), (1, 1), 0), reinterpret_tensor(buf9, (4, 4), (1, 4), 0),
reinterpret_tensor(primals_8, (1, 4), (1, 1), 0),
reinterpret_tensor(primals_7, (1, 4), (1, 1), 0),
reinterpret_tensor(buf0, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_4, (1, 4), (1, 1), 0), reinterpret_tensor(primals_3, (1, 4),
(1, 1), 0))
class GraphAttention(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttention, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
if torch.cuda.is_available():
param_type = torch.FloatTensor
else:
param_type = torch.FloatTensor
self.W = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
in_features, out_features).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.a1 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.a2 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(param_type), gain=np.sqrt(2.0)),
requires_grad=True)
self.leaky_relu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj):
h = torch.mm(input, self.W)
h.size()[0]
f_1 = torch.mm(h, self.a1)
f_2 = torch.mm(h, self.a2)
e = self.leaky_relu(f_1 + f_2.transpose(0, 1))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GATNew(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
super(GATNew, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttention(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttention(nhid * nheads, nclass, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, input_0, input_1):
primals_1 = self.attention_0.W
primals_3 = self.attention_0.a1
primals_4 = self.attention_0.a2
primals_2 = self.attention_1.W
primals_7 = self.attention_1.a1
primals_8 = self.attention_1.a2
primals_5 = self.attention_2.W
primals_10 = self.attention_2.a1
primals_11 = self.attention_2.a2
primals_6 = self.attention_3.W
primals_13 = self.attention_3.a1
primals_14 = self.attention_3.a2
primals_15 = self.out_att.W
primals_16 = self.out_att.a1
primals_17 = self.out_att.a2
primals_9 = input_0
primals_12 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17])
return output[0]
|
NightmareNyx/pygcn
|
GAT
| false
| 4,274
|
[
"MIT"
] | 0
|
3972f167ce7fcc41cb21284d75816dfd9a15f7ef
|
https://github.com/NightmareNyx/pygcn/tree/3972f167ce7fcc41cb21284d75816dfd9a15f7ef
|
Auto_Encoder_Model
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Auto_Encoder_Model(nn.Module):
def __init__(self):
super(Auto_Encoder_Model, self).__init__()
self.conv1 = nn.Conv2d(1, 64, padding=1, kernel_size=3)
self.max_pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(64, 32, padding=1, kernel_size=3)
self.max_pool2 = nn.MaxPool2d(2)
self.conv3 = nn.Conv2d(32, 16, padding=1, kernel_size=3)
self.tran_conv1 = nn.ConvTranspose2d(16, 32, kernel_size=3, stride=
2, padding=1, output_padding=1)
self.conv4 = nn.Conv2d(32, 32, kernel_size=3, padding=1)
self.tran_conv2 = nn.ConvTranspose2d(32, 64, kernel_size=3, stride=
2, padding=1, output_padding=1)
self.conv5 = nn.Conv2d(64, 1, kernel_size=3, padding=1)
def forward_pass(self, x):
output = F.relu(self.conv1(x))
output = self.max_pool1(output)
output = F.relu(self.conv2(output))
output = self.max_pool2(output)
output = F.relu(self.conv3(output))
return output
def reconstruct_pass(self, x):
output = F.relu(self.tran_conv1(x))
output = F.relu(self.conv4(output))
output = F.relu(self.tran_conv2(output))
output = torch.sigmoid(self.conv5(output))
return output
def forward(self, x):
output = self.forward_pass(x)
output = self.reconstruct_pass(output)
return output
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (32 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (33 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 16
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_sigmoid_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15) = args
args.clear()
assert_size_stride(primals_1, (64, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (16, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (16, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_11, (32,), (1,))
assert_size_stride(primals_12, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (1, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_15, (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, 64, 64, 64), (262144, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(1048576)](buf1, primals_2,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.float32)
buf3 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(262144)](buf1, buf2,
buf3, 262144, XBLOCK=512, num_warps=8, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(131072)](buf5, primals_5,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 32, 16, 16), (8192, 256, 16, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 32, 16, 16), (8192, 256, 16, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(32768)](buf5, buf6,
buf7, 32768, XBLOCK=128, num_warps=4, num_stages=1)
buf8 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 16, 16, 16), (4096, 256, 16, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(16384)](buf9, primals_7,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf10 = extern_kernels.convolution(buf9, primals_8, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(1, 1), groups=1, bias=None)
assert_size_stride(buf10, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_2[grid(131072)](buf11, primals_9,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_9
buf12 = extern_kernels.convolution(buf11, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_2[grid(131072)](buf13, primals_11,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_11
buf14 = extern_kernels.convolution(buf13, primals_12, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(1, 1), groups=1, bias=None)
assert_size_stride(buf14, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_relu_0[grid(1048576)](buf15,
primals_13, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf16 = extern_kernels.convolution(buf15, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf17 = buf16
del buf16
triton_poi_fused_convolution_sigmoid_5[grid(16384)](buf17,
primals_15, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_15
return (buf17, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, buf1, buf2, buf3, buf5, buf6,
buf7, buf9, buf11, buf13, buf15, buf17)
class Auto_Encoder_ModelNew(nn.Module):
def __init__(self):
super(Auto_Encoder_ModelNew, self).__init__()
self.conv1 = nn.Conv2d(1, 64, padding=1, kernel_size=3)
self.max_pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(64, 32, padding=1, kernel_size=3)
self.max_pool2 = nn.MaxPool2d(2)
self.conv3 = nn.Conv2d(32, 16, padding=1, kernel_size=3)
self.tran_conv1 = nn.ConvTranspose2d(16, 32, kernel_size=3, stride=
2, padding=1, output_padding=1)
self.conv4 = nn.Conv2d(32, 32, kernel_size=3, padding=1)
self.tran_conv2 = nn.ConvTranspose2d(32, 64, kernel_size=3, stride=
2, padding=1, output_padding=1)
self.conv5 = nn.Conv2d(64, 1, kernel_size=3, padding=1)
def forward_pass(self, x):
output = F.relu(self.conv1(x))
output = self.max_pool1(output)
output = F.relu(self.conv2(output))
output = self.max_pool2(output)
output = F.relu(self.conv3(output))
return output
def reconstruct_pass(self, x):
output = F.relu(self.tran_conv1(x))
output = F.relu(self.conv4(output))
output = F.relu(self.tran_conv2(output))
output = torch.sigmoid(self.conv5(output))
return output
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.tran_conv1.weight
primals_9 = self.tran_conv1.bias
primals_10 = self.conv4.weight
primals_11 = self.conv4.bias
primals_12 = self.tran_conv2.weight
primals_13 = self.tran_conv2.bias
primals_14 = self.conv5.weight
primals_15 = self.conv5.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
sarahESL/MICCAI19-MedVQA
|
Auto_Encoder_Model
| false
| 4,275
|
[
"MIT"
] | 0
|
aa751cb905f79cd356ad5746f8a0640f1d81b5d2
|
https://github.com/sarahESL/MICCAI19-MedVQA/tree/aa751cb905f79cd356ad5746f8a0640f1d81b5d2
|
ZeroLayer
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class ZeroLayer(nn.Module):
def __init__(self, stride):
super(ZeroLayer, self).__init__()
self.stride = stride
def forward(self, x):
"""n, c, h, w = x.size()
h //= self.stride
w //= self.stride
device = x.get_device() if x.is_cuda else torch.device('cpu')
# noinspection PyUnresolvedReferences
padding = torch.zeros(n, c, h, w, device=device, requires_grad=False)
return padding"""
return x * 0
@staticmethod
def is_zero_layer():
return True
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'stride': 1}]
|
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
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 ZeroLayerNew(nn.Module):
def __init__(self, stride):
super(ZeroLayerNew, self).__init__()
self.stride = stride
@staticmethod
def is_zero_layer():
return True
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
savan77/nni
|
ZeroLayer
| false
| 4,276
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
FCNet
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class FCNet(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.l1 = nn.Linear(input_size, 5)
self.relu = nn.ReLU()
self.l2 = nn.Linear(5, output_size)
def forward(self, x):
output = self.l1(x)
output = self.relu(output)
output = self.l2(output)
return output.view(-1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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
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 = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 5
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (5, 4), (4, 1))
assert_size_stride(primals_2, (5,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 5), (5, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 5), (5, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 5), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 5), (80, 20, 5, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 5), (80, 20, 5, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(320)](buf1,
primals_2, buf3, 320, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 5), (
5, 1), 0), reinterpret_tensor(primals_4, (5, 4), (1, 5), 0),
alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (256,), (1,), 0), reinterpret_tensor(
primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(buf1, (64, 5), (
5, 1), 0), primals_4, buf3
class FCNetNew(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.l1 = nn.Linear(input_size, 5)
self.relu = nn.ReLU()
self.l2 = nn.Linear(5, output_size)
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_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
savan77/nni
|
FCNet
| false
| 4,277
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
LinearCombine
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.nn.functional as F
class LinearCombine(nn.Module):
def __init__(self, layers_num, trainable=True, input_aware=False,
word_level=False):
super(LinearCombine, self).__init__()
self.input_aware = input_aware
self.word_level = word_level
if input_aware:
raise NotImplementedError('Input aware is not supported.')
self.w = nn.Parameter(torch.full((layers_num, 1, 1, 1), 1.0 /
layers_num), requires_grad=trainable)
def forward(self, seq):
nw = F.softmax(self.w, dim=0)
seq = torch.mul(seq, nw)
seq = torch.sum(seq, dim=0)
return seq
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'layers_num': 1}]
|
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.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__softmax_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp7 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp10 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp13 = tl.load(in_ptr0 + (192 + x0), xmask)
tmp3 = tmp2 - tmp2
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp4 / tmp4
tmp6 = tmp0 * tmp5
tmp8 = tmp7 * tmp5
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp5
tmp12 = tmp9 + tmp11
tmp14 = tmp13 * tmp5
tmp15 = tmp12 + tmp14
tl.store(out_ptr0 + x0, tmp15, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 1, 1), (1, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_mul_sum_0[grid(64)](primals_2, primals_1,
buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
return buf0, primals_1, primals_2
class LinearCombineNew(nn.Module):
def __init__(self, layers_num, trainable=True, input_aware=False,
word_level=False):
super(LinearCombineNew, self).__init__()
self.input_aware = input_aware
self.word_level = word_level
if input_aware:
raise NotImplementedError('Input aware is not supported.')
self.w = nn.Parameter(torch.full((layers_num, 1, 1, 1), 1.0 /
layers_num), requires_grad=trainable)
def forward(self, input_0):
primals_1 = self.w
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
savan77/nni
|
LinearCombine
| false
| 4,278
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
TorchAdd
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class TorchAdd(nn.Module):
"""
TorchAdd Module.
"""
def forward(self, input_list):
return input_list[0] + input_list[1]
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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_add_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0), xmask)
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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class TorchAddNew(nn.Module):
"""
TorchAdd Module.
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
savan77/nni
|
TorchAdd
| false
| 4,279
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
ActorCritic
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.nn.functional as F
class ActorCritic(nn.Module):
def __init__(self, num_states, num_actions, hidden_size):
super(ActorCritic, self).__init__()
self.num_actions = num_actions
self.fc = nn.Linear(num_states, hidden_size)
self.critic_linear2 = nn.Linear(hidden_size, 1)
self.actor_linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, state):
x = F.relu(self.fc(state))
value = self.critic_linear2(x)
policy_dist = F.softmax(self.actor_linear2(x))
return value, policy_dist
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_states': 4, 'num_actions': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 4), (4, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf7, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
return reinterpret_tensor(buf3, (4, 4, 4, 1), (16, 4, 1, 1), 0
), buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0
), buf6, primals_6, primals_4, buf7
class ActorCriticNew(nn.Module):
def __init__(self, num_states, num_actions, hidden_size):
super(ActorCriticNew, self).__init__()
self.num_actions = num_actions
self.fc = nn.Linear(num_states, hidden_size)
self.critic_linear2 = nn.Linear(hidden_size, 1)
self.actor_linear2 = nn.Linear(hidden_size, num_actions)
def forward(self, input_0):
primals_1 = self.fc.weight
primals_2 = self.fc.bias
primals_4 = self.critic_linear2.weight
primals_5 = self.critic_linear2.bias
primals_6 = self.actor_linear2.weight
primals_7 = self.actor_linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
savan77/nni
|
ActorCritic
| false
| 4,280
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
LipschitzCube
|
import torch
from torch import nn
import torch.utils.data.distributed
class LipschitzCube(nn.Module):
def forward(self, x):
return (x >= 1) * (x - 2 / 3) + (x <= -1) * (x + 2 / 3) + (x > -1) * (x
< 1) * x ** 3 / 3
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_ge_gt_le_lt_mul_pow_sub_0(in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 >= tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = 0.6666666666666666
tmp5 = tmp0 - tmp4
tmp6 = tmp3 * tmp5
tmp7 = -1.0
tmp8 = tmp0 <= tmp7
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp0 + tmp4
tmp11 = tmp9 * tmp10
tmp12 = tmp6 + tmp11
tmp13 = tmp0 > tmp7
tmp14 = tmp0 < tmp1
tmp15 = tmp13 & tmp14
tmp16 = tmp15.to(tl.float32)
tmp17 = tmp0 * tmp0
tmp18 = tmp17 * tmp0
tmp19 = tmp16 * tmp18
tmp20 = 0.3333333333333333
tmp21 = tmp19 * tmp20
tmp22 = tmp12 + tmp21
tl.store(out_ptr0 + x0, tmp22, 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_ge_gt_le_lt_mul_pow_sub_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LipschitzCubeNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
rh-ia/color-information
|
LipschitzCube
| false
| 4,281
|
[
"MIT"
] | 0
|
e912a1667e4fffb339dbc574c85020ec6cf78b02
|
https://github.com/rh-ia/color-information/tree/e912a1667e4fffb339dbc574c85020ec6cf78b02
|
ExtendedModel
|
import torch
import torch.nn as nn
class ExtendedModel(nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we instantiate two nn.Linear modules and assign them as
member variables.
"""
super(ExtendedModel, self).__init__()
self.linear1 = nn.Linear(D_in, H)
self.linear2 = nn.Linear(H, D_out)
def forward(self, x, bias=0.0):
"""
In the forward function we accept a Tensor of input data and an optional bias
"""
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred + bias
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'D_in': 4, 'H': 4, 'D_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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clamp_ge_0(in_ptr0, 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 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = tmp2 >= tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 + tmp3
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, (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.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.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_clamp_ge_0[grid(256)](buf0, primals_2, buf1, buf4,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = buf0
del buf0
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_add_1[grid(256)](buf3, primals_5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_5
return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), primals_4, buf4
class ExtendedModelNew(nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we instantiate two nn.Linear modules and assign them as
member variables.
"""
super(ExtendedModelNew, self).__init__()
self.linear1 = nn.Linear(D_in, H)
self.linear2 = nn.Linear(H, D_out)
def forward(self, input_0):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
sauyon/BentoML
|
ExtendedModel
| false
| 4,282
|
[
"Apache-2.0"
] | 0
|
ff702f1fc1ee7cc4cf7aab2e67d1e27512858fe4
|
https://github.com/sauyon/BentoML/tree/ff702f1fc1ee7cc4cf7aab2e67d1e27512858fe4
|
FullSort
|
import torch
from torch import nn
import torch.utils.data.distributed
class FullSort(nn.Module):
def forward(self, x):
return torch.sort(x, 1)[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
from torch._inductor.runtime import triton_helpers
from torch import nn
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_sort_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = r2
tmp2 = tmp1.to(tl.int16)
tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp4 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5, _tmp6 = triton_helpers.sort_with_index(tmp3, tmp4, None, 1,
stable=False, descending=False)
tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp5, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_sort_0[grid(64)](arg0_1, buf0, 64, 4, XBLOCK=1,
num_warps=2, num_stages=1)
del arg0_1
return buf0,
class FullSortNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
rh-ia/color-information
|
FullSort
| false
| 4,283
|
[
"MIT"
] | 0
|
e912a1667e4fffb339dbc574c85020ec6cf78b02
|
https://github.com/rh-ia/color-information/tree/e912a1667e4fffb339dbc574c85020ec6cf78b02
|
Clamp
|
import torch
from torch import nn
import torch.utils.data
class Clamp(nn.Module):
def __init__(self, min_out=-3, max_out=3):
super().__init__()
self.min_out = min_out
self.max_out = max_out
def forward(self, input):
return input.clamp(self.min_out, self.max_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 import triton_helpers
from torch import nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@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 = -3.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = 3.0
tmp4 = triton_helpers.minimum(tmp2, tmp3)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ClampNew(nn.Module):
def __init__(self, min_out=-3, max_out=3):
super().__init__()
self.min_out = min_out
self.max_out = max_out
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
sbuschjaeger/Pysembles
|
Clamp
| false
| 4,284
|
[
"MIT"
] | 0
|
7e69b0975a7d4373242c7026ade6c5fdbad4fe67
|
https://github.com/sbuschjaeger/Pysembles/tree/7e69b0975a7d4373242c7026ade6c5fdbad4fe67
|
SpatialAttentionGate
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.nn.functional as F
class SpatialAttentionGate(nn.Module):
def __init__(self, channel, reduction=16):
super(SpatialAttentionGate, self).__init__()
self.fc1 = nn.Conv2d(channel, reduction, kernel_size=1, padding=0)
self.fc2 = nn.Conv2d(reduction, 1, kernel_size=1, padding=0)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x, inplace=True)
x = self.fc2(x)
x = torch.sigmoid(x)
return x
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.parallel
import torch.optim
import torch.utils.data
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_sigmoid_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (16, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 16, 1, 1), (16, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 16, 4, 4), (256, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(1024)](buf1, primals_2,
1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 4, 4), (16, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_sigmoid_1[grid(64)](buf3, primals_5,
64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1, buf3
class SpatialAttentionGateNew(nn.Module):
def __init__(self, channel, reduction=16):
super(SpatialAttentionGateNew, self).__init__()
self.fc1 = nn.Conv2d(channel, reduction, kernel_size=1, padding=0)
self.fc2 = nn.Conv2d(reduction, 1, kernel_size=1, padding=0)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
savan77/nni
|
SpatialAttentionGate
| false
| 4,285
|
[
"MIT"
] | 0
|
510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
https://github.com/savan77/nni/tree/510213393d9cae58c5a8cccd21f322f7bba4e0cf
|
FlexibleDropout
|
import torch
import torch.nn as nn
from torch.distributions import Bernoulli
class FlexibleDropout(nn.Module):
"""FlexibleDropout disconnects the sampling step from the masking step of dropout.
There are two important differences between FlexibleDropout and nn.Dropout. First, FlexibleDropout exposes a
sample_mask and apply_mask function, that allows for the same mask to be used repeatedly. Second, FlexibleDropout
scales the input at test time with p, as opposed to scaling with 1/p at training time. This is convenient when
Dropout is used for uncertainty estimation.
"""
def __init__(self):
super().__init__()
def forward(self, input, p, shape=None):
"""Similar to F.dropout, a mask is sampled and directly applied to the input."""
if shape is None:
self.sample_mask(p, input.shape)
else:
self.sample_mask(p, shape)
return self.apply_mask(input)
def apply_mask(self, input):
"""Applies the sampled mask to the input."""
return input * self._mask
def sample_mask(self, p, shape):
"""Samples a dropout mask from a Bernoulli distribution.
Args:
p(float): the dropout probability [0, 1].
shape(torch.Size): shape of the mask to be sampled.
"""
if self.training:
self._mask = Bernoulli(1.0 - p).sample(shape)
else:
self._mask = 1.0 - p
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from torch.distributions import Bernoulli
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_rsub_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)
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp3 * tmp2
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp4, 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_mul_rsub_0[grid(256)](arg1_1, arg0_1, buf0, buf1,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf1, buf0
class FlexibleDropoutNew(nn.Module):
"""FlexibleDropout disconnects the sampling step from the masking step of dropout.
There are two important differences between FlexibleDropout and nn.Dropout. First, FlexibleDropout exposes a
sample_mask and apply_mask function, that allows for the same mask to be used repeatedly. Second, FlexibleDropout
scales the input at test time with p, as opposed to scaling with 1/p at training time. This is convenient when
Dropout is used for uncertainty estimation.
"""
def __init__(self):
super().__init__()
def apply_mask(self, input):
"""Applies the sampled mask to the input."""
return input * self._mask
def sample_mask(self, p, shape):
"""Samples a dropout mask from a Bernoulli distribution.
Args:
p(float): the dropout probability [0, 1].
shape(torch.Size): shape of the mask to be sampled.
"""
if self.training:
self._mask = Bernoulli(1.0 - p).sample(shape)
else:
self._mask = 1.0 - p
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
scfrank/deep-generative-lm
|
FlexibleDropout
| false
| 4,286
|
[
"MIT"
] | 0
|
70067fcda82aa035bba805ce6c2709097166a7a4
|
https://github.com/scfrank/deep-generative-lm/tree/70067fcda82aa035bba805ce6c2709097166a7a4
|
BertImagePooler
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.multiprocessing
class BertImagePooler(nn.Module):
def __init__(self, config):
super(BertImagePooler, self).__init__()
self.dense = nn.Linear(config.v_hidden_size, config.bi_hidden_size)
self.activation = nn.ReLU()
def forward(self, hidden_states):
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(v_hidden_size=4, bi_hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_1[grid(64)](buf2,
primals_3, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf3
class BertImagePoolerNew(nn.Module):
def __init__(self, config):
super(BertImagePoolerNew, self).__init__()
self.dense = nn.Linear(config.v_hidden_size, config.bi_hidden_size)
self.activation = nn.ReLU()
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ayushjain1144/vilbert-multi-task
|
BertImagePooler
| false
| 4,287
|
[
"MIT"
] | 0
|
cf30feee9617dd92bb030f380f8b59388b7054f6
|
https://github.com/ayushjain1144/vilbert-multi-task/tree/cf30feee9617dd92bb030f380f8b59388b7054f6
|
LipNormConv2d
|
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.data.distributed
def _max_except_dim(input, dim):
maxed = input
for axis in range(input.ndimension() - 1, dim, -1):
maxed, _ = maxed.max(axis, keepdim=True)
for axis in range(dim - 1, -1, -1):
maxed, _ = maxed.max(axis, keepdim=True)
return maxed
def _norm_except_dim(w, norm_type, dim):
if norm_type == 1 or norm_type == 2:
return torch.norm_except_dim(w, norm_type, dim)
elif norm_type == float('inf'):
return _max_except_dim(w, dim)
def operator_norm_settings(domain, codomain):
if domain == 1 and codomain == 1:
max_across_input_dims = True
norm_type = 1
elif domain == 1 and codomain == 2:
max_across_input_dims = True
norm_type = 2
elif domain == 1 and codomain == float('inf'):
max_across_input_dims = True
norm_type = float('inf')
elif domain == 2 and codomain == float('inf'):
max_across_input_dims = False
norm_type = 2
elif domain == float('inf') and codomain == float('inf'):
max_across_input_dims = False
norm_type = 1
else:
raise ValueError('Unknown combination of domain "{}" and codomain "{}"'
.format(domain, codomain))
return max_across_input_dims, norm_type
def _logit(p):
p = torch.max(torch.ones(1) * 0.1, torch.min(torch.ones(1) * 0.9, p))
return torch.log(p + 1e-10) + torch.log(1 - p + 1e-10)
class LipNormConv2d(nn.Conv2d):
"""Lipschitz constant defined using operator norms."""
def __init__(self, in_channels, out_channels, kernel_size, stride,
padding, bias=True, coeff=0.97, domain=float('inf'), codomain=float
('inf'), local_constraint=True, **unused_kwargs):
del unused_kwargs
super(LipNormConv2d, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, bias)
self.coeff = coeff
self.domain = domain
self.codomain = codomain
self.local_constraint = local_constraint
max_across_input_dims, self.norm_type = operator_norm_settings(self
.domain, self.codomain)
self.max_across_dim = 1 if max_across_input_dims else 0
with torch.no_grad():
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=
self.max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
self.scale = nn.Parameter(_logit(w_scale / self.coeff))
def compute_weight(self):
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=self.
max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
return self.weight / w_scale * torch.sigmoid(self.scale)
def forward(self, input):
weight = self.compute_weight()
return F.conv2d(input, weight, self.bias, self.stride, self.padding,
1, 1)
def extra_repr(self):
s = super(LipNormConv2d, self).extra_repr()
return s + ', coeff={}, domain={}, codomain={}, local={}'.format(self
.coeff, self.domain, self.codomain, self.local_constraint)
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.triton_helpers import math as tl_math
from torch import nn
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_div_mul_norm_sigmoid_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl_math.abs(tmp0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = tmp0 / tmp5
tmp8 = tl.sigmoid(tmp7)
tmp9 = tmp6 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp5, xmask)
tl.store(out_ptr0 + (r1 + 64 * x0), tmp9, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 1296
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 81 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_mul_norm_sigmoid_0[grid(4)](buf1, primals_1,
primals_2, buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = extern_kernels.convolution(primals_4, buf2, stride=(1, 1),
padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 9, 9), (324, 81, 9, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_1[grid(1296)](buf4, primals_3, 1296,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf4, primals_1, primals_2, primals_4, reinterpret_tensor(buf1,
(4, 1, 1, 1), (1, 1, 1, 1), 0), buf2
def _max_except_dim(input, dim):
maxed = input
for axis in range(input.ndimension() - 1, dim, -1):
maxed, _ = maxed.max(axis, keepdim=True)
for axis in range(dim - 1, -1, -1):
maxed, _ = maxed.max(axis, keepdim=True)
return maxed
def _norm_except_dim(w, norm_type, dim):
if norm_type == 1 or norm_type == 2:
return torch.norm_except_dim(w, norm_type, dim)
elif norm_type == float('inf'):
return _max_except_dim(w, dim)
def operator_norm_settings(domain, codomain):
if domain == 1 and codomain == 1:
max_across_input_dims = True
norm_type = 1
elif domain == 1 and codomain == 2:
max_across_input_dims = True
norm_type = 2
elif domain == 1 and codomain == float('inf'):
max_across_input_dims = True
norm_type = float('inf')
elif domain == 2 and codomain == float('inf'):
max_across_input_dims = False
norm_type = 2
elif domain == float('inf') and codomain == float('inf'):
max_across_input_dims = False
norm_type = 1
else:
raise ValueError('Unknown combination of domain "{}" and codomain "{}"'
.format(domain, codomain))
return max_across_input_dims, norm_type
def _logit(p):
p = torch.max(torch.ones(1) * 0.1, torch.min(torch.ones(1) * 0.9, p))
return torch.log(p + 1e-10) + torch.log(1 - p + 1e-10)
class LipNormConv2dNew(nn.Conv2d):
"""Lipschitz constant defined using operator norms."""
def __init__(self, in_channels, out_channels, kernel_size, stride,
padding, bias=True, coeff=0.97, domain=float('inf'), codomain=float
('inf'), local_constraint=True, **unused_kwargs):
del unused_kwargs
super(LipNormConv2dNew, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, bias)
self.coeff = coeff
self.domain = domain
self.codomain = codomain
self.local_constraint = local_constraint
max_across_input_dims, self.norm_type = operator_norm_settings(self
.domain, self.codomain)
self.max_across_dim = 1 if max_across_input_dims else 0
with torch.no_grad():
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=
self.max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
self.scale = nn.Parameter(_logit(w_scale / self.coeff))
def compute_weight(self):
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=self.
max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
return self.weight / w_scale * torch.sigmoid(self.scale)
def extra_repr(self):
s = super(LipNormConv2dNew, self).extra_repr()
return s + ', coeff={}, domain={}, codomain={}, local={}'.format(self
.coeff, self.domain, self.codomain, self.local_constraint)
def forward(self, input_0):
primals_1 = self.weight
primals_3 = self.bias
primals_2 = self.scale
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
rh-ia/color-information
|
LipNormConv2d
| false
| 4,288
|
[
"MIT"
] | 0
|
e912a1667e4fffb339dbc574c85020ec6cf78b02
|
https://github.com/rh-ia/color-information/tree/e912a1667e4fffb339dbc574c85020ec6cf78b02
|
RelevanceVector
|
import torch
import torch.nn as nn
class RelevanceVector(nn.Module):
def __init__(self, z_dim):
super(RelevanceVector, self).__init__()
self.rvlogit = nn.Parameter(0.001 * torch.randn(z_dim))
def forward(self):
rv = torch.sigmoid(self.rvlogit)
return self.rvlogit, rv
def get_inputs():
return []
def get_init_inputs():
return [[], {'z_dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_sigmoid_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, = args
args.clear()
assert_size_stride(primals_1, (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_sigmoid_0[grid(4)](primals_1, buf0, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_1
return buf0, buf0
class RelevanceVectorNew(nn.Module):
def __init__(self, z_dim):
super(RelevanceVectorNew, self).__init__()
self.rvlogit = nn.Parameter(0.001 * torch.randn(z_dim))
def forward(self):
primals_1 = self.rvlogit
output = call([primals_1])
return output[0], output[1]
|
seqam-lab/rfvae
|
RelevanceVector
| false
| 4,289
|
[
"MIT"
] | 0
|
07089e2cca6d51f305731750c2c67b83a42df12a
|
https://github.com/seqam-lab/rfvae/tree/07089e2cca6d51f305731750c2c67b83a42df12a
|
QNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64, fc2=128):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2 (int): Number of nodes in the hidden layers
"""
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2)
self.fc3 = nn.Linear(fc2, action_size)
def forward(self, state):
"""Build a network that maps state -> action values."""
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
return self.fc3(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 64), (64, 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, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf6, 4096, XBLOCK=256, 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, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 128), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf3,
primals_5, buf5, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_6, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(
buf3, (64, 128), (128, 1), 0), primals_6, buf5, primals_4, buf6
class QNetworkNew(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64, fc2=128):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2 (int): Number of nodes in the hidden layers
"""
super(QNetworkNew, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2)
self.fc3 = nn.Linear(fc2, action_size)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
schottkey7/deep-reinforcement-learning
|
QNetwork
| false
| 4,290
|
[
"MIT"
] | 0
|
92c97fadbb5b95caa3fd3813a0757debc2c2747a
|
https://github.com/schottkey7/deep-reinforcement-learning/tree/92c97fadbb5b95caa3fd3813a0757debc2c2747a
|
LipNormLinear
|
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.data.distributed
def _max_except_dim(input, dim):
maxed = input
for axis in range(input.ndimension() - 1, dim, -1):
maxed, _ = maxed.max(axis, keepdim=True)
for axis in range(dim - 1, -1, -1):
maxed, _ = maxed.max(axis, keepdim=True)
return maxed
def _norm_except_dim(w, norm_type, dim):
if norm_type == 1 or norm_type == 2:
return torch.norm_except_dim(w, norm_type, dim)
elif norm_type == float('inf'):
return _max_except_dim(w, dim)
def operator_norm_settings(domain, codomain):
if domain == 1 and codomain == 1:
max_across_input_dims = True
norm_type = 1
elif domain == 1 and codomain == 2:
max_across_input_dims = True
norm_type = 2
elif domain == 1 and codomain == float('inf'):
max_across_input_dims = True
norm_type = float('inf')
elif domain == 2 and codomain == float('inf'):
max_across_input_dims = False
norm_type = 2
elif domain == float('inf') and codomain == float('inf'):
max_across_input_dims = False
norm_type = 1
else:
raise ValueError('Unknown combination of domain "{}" and codomain "{}"'
.format(domain, codomain))
return max_across_input_dims, norm_type
def _logit(p):
p = torch.max(torch.ones(1) * 0.1, torch.min(torch.ones(1) * 0.9, p))
return torch.log(p + 1e-10) + torch.log(1 - p + 1e-10)
class LipNormLinear(nn.Linear):
"""Lipschitz constant defined using operator norms."""
def __init__(self, in_features, out_features, bias=True, coeff=0.97,
domain=float('inf'), codomain=float('inf'), local_constraint=True,
**unused_kwargs):
del unused_kwargs
super(LipNormLinear, self).__init__(in_features, out_features, bias)
self.coeff = coeff
self.domain = domain
self.codomain = codomain
self.local_constraint = local_constraint
max_across_input_dims, self.norm_type = operator_norm_settings(self
.domain, self.codomain)
self.max_across_dim = 1 if max_across_input_dims else 0
with torch.no_grad():
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=
self.max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
self.scale = nn.Parameter(_logit(w_scale / self.coeff))
def compute_weight(self):
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=self.
max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
return self.weight / w_scale * torch.sigmoid(self.scale) * self.coeff
def forward(self, input):
weight = self.compute_weight()
return F.linear(input, weight, self.bias)
def extra_repr(self):
s = super(LipNormLinear, self).extra_repr()
return s + ', coeff={}, domain={}, codomain={}, local={}'.format(self
.coeff, self.domain, self.codomain, self.local_constraint)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_mul_sigmoid_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
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')
tmp13 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl_math.abs(tmp1)
tmp4 = tl_math.abs(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.abs(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.abs(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tmp0 / tmp11
tmp14 = tl.sigmoid(tmp13)
tmp15 = tmp12 * tmp14
tmp16 = 0.97
tmp17 = tmp15 * tmp16
tl.store(out_ptr0 + x2, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 1), (1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_mul_sigmoid_0[grid(16)](primals_1, primals_2,
buf0, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf1 = 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(buf0, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del buf0
del primals_3
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, primals_2, reinterpret_tensor(primals_4, (64, 4), (4,
1), 0)
def _max_except_dim(input, dim):
maxed = input
for axis in range(input.ndimension() - 1, dim, -1):
maxed, _ = maxed.max(axis, keepdim=True)
for axis in range(dim - 1, -1, -1):
maxed, _ = maxed.max(axis, keepdim=True)
return maxed
def _norm_except_dim(w, norm_type, dim):
if norm_type == 1 or norm_type == 2:
return torch.norm_except_dim(w, norm_type, dim)
elif norm_type == float('inf'):
return _max_except_dim(w, dim)
def operator_norm_settings(domain, codomain):
if domain == 1 and codomain == 1:
max_across_input_dims = True
norm_type = 1
elif domain == 1 and codomain == 2:
max_across_input_dims = True
norm_type = 2
elif domain == 1 and codomain == float('inf'):
max_across_input_dims = True
norm_type = float('inf')
elif domain == 2 and codomain == float('inf'):
max_across_input_dims = False
norm_type = 2
elif domain == float('inf') and codomain == float('inf'):
max_across_input_dims = False
norm_type = 1
else:
raise ValueError('Unknown combination of domain "{}" and codomain "{}"'
.format(domain, codomain))
return max_across_input_dims, norm_type
def _logit(p):
p = torch.max(torch.ones(1) * 0.1, torch.min(torch.ones(1) * 0.9, p))
return torch.log(p + 1e-10) + torch.log(1 - p + 1e-10)
class LipNormLinearNew(nn.Linear):
"""Lipschitz constant defined using operator norms."""
def __init__(self, in_features, out_features, bias=True, coeff=0.97,
domain=float('inf'), codomain=float('inf'), local_constraint=True,
**unused_kwargs):
del unused_kwargs
super(LipNormLinearNew, self).__init__(in_features, out_features, bias)
self.coeff = coeff
self.domain = domain
self.codomain = codomain
self.local_constraint = local_constraint
max_across_input_dims, self.norm_type = operator_norm_settings(self
.domain, self.codomain)
self.max_across_dim = 1 if max_across_input_dims else 0
with torch.no_grad():
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=
self.max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
self.scale = nn.Parameter(_logit(w_scale / self.coeff))
def compute_weight(self):
w_scale = _norm_except_dim(self.weight, self.norm_type, dim=self.
max_across_dim)
if not self.local_constraint:
w_scale = w_scale.max()
return self.weight / w_scale * torch.sigmoid(self.scale) * self.coeff
def extra_repr(self):
s = super(LipNormLinearNew, self).extra_repr()
return s + ', coeff={}, domain={}, codomain={}, local={}'.format(self
.coeff, self.domain, self.codomain, self.local_constraint)
def forward(self, input_0):
primals_1 = self.weight
primals_3 = self.bias
primals_2 = self.scale
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
rh-ia/color-information
|
LipNormLinear
| false
| 4,291
|
[
"MIT"
] | 0
|
e912a1667e4fffb339dbc574c85020ec6cf78b02
|
https://github.com/rh-ia/color-information/tree/e912a1667e4fffb339dbc574c85020ec6cf78b02
|
Net1
|
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.nn.functional as F
class Net1(nn.Module):
def __init__(self):
super(Net1, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = torch.flatten(x, 1)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 492032
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3844 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 3600 % 64
x0 = xindex % 3600
x4 = xindex // 3600
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x0 + 3616 * x4), tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 230400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 30
x1 = xindex // 30 % 30
x2 = xindex // 900
x3 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 120 * x1 + 3616 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 120 * x1 + 3616 * x2), xmask,
eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (60 + 2 * x0 + 120 * x1 + 3616 * x2), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (61 + 2 * x0 + 120 * x1 + 3616 * x2), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x3, tmp15, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (32, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (64,), (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, 32, 62, 62), (123008, 3844, 62, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(492032)](buf1, primals_2,
492032, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 64, 60, 60), (230400, 3600, 60, 1))
buf3 = empty_strided_cuda((4, 64, 60, 60), (231424, 3616, 60, 1),
torch.float32)
triton_poi_fused_convolution_relu_1[grid(921600)](buf2, primals_5,
buf3, 921600, XBLOCK=1024, num_warps=4, num_stages=1)
del buf2
del primals_5
buf4 = empty_strided_cuda((4, 64, 30, 30), (57600, 900, 30, 1),
torch.int8)
buf5 = empty_strided_cuda((4, 64, 30, 30), (57600, 900, 30, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_2[grid(230400)](buf3, buf4,
buf5, 230400, XBLOCK=512, num_warps=8, num_stages=1)
return reinterpret_tensor(buf5, (4, 57600), (57600, 1), 0
), primals_1, primals_3, primals_4, buf1, buf3, buf4
class Net1New(nn.Module):
def __init__(self):
super(Net1New, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
sermolin/amazon-sagemaker-examples
|
Net1
| false
| 4,292
|
[
"Apache-2.0"
] | 0
|
3e6083d1b53cb718893a04c46513a9482a17bd6b
|
https://github.com/sermolin/amazon-sagemaker-examples/tree/3e6083d1b53cb718893a04c46513a9482a17bd6b
|
DemodulatedConv2d
|
import torch
import torch.utils.data
import torch
from torchvision.transforms import functional as F
import torch.nn as nn
from torch.nn import functional as F
class DemodulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size=3, stride=1,
padding=0, bias=False, dilation=1):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.bias = None
if bias:
self.bias = nn.Parameter(torch.randn(out_channel))
self.stride = stride
self.padding = padding
self.dilation = dilation
def forward(self, input):
batch, in_channel, height, width = input.shape
demod = torch.rsqrt(self.weight.pow(2).sum([2, 3, 4]) + 1e-08)
weight = self.weight * demod.repeat([batch, 1]).view(batch, self.
out_channel, 1, 1, 1)
weight = weight.view(batch * self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
input = input.view(1, batch * in_channel, height, width)
if self.bias is None:
out = F.conv2d(input, weight, padding=self.padding, groups=
batch, dilation=self.dilation, stride=self.stride)
else:
out = F.conv2d(input, weight, bias=self.bias, padding=self.
padding, groups=batch, dilation=self.dilation, stride=self.
stride)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_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.triton_helpers import libdevice
import torch.utils.data
import torch
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_pow_rsqrt_sum_0(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 36
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 36 * x0), rmask & xmask, other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(rmask & xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = 1e-08
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_repeat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
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_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 144
x4 = xindex // 36
x5 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x5, tmp2, 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, (1, 4, 4, 3, 3), (144, 36, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_pow_rsqrt_sum_0[grid(4)](buf1, primals_2, 4,
36, XBLOCK=1, num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_repeat_1[grid(16)](buf1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 3, 3), (144, 36, 9, 3, 1),
torch.float32)
triton_poi_fused_mul_2[grid(576)](primals_2, buf2, buf3, 576,
XBLOCK=256, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (16, 4,
3, 3), (36, 9, 3, 1), 0), stride=(1, 1), padding=(0, 0),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf4, (1, 16, 2, 2), (64, 4, 2, 1))
return reinterpret_tensor(buf4, (4, 4, 2, 2), (16, 4, 2, 1), 0
), primals_2, buf1, buf2, reinterpret_tensor(buf3, (16, 4, 3, 3), (
36, 9, 3, 1), 0), reinterpret_tensor(primals_1, (1, 16, 4, 4), (256,
16, 4, 1), 0)
class DemodulatedConv2dNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size=3, stride=1,
padding=0, bias=False, dilation=1):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.bias = None
if bias:
self.bias = nn.Parameter(torch.randn(out_channel))
self.stride = stride
self.padding = padding
self.dilation = dilation
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
seawee1/ForkGAN-pytorch
|
DemodulatedConv2d
| false
| 4,293
|
[
"BSD-3-Clause"
] | 0
|
02d721875d47e4a1e96a14cc4770edcb6b68a5d0
|
https://github.com/seawee1/ForkGAN-pytorch/tree/02d721875d47e4a1e96a14cc4770edcb6b68a5d0
|
ATLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ATLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, logits, labels):
th_label = torch.zeros_like(labels, dtype=torch.float)
th_label[:, 0] = 1.0
labels[:, 0] = 0.0
p_mask = labels + th_label
n_mask = 1 - labels
logit1 = logits - (1 - p_mask) * 1e+30
loss1 = -(F.log_softmax(logit1, dim=-1) * labels).sum(1)
logit2 = logits - (1 - n_mask) * 1e+30
loss2 = -(F.log_softmax(logit2, dim=-1) * th_label).sum(1)
loss = loss1 + loss2
loss = loss.mean()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
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_fill_lift_fresh_0(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
tmp0 = 0.0
tl.store(out_ptr0 + (x0 + 64 * x1), tmp0, xmask)
@triton.jit
def triton_poi_fused__log_softmax_add_fill_lift_fresh_mul_rsub_sub_zeros_like_1(
in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_ptr0 + 4 * x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x3, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr0 + (1 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + (1 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (2 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp27 = tl.load(in_ptr0 + (3 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp28 = tl.load(in_ptr1 + (3 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp2 = x1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp5 = 1.0
tmp6 = 0.0
tmp7 = tl.where(tmp4, tmp5, tmp6)
tmp8 = tmp1 + tmp7
tmp9 = tmp5 - tmp8
tmp10 = 1e+30
tmp11 = tmp9 * tmp10
tmp12 = tmp0 - tmp11
tmp15 = tmp14 + tmp7
tmp16 = tmp5 - tmp15
tmp17 = tmp16 * tmp10
tmp18 = tmp13 - tmp17
tmp19 = triton_helpers.maximum(tmp12, tmp18)
tmp22 = tmp21 + tmp7
tmp23 = tmp5 - tmp22
tmp24 = tmp23 * tmp10
tmp25 = tmp20 - tmp24
tmp26 = triton_helpers.maximum(tmp19, tmp25)
tmp29 = tmp28 + tmp7
tmp30 = tmp5 - tmp29
tmp31 = tmp30 * tmp10
tmp32 = tmp27 - tmp31
tmp33 = triton_helpers.maximum(tmp26, tmp32)
tmp34 = tmp12 - tmp33
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp18 - tmp33
tmp37 = tl_math.exp(tmp36)
tmp38 = tmp35 + tmp37
tmp39 = tmp25 - tmp33
tmp40 = tl_math.exp(tmp39)
tmp41 = tmp38 + tmp40
tmp42 = tmp32 - tmp33
tmp43 = tl_math.exp(tmp42)
tmp44 = tmp41 + tmp43
tmp45 = tmp5 - tmp1
tmp46 = tmp5 - tmp45
tmp47 = tmp46 * tmp10
tmp48 = tmp0 - tmp47
tmp49 = tmp5 - tmp14
tmp50 = tmp5 - tmp49
tmp51 = tmp50 * tmp10
tmp52 = tmp13 - tmp51
tmp53 = triton_helpers.maximum(tmp48, tmp52)
tmp54 = tmp5 - tmp21
tmp55 = tmp5 - tmp54
tmp56 = tmp55 * tmp10
tmp57 = tmp20 - tmp56
tmp58 = triton_helpers.maximum(tmp53, tmp57)
tmp59 = tmp5 - tmp28
tmp60 = tmp5 - tmp59
tmp61 = tmp60 * tmp10
tmp62 = tmp27 - tmp61
tmp63 = triton_helpers.maximum(tmp58, tmp62)
tmp64 = tmp48 - tmp63
tmp65 = tl_math.exp(tmp64)
tmp66 = tmp52 - tmp63
tmp67 = tl_math.exp(tmp66)
tmp68 = tmp65 + tmp67
tmp69 = tmp57 - tmp63
tmp70 = tl_math.exp(tmp69)
tmp71 = tmp68 + tmp70
tmp72 = tmp62 - tmp63
tmp73 = tl_math.exp(tmp72)
tmp74 = tmp71 + tmp73
tl.store(out_ptr0 + x3, tmp33, xmask)
tl.store(out_ptr1 + x3, tmp44, xmask)
tl.store(out_ptr2 + x3, tmp63, xmask)
tl.store(out_ptr3 + x3, tmp74, xmask)
@triton.jit
def triton_per_fused__log_softmax_add_fill_lift_fresh_mean_mul_neg_rsub_sub_sum_zeros_like_2(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex // 16
r4 = rindex % 16
r1 = rindex // 4 % 4
tmp0 = tl.load(in_ptr0 + (r4 + 64 * r2), None)
tmp1 = tl.load(in_ptr1 + (r4 + 64 * r2), None)
tmp12 = tl.load(in_ptr2 + (r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr3 + (r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (16 + r4 + 64 * r2), None)
tmp19 = tl.load(in_ptr1 + (16 + r4 + 64 * r2), None)
tmp27 = tl.load(in_ptr2 + (4 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr3 + (4 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp34 = tl.load(in_ptr0 + (32 + r4 + 64 * r2), None)
tmp35 = tl.load(in_ptr1 + (32 + r4 + 64 * r2), None)
tmp43 = tl.load(in_ptr2 + (8 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp45 = tl.load(in_ptr3 + (8 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp50 = tl.load(in_ptr0 + (48 + r4 + 64 * r2), None)
tmp51 = tl.load(in_ptr1 + (48 + r4 + 64 * r2), None)
tmp59 = tl.load(in_ptr2 + (12 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp61 = tl.load(in_ptr3 + (12 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp70 = tl.load(in_ptr4 + (r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp72 = tl.load(in_ptr5 + (r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp80 = tl.load(in_ptr4 + (4 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp82 = tl.load(in_ptr5 + (4 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp91 = tl.load(in_ptr4 + (8 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp93 = tl.load(in_ptr5 + (8 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp102 = tl.load(in_ptr4 + (12 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp104 = tl.load(in_ptr5 + (12 + r1 + 16 * r2), None, eviction_policy=
'evict_last')
tmp2 = tl.full([1, 1], 0, tl.int32)
tmp3 = tmp2 == tmp2
tmp4 = 1.0
tmp5 = 0.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp1 + tmp6
tmp8 = tmp4 - tmp7
tmp9 = 1e+30
tmp10 = tmp8 * tmp9
tmp11 = tmp0 - tmp10
tmp13 = tmp11 - tmp12
tmp15 = tl_math.log(tmp14)
tmp16 = tmp13 - tmp15
tmp17 = tmp16 * tmp1
tmp20 = tl.full([1, 1], 1, tl.int32)
tmp21 = tmp20 == tmp2
tmp22 = tl.where(tmp21, tmp4, tmp5)
tmp23 = tmp19 + tmp22
tmp24 = tmp4 - tmp23
tmp25 = tmp24 * tmp9
tmp26 = tmp18 - tmp25
tmp28 = tmp26 - tmp27
tmp30 = tl_math.log(tmp29)
tmp31 = tmp28 - tmp30
tmp32 = tmp31 * tmp19
tmp33 = tmp17 + tmp32
tmp36 = tl.full([1, 1], 2, tl.int32)
tmp37 = tmp36 == tmp2
tmp38 = tl.where(tmp37, tmp4, tmp5)
tmp39 = tmp35 + tmp38
tmp40 = tmp4 - tmp39
tmp41 = tmp40 * tmp9
tmp42 = tmp34 - tmp41
tmp44 = tmp42 - tmp43
tmp46 = tl_math.log(tmp45)
tmp47 = tmp44 - tmp46
tmp48 = tmp47 * tmp35
tmp49 = tmp33 + tmp48
tmp52 = tl.full([1, 1], 3, tl.int32)
tmp53 = tmp52 == tmp2
tmp54 = tl.where(tmp53, tmp4, tmp5)
tmp55 = tmp51 + tmp54
tmp56 = tmp4 - tmp55
tmp57 = tmp56 * tmp9
tmp58 = tmp50 - tmp57
tmp60 = tmp58 - tmp59
tmp62 = tl_math.log(tmp61)
tmp63 = tmp60 - tmp62
tmp64 = tmp63 * tmp51
tmp65 = tmp49 + tmp64
tmp66 = tmp4 - tmp1
tmp67 = tmp4 - tmp66
tmp68 = tmp67 * tmp9
tmp69 = tmp0 - tmp68
tmp71 = tmp69 - tmp70
tmp73 = tl_math.log(tmp72)
tmp74 = tmp71 - tmp73
tmp75 = tmp74 * tmp6
tmp76 = tmp4 - tmp19
tmp77 = tmp4 - tmp76
tmp78 = tmp77 * tmp9
tmp79 = tmp18 - tmp78
tmp81 = tmp79 - tmp80
tmp83 = tl_math.log(tmp82)
tmp84 = tmp81 - tmp83
tmp85 = tmp84 * tmp22
tmp86 = tmp75 + tmp85
tmp87 = tmp4 - tmp35
tmp88 = tmp4 - tmp87
tmp89 = tmp88 * tmp9
tmp90 = tmp34 - tmp89
tmp92 = tmp90 - tmp91
tmp94 = tl_math.log(tmp93)
tmp95 = tmp92 - tmp94
tmp96 = tmp95 * tmp38
tmp97 = tmp86 + tmp96
tmp98 = tmp4 - tmp51
tmp99 = tmp4 - tmp98
tmp100 = tmp99 * tmp9
tmp101 = tmp50 - tmp100
tmp103 = tmp101 - tmp102
tmp105 = tl_math.log(tmp104)
tmp106 = tmp103 - tmp105
tmp107 = tmp106 * tmp54
tmp108 = tmp97 + tmp107
tmp109 = -tmp65
tmp110 = -tmp108
tmp111 = tmp109 + tmp110
tmp112 = tl.broadcast_to(tmp111, [XBLOCK, RBLOCK])
tmp114 = tl.sum(tmp112, 1)[:, None]
tmp115 = 64.0
tmp116 = tmp114 / tmp115
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp116, 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)
get_raw_stream(0)
triton_poi_fused_fill_lift_fresh_0[grid(64)](arg0_1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__log_softmax_add_fill_lift_fresh_mul_rsub_sub_zeros_like_1[
grid(64)](arg1_1, arg0_1, buf1, buf2, buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = buf7
del buf7
triton_per_fused__log_softmax_add_fill_lift_fresh_mean_mul_neg_rsub_sub_sum_zeros_like_2[
grid(1)](buf8, arg1_1, arg0_1, buf1, buf2, buf4, buf5, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del buf1
del buf2
del buf4
del buf5
return buf8,
class ATLossNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
seanswyi/R-BERT
|
ATLoss
| false
| 4,294
|
[
"Apache-2.0"
] | 0
|
4a4aeab3a9314307ce4458bd2b943d94aaf4a706
|
https://github.com/seanswyi/R-BERT/tree/4a4aeab3a9314307ce4458bd2b943d94aaf4a706
|
Planar
|
import torch
import torch.nn as nn
class PlanarStep(nn.Module):
def __init__(self):
super(PlanarStep, self).__init__()
self.h = nn.Tanh()
self.softplus = nn.Softplus()
def _der_h(self, x):
"""Derivative of activation function h."""
return self._der_tanh(x)
def _der_tanh(self, x):
"""Derivative of the Tanh function."""
return 1 - self.h(x) ** 2
def forward(self, zk, u, w, b):
"""
Forward pass. Assumes amortized u, w and b. Conditions on diagonals of u and w for invertibility
will be be satisfied inside this function. Computes the following transformation:
z' = z + u h( w^T z + b)
or actually
z'^T = z^T + h(z^T w + b)u^T
Assumes the following input shapes:
shape u = (batch_size, z_dim, 1)
shape w = (batch_size, 1, z_dim)
shape b = (batch_size, 1, 1)
shape z = (batch_size, z_dim).
"""
zk = zk.unsqueeze(2)
uw = torch.bmm(w, u)
m_uw = -1.0 + self.softplus(uw)
w_norm_sq = torch.sum(w ** 2, dim=2, keepdim=True)
u_hat = u + (m_uw - uw) * w.transpose(2, 1) / w_norm_sq
wzb = torch.bmm(w, zk) + b
z = zk + u_hat * self.h(wzb)
z = z.squeeze(2)
psi = w * self._der_h(wzb)
logdet = torch.log(torch.abs(1 + torch.bmm(psi, u_hat)))
logdet = logdet.squeeze(2).squeeze(1)
return z, logdet
class Error(Exception):
"""Base error class, from which all other errors derive."""
pass
class InvalidArgumentError(Error):
"""This error will be shown when a given argument has an invalid value."""
pass
class NormalizingFlow(nn.Module):
"""Base class for normalizing flows."""
def __init__(self, h_dim, z_dim, flow_depth, hidden_depth):
super(NormalizingFlow, self).__init__()
self.h_dim = h_dim
self.z_dim = z_dim
self.flow_depth = flow_depth
self.hidden_depth = hidden_depth
@property
def flow_depth(self):
return self._flow_depth
@flow_depth.setter
def flow_depth(self, value):
if not isinstance(value, int):
raise InvalidArgumentError('flow_depth should be an integer.')
elif value < 1:
raise InvalidArgumentError(
'flow_depth should be strictly positive.')
else:
self._flow_depth = value
@property
def hidden_depth(self):
return self._hidden_depth
@hidden_depth.setter
def hidden_depth(self, value):
if not isinstance(value, int):
raise InvalidArgumentError('hidden_depth should be an integer.')
elif value < 0:
raise InvalidArgumentError('hidden_depth should be positive.')
else:
self._hidden_depth = value
class Planar(NormalizingFlow):
"""Planar Normalizing flow with single unit bottleneck."""
def __init__(self, h_dim, z_dim, flow_depth):
super(Planar, self).__init__(h_dim, z_dim, flow_depth, 0)
self.flow = PlanarStep()
self.h_to_u = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
self.h_to_w = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
self.h_to_b = nn.Linear(self.h_dim, self.flow_depth)
def forward(self, z, h):
u = self.h_to_u(h).view(-1, self.flow_depth, self.z_dim, 1)
w = self.h_to_w(h).view(-1, self.flow_depth, 1, self.z_dim)
b = self.h_to_b(h).view(-1, self.flow_depth, 1, 1)
z_k = z
logdet = 0.0
for k in range(self.flow_depth):
z_k, ldj = self.flow(z_k, u[:, k, :, :], w[:, k, :, :], b[:, k,
:, :])
logdet += ldj
return z_k, logdet
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'h_dim': 4, 'z_dim': 4, 'flow_depth': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_pow_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
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_out_ptr0 + x0, xmask)
tmp2 = tl.load(in_ptr1 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = tmp0 + tmp4
tmp6 = libdevice.tanh(tmp5)
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, out_ptr1, out_ptr2,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr2 + x2, xmask)
tmp15 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr4 + x2, xmask)
tmp19 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = 20.0
tmp5 = tmp3 > tmp4
tmp6 = tl_math.exp(tmp3)
tmp7 = libdevice.log1p(tmp6)
tmp8 = tmp7 * tmp2
tmp9 = tl.where(tmp5, tmp1, tmp8)
tmp10 = -1.0
tmp11 = tmp9 + tmp10
tmp12 = tmp11 - tmp1
tmp14 = tmp12 * tmp13
tmp16 = tmp14 / tmp15
tmp17 = tmp0 + tmp16
tmp20 = tmp17 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp19 * tmp19
tmp23 = tmp2 - tmp22
tmp24 = tmp13 * tmp23
tl.store(out_ptr0 + x2, tmp17, xmask)
tl.store(out_ptr1 + x2, tmp21, xmask)
tl.store(out_ptr2 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_add_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tl_math.log(tmp3)
tmp5 = 0.0
tmp6 = tmp4 + tmp5
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, primals_3, reinterpret_tensor(
primals_1, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, primals_3, reinterpret_tensor(
primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_6, (4, 1),
(1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
), reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_pow_sum_0[grid(4)](buf1, buf4, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
), reinterpret_tensor(primals_8, (4, 4, 1), (4, 1, 1), 0), out=buf6
)
buf7 = reinterpret_tensor(buf2, (4, 1, 1), (1, 1, 1), 0)
del buf2
triton_poi_fused_add_tanh_1[grid(4)](buf7, buf6, primals_7, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_7
buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
buf9 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2[grid(16)](buf0,
buf3, buf1, buf4, primals_8, buf7, buf5, buf8, buf9, 16, XBLOCK
=16, num_warps=1, num_stages=1)
buf10 = buf6
del buf6
extern_kernels.bmm(buf9, buf5, out=buf10)
buf11 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_add_3[grid(4)](buf10, buf11, 4, XBLOCK=4,
num_warps=1, num_stages=1)
return reinterpret_tensor(buf8, (4, 4), (4, 1), 0
), buf11, primals_3, reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
), buf3, buf4, buf5, buf7, buf10, reinterpret_tensor(buf9, (4, 4, 1
), (4, 1, 4), 0), reinterpret_tensor(primals_8, (4, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf0, (4, 1, 4), (4, 1, 1), 0)
class PlanarStep(nn.Module):
def __init__(self):
super(PlanarStep, self).__init__()
self.h = nn.Tanh()
self.softplus = nn.Softplus()
def _der_h(self, x):
"""Derivative of activation function h."""
return self._der_tanh(x)
def _der_tanh(self, x):
"""Derivative of the Tanh function."""
return 1 - self.h(x) ** 2
def forward(self, zk, u, w, b):
"""
Forward pass. Assumes amortized u, w and b. Conditions on diagonals of u and w for invertibility
will be be satisfied inside this function. Computes the following transformation:
z' = z + u h( w^T z + b)
or actually
z'^T = z^T + h(z^T w + b)u^T
Assumes the following input shapes:
shape u = (batch_size, z_dim, 1)
shape w = (batch_size, 1, z_dim)
shape b = (batch_size, 1, 1)
shape z = (batch_size, z_dim).
"""
zk = zk.unsqueeze(2)
uw = torch.bmm(w, u)
m_uw = -1.0 + self.softplus(uw)
w_norm_sq = torch.sum(w ** 2, dim=2, keepdim=True)
u_hat = u + (m_uw - uw) * w.transpose(2, 1) / w_norm_sq
wzb = torch.bmm(w, zk) + b
z = zk + u_hat * self.h(wzb)
z = z.squeeze(2)
psi = w * self._der_h(wzb)
logdet = torch.log(torch.abs(1 + torch.bmm(psi, u_hat)))
logdet = logdet.squeeze(2).squeeze(1)
return z, logdet
class Error(Exception):
"""Base error class, from which all other errors derive."""
pass
class InvalidArgumentError(Error):
"""This error will be shown when a given argument has an invalid value."""
pass
class NormalizingFlow(nn.Module):
"""Base class for normalizing flows."""
def __init__(self, h_dim, z_dim, flow_depth, hidden_depth):
super(NormalizingFlow, self).__init__()
self.h_dim = h_dim
self.z_dim = z_dim
self.flow_depth = flow_depth
self.hidden_depth = hidden_depth
@property
def flow_depth(self):
return self._flow_depth
@flow_depth.setter
def flow_depth(self, value):
if not isinstance(value, int):
raise InvalidArgumentError('flow_depth should be an integer.')
elif value < 1:
raise InvalidArgumentError(
'flow_depth should be strictly positive.')
else:
self._flow_depth = value
@property
def hidden_depth(self):
return self._hidden_depth
@hidden_depth.setter
def hidden_depth(self, value):
if not isinstance(value, int):
raise InvalidArgumentError('hidden_depth should be an integer.')
elif value < 0:
raise InvalidArgumentError('hidden_depth should be positive.')
else:
self._hidden_depth = value
class PlanarNew(NormalizingFlow):
"""Planar Normalizing flow with single unit bottleneck."""
def __init__(self, h_dim, z_dim, flow_depth):
super(PlanarNew, self).__init__(h_dim, z_dim, flow_depth, 0)
self.flow = PlanarStep()
self.h_to_u = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
self.h_to_w = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
self.h_to_b = nn.Linear(self.h_dim, self.flow_depth)
def forward(self, input_0, input_1):
primals_1 = self.h_to_u.weight
primals_2 = self.h_to_u.bias
primals_3 = self.h_to_w.weight
primals_5 = self.h_to_w.bias
primals_6 = self.h_to_b.weight
primals_7 = self.h_to_b.bias
primals_4 = input_0
primals_8 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
scfrank/deep-generative-lm
|
Planar
| false
| 4,295
|
[
"MIT"
] | 0
|
70067fcda82aa035bba805ce6c2709097166a7a4
|
https://github.com/scfrank/deep-generative-lm/tree/70067fcda82aa035bba805ce6c2709097166a7a4
|
Decoder_h
|
import torch
import torch.distributions as dist
import torch.nn as nn
class Decoder_h(nn.Module):
def __init__(self, B, H_dim):
super().__init__()
self.B = B
self.H_dim = H_dim
self.make_parameters()
def make_parameters(self):
self.mu = nn.Linear(self.H_dim, self.B, bias=False)
self.sigma = nn.Linear(self.H_dim, self.B, bias=False)
torch.nn.init.uniform_(self.sigma.weight, a=1.0, b=2.0)
def _log_likelihood(self, h):
"""
h: shape=(BS,N,H_dim)
"""
BS, S, H_dim = h.shape
return dist.Normal(self.mu.weight.view(1, 1, self.B, H_dim), self.
sigma.weight.view(1, 1, self.B, self.H_dim)).log_prob(h.view(BS,
S, 1, H_dim))
def forward(self, z):
"""
z: shape = (BS,N) or (BS,) or (1,)
"""
h_dist = dist.Normal(self.mu.weight[z], self.sigma.weight[z])
return h_dist.rsample()
def get_inputs():
return [torch.ones([4], dtype=torch.int64)]
def get_init_inputs():
return [[], {'B': 4, 'H_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.distributions as dist
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_index_mul_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr2 + x2, xmask)
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)
tmp8 = tl.load(in_ptr3 + (x0 + 4 * tmp4), xmask)
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = torch.ops.aten.normal_functional.default(buf0)
buf2 = buf1
del buf1
buf3 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_index_mul_0[grid(16)](primals_2, primals_1,
buf2, primals_3, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_1
del primals_3
return buf3, primals_2, buf2
class Decoder_hNew(nn.Module):
def __init__(self, B, H_dim):
super().__init__()
self.B = B
self.H_dim = H_dim
self.make_parameters()
def make_parameters(self):
self.mu = nn.Linear(self.H_dim, self.B, bias=False)
self.sigma = nn.Linear(self.H_dim, self.B, bias=False)
torch.nn.init.uniform_(self.sigma.weight, a=1.0, b=2.0)
def _log_likelihood(self, h):
"""
h: shape=(BS,N,H_dim)
"""
BS, S, H_dim = h.shape
return dist.Normal(self.mu.weight.view(1, 1, self.B, H_dim), self.
sigma.weight.view(1, 1, self.B, self.H_dim)).log_prob(h.view(BS,
S, 1, H_dim))
def forward(self, input_0):
primals_1 = self.mu.weight
primals_3 = self.sigma.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
shaabhishek/pp_lvm
|
Decoder_h
| false
| 4,296
|
[
"Apache-2.0"
] | 0
|
0fcceb7f004ab01da7c5508b576983b9d4af36c8
|
https://github.com/shaabhishek/pp_lvm/tree/0fcceb7f004ab01da7c5508b576983b9d4af36c8
|
VDB
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class VDB(nn.Module):
def __init__(self, num_inputs, args):
super(VDB, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.z_size)
self.fc3 = nn.Linear(args.hidden_size, args.z_size)
self.fc4 = nn.Linear(args.z_size, args.hidden_size)
self.fc5 = nn.Linear(args.hidden_size, 1)
self.fc5.weight.data.mul_(0.1)
self.fc5.bias.data.mul_(0.0)
def encoder(self, x):
h = torch.tanh(self.fc1(x))
return self.fc2(h), self.fc3(h)
def reparameterize(self, mu, logvar):
std = torch.exp(logvar / 2)
eps = torch.randn_like(std)
return mu + std * eps
def discriminator(self, z):
h = torch.tanh(self.fc4(z))
return torch.sigmoid(self.fc5(h))
def forward(self, x):
mu, logvar = self.encoder(x)
z = self.reparameterize(mu, logvar)
prob = self.discriminator(z)
return prob, mu, logvar
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'args': _mock_config(hidden_size=4,
z_size=4)}]
|
import torch
from torch import device
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language 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.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_add_div_exp_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp5 = tl.load(in_ptr2 + x0, xmask)
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tl_math.exp(tmp3)
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (1, 4), (4, 1))
assert_size_stride(primals_11, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_7
buf4 = torch.ops.aten.randn.default([4, 4, 4, 4], dtype=torch.
float32, device=device(type='cuda', index=0), pin_memory=False)
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_exp_mul_1[grid(256)](buf2, buf3, buf5,
buf6, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf7
triton_poi_fused_tanh_0[grid(256)](buf8, primals_9, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_9
buf9 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf8, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 1), (1, 4), 0), out=buf9)
buf10 = reinterpret_tensor(buf9, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf9
triton_poi_fused_sigmoid_2[grid(64)](buf10, primals_11, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del primals_11
return buf10, reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf5, reinterpret_tensor(buf6, (64, 4), (4, 1), 0
), buf8, buf10, primals_10, primals_8, primals_6, primals_4
class VDBNew(nn.Module):
def __init__(self, num_inputs, args):
super(VDBNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.z_size)
self.fc3 = nn.Linear(args.hidden_size, args.z_size)
self.fc4 = nn.Linear(args.z_size, args.hidden_size)
self.fc5 = nn.Linear(args.hidden_size, 1)
self.fc5.weight.data.mul_(0.1)
self.fc5.bias.data.mul_(0.0)
def encoder(self, x):
h = torch.tanh(self.fc1(x))
return self.fc2(h), self.fc3(h)
def reparameterize(self, mu, logvar):
std = torch.exp(logvar / 2)
eps = torch.randn_like(std)
return mu + std * eps
def discriminator(self, z):
h = torch.tanh(self.fc4(z))
return torch.sigmoid(self.fc5(h))
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_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_10 = self.fc5.weight
primals_11 = self.fc5.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], output[2]
|
sgrimbly/lets-do-irl
|
VDB
| false
| 4,297
|
[
"MIT"
] | 0
|
4233e238342394feef6a7bd495cc6b700d435b00
|
https://github.com/sgrimbly/lets-do-irl/tree/4233e238342394feef6a7bd495cc6b700d435b00
|
FCDiscriminator_low
|
import torch
from torch import nn
class FCDiscriminator_low(nn.Module):
def __init__(self, inplanes, planes=64):
super(FCDiscriminator_low, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=2,
padding=1)
self.conv2 = nn.Conv2d(planes, planes * 2, kernel_size=3, stride=2,
padding=1)
self.conv3 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
stride=2, padding=1)
self.relu = nn.ReLU(inplace=True)
self.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.classifier = nn.Conv2d(planes * 4, 1, kernel_size=1)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.relu(x)
x = self.conv3(x)
x = self.leaky_relu(x)
x = self.classifier(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 256
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_7(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
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (64, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (1, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4, 3, 3), (36, 1, 12, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(256, 9)](primals_1, buf0, 256, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_1[grid(16, 16)](primals_3, buf1, 16, 16, XBLOCK=16,
YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_2[grid(8192, 9)](primals_4, buf2, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_3[grid(32768, 9)](primals_6, buf3, 32768, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = extern_kernels.convolution(buf1, buf0, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 64, 2, 2), (256, 1, 128, 64))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_4[grid(1024)](buf5, primals_2,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf6 = extern_kernels.convolution(buf5, buf2, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 128, 1, 1), (128, 1, 128, 128))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_5[grid(512)](buf7, primals_5, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf8 = extern_kernels.convolution(buf7, buf3, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 256, 1, 1), (256, 1, 256, 256))
buf9 = buf8
del buf8
triton_poi_fused_convolution_leaky_relu_6[grid(1024)](buf9,
primals_7, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf10 = extern_kernels.convolution(buf9, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 1, 1, 1), (1, 1, 1, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_7[grid(4)](buf11, primals_9, 4, XBLOCK
=4, num_warps=1, num_stages=1)
del primals_9
return buf11, buf0, buf1, buf2, buf3, primals_8, buf5, buf7, buf9
class FCDiscriminator_lowNew(nn.Module):
def __init__(self, inplanes, planes=64):
super(FCDiscriminator_lowNew, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=2,
padding=1)
self.conv2 = nn.Conv2d(planes, planes * 2, kernel_size=3, stride=2,
padding=1)
self.conv3 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
stride=2, padding=1)
self.relu = nn.ReLU(inplace=True)
self.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.classifier = nn.Conv2d(planes * 4, 1, kernel_size=1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.classifier.weight
primals_9 = self.classifier.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]
|
seabearlmx/PA-DAN
|
FCDiscriminator_low
| false
| 4,298
|
[
"MIT"
] | 0
|
bdd1200396d102e68acdd265db9d22ddb83b6404
|
https://github.com/seabearlmx/PA-DAN/tree/bdd1200396d102e68acdd265db9d22ddb83b6404
|
ParallelPolarizedSelfAttention
|
import torch
from torch import nn
class ParallelPolarizedSelfAttention(nn.Module):
def __init__(self, channel=512):
super().__init__()
self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
self.softmax_channel = nn.Softmax(1)
self.softmax_spatial = nn.Softmax(-1)
self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
self.ln = nn.LayerNorm(channel)
self.sigmoid = nn.Sigmoid()
self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.agp = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, x):
b, c, h, w = x.size()
channel_wv = self.ch_wv(x)
channel_wq = self.ch_wq(x)
channel_wv = channel_wv.reshape(b, c // 2, -1)
channel_wq = channel_wq.reshape(b, -1, 1)
channel_wq = self.softmax_channel(channel_wq)
channel_wz = torch.matmul(channel_wv, channel_wq).unsqueeze(-1)
channel_weight = self.sigmoid(self.ln(self.ch_wz(channel_wz).
reshape(b, c, 1).permute(0, 2, 1))).permute(0, 2, 1).reshape(b,
c, 1, 1)
channel_out = channel_weight * x
spatial_wv = self.sp_wv(x)
spatial_wq = self.sp_wq(x)
spatial_wq = self.agp(spatial_wq)
spatial_wv = spatial_wv.reshape(b, c // 2, -1)
spatial_wq = spatial_wq.permute(0, 2, 3, 1).reshape(b, 1, c // 2)
spatial_wq = self.softmax_spatial(spatial_wq)
spatial_wz = torch.matmul(spatial_wq, spatial_wv)
spatial_weight = self.sigmoid(spatial_wz.reshape(b, 1, h, w))
spatial_out = spatial_weight * x
out = spatial_out + channel_out
return out
def get_inputs():
return [torch.rand([4, 512, 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, 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_red_fused__softmax_1(in_ptr0, in_ptr1, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 4
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
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
_tmp5 = tl.full([XBLOCK, RBLOCK], float('-inf'), 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)
tmp3 = tmp0 + tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = triton_helpers.maximum(_tmp5, tmp4)
_tmp5 = tl.where(rmask & xmask, tmp6, _tmp5)
tmp5 = triton_helpers.max2(_tmp5, 1)[:, None]
tmp8 = tl.load(in_ptr1 + 0)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
_tmp14 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
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_last', other=0.0)
tmp10 = tmp7 + tmp9
tmp11 = tmp10 - tmp5
tmp12 = tl_math.exp(tmp11)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = _tmp14 + tmp13
_tmp14 = tl.where(rmask & xmask, tmp15, _tmp14)
tmp14 = tl.sum(_tmp14, 1)[:, None]
tmp17 = tl.load(in_ptr1 + 0)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp16 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp19 = tmp16 + tmp18
tmp20 = tmp19 - tmp5
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp21 / tmp14
tl.store(out_ptr2 + (r1 + 4096 * x0), tmp22, rmask & xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 256
y1 = yindex // 256
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 1048576 * y1), None,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, None)
@triton.jit
def triton_per_fused_convolution_native_layer_norm_sigmoid_3(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel
):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + (r1 + 512 * x0), None)
tmp1 = tl.load(in_ptr0 + r1, None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + r1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = tl.broadcast_to(tmp3, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tl.full([1], 512, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp3 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 512.0
tmp17 = tmp15 / tmp16
tmp18 = 1e-05
tmp19 = tmp17 + tmp18
tmp20 = libdevice.rsqrt(tmp19)
tmp21 = tmp2 - tmp10
tmp22 = tmp21 * tmp20
tmp24 = tmp22 * tmp23
tmp26 = tmp24 + tmp25
tmp27 = tl.sigmoid(tmp26)
tl.store(in_out_ptr0 + (r1 + 512 * x0), tmp2, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp20, None)
tl.store(out_ptr1 + (r1 + 512 * x0), tmp27, None)
tl.store(out_ptr0 + x0, tmp10, None)
@triton.jit
def triton_red_fused_convolution_mean_4(in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
rnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 256
x1 = xindex // 256
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
_tmp4 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * r2 + 32768 * x1), rmask,
eviction_policy='evict_first', other=0.0)
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = _tmp4 + tmp3
_tmp4 = tl.where(rmask, tmp5, _tmp4)
tmp4 = tl.sum(_tmp4, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_per_fused_convolution_mean_5(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 256
x1 = xindex // 256
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * r2 + 8192 * x1), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_per_fused__softmax_6(in_ptr0, out_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 256 * x0), None)
tmp1 = 4096.0
tmp2 = tmp0 / tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp3, 0))
tmp6 = tmp2 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = tmp7 / tmp10
tl.store(out_ptr2 + (r1 + 256 * x0), tmp11, None)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_7(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 512
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
y3 = yindex
x2 = xindex
y1 = yindex // 4096
y0 = yindex % 4096
tmp0 = tl.load(in_ptr0 + y3, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + (x2 + 512 * y3), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr2 + (x2 + 512 * y1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp5 = tmp4 * tmp2
tmp6 = tmp3 + tmp5
tl.store(out_ptr0 + (y0 + 4096 * x2 + 2097152 * y1), tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 512, 64, 64), (2097152, 4096, 64, 1))
assert_size_stride(primals_2, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_3, (256,), (1,))
assert_size_stride(primals_4, (1, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (512, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_7, (512,), (1,))
assert_size_stride(primals_8, (512,), (1,))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_13, (256,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_1, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, 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, 256, 64, 64), (1048576, 1, 16384, 256))
buf2 = extern_kernels.convolution(buf0, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 64, 64), (4096, 1, 64, 1))
buf5 = empty_strided_cuda((4, 4096, 1), (4096, 1, 1), torch.float32)
triton_red_fused__softmax_1[grid(4)](buf2, primals_5, buf5, 4, 4096,
XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 256, 64, 64), (1048576, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_2[grid(1024, 4096)](buf1, primals_3,
buf6, 1024, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del buf1
del primals_3
buf7 = empty_strided_cuda((4, 256, 1), (256, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf6, (4, 256, 4096), (
1048576, 4096, 1), 0), buf5, out=buf7)
buf8 = extern_kernels.convolution(reinterpret_tensor(buf7, (4, 256,
1, 1), (256, 1, 1, 1), 0), primals_6, stride=(1, 1), padding=(0,
0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf8, (4, 512, 1, 1), (512, 1, 1, 1))
buf9 = reinterpret_tensor(buf8, (4, 512, 1, 1), (512, 1, 512, 512), 0)
del buf8
buf10 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
buf11 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf13 = reinterpret_tensor(buf11, (4, 1, 1), (1, 1, 1), 0)
del buf11
buf14 = empty_strided_cuda((4, 1, 512), (512, 2048, 1), torch.float32)
triton_per_fused_convolution_native_layer_norm_sigmoid_3[grid(4)](buf9,
buf13, primals_7, primals_8, primals_9, buf10, buf14, 4, 512,
num_warps=4, num_stages=1)
del primals_7
buf15 = extern_kernels.convolution(buf0, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf15, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf16 = extern_kernels.convolution(buf0, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf17 = empty_strided_cuda((4, 256, 1, 1, 32), (8192, 1, 32768,
32768, 256), torch.float32)
triton_red_fused_convolution_mean_4[grid(32768)](buf16, primals_13,
buf17, 32768, 128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
del primals_13
buf18 = empty_strided_cuda((4, 256, 1, 1), (256, 1, 1024, 1024),
torch.float32)
triton_per_fused_convolution_mean_5[grid(1024)](buf17, buf18, 1024,
32, XBLOCK=128, num_warps=8, num_stages=1)
del buf17
buf21 = empty_strided_cuda((4, 1, 256), (256, 256, 1), torch.float32)
triton_per_fused__softmax_6[grid(4)](buf18, buf21, 4, 256,
num_warps=2, num_stages=1)
del buf18
buf22 = reinterpret_tensor(buf16, (4, 256, 64, 64), (1048576, 4096,
64, 1), 0)
del buf16
triton_poi_fused_convolution_2[grid(1024, 4096)](buf15, primals_11,
buf22, 1024, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del buf15
del primals_11
buf23 = reinterpret_tensor(buf2, (4, 1, 4096), (4096, 4096, 1), 0)
del buf2
extern_kernels.bmm(buf21, reinterpret_tensor(buf22, (4, 256, 4096),
(1048576, 4096, 1), 0), out=buf23)
buf24 = empty_strided_cuda((4, 512, 64, 64), (2097152, 4096, 64, 1),
torch.float32)
triton_poi_fused_add_mul_sigmoid_7[grid(16384, 512)](buf23, buf0,
buf14, buf24, 16384, 512, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf14
return (buf24, buf0, primals_2, primals_4, primals_6, primals_8,
primals_9, primals_10, primals_12, buf5, reinterpret_tensor(buf7, (
4, 256, 1, 1), (256, 1, 1, 1), 0), buf9, buf10, buf13, buf21, buf23,
reinterpret_tensor(buf22, (4, 4096, 256), (1048576, 1, 4096), 0),
reinterpret_tensor(buf6, (4, 4096, 256), (1048576, 1, 4096), 0))
class ParallelPolarizedSelfAttentionNew(nn.Module):
def __init__(self, channel=512):
super().__init__()
self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
self.softmax_channel = nn.Softmax(1)
self.softmax_spatial = nn.Softmax(-1)
self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
self.ln = nn.LayerNorm(channel)
self.sigmoid = nn.Sigmoid()
self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.agp = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, input_0):
primals_2 = self.ch_wv.weight
primals_3 = self.ch_wv.bias
primals_4 = self.ch_wq.weight
primals_5 = self.ch_wq.bias
primals_6 = self.ch_wz.weight
primals_7 = self.ch_wz.bias
primals_8 = self.ln.weight
primals_9 = self.ln.bias
primals_10 = self.sp_wv.weight
primals_11 = self.sp_wv.bias
primals_12 = self.sp_wq.weight
primals_13 = self.sp_wq.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
rushirajsherlocked/External-Attention-pytorch
|
ParallelPolarizedSelfAttention
| false
| 4,299
|
[
"MIT"
] | 0
|
7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
https://github.com/rushirajsherlocked/External-Attention-pytorch/tree/7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
BertSelfAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.functional as F
class BertSelfAttention(nn.Module):
def __init__(self, config):
super(BertSelfAttention, self).__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = torch.reshape(x, new_x_shape)
return x.permute(0, 2, 1, 3)
def transpose_key_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = torch.reshape(x, new_x_shape)
return x.permute(0, 2, 3, 1)
def forward(self, hidden_states, attention_mask):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_key_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer)
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
attention_scores = attention_scores + attention_mask
attention_probs = F.softmax(attention_scores, dim=-1)
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = torch.reshape(context_layer, new_context_layer_shape)
return context_layer
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_add_div_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = 1.0
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_div_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
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 = 1.0
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_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf1
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_div_1[grid(64)](buf5, primals_8, buf6,
buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_add_div_2[grid(256)](buf8, primals_8,
buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf7
triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_7, buf9, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf10 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10)
buf11 = reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf6
triton_poi_fused_clone_3[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf10
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf9, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class BertSelfAttentionNew(nn.Module):
def __init__(self, config):
super(BertSelfAttentionNew, self).__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = torch.reshape(x, new_x_shape)
return x.permute(0, 2, 1, 3)
def transpose_key_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = torch.reshape(x, new_x_shape)
return x.permute(0, 2, 3, 1)
def forward(self, input_0, input_1):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_6 = self.value.weight
primals_7 = self.value.bias
primals_3 = input_0
primals_8 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
sermolin/amazon-sagemaker-examples
|
BertSelfAttention
| false
| 4,300
|
[
"Apache-2.0"
] | 0
|
3e6083d1b53cb718893a04c46513a9482a17bd6b
|
https://github.com/sermolin/amazon-sagemaker-examples/tree/3e6083d1b53cb718893a04c46513a9482a17bd6b
|
BaselineNN
|
import torch
from torch import nn
import torch.nn.functional as F
class BaselineNN(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 32)
self.fc2 = nn.Linear(32, 32)
self.fc3 = nn.Linear(32, 32)
self.fc4 = nn.Linear(32, 32)
self.fc5 = nn.Linear(32, 4)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.relu(self.fc4(x))
x = torch.sigmoid(self.fc5(x))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (32, 4), (4, 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), (32, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32), (32, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (32, 32), (32, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (4, 32), (32, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 32), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 32), (512, 128, 32, 1), 0)
del buf0
buf13 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(2048)](buf1,
primals_2, buf13, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 32), (32, 1), 0),
reinterpret_tensor(primals_4, (32, 32), (1, 32), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 32), (512, 128, 32, 1), 0)
del buf2
buf12 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(2048)](buf3,
primals_5, buf12, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 32), (32, 1), 0),
reinterpret_tensor(primals_6, (32, 32), (1, 32), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 32), (512, 128, 32, 1), 0)
del buf4
buf11 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(2048)](buf5,
primals_7, buf11, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (64, 32), (32, 1), 0),
reinterpret_tensor(primals_8, (32, 32), (1, 32), 0), out=buf6)
buf7 = reinterpret_tensor(buf6, (4, 4, 4, 32), (512, 128, 32, 1), 0)
del buf6
buf10 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(2048)](buf7,
primals_9, buf10, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (64, 32), (32, 1), 0),
reinterpret_tensor(primals_10, (32, 4), (1, 32), 0), out=buf8)
buf9 = reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf8
triton_poi_fused_sigmoid_1[grid(256)](buf9, primals_11, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del primals_11
return (buf9, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (64, 32), (32, 1), 0), reinterpret_tensor(
buf3, (64, 32), (32, 1), 0), reinterpret_tensor(buf5, (64, 32), (32,
1), 0), reinterpret_tensor(buf7, (64, 32), (32, 1), 0), buf9,
primals_10, buf10, primals_8, buf11, primals_6, buf12, primals_4, buf13
)
class BaselineNNNew(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 32)
self.fc2 = nn.Linear(32, 32)
self.fc3 = nn.Linear(32, 32)
self.fc4 = nn.Linear(32, 32)
self.fc5 = nn.Linear(32, 4)
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_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_10 = self.fc5.weight
primals_11 = self.fc5.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]
|
severilov/master-thesis
|
BaselineNN
| false
| 4,301
|
[
"MIT"
] | 0
|
145382d5d551761fcdbd2b77d7b96fabcc8f78ec
|
https://github.com/severilov/master-thesis/tree/145382d5d551761fcdbd2b77d7b96fabcc8f78ec
|
Maxout
|
import torch
from torch import nn
class Maxout(nn.Module):
def __init__(self, in_features, out_features):
super(Maxout, self).__init__()
self.layer1 = nn.Linear(in_features, out_features)
self.layer2 = nn.Linear(in_features, out_features)
def forward(self, x):
output1 = self.layer1(x)
output2 = self.layer2(x)
return torch.max(output1, output2)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch 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_eq_gt_lt_maximum_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
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
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, xmask)
tmp4 = tl.load(in_ptr3 + x0, 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 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
tl.store(out_ptr2 + x2, tmp8, xmask)
tl.store(out_ptr3 + 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, 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.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
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)
buf5 = 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, primals_5, buf2, buf3, buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf0
del buf1
del primals_2
del primals_5
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf3, buf4, buf5
class MaxoutNew(nn.Module):
def __init__(self, in_features, out_features):
super(MaxoutNew, self).__init__()
self.layer1 = nn.Linear(in_features, out_features)
self.layer2 = nn.Linear(in_features, out_features)
def forward(self, input_0):
primals_1 = self.layer1.weight
primals_2 = self.layer1.bias
primals_4 = self.layer2.weight
primals_5 = self.layer2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
shadow2496/KAIST_2019_Deep-Learning_HW4
|
Maxout
| false
| 4,302
|
[
"MIT"
] | 0
|
f837ee23816c7486952733925b1f338b54d7086f
|
https://github.com/shadow2496/KAIST_2019_Deep-Learning_HW4/tree/f837ee23816c7486952733925b1f338b54d7086f
|
ResidualAttention
|
import torch
from torch import nn
class ResidualAttention(nn.Module):
def __init__(self, channel=512, num_class=1000, la=0.2):
super().__init__()
self.la = la
self.fc = nn.Conv2d(in_channels=channel, out_channels=num_class,
kernel_size=1, stride=1, bias=False)
def forward(self, x):
_b, _c, _h, _w = x.shape
y_raw = self.fc(x).flatten(2)
y_avg = torch.mean(y_raw, dim=2)
y_max = torch.max(y_raw, dim=2)[0]
score = y_avg + self.la * y_max
return score
def get_inputs():
return [torch.rand([4, 512, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_red_fused_max_mean_1(in_ptr0, out_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 128000
rnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 1000
x1 = xindex // 1000
_tmp2 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
_tmp4 = tl.full([XBLOCK, RBLOCK], float('-inf'), tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 1000 * r2 + 128000 * x1), rmask &
xmask, eviction_policy='evict_first', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = _tmp2 + tmp1
_tmp2 = tl.where(rmask & xmask, tmp3, _tmp2)
tmp5 = triton_helpers.maximum(_tmp4, tmp1)
_tmp4 = tl.where(rmask & xmask, tmp5, _tmp4)
tmp2 = tl.sum(_tmp2, 1)[:, None]
tl.store(out_ptr0 + x3, tmp2, xmask)
tmp4 = triton_helpers.max2(_tmp4, 1)[:, None]
tl.store(out_ptr1 + x3, tmp4, xmask)
@triton.jit
def triton_per_fused_add_max_mean_mul_2(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4000
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 1000
x1 = xindex // 1000
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 1000 * r2 + 32000 * x1), xmask, other=0.0)
tmp5 = tl.load(in_ptr1 + (x0 + 1000 * r2 + 32000 * x1), 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(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, float('-inf'))
tmp9 = triton_helpers.max2(tmp8, 1)[:, None]
tmp10 = 4096.0
tmp11 = tmp4 / tmp10
tmp12 = 0.2
tmp13 = tmp9 * tmp12
tmp14 = tmp11 + tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, tmp14, xmask)
@triton.jit
def triton_red_fused_max_3(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr, RBLOCK: tl.constexpr):
xnumel = 4000
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 % 1000
x1 = xindex // 1000
_tmp2 = tl.full([XBLOCK, RBLOCK], float('-inf'), tl.float32)
_tmp2_index = tl.full([XBLOCK, RBLOCK], 9223372036854775807, tl.int64)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 1000 * r2 + 4096000 * x1), rmask &
xmask, eviction_policy='evict_first', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
_tmp2_next, _tmp2_index_next = triton_helpers.maximum_with_index(_tmp2,
_tmp2_index, tmp1, rindex)
_tmp2 = tl.where(rmask & xmask, _tmp2_next, _tmp2)
_tmp2_index = tl.where(rmask & xmask, _tmp2_index_next, _tmp2_index)
_, tmp2_tmp = triton_helpers.max_with_index(_tmp2, _tmp2_index, 1)
tmp2 = tmp2_tmp[:, None]
tl.store(out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 512, 64, 64), (2097152, 4096, 64, 1))
assert_size_stride(primals_2, (1000, 512, 1, 1), (512, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_1, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, 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, 1000, 64, 64), (4096000, 1, 64000, 1000))
buf2 = empty_strided_cuda((4, 1000, 32), (32000, 1, 1000), torch.
float32)
buf4 = empty_strided_cuda((4, 1000, 32), (32000, 1, 1000), torch.
float32)
triton_red_fused_max_mean_1[grid(128000)](buf1, buf2, buf4, 128000,
128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 1000), (1000, 1), torch.float32)
buf7 = buf3
del buf3
triton_per_fused_add_max_mean_mul_2[grid(4000)](buf7, buf2, buf4,
4000, 32, XBLOCK=128, num_warps=8, num_stages=1)
del buf2
del buf4
buf6 = empty_strided_cuda((4, 1000), (1000, 1), torch.int64)
triton_red_fused_max_3[grid(4000)](buf1, buf6, 4000, 4096, XBLOCK=8,
RBLOCK=512, num_warps=16, num_stages=1)
del buf1
return buf7, buf0, primals_2, reinterpret_tensor(buf6, (4, 1000, 1), (
1000, 1, 1), 0)
class ResidualAttentionNew(nn.Module):
def __init__(self, channel=512, num_class=1000, la=0.2):
super().__init__()
self.la = la
self.fc = nn.Conv2d(in_channels=channel, out_channels=num_class,
kernel_size=1, stride=1, bias=False)
def forward(self, input_0):
primals_2 = self.fc.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
rushirajsherlocked/External-Attention-pytorch
|
ResidualAttention
| false
| 4,303
|
[
"MIT"
] | 0
|
7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
https://github.com/rushirajsherlocked/External-Attention-pytorch/tree/7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
LipSwish
|
import torch
class LipSwish(torch.nn.Module):
def forward(self, x):
return 0.909 * torch.nn.functional.silu(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
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_silu_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.sigmoid(tmp0)
tmp2 = tmp0 * tmp1
tmp3 = 0.909
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_silu_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LipSwishNew(torch.nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
shi27feng/torchsde
|
LipSwish
| false
| 4,304
|
[
"Apache-2.0"
] | 0
|
58105bb6b839766c1d27b73c4fe3f949869d7394
|
https://github.com/shi27feng/torchsde/tree/58105bb6b839766c1d27b73c4fe3f949869d7394
|
Actor
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class Actor(nn.Module):
def __init__(self, num_inputs, num_outputs, args):
super(Actor, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, num_outputs)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, x):
x = torch.tanh(self.fc1(x))
x = torch.tanh(self.fc2(x))
mu = self.fc3(x)
logstd = torch.zeros_like(mu)
std = torch.exp(logstd)
return mu, std
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_outputs': 4, 'args': _mock_config(
hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_exp_1(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 = 1.0
tl.store(out_ptr0 + x0, tmp0, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_exp_1[grid(256)](buf5, 256, XBLOCK=256, num_warps=
4, num_stages=1)
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, primals_6, primals_4
class ActorNew(nn.Module):
def __init__(self, num_inputs, num_outputs, args):
super(ActorNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, num_outputs)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
sgrimbly/lets-do-irl
|
Actor
| false
| 4,305
|
[
"MIT"
] | 0
|
4233e238342394feef6a7bd495cc6b700d435b00
|
https://github.com/sgrimbly/lets-do-irl/tree/4233e238342394feef6a7bd495cc6b700d435b00
|
Encoder1
|
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
def kaiming_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.kaiming_normal_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.weight.data.fill_(1)
if m.bias is not None:
m.bias.data.fill_(0)
def normal_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.normal_(m.weight, 0, 0.02)
if m.bias is not None:
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.weight.data.fill_(1)
if m.bias is not None:
m.bias.data.fill_(0)
class Encoder1(nn.Module):
"""
encoder architecture for the "dsprites" data
"""
def __init__(self, z_dim=10):
super(Encoder1, self).__init__()
self.z_dim = z_dim
self.conv1 = nn.Conv2d(1, 32, 4, 2, 1)
self.conv2 = nn.Conv2d(32, 32, 4, 2, 1)
self.conv3 = nn.Conv2d(32, 64, 4, 2, 1)
self.conv4 = nn.Conv2d(64, 64, 4, 2, 1)
self.fc5 = nn.Linear(64 * 4 * 4, 128)
self.fc6 = nn.Linear(128, 2 * z_dim)
self.weight_init()
def weight_init(self, mode='normal'):
if mode == 'kaiming':
initializer = kaiming_init
elif mode == 'normal':
initializer = normal_init
for m in self._modules:
initializer(self._modules[m])
def forward(self, x):
out = F.relu(self.conv1(x))
out = F.relu(self.conv2(out))
out = F.relu(self.conv3(out))
out = F.relu(self.conv4(out))
out = out.view(out.size(0), -1)
out = F.relu(self.fc5(out))
stats = self.fc6(out)
mu = stats[:, :self.z_dim]
logvar = stats[:, self.z_dim:]
std = torch.sqrt(torch.exp(logvar))
return mu, std, logvar
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.init as init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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 // 1024 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_3(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, None)
tl.store(out_ptr0 + x3, tmp6, None)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_exp_sqrt_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 40
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 10
x1 = xindex // 10
x2 = xindex
tmp0 = tl.load(in_ptr0 + (10 + x0 + 20 * x1), xmask)
tmp1 = tl_math.exp(tmp0)
tmp2 = libdevice.sqrt(tmp1)
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (32, 1, 4, 4), (16, 16, 4, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 4, 4), (512, 16, 4, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 4, 4), (512, 16, 4, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64, 64, 4, 4), (1024, 16, 4, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (128, 1024), (1024, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (20, 128), (128, 1))
assert_size_stride(primals_13, (20,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(131072)](buf1, primals_2,
131072, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 16, 16), (8192, 256, 16, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(32768)](buf3, primals_5,
32768, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 64, 8, 8), (4096, 64, 8, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(16384)](buf5, primals_7,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 64, 4, 4), (1024, 16, 4, 1))
buf7 = buf6
del buf6
buf12 = empty_strided_cuda((4, 64, 4, 4), (1024, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(4096)](buf7
, primals_9, buf12, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 1024), (1024, 1), 0),
reinterpret_tensor(primals_10, (1024, 128), (1, 1024), 0), out=buf8
)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(512)](buf9, primals_11, 512, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_11
buf10 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.addmm(primals_13, buf9, reinterpret_tensor(
primals_12, (128, 20), (1, 128), 0), alpha=1, beta=1, out=buf10)
del primals_13
buf11 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
triton_poi_fused_exp_sqrt_5[grid(40)](buf10, buf11, 40, XBLOCK=64,
num_warps=1, num_stages=1)
return (reinterpret_tensor(buf10, (4, 10), (20, 1), 0), buf11,
reinterpret_tensor(buf10, (4, 10), (20, 1), 10), buf10, primals_1,
primals_3, primals_4, primals_6, primals_8, buf1, buf3, buf5,
reinterpret_tensor(buf7, (4, 1024), (1024, 1), 0), buf9,
reinterpret_tensor(buf10, (4, 10), (20, 1), 10), buf11, primals_12,
primals_10, buf12)
def kaiming_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.kaiming_normal_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.weight.data.fill_(1)
if m.bias is not None:
m.bias.data.fill_(0)
def normal_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.normal_(m.weight, 0, 0.02)
if m.bias is not None:
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):
m.weight.data.fill_(1)
if m.bias is not None:
m.bias.data.fill_(0)
class Encoder1New(nn.Module):
"""
encoder architecture for the "dsprites" data
"""
def __init__(self, z_dim=10):
super(Encoder1New, self).__init__()
self.z_dim = z_dim
self.conv1 = nn.Conv2d(1, 32, 4, 2, 1)
self.conv2 = nn.Conv2d(32, 32, 4, 2, 1)
self.conv3 = nn.Conv2d(32, 64, 4, 2, 1)
self.conv4 = nn.Conv2d(64, 64, 4, 2, 1)
self.fc5 = nn.Linear(64 * 4 * 4, 128)
self.fc6 = nn.Linear(128, 2 * z_dim)
self.weight_init()
def weight_init(self, mode='normal'):
if mode == 'kaiming':
initializer = kaiming_init
elif mode == 'normal':
initializer = normal_init
for m in self._modules:
initializer(self._modules[m])
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.fc5.weight
primals_11 = self.fc5.bias
primals_12 = self.fc6.weight
primals_13 = self.fc6.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0], output[1], output[2]
|
seqam-lab/rfvae
|
Encoder1
| false
| 4,306
|
[
"MIT"
] | 0
|
07089e2cca6d51f305731750c2c67b83a42df12a
|
https://github.com/seqam-lab/rfvae/tree/07089e2cca6d51f305731750c2c67b83a42df12a
|
SelfAttention
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class SelfAttention(nn.Module):
"""
Implementation of the attention block
"""
def __init__(self, input_size, hidden_size, output_size):
super(SelfAttention, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size, bias=False)
self.layer2 = nn.Linear(hidden_size, output_size, bias=False)
def forward(self, attention_input):
out = self.layer1(attention_input)
out = torch.tanh(out)
out = self.layer2(out)
out = out.permute(0, 2, 1)
out = F.softmax(out, dim=2)
return out
def get_inputs():
return [torch.rand([4, 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 libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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, 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_ptr0 + (y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / 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, 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, 1, 4), 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(16, 4)](buf3, buf4, 16, 4, XBLOCK=
4, YBLOCK=16, num_warps=1, num_stages=1)
del buf3
return buf4, reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), buf1, buf4, primals_3
class SelfAttentionNew(nn.Module):
"""
Implementation of the attention block
"""
def __init__(self, input_size, hidden_size, output_size):
super(SelfAttentionNew, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size, bias=False)
self.layer2 = nn.Linear(hidden_size, output_size, bias=False)
def forward(self, input_0):
primals_1 = self.layer1.weight
primals_3 = self.layer2.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
shahrukhx01/model_serve_pytorch
|
SelfAttention
| false
| 4,307
|
[
"MIT"
] | 0
|
c97ab45264b41ce349828e8b230ed85a51d6b213
|
https://github.com/shahrukhx01/model_serve_pytorch/tree/c97ab45264b41ce349828e8b230ed85a51d6b213
|
Discriminator
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, num_inputs, args):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, 1)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, x):
x = torch.tanh(self.fc1(x))
x = torch.tanh(self.fc2(x))
prob = torch.sigmoid(self.fc3(x))
return prob
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'args': _mock_config(hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 1), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf4
triton_poi_fused_sigmoid_1[grid(64)](buf5, primals_7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_7
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, buf5, primals_6, primals_4
class DiscriminatorNew(nn.Module):
def __init__(self, num_inputs, args):
super(DiscriminatorNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, 1)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
sgrimbly/lets-do-irl
|
Discriminator
| false
| 4,308
|
[
"MIT"
] | 0
|
4233e238342394feef6a7bd495cc6b700d435b00
|
https://github.com/sgrimbly/lets-do-irl/tree/4233e238342394feef6a7bd495cc6b700d435b00
|
Attention
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
class Attention(nn.Module):
def __init__(self, opt):
super(Attention, self).__init__()
self.rnn_size = opt.rnn_size
self.att_hid_size = opt.att_hid_size
self.h2att = nn.Linear(self.rnn_size, self.att_hid_size)
self.alpha_net = nn.Linear(self.att_hid_size, 1)
def forward(self, h, att_feats, p_att_feats, att_masks=None):
att_size = att_feats.numel() // att_feats.size(0) // att_feats.size(-1)
att = p_att_feats.view(-1, att_size, self.att_hid_size)
att_h = self.h2att(h)
att_h = att_h.unsqueeze(1).expand_as(att)
dot = att + att_h
dot = torch.tanh(dot)
dot = dot.view(-1, self.att_hid_size)
dot = self.alpha_net(dot)
dot = dot.view(-1, att_size)
weight = F.softmax(dot, dim=1)
if att_masks is not None:
weight = weight * att_masks.view(-1, att_size)
weight = weight / weight.sum(1, keepdim=True)
att_feats_ = att_feats.view(-1, att_size, att_feats.size(-1))
att_res = torch.bmm(weight.unsqueeze(1), att_feats_).squeeze(1)
return att_res
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4,
4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(rnn_size=4, att_hid_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
from torch.autograd import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_tanh_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp5 = libdevice.tanh(tmp4)
tl.store(out_ptr0 + x3, tmp5, xmask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr0, out_ptr1, out_ptr2,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tmp6 / tmp10
tl.store(out_ptr2 + (r1 + 16 * x0), tmp11, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr1 + x0, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 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, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_5, reinterpret_tensor(primals_3, (4, 4),
(1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_tanh_0[grid(256)](primals_2, buf0, primals_4,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_4
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
buf6 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_per_fused__softmax_1[grid(4)](buf3, buf4, buf5, buf6, 4, 16,
XBLOCK=1, num_warps=2, num_stages=1)
buf7 = reinterpret_tensor(buf0, (4, 1, 4), (4, 4, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf6, (4, 1, 16), (16, 0, 1),
0), reinterpret_tensor(primals_1, (4, 16, 4), (64, 4, 1), 0),
out=buf7)
del buf6
return reinterpret_tensor(buf7, (4, 4), (4, 1), 0
), primals_5, buf1, buf3, buf4, buf5, reinterpret_tensor(primals_1,
(4, 4, 16), (64, 1, 4), 0), primals_6
class AttentionNew(nn.Module):
def __init__(self, opt):
super(AttentionNew, self).__init__()
self.rnn_size = opt.rnn_size
self.att_hid_size = opt.att_hid_size
self.h2att = nn.Linear(self.rnn_size, self.att_hid_size)
self.alpha_net = nn.Linear(self.att_hid_size, 1)
def forward(self, input_0, input_1, input_2):
primals_3 = self.h2att.weight
primals_4 = self.h2att.bias
primals_6 = self.alpha_net.weight
primals_7 = self.alpha_net.bias
primals_5 = input_0
primals_1 = input_1
primals_2 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Romero027/ImageCaptioning.pytorch
|
Attention
| false
| 4,309
|
[
"MIT"
] | 0
|
069c95f5d343fb126afa8b10ec18e472f30b7b35
|
https://github.com/Romero027/ImageCaptioning.pytorch/tree/069c95f5d343fb126afa8b10ec18e472f30b7b35
|
DeltaGFit
|
import torch
from scipy import constants
import torch.nn as nn
import torch as t
class DeltaGFit(nn.Module):
def __init__(self, deltaG):
super(DeltaGFit, self).__init__()
self.deltaG = deltaG
def forward(self, temperature, X, k_int, timepoints):
"""
# inputs, list of:
temperatures: scalar (1,)
X (N_peptides, N_residues)
k_int: (N_peptides, 1)
"""
pfact = t.exp(self.deltaG / (constants.R * temperature))
uptake = 1 - t.exp(-t.matmul(k_int / (1 + pfact), timepoints))
return t.matmul(X, uptake)
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 [[], {'deltaG': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_exp_mul_reciprocal_0(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = 8.31446261815324
tmp3 = tmp1 * tmp2
tmp4 = tl.full([1], 1, tl.int32)
tmp5 = tmp4 / tmp3
tmp6 = 4.0
tmp7 = tmp5 * tmp6
tmp8 = tl_math.exp(tmp7)
tmp9 = 1.0
tmp10 = tmp8 + tmp9
tmp11 = tmp0 / tmp10
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused_exp_neg_rsub_1(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 = -tmp0
tmp2 = tl_math.exp(tmp1)
tmp3 = 1.0
tmp4 = tmp3 - tmp2
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_exp_mul_reciprocal_0[grid(256)](arg1_1,
arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
buf1 = 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(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf1
)
del arg2_1
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused_exp_neg_rsub_1[grid(256)](buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(arg3_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0), out
=buf3)
del arg3_1
del buf2
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0),
class DeltaGFitNew(nn.Module):
def __init__(self, deltaG):
super(DeltaGFitNew, self).__init__()
self.deltaG = deltaG
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]
|
sajetan/PyHDX
|
DeltaGFit
| false
| 4,310
|
[
"MIT"
] | 0
|
f764849e33b2dd1bcae5824795a38c64ef01e13c
|
https://github.com/sajetan/PyHDX/tree/f764849e33b2dd1bcae5824795a38c64ef01e13c
|
SequentialPolarizedSelfAttention
|
import torch
from torch import nn
class SequentialPolarizedSelfAttention(nn.Module):
def __init__(self, channel=512):
super().__init__()
self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
self.softmax_channel = nn.Softmax(1)
self.softmax_spatial = nn.Softmax(-1)
self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
self.ln = nn.LayerNorm(channel)
self.sigmoid = nn.Sigmoid()
self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.agp = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, x):
b, c, h, w = x.size()
channel_wv = self.ch_wv(x)
channel_wq = self.ch_wq(x)
channel_wv = channel_wv.reshape(b, c // 2, -1)
channel_wq = channel_wq.reshape(b, -1, 1)
channel_wq = self.softmax_channel(channel_wq)
channel_wz = torch.matmul(channel_wv, channel_wq).unsqueeze(-1)
channel_weight = self.sigmoid(self.ln(self.ch_wz(channel_wz).
reshape(b, c, 1).permute(0, 2, 1))).permute(0, 2, 1).reshape(b,
c, 1, 1)
channel_out = channel_weight * x
spatial_wv = self.sp_wv(channel_out)
spatial_wq = self.sp_wq(channel_out)
spatial_wq = self.agp(spatial_wq)
spatial_wv = spatial_wv.reshape(b, c // 2, -1)
spatial_wq = spatial_wq.permute(0, 2, 3, 1).reshape(b, 1, c // 2)
spatial_wq = self.softmax_spatial(spatial_wq)
spatial_wz = torch.matmul(spatial_wq, spatial_wv)
spatial_weight = self.sigmoid(spatial_wz.reshape(b, 1, h, w))
spatial_out = spatial_weight * channel_out
return spatial_out
def get_inputs():
return [torch.rand([4, 512, 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, 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_red_fused__softmax_1(in_ptr0, in_ptr1, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 4
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
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
_tmp5 = tl.full([XBLOCK, RBLOCK], float('-inf'), 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)
tmp3 = tmp0 + tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = triton_helpers.maximum(_tmp5, tmp4)
_tmp5 = tl.where(rmask & xmask, tmp6, _tmp5)
tmp5 = triton_helpers.max2(_tmp5, 1)[:, None]
tmp8 = tl.load(in_ptr1 + 0)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
_tmp14 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
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_last', other=0.0)
tmp10 = tmp7 + tmp9
tmp11 = tmp10 - tmp5
tmp12 = tl_math.exp(tmp11)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = _tmp14 + tmp13
_tmp14 = tl.where(rmask & xmask, tmp15, _tmp14)
tmp14 = tl.sum(_tmp14, 1)[:, None]
tmp17 = tl.load(in_ptr1 + 0)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp16 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp19 = tmp16 + tmp18
tmp20 = tmp19 - tmp5
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp21 / tmp14
tl.store(out_ptr2 + (r1 + 4096 * x0), tmp22, rmask & xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 256
y1 = yindex // 256
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 1048576 * y1), None,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, None)
@triton.jit
def triton_per_fused_convolution_native_layer_norm_sigmoid_3(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel
):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + (r1 + 512 * x0), None)
tmp1 = tl.load(in_ptr0 + r1, None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr2 + r1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = tl.broadcast_to(tmp3, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tl.full([1], 512, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp3 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 512.0
tmp17 = tmp15 / tmp16
tmp18 = 1e-05
tmp19 = tmp17 + tmp18
tmp20 = libdevice.rsqrt(tmp19)
tmp21 = tmp2 - tmp10
tmp22 = tmp21 * tmp20
tmp24 = tmp22 * tmp23
tmp26 = tmp24 + tmp25
tmp27 = tl.sigmoid(tmp26)
tl.store(in_out_ptr0 + (r1 + 512 * x0), tmp2, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp20, None)
tl.store(out_ptr1 + (r1 + 512 * x0), tmp27, None)
tl.store(out_ptr0 + x0, tmp10, None)
@triton.jit
def triton_poi_fused_mul_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 512
x2 = xindex // 2097152
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 512 * x2), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x3, None)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_red_fused_convolution_mean_5(in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
rnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 256
x1 = xindex // 256
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
_tmp4 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * r2 + 32768 * x1), rmask,
eviction_policy='evict_first', other=0.0)
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = _tmp4 + tmp3
_tmp4 = tl.where(rmask, tmp5, _tmp4)
tmp4 = tl.sum(_tmp4, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_per_fused_convolution_mean_6(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 256
x1 = xindex // 256
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * r2 + 8192 * x1), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_per_fused__softmax_7(in_ptr0, out_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 256 * x0), None)
tmp1 = 4096.0
tmp2 = tmp0 / tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp3, 0))
tmp6 = tmp2 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = tmp7 / tmp10
tl.store(out_ptr2 + (r1 + 256 * x0), tmp11, None)
@triton.jit
def triton_poi_fused_mul_sigmoid_8(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y1 = yindex // 512
y0 = yindex % 512
y3 = yindex
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y1), None, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr1 + (y0 + 512 * x2 + 2097152 * y1), None,
eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp3, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 512, 64, 64), (2097152, 4096, 64, 1))
assert_size_stride(primals_2, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_3, (256,), (1,))
assert_size_stride(primals_4, (1, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (512, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_7, (512,), (1,))
assert_size_stride(primals_8, (512,), (1,))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_13, (256,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_1, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, 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, 256, 64, 64), (1048576, 1, 16384, 256))
buf2 = extern_kernels.convolution(buf0, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 64, 64), (4096, 1, 64, 1))
buf5 = empty_strided_cuda((4, 4096, 1), (4096, 1, 1), torch.float32)
triton_red_fused__softmax_1[grid(4)](buf2, primals_5, buf5, 4, 4096,
XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 256, 64, 64), (1048576, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_2[grid(1024, 4096)](buf1, primals_3,
buf6, 1024, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del buf1
del primals_3
buf7 = empty_strided_cuda((4, 256, 1), (256, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf6, (4, 256, 4096), (
1048576, 4096, 1), 0), buf5, out=buf7)
buf8 = extern_kernels.convolution(reinterpret_tensor(buf7, (4, 256,
1, 1), (256, 1, 1, 1), 0), primals_6, stride=(1, 1), padding=(0,
0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf8, (4, 512, 1, 1), (512, 1, 1, 1))
buf9 = reinterpret_tensor(buf8, (4, 512, 1, 1), (512, 1, 512, 512), 0)
del buf8
buf10 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
buf11 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf13 = reinterpret_tensor(buf11, (4, 1, 1), (1, 1, 1), 0)
del buf11
buf14 = empty_strided_cuda((4, 1, 512), (512, 2048, 1), torch.float32)
triton_per_fused_convolution_native_layer_norm_sigmoid_3[grid(4)](buf9,
buf13, primals_7, primals_8, primals_9, buf10, buf14, 4, 512,
num_warps=4, num_stages=1)
del primals_7
buf15 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768,
512), torch.float32)
triton_poi_fused_mul_4[grid(8388608)](buf14, buf0, buf15, 8388608,
XBLOCK=1024, num_warps=4, num_stages=1)
del buf14
buf16 = extern_kernels.convolution(buf15, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf17 = extern_kernels.convolution(buf15, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf18 = empty_strided_cuda((4, 256, 1, 1, 32), (8192, 1, 32768,
32768, 256), torch.float32)
triton_red_fused_convolution_mean_5[grid(32768)](buf17, primals_13,
buf18, 32768, 128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
del primals_13
buf19 = empty_strided_cuda((4, 256, 1, 1), (256, 1, 1024, 1024),
torch.float32)
triton_per_fused_convolution_mean_6[grid(1024)](buf18, buf19, 1024,
32, XBLOCK=128, num_warps=8, num_stages=1)
del buf18
buf22 = empty_strided_cuda((4, 1, 256), (256, 256, 1), torch.float32)
triton_per_fused__softmax_7[grid(4)](buf19, buf22, 4, 256,
num_warps=2, num_stages=1)
del buf19
buf23 = reinterpret_tensor(buf17, (4, 256, 64, 64), (1048576, 4096,
64, 1), 0)
del buf17
triton_poi_fused_convolution_2[grid(1024, 4096)](buf16, primals_11,
buf23, 1024, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del buf16
del primals_11
buf24 = reinterpret_tensor(buf2, (4, 1, 4096), (4096, 4096, 1), 0)
del buf2
extern_kernels.bmm(buf22, reinterpret_tensor(buf23, (4, 256, 4096),
(1048576, 4096, 1), 0), out=buf24)
buf25 = empty_strided_cuda((4, 512, 64, 64), (2097152, 4096, 64, 1),
torch.float32)
triton_poi_fused_mul_sigmoid_8[grid(2048, 4096)](buf24, buf15,
buf25, 2048, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
return (buf25, buf0, primals_2, primals_4, primals_6, primals_8,
primals_9, primals_10, primals_12, buf5, reinterpret_tensor(buf7, (
4, 256, 1, 1), (256, 1, 1, 1), 0), buf9, buf10, buf13, buf15, buf22,
buf24, reinterpret_tensor(buf23, (4, 4096, 256), (1048576, 1, 4096),
0), reinterpret_tensor(buf6, (4, 4096, 256), (1048576, 1, 4096), 0))
class SequentialPolarizedSelfAttentionNew(nn.Module):
def __init__(self, channel=512):
super().__init__()
self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
self.softmax_channel = nn.Softmax(1)
self.softmax_spatial = nn.Softmax(-1)
self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
self.ln = nn.LayerNorm(channel)
self.sigmoid = nn.Sigmoid()
self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
self.agp = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, input_0):
primals_2 = self.ch_wv.weight
primals_3 = self.ch_wv.bias
primals_4 = self.ch_wq.weight
primals_5 = self.ch_wq.bias
primals_6 = self.ch_wz.weight
primals_7 = self.ch_wz.bias
primals_8 = self.ln.weight
primals_9 = self.ln.bias
primals_10 = self.sp_wv.weight
primals_11 = self.sp_wv.bias
primals_12 = self.sp_wq.weight
primals_13 = self.sp_wq.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
rushirajsherlocked/External-Attention-pytorch
|
SequentialPolarizedSelfAttention
| false
| 4,311
|
[
"MIT"
] | 0
|
7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
https://github.com/rushirajsherlocked/External-Attention-pytorch/tree/7d6814b2d90909adf81c62f3f8a89e30a59d6481
|
SimulatorReward
|
import torch
import torch.nn.functional as F
class SimulatorReward(torch.nn.Module):
def __init__(self):
super(SimulatorReward, self).__init__()
self.conv1 = torch.nn.Conv2d(4, 8, kernel_size=3, padding=1)
self.conv2 = torch.nn.Conv2d(8, 16, kernel_size=3, padding=1)
self.conv3 = torch.nn.Conv2d(16, 32, kernel_size=3, padding=1)
self.fc1 = torch.nn.Linear(512, 200)
self.fc2 = torch.nn.Linear(200, 100)
self.fc3 = torch.nn.Linear(100, 3)
def forward(self, x):
x = x.reshape(-1, 4, 4, 4)
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = self.conv3(x)
x = x.view(-1, 512)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return F.softmax(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
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_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_relu_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 200
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_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 100
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 12
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 3
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 3 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 3 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 3 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp6 = tmp0 - tmp5
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp1 - tmp5
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp2 - tmp5
tmp11 = tl_math.exp(tmp10)
tmp12 = tmp9 + tmp11
tmp13 = tmp4 - tmp5
tmp14 = tl_math.exp(tmp13)
tmp15 = tmp12 + tmp14
tmp16 = tmp7 / tmp15
tl.store(out_ptr0 + x2, tmp16, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (16, 8, 3, 3), (72, 9, 3, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (32, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (200, 512), (512, 1))
assert_size_stride(primals_9, (200,), (1,))
assert_size_stride(primals_10, (100, 200), (200, 1))
assert_size_stride(primals_11, (100,), (1,))
assert_size_stride(primals_12, (3, 100), (100, 1))
assert_size_stride(primals_13, (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, 8, 4, 4), (128, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(512)](buf1, primals_3, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 16, 4, 4), (256, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(1024)](buf3, primals_5,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 4, 4), (512, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(2048)](buf5, primals_7, 2048,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((4, 200), (200, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (4, 512), (512, 1), 0),
reinterpret_tensor(primals_8, (512, 200), (1, 512), 0), out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_relu_3[grid(800)](buf7, primals_9, 800, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 100), (100, 1), torch.float32)
extern_kernels.mm(buf7, reinterpret_tensor(primals_10, (200, 100),
(1, 200), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(400)](buf9, primals_11, 400, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_11
buf10 = empty_strided_cuda((4, 3), (3, 1), torch.float32)
extern_kernels.addmm(primals_13, buf9, reinterpret_tensor(
primals_12, (100, 3), (1, 100), 0), alpha=1, beta=1, out=buf10)
del primals_13
buf11 = empty_strided_cuda((4, 3), (3, 1), torch.float32)
triton_poi_fused__softmax_5[grid(12)](buf10, buf11, 12, XBLOCK=16,
num_warps=1, num_stages=1)
del buf10
return (buf11, primals_2, primals_4, primals_6, primals_1, buf1, buf3,
reinterpret_tensor(buf5, (4, 512), (512, 1), 0), buf7, buf9, buf11,
primals_12, primals_10, primals_8)
class SimulatorRewardNew(torch.nn.Module):
def __init__(self):
super(SimulatorRewardNew, self).__init__()
self.conv1 = torch.nn.Conv2d(4, 8, kernel_size=3, padding=1)
self.conv2 = torch.nn.Conv2d(8, 16, kernel_size=3, padding=1)
self.conv3 = torch.nn.Conv2d(16, 32, kernel_size=3, padding=1)
self.fc1 = torch.nn.Linear(512, 200)
self.fc2 = torch.nn.Linear(200, 100)
self.fc3 = torch.nn.Linear(100, 3)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_12 = self.fc3.weight
primals_13 = self.fc3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
seulbinHwang/DeepReinforcementLearningInAction
|
SimulatorReward
| false
| 4,312
|
[
"MIT"
] | 0
|
c9039fd6951c46c8902cda04580c69159d172c82
|
https://github.com/seulbinHwang/DeepReinforcementLearningInAction/tree/c9039fd6951c46c8902cda04580c69159d172c82
|
VNLinear
|
import torch
import torch.nn as nn
import torch.utils.data
import torch
import torch.nn.parallel
class VNLinear(nn.Module):
def __init__(self, in_channels, out_channels):
super(VNLinear, self).__init__()
self.map_to_feat = nn.Linear(in_channels, out_channels, bias=False)
def forward(self, x):
"""
x: point features of shape [B, N_feat, 3, N_samples, ...]
"""
x_out = self.map_to_feat(x.transpose(1, -1)).transpose(1, -1)
return x_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
import torch.nn as nn
import torch.utils.data
import torch
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_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 % 4
x3 = xindex // 4
y0 = yindex % 4
y1 = yindex // 4
x5 = xindex
y4 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x3 + 16 * x2 + 64 * y1), xmask & ymask)
tl.store(out_ptr0 + (x5 + 16 * y4), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 16)](primals_1, buf0, 16, 16,
XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 1, 4, 16), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class VNLinearNew(nn.Module):
def __init__(self, in_channels, out_channels):
super(VNLinearNew, self).__init__()
self.map_to_feat = nn.Linear(in_channels, out_channels, bias=False)
def forward(self, input_0):
primals_2 = self.map_to_feat.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
shiyani21/vnn
|
VNLinear
| false
| 4,313
|
[
"MIT"
] | 0
|
921be51d6651ff32bff895f4da99ef83d50900da
|
https://github.com/shiyani21/vnn/tree/921be51d6651ff32bff895f4da99ef83d50900da
|
ConvAutoencoder
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvAutoencoder(nn.Module):
"""Simple convolutional autoencoder
...
Methods
-------
forward(x)
Forward pass of x
"""
def __init__(self):
super(ConvAutoencoder, self).__init__()
self.conv_1 = nn.Conv2d(1, 16, 3, padding=1)
self.conv_2 = nn.Conv2d(16, 4, 3, padding=1)
self.pooling_func = nn.MaxPool2d(2, 2)
self.trans_conv_1 = nn.ConvTranspose2d(4, 16, 2, stride=2)
self.trans_conv_2 = nn.ConvTranspose2d(16, 1, 2, stride=2)
def forward(self, x):
out = F.relu(self.conv_1(x))
out = self.pooling_func(out)
out = F.relu(self.conv_2(out))
out = self.pooling_func(out)
out = F.relu(self.trans_conv_1(out))
out = torch.sigmoid(self.trans_conv_2(out))
return out
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 16
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 4
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (32 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (33 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 16
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_sigmoid_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, 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, (16, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (4, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 16, 2, 2), (64, 4, 2, 1))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (16, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_9, (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, 16, 64, 64), (65536, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(262144)](buf1, primals_2,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 16, 32, 32), (16384, 1024, 32, 1),
torch.float32)
buf3 = empty_strided_cuda((4, 16, 32, 32), (16384, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(65536)](buf1, buf2,
buf3, 65536, XBLOCK=512, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 32, 32), (4096, 1024, 32, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(16384)](buf5, primals_5,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch
.float32)
buf7 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(4096)](buf5, buf6,
buf7, 4096, XBLOCK=256, num_warps=4, num_stages=1)
buf8 = extern_kernels.convolution(buf6, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 16, 32, 32), (16384, 1024, 32, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(65536)](buf9, primals_7,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_7
buf10 = extern_kernels.convolution(buf9, primals_8, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_sigmoid_5[grid(16384)](buf11,
primals_9, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
return (buf11, primals_1, primals_3, primals_4, primals_6, primals_8,
buf1, buf2, buf3, buf5, buf6, buf7, buf9, buf11)
class ConvAutoencoderNew(nn.Module):
"""Simple convolutional autoencoder
...
Methods
-------
forward(x)
Forward pass of x
"""
def __init__(self):
super(ConvAutoencoderNew, self).__init__()
self.conv_1 = nn.Conv2d(1, 16, 3, padding=1)
self.conv_2 = nn.Conv2d(16, 4, 3, padding=1)
self.pooling_func = nn.MaxPool2d(2, 2)
self.trans_conv_1 = nn.ConvTranspose2d(4, 16, 2, stride=2)
self.trans_conv_2 = nn.ConvTranspose2d(16, 1, 2, stride=2)
def forward(self, input_0):
primals_1 = self.conv_1.weight
primals_2 = self.conv_1.bias
primals_4 = self.conv_2.weight
primals_5 = self.conv_2.bias
primals_6 = self.trans_conv_1.weight
primals_7 = self.trans_conv_1.bias
primals_8 = self.trans_conv_2.weight
primals_9 = self.trans_conv_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
shankal17/Autoencoders
|
ConvAutoencoder
| false
| 4,314
|
[
"MIT"
] | 0
|
17aa9f1fe573008fa84694e30e9d395127684191
|
https://github.com/shankal17/Autoencoders/tree/17aa9f1fe573008fa84694e30e9d395127684191
|
GatedLinearUnit
|
import torch
import torch.nn as nn
class GatedLinearUnit(nn.Module):
def __init__(self, input_size, hidden_layer_size, dropout_rate,
activation=None):
super(GatedLinearUnit, self).__init__()
self.input_size = input_size
self.hidden_layer_size = hidden_layer_size
self.dropout_rate = dropout_rate
self.activation_name = activation
if self.dropout_rate:
self.dropout = nn.Dropout(p=self.dropout_rate)
self.W4 = torch.nn.Linear(self.input_size, self.hidden_layer_size)
self.W5 = torch.nn.Linear(self.input_size, self.hidden_layer_size)
if self.activation_name:
self.activation = getattr(nn, self.activation_name)()
self.sigmoid = nn.Sigmoid()
self.init_weights()
def init_weights(self):
for n, p in self.named_parameters():
if 'bias' not in n:
torch.nn.init.xavier_uniform_(p)
elif 'bias' in n:
torch.nn.init.zeros_(p)
def forward(self, x):
if self.dropout_rate:
x = self.dropout(x)
if self.activation_name:
output = self.sigmoid(self.W4(x)) * self.activation(self.W5(x))
else:
output = self.sigmoid(self.W4(x)) * self.W5(x)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_layer_size': 1, 'dropout_rate': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_sigmoid_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 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)
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x0, 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, (1, 4), (4, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf3)
del primals_4
del primals_5
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(64)](buf1, buf3, buf4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
return buf4, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), buf1, buf3
class GatedLinearUnitNew(nn.Module):
def __init__(self, input_size, hidden_layer_size, dropout_rate,
activation=None):
super(GatedLinearUnitNew, self).__init__()
self.input_size = input_size
self.hidden_layer_size = hidden_layer_size
self.dropout_rate = dropout_rate
self.activation_name = activation
if self.dropout_rate:
self.dropout = nn.Dropout(p=self.dropout_rate)
self.W4 = torch.nn.Linear(self.input_size, self.hidden_layer_size)
self.W5 = torch.nn.Linear(self.input_size, self.hidden_layer_size)
if self.activation_name:
self.activation = getattr(nn, self.activation_name)()
self.sigmoid = nn.Sigmoid()
self.init_weights()
def init_weights(self):
for n, p in self.named_parameters():
if 'bias' not in n:
torch.nn.init.xavier_uniform_(p)
elif 'bias' in n:
torch.nn.init.zeros_(p)
def forward(self, input_0):
primals_2 = self.W4.weight
primals_3 = self.W4.bias
primals_4 = self.W5.weight
primals_5 = self.W5.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
sherpahu/AutoX
|
GatedLinearUnit
| false
| 4,315
|
[
"Apache-2.0"
] | 0
|
37aca6bb848ecfdde6868b9f8eb869563fece3eb
|
https://github.com/sherpahu/AutoX/tree/37aca6bb848ecfdde6868b9f8eb869563fece3eb
|
MLP
|
import torch
from torch import nn
from torch.nn import functional as F
class MLP(torch.nn.Module):
"""MLP for patch segmentation."""
def __init__(self, n_classes, input_dim):
super().__init__()
self.layer_1 = nn.Linear(input_dim, 200)
self.layer_2 = nn.Linear(200, 100)
self.layer_3 = nn.Linear(100, n_classes)
def forward(self, x):
x = self.layer_1(x)
x = F.relu(x)
x = self.layer_2(x)
x = F.relu(x)
x = self.layer_3(x)
x = F.log_softmax(x, dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_classes': 4, '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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 12800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 200
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (200, 4), (4, 1))
assert_size_stride(primals_2, (200,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (100, 200), (200, 1))
assert_size_stride(primals_5, (100,), (1,))
assert_size_stride(primals_6, (4, 100), (100, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 200), (200, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 200), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 200), (3200, 800, 200, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 200), (3200, 800, 200, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(12800)](buf1,
primals_2, buf8, 12800, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 200), (200, 1), 0),
reinterpret_tensor(primals_4, (200, 100), (1, 200), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf2
buf7 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(6400)](buf3,
primals_5, buf7, 6400, 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, 100),
(100, 1), 0), reinterpret_tensor(primals_6, (100, 4), (1, 100),
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__log_softmax_2[grid(256)](buf4, buf5, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused__log_softmax_3[grid(256)](buf5, buf6, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf5
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 200), (200, 1), 0
), reinterpret_tensor(buf3, (64, 100), (100, 1), 0
), buf6, primals_6, buf7, primals_4, buf8
class MLPNew(torch.nn.Module):
"""MLP for patch segmentation."""
def __init__(self, n_classes, input_dim):
super().__init__()
self.layer_1 = nn.Linear(input_dim, 200)
self.layer_2 = nn.Linear(200, 100)
self.layer_3 = nn.Linear(100, n_classes)
def forward(self, input_0):
primals_1 = self.layer_1.weight
primals_2 = self.layer_1.bias
primals_4 = self.layer_2.weight
primals_5 = self.layer_2.bias
primals_6 = self.layer_3.weight
primals_7 = self.layer_3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
sachaMorin/dino
|
MLP
| false
| 4,316
|
[
"Apache-2.0"
] | 0
|
b5c42ecffb535a8e6735c63ddc314118927cfd52
|
https://github.com/sachaMorin/dino/tree/b5c42ecffb535a8e6735c63ddc314118927cfd52
|
ContinuousLoss_L2
|
import torch
import torch.nn as nn
class ContinuousLoss_L2(nn.Module):
""" Class to measure loss between continuous emotion dimension predictions and labels. Using l2 loss as base. """
def __init__(self, margin=1):
super(ContinuousLoss_L2, self).__init__()
self.margin = margin
def forward(self, pred, target):
labs = torch.abs(pred - target)
loss = labs ** 2
loss[labs < self.margin] = 0.0
return loss.sum()
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_per_fused_abs_index_put_lift_fresh_pow_sub_sum_0(in_ptr0,
in_ptr1, out_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 = tmp3 * tmp3
tmp7 = 0.0
tmp8 = tl.where(tmp5, tmp7, tmp6)
tmp9 = tl.broadcast_to(tmp8, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tl.store(out_ptr1 + 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)
buf1 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_index_put_lift_fresh_pow_sub_sum_0[grid(1)](arg0_1
, arg1_1, buf1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class ContinuousLoss_L2New(nn.Module):
""" Class to measure loss between continuous emotion dimension predictions and labels. Using l2 loss as base. """
def __init__(self, margin=1):
super(ContinuousLoss_L2New, self).__init__()
self.margin = margin
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
shrookehab/Body-Language-and-Emotion-Recognition
|
ContinuousLoss_L2
| false
| 4,317
|
[
"MIT"
] | 0
|
a13068be1f8599fa2df6db925a98ac64fd2adf42
|
https://github.com/shrookehab/Body-Language-and-Emotion-Recognition/tree/a13068be1f8599fa2df6db925a98ac64fd2adf42
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
"""policy-value network module"""
def __init__(self, board_width, board_height):
super(Net, self).__init__()
self.board_width = board_width
self.board_height = board_height
self.conv1 = nn.Conv2d(4, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.act_conv1 = nn.Conv2d(128, 4, kernel_size=1)
self.act_fc1 = nn.Linear(4 * board_width * board_height,
board_width * board_height)
self.val_conv1 = nn.Conv2d(128, 2, kernel_size=1)
self.val_fc1 = nn.Linear(2 * board_width * board_height, 64)
self.val_fc2 = nn.Linear(64, 1)
def forward(self, state_input):
x = F.relu(self.conv1(state_input))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x_act = F.relu(self.act_conv1(x))
x_act = x_act.view(-1, 4 * self.board_width * self.board_height)
x_act = F.log_softmax(self.act_fc1(x_act))
x_val = F.relu(self.val_conv1(x))
x_val = x_val.view(-1, 2 * self.board_width * self.board_height)
x_val = F.relu(self.val_fc1(x_val))
x_val = F.tanh(self.val_fc2(x_val))
return x_act, x_val
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'board_width': 4, 'board_height': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 128
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 32
y1 = yindex // 32
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 32 * x2 + 288 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_7(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 64 * y1), xmask & ymask)
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x2 + 16 * y3), tmp4, xmask & ymask)
tl.store(out_ptr1 + (y0 + 4 * x2 + 64 * y1), tmp6, xmask & ymask)
@triton.jit
def triton_per_fused__log_softmax_8(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 16 * x0), tmp12, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_9(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 8
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 2
y1 = yindex // 2
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 2 * x2 + 32 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x2 + 16 * y3), tmp4, xmask & ymask)
tl.store(out_ptr1 + (y0 + 2 * x2 + 32 * y1), tmp6, xmask & ymask)
@triton.jit
def triton_poi_fused_relu_10(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 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_tanh_11(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 = libdevice.tanh(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = args
args.clear()
assert_size_stride(primals_1, (32, 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, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (4, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (16, 64), (64, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (2, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_13, (2,), (1,))
assert_size_stride(primals_14, (64, 32), (32, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (1, 64), (64, 1))
assert_size_stride(primals_17, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((32, 4, 3, 3), (36, 1, 12, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(128, 9)](primals_1, buf0, 128, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_1[grid(16, 16)](primals_3, buf1, 16, 16, XBLOCK=16,
YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 32, 3, 3), (288, 1, 96, 32), torch.
float32)
triton_poi_fused_2[grid(2048, 9)](primals_4, buf2, 2048, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_3[grid(8192, 9)](primals_6, buf3, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = extern_kernels.convolution(buf1, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 4, 4), (512, 1, 128, 32))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_4[grid(2048)](buf5, primals_2,
2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf6 = extern_kernels.convolution(buf5, buf2, 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, 4, 4), (1024, 1, 256, 64))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_5[grid(4096)](buf7, primals_5,
4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf8 = extern_kernels.convolution(buf7, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 128, 4, 4), (2048, 1, 512, 128))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_6[grid(8192)](buf9, primals_7,
8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf10 = extern_kernels.convolution(buf9, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 4, 4, 4), (64, 1, 16, 4))
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf23 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_7[grid(16, 16)](
buf10, primals_9, buf11, buf23, 16, 16, XBLOCK=16, YBLOCK=16,
num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf11, (4, 64),
(64, 1), 0), reinterpret_tensor(primals_10, (64, 16), (1, 64),
0), alpha=1, beta=1, out=buf12)
del primals_11
buf15 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_per_fused__log_softmax_8[grid(4)](buf12, buf15, 4, 16,
XBLOCK=1, num_warps=2, num_stages=1)
del buf12
buf16 = extern_kernels.convolution(buf9, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 2, 4, 4), (32, 1, 8, 2))
buf17 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
buf22 = empty_strided_cuda((4, 2, 4, 4), (32, 1, 8, 2), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_9[grid(8, 16)](
buf16, primals_13, buf17, buf22, 8, 16, XBLOCK=16, YBLOCK=2,
num_warps=1, num_stages=1)
del buf16
del primals_13
buf18 = reinterpret_tensor(buf10, (4, 64), (64, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf17, (4, 32), (32, 1), 0),
reinterpret_tensor(primals_14, (32, 64), (1, 32), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_relu_10[grid(256)](buf19, primals_15, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_15
buf20 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf19, reinterpret_tensor(primals_16, (64, 1), (1,
64), 0), out=buf20)
buf21 = buf20
del buf20
triton_poi_fused_tanh_11[grid(4)](buf21, primals_17, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_17
return (buf15, buf21, buf0, buf1, buf2, buf3, primals_8, primals_12,
buf5, buf7, buf9, reinterpret_tensor(buf11, (4, 64), (64, 1), 0),
buf15, reinterpret_tensor(buf17, (4, 32), (32, 1), 0), buf19, buf21,
primals_16, primals_14, buf22, primals_10, buf23)
class NetNew(nn.Module):
"""policy-value network module"""
def __init__(self, board_width, board_height):
super(NetNew, self).__init__()
self.board_width = board_width
self.board_height = board_height
self.conv1 = nn.Conv2d(4, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.act_conv1 = nn.Conv2d(128, 4, kernel_size=1)
self.act_fc1 = nn.Linear(4 * board_width * board_height,
board_width * board_height)
self.val_conv1 = nn.Conv2d(128, 2, kernel_size=1)
self.val_fc1 = nn.Linear(2 * board_width * board_height, 64)
self.val_fc2 = nn.Linear(64, 1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.act_conv1.weight
primals_9 = self.act_conv1.bias
primals_10 = self.act_fc1.weight
primals_11 = self.act_fc1.bias
primals_12 = self.val_conv1.weight
primals_13 = self.val_conv1.bias
primals_14 = self.val_fc1.weight
primals_15 = self.val_fc1.bias
primals_16 = self.val_fc2.weight
primals_17 = self.val_fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17])
return output[0], output[1]
|
sewon0918/pj4
|
Net
| false
| 4,318
|
[
"MIT"
] | 0
|
144996e7f99e7639f1fffb34770ab9713307428d
|
https://github.com/sewon0918/pj4/tree/144996e7f99e7639f1fffb34770ab9713307428d
|
MyBatchNorm
|
import torch
import torch.nn as nn
class MyBatchNorm(nn.Module):
def __init__(self, size, epsilon=1e-05):
super(MyBatchNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(size))
self.beta = nn.Parameter(torch.zeros(size))
self.epsilon = epsilon
def forward(self, x):
var, meu = torch.var_mean(x, axis=0)
zed_prime = (x - meu) / torch.sqrt(var + self.epsilon)
zed_norm = self.gamma * zed_prime + self.beta
return zed_norm
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_sqrt_var_mean_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (192 + x0), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
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 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp24, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_sqrt_sub_var_mean_1(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x3 = xindex
x4 = xindex % 64
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 - tmp2
tmp5 = tmp3 / tmp4
tmp6 = tmp0 * tmp5
tmp8 = tmp6 + 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, 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((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_sqrt_var_mean_0[grid(64)](primals_1, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mul_sqrt_sub_var_mean_1[grid(256)](primals_2,
primals_1, buf0, buf1, primals_3, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf0
del buf1
del primals_2
del primals_3
return buf2, primals_1
class MyBatchNormNew(nn.Module):
def __init__(self, size, epsilon=1e-05):
super(MyBatchNormNew, self).__init__()
self.gamma = nn.Parameter(torch.ones(size))
self.beta = nn.Parameter(torch.zeros(size))
self.epsilon = epsilon
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]
|
shohamda/deep-learning
|
MyBatchNorm
| false
| 4,319
|
[
"MIT"
] | 0
|
160296c403cefd5351ffe5161e07789c22637284
|
https://github.com/shohamda/deep-learning/tree/160296c403cefd5351ffe5161e07789c22637284
|
MSELoss
|
import torch
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class MSELoss(nn.Module):
"""DiceLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(MSELoss, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
def forward(self, predict, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
"""Forward function."""
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
if self.class_weight is not None:
class_weight = torch.tensor(self.class_weight).type_as(predict)
else:
class_weight = None
error = (predict - target) ** 2
class_wise_loss = torch.mean(error, dim=(2, 3))
if class_weight is not None:
class_wise_loss = class_wise_loss * class_weight
loss = self.loss_weight * weight_reduce_loss(class_wise_loss,
weight, reduction=reduction, avg_factor=avg_factor)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mean_pow_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0), xmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_per_fused_mean_mul_pow_sub_1(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 16.0
tmp2 = tmp0 / tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.sum(tmp3, 1)[:, None]
tmp6 = tmp5 / tmp1
tmp7 = 1.0
tmp8 = tmp6 * tmp7
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, 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_per_fused_mean_pow_sub_0[grid(16)](arg0_1, arg1_1, buf0, 16,
16, XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_mean_mul_pow_sub_1[grid(1)](buf2, buf0, 1, 16,
XBLOCK=1, num_warps=2, num_stages=1)
del buf0
return buf2,
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class MSELossNew(nn.Module):
"""DiceLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(MSELossNew, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_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]
|
shuaizzZ/mmsegmentation
|
MSELoss
| false
| 4,320
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
GCN
|
from torch.nn import Module
import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.nn as nn
import torch.nn.functional as F
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dropout = dropout
def forward(self, x, adj):
x = F.relu(self.gc1(x, adj))
x = F.dropout(x, self.dropout, training=self.training)
x = self.gc2(x, adj)
return x, F.log_softmax(x, dim=1)
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
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_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)
@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, 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 primals_6
buf5 = buf3
del buf3
triton_poi_fused__log_softmax_1[grid(16)](buf4, buf5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_2[grid(16)](buf5, buf6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf5
return buf4, buf6, buf2, buf6, 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(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCNNew(nn.Module):
def __init__(self, nfeat, nhid, 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], output[1]
|
shovalf/OGRE-1
|
GCN
| false
| 4,321
|
[
"MIT"
] | 0
|
08efad50fac27e8c9621897838e122a2e8fdae1c
|
https://github.com/shovalf/OGRE-1/tree/08efad50fac27e8c9621897838e122a2e8fdae1c
|
ECA
|
import torch
import torch._C
import torch.serialization
from torch import nn
from typing import *
def int_size(x):
size = tuple(int(s) for s in x.size())
return size
class ECA(nn.Module):
"""Constructs a ECA module.
Args:
channel: Number of channels of the input feature map
k_size: Adaptive selection of kernel size
"""
def __init__(self, in_channels, k_size=3):
super(ECA, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=(k_size - 1
) // 2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
_b, _c, _h, _w = int_size(x)
y = self.avg_pool(x)
y = self.conv(y.permute(0, 3, 2, 1)).permute(0, 3, 2, 1)
y = self.sigmoid(y)
return x * y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch._C
import torch.serialization
from torch import nn
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_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_mul_sigmoid_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 1, 3, 3), (9, 9, 3, 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 = extern_kernels.convolution(reinterpret_tensor(buf1, (4, 1, 1,
4), (4, 0, 0, 1), 0), primals_2, stride=(1, 1), padding=(1, 1),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 1, 4), (4, 4, 4, 1))
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_1[grid(256)](primals_1, buf2, buf3,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf3, primals_1, primals_2, reinterpret_tensor(buf1, (4, 1, 1, 4
), (4, 1, 1, 1), 0), buf2
def int_size(x):
size = tuple(int(s) for s in x.size())
return size
class ECANew(nn.Module):
"""Constructs a ECA module.
Args:
channel: Number of channels of the input feature map
k_size: Adaptive selection of kernel size
"""
def __init__(self, in_channels, k_size=3):
super(ECANew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=(k_size - 1
) // 2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.conv.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
shuaizzZ/mmsegmentation
|
ECA
| false
| 4,322
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
Mix2Pooling
|
import torch
import torch._C
import torch.serialization
from torch import nn
from typing import *
class Mix2Pooling(nn.Module):
def __init__(self, size):
super(Mix2Pooling, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(size)
self.max_pool = nn.AdaptiveMaxPool2d(size)
def forward(self, x):
spx = torch.chunk(x, 2, 1)
out = torch.cat((self.avg_pool(spx[0]), self.max_pool(spx[1])), 1)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'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
import torch._C
import torch.serialization
from torch import nn
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 4
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp9 = tl.load(in_ptr0 + (32 + x0 + 16 * (-2 + x1) + 64 * x2), tmp6 &
xmask, other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class Mix2PoolingNew(nn.Module):
def __init__(self, size):
super(Mix2PoolingNew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(size)
self.max_pool = nn.AdaptiveMaxPool2d(size)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
shuaizzZ/mmsegmentation
|
Mix2Pooling
| false
| 4,323
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
CDiceLoss
|
import torch
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class CDiceLoss(nn.Module):
"""class-wise DiceLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(CDiceLoss, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, predict, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
"""Forward function."""
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
if self.class_weight is not None:
class_weight = torch.tensor(self.class_weight).type_as(predict)
else:
class_weight = None
N, _C, H, W = predict.size()
probs = F.softmax(predict, dim=1)
target_onehot = torch.zeros(predict.size()).type_as(target)
target_onehot.scatter_(1, target.view(N, 1, H, W), 1)
intersection = torch.sum(probs * target_onehot, dim=(2, 3))
union = torch.sum(probs.pow(2), dim=(2, 3)) + torch.sum(target_onehot,
dim=(2, 3))
class_wise_loss = (2 * intersection + self.smooth) / (union + self.
smooth)
if class_weight is not None:
class_wise_loss = class_wise_loss * class_weight
loss = self.loss_weight * (1 - weight_reduce_loss(class_wise_loss,
weight, reduction=reduction, avg_factor=avg_factor))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4, 1, 4, 4], dtype=torch.
int64)]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__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_per_fused__softmax_mul_pow_scatter_sum_1(in_ptr0, in_ptr1,
out_ptr1, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + (r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp2 = tl.load(in_ptr0 + (16 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp4 = tl.load(in_ptr0 + (32 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (48 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp9 = tl.load(in_ptr1 + (r2 + 16 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp10 = x0
tmp11 = tmp9 == tmp10
tmp12 = tl.full([1, 1], 1, tl.int64)
tmp13 = tl.full([1, 1], 0, tl.int64)
tmp14 = tl.where(tmp11, tmp12, tmp13)
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp8 * tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = tl.where(xmask, tmp17, 0)
tmp20 = tl.sum(tmp19, 1)[:, None]
tmp21 = tmp8 * tmp8
tmp22 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK])
tmp24 = tl.where(xmask, tmp22, 0)
tmp25 = tl.sum(tmp24, 1)[:, None]
tmp26 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp28 = tl.where(xmask, tmp26, 0)
tmp29 = tl.sum(tmp28, 1)[:, None]
tl.store(out_ptr1 + x3, tmp20, xmask)
tl.store(out_ptr2 + x3, tmp25, xmask)
tl.store(out_ptr3 + x3, tmp29, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp6 = tl.load(in_ptr2 + r0, None)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp5 + tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp4 / tmp9
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.sum(tmp11, 1)[:, None]
tmp14 = 16.0
tmp15 = tmp13 / tmp14
tmp16 = 1.0
tmp17 = tmp16 - tmp15
tmp18 = tmp17 * tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp18, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 1, 4, 4), (16, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
triton_per_fused__softmax_mul_pow_scatter_sum_1[grid(16)](buf0,
arg1_1, buf2, buf3, buf4, 16, 16, XBLOCK=8, num_warps=2,
num_stages=1)
del arg1_1
del buf0
buf5 = empty_strided_cuda((), (), torch.float32)
buf6 = buf5
del buf5
triton_per_fused_add_div_mean_mul_rsub_2[grid(1)](buf6, buf2, buf3,
buf4, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf3
del buf4
return buf6,
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class CDiceLossNew(nn.Module):
"""class-wise DiceLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(CDiceLossNew, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
shuaizzZ/mmsegmentation
|
CDiceLoss
| false
| 4,324
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
SpatialAttention
|
import torch
import torch._C
import torch.serialization
from torch import nn
from typing import *
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super(SpatialAttention, self).__init__()
assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
padding = 3 if kernel_size == 7 else 1
self.conv = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avgout = torch.mean(x, dim=1, keepdim=True)
maxout, _ = torch.max(x, dim=1, keepdim=True)
out = torch.cat([avgout, maxout], dim=1)
out = self.conv(out)
return x * self.sigmoid(out)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch._C
import torch.serialization
from torch import nn
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 2
x0 = xindex % 16
x2 = xindex // 32
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp9 = tmp7 + tmp8
tmp10 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp9 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp4, tmp13, tmp14)
tmp16 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp19 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = triton_helpers.maximum(tmp19, tmp20)
tmp22 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = triton_helpers.maximum(tmp21, tmp22)
tmp24 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp25 = triton_helpers.maximum(tmp23, tmp24)
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp16, tmp25, tmp26)
tmp28 = tl.where(tmp4, tmp15, tmp27)
tl.store(out_ptr0 + x3, tmp28, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x3, tmp3, 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, (1, 2, 7, 7), (98, 49, 7, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](primals_1, buf0, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 1, 4, 4), (16, 16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_1[grid(256)](primals_1, buf1, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf2, primals_1, primals_2, buf0, buf1
class SpatialAttentionNew(nn.Module):
def __init__(self, kernel_size=7):
super(SpatialAttentionNew, self).__init__()
assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
padding = 3 if kernel_size == 7 else 1
self.conv = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.conv.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
shuaizzZ/mmsegmentation
|
SpatialAttention
| false
| 4,325
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
RecallLoss
|
import torch
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class RecallLoss(nn.Module):
"""RecallLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(RecallLoss, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, predict, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
"""Forward function."""
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
if self.class_weight is not None:
class_weight = torch.tensor(self.class_weight).type_as(predict)
else:
class_weight = None
N, _C, H, W = predict.size()
probs = F.softmax(predict, dim=1)
target_onehot = torch.zeros(predict.size()).type_as(target)
target_onehot.scatter_(1, target.view(N, 1, H, W), 1)
true_positive = torch.sum(probs * target_onehot, dim=(2, 3))
total_target = torch.sum(target_onehot, dim=(2, 3))
class_wise_loss = (true_positive + self.smooth) / (total_target +
self.smooth)
if class_weight is not None:
class_wise_loss = class_wise_loss * class_weight
loss = self.loss_weight * (1 - weight_reduce_loss(class_wise_loss,
weight, reduction=reduction, avg_factor=avg_factor))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4, 1, 4, 4], dtype=torch.
int64)]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__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_per_fused__softmax_mul_scatter_sum_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + (r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp2 = tl.load(in_ptr0 + (16 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp4 = tl.load(in_ptr0 + (32 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (48 + r2 + 64 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp9 = tl.load(in_ptr1 + (r2 + 16 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp10 = x0
tmp11 = tmp9 == tmp10
tmp12 = tl.full([1, 1], 1, tl.int64)
tmp13 = tl.full([1, 1], 0, tl.int64)
tmp14 = tl.where(tmp11, tmp12, tmp13)
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp8 * tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = tl.where(xmask, tmp17, 0)
tmp20 = tl.sum(tmp19, 1)[:, None]
tmp21 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp23 = tl.where(xmask, tmp21, 0)
tmp24 = tl.sum(tmp23, 1)[:, None]
tl.store(out_ptr0 + x3, tmp20, xmask)
tl.store(out_ptr1 + x3, tmp24, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_2(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1e-06
tmp2 = tmp0 + tmp1
tmp4 = tmp3.to(tl.float32)
tmp5 = tmp4 + tmp1
tmp6 = tmp2 / tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 16.0
tmp11 = tmp9 / tmp10
tmp12 = 1.0
tmp13 = tmp12 - tmp11
tmp14 = tmp13 * tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 1, 4, 4), (16, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
triton_per_fused__softmax_mul_scatter_sum_1[grid(16)](buf0, arg1_1,
buf1, buf2, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf0
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused_add_div_mean_mul_rsub_2[grid(1)](buf4, buf1, buf2,
1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf1
del buf2
return buf4,
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class RecallLossNew(nn.Module):
"""RecallLoss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', class_weight=None, loss_weight=1.0):
super(RecallLossNew, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
shuaizzZ/mmsegmentation
|
RecallLoss
| false
| 4,326
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
ContrastiveLoss
|
import torch
from torch import nn
from torch.nn import functional as F
class ContrastiveLoss(nn.Module):
"""
Contrastive loss function.
Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
"""
def __init__(self, margin=5.0):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, output1, output2, label):
euclidean_distance = F.pairwise_distance(output1, output2, keepdim=True
)
loss_contrastive = torch.mean((1 - label) * torch.pow(
euclidean_distance, 2) + label * torch.pow(torch.clamp(self.
margin - euclidean_distance, min=0.0), 2))
return loss_contrastive
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_norm_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp9 * tmp9
tmp11 = tmp5 + tmp10
tmp14 = tmp12 - tmp13
tmp15 = tmp14 + tmp3
tmp16 = tmp15 * tmp15
tmp17 = tmp11 + tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 + tmp3
tmp22 = tmp21 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tl.store(out_ptr0 + x0, tmp24, xmask)
@triton.jit
def triton_per_fused_add_clamp_mean_mul_pow_rsub_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r2 = rindex
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp3 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp3 * tmp3
tmp5 = tmp2 * tmp4
tmp6 = 5.0
tmp7 = tmp6 - tmp3
tmp8 = 0.0
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp9 * tmp9
tmp11 = tmp0 * tmp10
tmp12 = tmp5 + tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_norm_sub_0[grid(64)](arg1_1, arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_add_clamp_mean_mul_pow_rsub_1[grid(1)](buf2,
arg2_1, buf0, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf0
return buf2,
class ContrastiveLossNew(nn.Module):
"""
Contrastive loss function.
Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
"""
def __init__(self, margin=5.0):
super(ContrastiveLossNew, self).__init__()
self.margin = margin
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
shuuchen/siamese_network
|
ContrastiveLoss
| false
| 4,327
|
[
"Apache-2.0"
] | 0
|
54a952d320800c6bb5618cb40386e4c25bdde6fb
|
https://github.com/shuuchen/siamese_network/tree/54a952d320800c6bb5618cb40386e4c25bdde6fb
|
TripletLoss
|
import torch
from torch import nn
from torch.nn.modules.distance import PairwiseDistance
class TripletLoss(nn.Module):
def __init__(self, margin=5.0):
super(TripletLoss, self).__init__()
self.margin = margin
self.pdist = PairwiseDistance(2)
def forward(self, anchor, negative, positive):
pos_dist = self.pdist.forward(anchor, positive)
neg_dist = self.pdist.forward(anchor, negative)
hinge_dist = torch.clamp(self.margin + pos_dist - neg_dist, min=0.0)
loss = torch.mean(hinge_dist)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
from torch.nn.modules.distance import PairwiseDistance
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_mean_norm_sub_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp36 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp41 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp9 * tmp9
tmp11 = tmp5 + tmp10
tmp14 = tmp12 - tmp13
tmp15 = tmp14 + tmp3
tmp16 = tmp15 * tmp15
tmp17 = tmp11 + tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 + tmp3
tmp22 = tmp21 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = 5.0
tmp26 = tmp24 + tmp25
tmp28 = tmp0 - tmp27
tmp29 = tmp28 + tmp3
tmp30 = tmp29 * tmp29
tmp32 = tmp6 - tmp31
tmp33 = tmp32 + tmp3
tmp34 = tmp33 * tmp33
tmp35 = tmp30 + tmp34
tmp37 = tmp12 - tmp36
tmp38 = tmp37 + tmp3
tmp39 = tmp38 * tmp38
tmp40 = tmp35 + tmp39
tmp42 = tmp18 - tmp41
tmp43 = tmp42 + tmp3
tmp44 = tmp43 * tmp43
tmp45 = tmp40 + tmp44
tmp46 = libdevice.sqrt(tmp45)
tmp47 = tmp26 - tmp46
tmp48 = 0.0
tmp49 = triton_helpers.maximum(tmp47, tmp48)
tmp50 = tl.broadcast_to(tmp49, [XBLOCK, RBLOCK])
tmp52 = tl.sum(tmp50, 1)[:, None]
tmp53 = 64.0
tmp54 = tmp52 / tmp53
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp54, None)
def call(args):
arg0_1, arg1_1, 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)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_clamp_mean_norm_sub_0[grid(1)](buf2, arg1_1,
arg0_1, arg2_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf2,
class TripletLossNew(nn.Module):
def __init__(self, margin=5.0):
super(TripletLossNew, self).__init__()
self.margin = margin
self.pdist = PairwiseDistance(2)
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
shuuchen/siamese_network
|
TripletLoss
| false
| 4,328
|
[
"Apache-2.0"
] | 0
|
54a952d320800c6bb5618cb40386e4c25bdde6fb
|
https://github.com/shuuchen/siamese_network/tree/54a952d320800c6bb5618cb40386e4c25bdde6fb
|
BinaryFocalLossWithLogits
|
import torch
import warnings
from typing import Optional
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
def binary_focal_loss_with_logits(input: 'torch.Tensor', target:
'torch.Tensor', alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='none', eps: 'Optional[float]'=None) ->torch.Tensor:
"""Function that computes Binary Focal loss.
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
input: input data tensor of arbitrary shape.
target: the target tensor with shape matching input.
alpha: Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
eps: Deprecated: scalar for numerically stability when dividing. This is no longer used.
Returns:
the computed loss.
Examples:
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> logits = torch.tensor([[[6.325]],[[5.26]],[[87.49]]])
>>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
>>> binary_focal_loss_with_logits(logits, labels, **kwargs)
tensor(21.8725)
"""
if eps is not None and not torch.jit.is_scripting():
warnings.warn(
'`binary_focal_loss_with_logits` has been reworked for improved numerical stability and the `eps` argument is no longer necessary'
, DeprecationWarning, stacklevel=2)
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not len(input.shape) >= 2:
raise ValueError(
f'Invalid input shape, we expect BxCx*. Got: {input.shape}')
if input.size(0) != target.size(0):
raise ValueError(
f'Expected input batch_size ({input.size(0)}) to match target batch_size ({target.size(0)}).'
)
probs_pos = torch.sigmoid(input)
probs_neg = torch.sigmoid(-input)
loss_tmp = -alpha * torch.pow(probs_neg, gamma) * target * F.logsigmoid(
input) - (1 - alpha) * torch.pow(probs_pos, gamma) * (1.0 - target
) * F.logsigmoid(-input)
if reduction == 'none':
loss = loss_tmp
elif reduction == 'mean':
loss = torch.mean(loss_tmp)
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError(f'Invalid reduction mode: {reduction}')
return loss
class BinaryFocalLossWithLogits(nn.Module):
"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
alpha): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
Shape:
- Input: :math:`(N, *)`.
- Target: :math:`(N, *)`.
Examples:
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> loss = BinaryFocalLossWithLogits(**kwargs)
>>> input = torch.randn(1, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(2)
>>> output = loss(input, target)
>>> output.backward()
"""
def __init__(self, alpha: 'float', gamma: 'float'=2.0, reduction: 'str'
='none') ->None:
super().__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
def forward(self, input: 'torch.Tensor', target: 'torch.Tensor'
) ->torch.Tensor:
return binary_focal_loss_with_logits(input, target, self.alpha,
self.gamma, self.reduction)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'alpha': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import warnings
from typing import Optional
import torch.nn as nn
import torch.nn.functional as F
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_log_sigmoid_forward_mul_neg_pow_rsub_sigmoid_sub_0(in_ptr0
, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp6 = tl.load(in_ptr1 + x0, xmask)
tmp1 = -tmp0
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp2 * tmp2
tmp4 = -4.0
tmp5 = tmp3 * tmp4
tmp7 = tmp5 * tmp6
tmp8 = 0.0
tmp9 = triton_helpers.minimum(tmp8, tmp0)
tmp10 = tl_math.abs(tmp0)
tmp11 = -tmp10
tmp12 = tl_math.exp(tmp11)
tmp13 = libdevice.log1p(tmp12)
tmp14 = tmp9 - tmp13
tmp15 = tmp7 * tmp14
tmp16 = tl.sigmoid(tmp0)
tmp17 = tmp16 * tmp16
tmp18 = -3.0
tmp19 = tmp17 * tmp18
tmp20 = 1.0
tmp21 = tmp20 - tmp6
tmp22 = tmp19 * tmp21
tmp23 = triton_helpers.minimum(tmp8, tmp1)
tmp24 = tl_math.abs(tmp1)
tmp25 = -tmp24
tmp26 = tl_math.exp(tmp25)
tmp27 = libdevice.log1p(tmp26)
tmp28 = tmp23 - tmp27
tmp29 = tmp22 * tmp28
tmp30 = tmp15 - tmp29
tl.store(out_ptr0 + x0, tmp30, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_log_sigmoid_forward_mul_neg_pow_rsub_sigmoid_sub_0[
grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
return buf0,
def binary_focal_loss_with_logits(input: 'torch.Tensor', target:
'torch.Tensor', alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='none', eps: 'Optional[float]'=None) ->torch.Tensor:
"""Function that computes Binary Focal loss.
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
input: input data tensor of arbitrary shape.
target: the target tensor with shape matching input.
alpha: Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
eps: Deprecated: scalar for numerically stability when dividing. This is no longer used.
Returns:
the computed loss.
Examples:
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> logits = torch.tensor([[[6.325]],[[5.26]],[[87.49]]])
>>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
>>> binary_focal_loss_with_logits(logits, labels, **kwargs)
tensor(21.8725)
"""
if eps is not None and not torch.jit.is_scripting():
warnings.warn(
'`binary_focal_loss_with_logits` has been reworked for improved numerical stability and the `eps` argument is no longer necessary'
, DeprecationWarning, stacklevel=2)
if not isinstance(input, torch.Tensor):
raise TypeError(f'Input type is not a torch.Tensor. Got {type(input)}')
if not len(input.shape) >= 2:
raise ValueError(
f'Invalid input shape, we expect BxCx*. Got: {input.shape}')
if input.size(0) != target.size(0):
raise ValueError(
f'Expected input batch_size ({input.size(0)}) to match target batch_size ({target.size(0)}).'
)
probs_pos = torch.sigmoid(input)
probs_neg = torch.sigmoid(-input)
loss_tmp = -alpha * torch.pow(probs_neg, gamma) * target * F.logsigmoid(
input) - (1 - alpha) * torch.pow(probs_pos, gamma) * (1.0 - target
) * F.logsigmoid(-input)
if reduction == 'none':
loss = loss_tmp
elif reduction == 'mean':
loss = torch.mean(loss_tmp)
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError(f'Invalid reduction mode: {reduction}')
return loss
class BinaryFocalLossWithLogitsNew(nn.Module):
"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
alpha): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
Shape:
- Input: :math:`(N, *)`.
- Target: :math:`(N, *)`.
Examples:
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> loss = BinaryFocalLossWithLogits(**kwargs)
>>> input = torch.randn(1, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(2)
>>> output = loss(input, target)
>>> output.backward()
"""
def __init__(self, alpha: 'float', gamma: 'float'=2.0, reduction: 'str'
='none') ->None:
super().__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
shubham-gupta-iitr/mmmlX
|
BinaryFocalLossWithLogits
| false
| 4,329
|
[
"Apache-2.0"
] | 0
|
3485e6191e0e45bf1c8168e4e928a36ab9264d22
|
https://github.com/shubham-gupta-iitr/mmmlX/tree/3485e6191e0e45bf1c8168e4e928a36ab9264d22
|
FCDiscriminator
|
import torch
import torch.nn as nn
import torch.utils.data
class FCDiscriminator(nn.Module):
"""
inplanes, planes. Patch-gan
"""
def __init__(self, inplanes, planes=64):
super(FCDiscriminator, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=2,
padding=1)
self.conv2 = nn.Conv2d(planes, planes * 2, kernel_size=3, stride=2,
padding=1)
self.conv3 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
stride=2, padding=1)
self.conv4 = nn.Conv2d(planes * 4, planes * 8, kernel_size=3,
stride=2, padding=1)
self.relu = nn.ReLU(inplace=True)
self.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.classifier = nn.Conv2d(planes * 8, 1, kernel_size=1)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.relu(x)
x = self.conv3(x)
x = self.relu(x)
x = self.conv4(x)
x = self.leaky_relu(x)
x = self.classifier(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 256
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_7(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
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_convolution_leaky_relu_8(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x2, tmp7, None)
@triton.jit
def triton_poi_fused_convolution_9(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
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (64, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (1, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_11, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4, 3, 3), (36, 1, 12, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(256, 9)](primals_1, buf0, 256, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_1[grid(16, 16)](primals_3, buf1, 16, 16, XBLOCK=16,
YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_2[grid(8192, 9)](primals_4, buf2, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_3[grid(32768, 9)](primals_6, buf3, 32768, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((512, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_4[grid(131072, 9)](primals_8, buf4, 131072, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = extern_kernels.convolution(buf1, buf0, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 64, 2, 2), (256, 1, 128, 64))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_5[grid(1024)](buf6, primals_2,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf7 = extern_kernels.convolution(buf6, buf2, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 128, 1, 1), (128, 1, 128, 128))
buf8 = buf7
del buf7
triton_poi_fused_convolution_relu_6[grid(512)](buf8, primals_5, 512,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf9 = extern_kernels.convolution(buf8, buf3, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 256, 1, 1), (256, 1, 256, 256))
buf10 = buf9
del buf9
triton_poi_fused_convolution_relu_7[grid(1024)](buf10, primals_7,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf11 = extern_kernels.convolution(buf10, buf4, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 512, 1, 1), (512, 1, 512, 512))
buf12 = buf11
del buf11
triton_poi_fused_convolution_leaky_relu_8[grid(2048)](buf12,
primals_9, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf13 = extern_kernels.convolution(buf12, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 1, 1, 1), (1, 1, 1, 1))
buf14 = buf13
del buf13
triton_poi_fused_convolution_9[grid(4)](buf14, primals_11, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_11
return (buf14, buf0, buf1, buf2, buf3, buf4, primals_10, buf6, buf8,
buf10, buf12)
class FCDiscriminatorNew(nn.Module):
"""
inplanes, planes. Patch-gan
"""
def __init__(self, inplanes, planes=64):
super(FCDiscriminatorNew, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=2,
padding=1)
self.conv2 = nn.Conv2d(planes, planes * 2, kernel_size=3, stride=2,
padding=1)
self.conv3 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
stride=2, padding=1)
self.conv4 = nn.Conv2d(planes * 4, planes * 8, kernel_size=3,
stride=2, padding=1)
self.relu = nn.ReLU(inplace=True)
self.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.classifier = nn.Conv2d(planes * 8, 1, kernel_size=1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.classifier.weight
primals_11 = self.classifier.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]
|
shiyutang/ProDA
|
FCDiscriminator
| false
| 4,330
|
[
"MIT"
] | 0
|
38209ced03c6044743273bb60e07cd915ac2ae12
|
https://github.com/shiyutang/ProDA/tree/38209ced03c6044743273bb60e07cd915ac2ae12
|
F1Loss
|
import torch
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class F1Loss(nn.Module):
"""F1Loss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', rp_weight=[1.0, 1.0], class_weight
=None, loss_weight=1.0):
super(F1Loss, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.rp_weight = rp_weight
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, predict, target, weight=None, avg_factor=None,
reduction_override=None, **kwargs):
"""Forward function."""
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (reduction_override if reduction_override else self.
reduction)
if self.class_weight is not None:
class_weight = torch.tensor(self.class_weight).type_as(predict)
else:
class_weight = None
N, _C, H, W = predict.size()
_, maxpred = torch.max(predict, 1)
predict_onehot = torch.zeros(predict.size()).type_as(maxpred)
predict_onehot.scatter_(1, maxpred.view(N, 1, H, W), 1)
target_onehot = torch.zeros(predict.size()).type_as(target)
target_onehot.scatter_(1, target.view(N, 1, H, W), 1)
true_positive = torch.sum(predict_onehot * target_onehot, dim=(2, 3))
total_target = torch.sum(target_onehot, dim=(2, 3))
total_predict = torch.sum(predict_onehot, dim=(2, 3))
recall = self.rp_weight[0] * (true_positive + self.smooth) / (
total_target + self.smooth)
precision = self.rp_weight[1] * (true_positive + self.smooth) / (
total_predict + self.smooth)
class_wise_loss = 2 * recall * precision / (recall + precision)
if class_weight is not None:
class_wise_loss = class_wise_loss * class_weight
loss = self.loss_weight * (1 - weight_reduce_loss(class_wise_loss,
weight, reduction=reduction, avg_factor=avg_factor))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4, 1, 4, 4], dtype=torch.
int64)]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch._C
import torch.serialization
from torch import nn
import torch.nn.functional as F
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp17 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp32 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 > tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = tl.full([1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 > tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 > tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tl.store(out_ptr0 + x2, tmp46, xmask)
@triton.jit
def triton_per_fused_mul_scatter_sum_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x1 = xindex // 4
x0 = xindex % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + (r2 + 16 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1, 1], 1, tl.int64)
tmp4 = tl.full([1, 1], 0, tl.int64)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp7 = tmp6 == tmp1
tmp8 = tl.where(tmp7, tmp3, tmp4)
tmp9 = tmp5 * tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tmp14 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp16 = tl.where(xmask, tmp14, 0)
tmp17 = tl.sum(tmp16, 1)[:, None]
tmp18 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp20 = tl.where(xmask, tmp18, 0)
tmp21 = tl.sum(tmp20, 1)[:, None]
tl.store(out_ptr0 + x3, tmp13, xmask)
tl.store(out_ptr1 + x3, tmp17, xmask)
tl.store(out_ptr2 + x3, tmp21, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp6 = tl.load(in_ptr1 + r0, None)
tmp12 = tl.load(in_ptr2 + r0, None)
tmp1 = tmp0.to(tl.float32)
tmp2 = 1e-06
tmp3 = tmp1 + tmp2
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp7 + tmp2
tmp9 = tmp5 / tmp8
tmp10 = 2.0
tmp11 = tmp9 * tmp10
tmp13 = tmp12.to(tl.float32)
tmp14 = tmp13 + tmp2
tmp15 = tmp5 / tmp14
tmp16 = tmp11 * tmp15
tmp17 = tmp9 + tmp15
tmp18 = tmp16 / tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = tl.sum(tmp19, 1)[:, None]
tmp22 = 16.0
tmp23 = tmp21 / tmp22
tmp24 = tmp4 - tmp23
tmp25 = tmp24 * tmp4
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp25, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 1, 4, 4), (16, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused_max_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
triton_per_fused_mul_scatter_sum_1[grid(16)](buf0, arg1_1, buf1,
buf2, buf3, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf0
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = buf4
del buf4
triton_per_fused_add_div_mean_mul_rsub_2[grid(1)](buf5, buf1, buf2,
buf3, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf1
del buf2
del buf3
return buf5,
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:
assert weight.dim() == loss.dim()
if weight.dim() > 1:
assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
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
class F1LossNew(nn.Module):
"""F1Loss.
Args:
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
def __init__(self, reduction='mean', rp_weight=[1.0, 1.0], class_weight
=None, loss_weight=1.0):
super(F1LossNew, self).__init__()
assert reduction in ('none', 'mean', 'sum')
self.reduction = reduction
self.rp_weight = rp_weight
self.loss_weight = loss_weight
self.class_weight = class_weight
self.smooth = 1e-06
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
shuaizzZ/mmsegmentation
|
F1Loss
| false
| 4,331
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
NonLocal
|
import torch
import torch._C
import torch.serialization
from torch import nn
from typing import *
def int_size(x):
size = tuple(int(s) for s in x.size())
return size
class NonLocal(nn.Module):
def __init__(self, in_channels):
super(NonLocal, self).__init__()
self.inter_channel = in_channels // 2
self.conv_phi = nn.Conv2d(in_channels=in_channels, out_channels=
self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.conv_theta = nn.Conv2d(in_channels=in_channels, out_channels=
self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.conv_g = nn.Conv2d(in_channels=in_channels, out_channels=self.
inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.softmax = nn.Softmax(dim=1)
self.conv_mask = nn.Conv2d(in_channels=self.inter_channel,
out_channels=in_channels, kernel_size=1, stride=1, padding=0,
bias=False)
def forward(self, x):
b, c, h, w = int_size(x)
x_phi = self.conv_phi(x).view(b, c, -1)
x_theta = self.conv_theta(x).view(b, c, -1).permute(0, 2, 1
).contiguous()
x_g = self.conv_g(x).view(b, c, -1).permute(0, 2, 1).contiguous()
mul_theta_phi = torch.matmul(x_theta, x_phi)
mul_theta_phi = self.softmax(mul_theta_phi)
mul_theta_phi_g = torch.matmul(mul_theta_phi, x_g)
mul_theta_phi_g = mul_theta_phi_g.permute(0, 2, 1).contiguous().view(b,
self.inter_channel, h, w)
mask = self.conv_mask(mul_theta_phi_g)
out = mask + x
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch._C
import torch.serialization
from torch import nn
from typing import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_transpose_0(in_out_ptr0, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 8
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
y2 = yindex % 4
y3 = yindex // 4
tmp0 = tl.load(in_out_ptr0 + (x1 + 8 * y0), xmask & ymask,
eviction_policy='evict_last')
tl.debug_barrier()
tl.store(in_out_ptr0 + (x1 + 8 * y0), tmp0, xmask & ymask)
tl.store(out_ptr0 + (y2 + 4 * x1 + 32 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 32
RBLOCK: tl.constexpr = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 8
x1 = xindex // 8
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 8 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused__softmax_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 % 8
x2 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 8 * x2), xmask, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr1 + (x0 + 8 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.exp(tmp2)
tmp5 = tmp3 / tmp4
tl.store(in_out_ptr0 + x3, tmp5, xmask)
@triton.jit
def triton_poi_fused_clone_view_3(in_out_ptr0, in_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 8
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 32 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.debug_barrier()
tl.store(in_out_ptr0 + (x2 + 8 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4, 2, 1, 1), (2, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 2, 4, 4), (32, 16, 4, 1))
buf1 = extern_kernels.convolution(primals_1, primals_3, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 2, 4, 4), (32, 16, 4, 1))
buf2 = extern_kernels.convolution(primals_1, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 4, 4), (32, 16, 4, 1))
buf3 = reinterpret_tensor(buf1, (4, 8, 4), (32, 1, 8), 0)
del buf1
buf15 = empty_strided_cuda((4, 4, 8), (32, 1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_transpose_0[grid(16, 8)](buf3, buf15, 16, 8,
XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((4, 8, 8), (64, 8, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf0, (4, 4, 8), (32, 8,
1), 0), out=buf4)
buf5 = empty_strided_cuda((4, 1, 8), (8, 32, 1), torch.float32)
buf6 = empty_strided_cuda((4, 1, 8), (8, 32, 1), torch.float32)
triton_per_fused__softmax_1[grid(32)](buf4, buf5, buf6, 32, 8,
XBLOCK=32, num_warps=2, num_stages=1)
buf7 = buf4
del buf4
triton_poi_fused__softmax_2[grid(256)](buf7, buf5, buf6, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf2, (4, 8, 4), (32, 1, 8), 0)
del buf2
buf14 = reinterpret_tensor(buf3, (4, 4, 8), (32, 1, 4), 0)
del buf3
triton_poi_fused_clone_transpose_0[grid(16, 8)](buf8, buf14, 16, 8,
XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 8, 4), (32, 4, 1), torch.float32)
extern_kernels.bmm(buf7, buf8, out=buf9)
buf10 = reinterpret_tensor(buf8, (4, 4, 8), (32, 8, 1), 0)
del buf8
buf11 = reinterpret_tensor(buf10, (4, 2, 4, 4), (32, 16, 4, 1), 0)
del buf10
triton_poi_fused_clone_view_3[grid(16, 8)](buf11, buf9, 16, 8,
XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
del buf9
buf12 = extern_kernels.convolution(buf11, primals_5, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 4, 4, 4), (64, 16, 4, 1))
buf13 = buf12
del buf12
triton_poi_fused_add_4[grid(256)](buf13, primals_1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return (buf13, primals_1, primals_2, primals_3, primals_4, primals_5,
buf7, buf11, buf14, buf15, reinterpret_tensor(buf0, (4, 8, 4), (32,
1, 8), 0))
def int_size(x):
size = tuple(int(s) for s in x.size())
return size
class NonLocalNew(nn.Module):
def __init__(self, in_channels):
super(NonLocalNew, self).__init__()
self.inter_channel = in_channels // 2
self.conv_phi = nn.Conv2d(in_channels=in_channels, out_channels=
self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.conv_theta = nn.Conv2d(in_channels=in_channels, out_channels=
self.inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.conv_g = nn.Conv2d(in_channels=in_channels, out_channels=self.
inter_channel, kernel_size=1, stride=1, padding=0, bias=False)
self.softmax = nn.Softmax(dim=1)
self.conv_mask = nn.Conv2d(in_channels=self.inter_channel,
out_channels=in_channels, kernel_size=1, stride=1, padding=0,
bias=False)
def forward(self, input_0):
primals_2 = self.conv_phi.weight
primals_3 = self.conv_theta.weight
primals_4 = self.conv_g.weight
primals_5 = self.conv_mask.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
shuaizzZ/mmsegmentation
|
NonLocal
| false
| 4,332
|
[
"Apache-2.0"
] | 0
|
a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
https://github.com/shuaizzZ/mmsegmentation/tree/a6c6b348dbf8c4a0a39ffbdb832a1e82309c533c
|
BertOutput
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.utils.data
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-05):
"""Construct a layernorm module in the TF style (epsilon inside the square root)."""
super(BertLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class BertOutput(nn.Module):
def __init__(self, config):
super(BertOutput, self).__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-05)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(intermediate_size=4, hidden_size=4,
hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.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_add_mean_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + 1)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp10 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + 2)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp17 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + 3)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK])
tmp24 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp0 + tmp2
tmp5 = tmp3 + tmp4
tmp9 = tmp6 + tmp8
tmp11 = tmp9 + tmp10
tmp12 = tmp5 + tmp11
tmp16 = tmp13 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tmp12 + tmp18
tmp23 = tmp20 + tmp22
tmp25 = tmp23 + tmp24
tmp26 = tmp19 + tmp25
tmp27 = 4.0
tmp28 = tmp26 / tmp27
tl.store(out_ptr0 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_sub_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 - tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1e-05
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mean_0[grid(64)](buf0, primals_2, primals_4,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_add_sub_1[grid(256)](buf2, primals_2, primals_4,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf1
del primals_2
del primals_4
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_2[grid(256)](primals_5,
buf2, primals_6, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_6
return buf3, primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-05):
"""Construct a layernorm module in the TF style (epsilon inside the square root)."""
super(BertLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class BertOutputNew(nn.Module):
def __init__(self, config):
super(BertOutputNew, self).__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-05)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.dense.weight
primals_2 = self.dense.bias
primals_5 = self.LayerNorm.weight
primals_6 = self.LayerNorm.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
shubham-gupta-iitr/mmmlX
|
BertOutput
| false
| 4,333
|
[
"Apache-2.0"
] | 0
|
3485e6191e0e45bf1c8168e4e928a36ab9264d22
|
https://github.com/shubham-gupta-iitr/mmmlX/tree/3485e6191e0e45bf1c8168e4e928a36ab9264d22
|
GELU
|
import math
import torch
from torch import nn
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, tensor):
geluPow = tensor + 0.044715 * torch.pow(tensor, 3)
geluTanh = torch.tanh(math.sqrt(2 / math.pi) * geluPow)
geluResult = 1 + geluTanh
return 0.5 * tensor * geluResult
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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_pow_tanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = 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_pow_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(GELUNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
simonepreite/QABERT
|
GELU
| false
| 4,334
|
[
"MIT"
] | 0
|
ed3e49f6619f3ff660068291231909693cb8f5d5
|
https://github.com/simonepreite/QABERT/tree/ed3e49f6619f3ff660068291231909693cb8f5d5
|
RefModel1d
|
import torch
import torch.nn.functional as F
class RefModel1d(torch.nn.Module):
"""The 3D reference model."""
def __init__(self):
super().__init__()
self.l1 = torch.nn.Conv1d(2, 2, 1, bias=True)
self.l2 = torch.nn.InstanceNorm1d(2, affine=True)
self.l3 = torch.nn.ReLU()
self.l4 = torch.nn.Dropout(0.2)
self.l5 = torch.nn.AvgPool1d(2)
self.l7 = torch.nn.AdaptiveAvgPool1d(1)
def forward(self, x):
output = self.l1(x)
output = self.l2(output)
output = self.l3(output)
output = self.l4(output)
output = self.l5(output)
output = F.interpolate(output, mode='linear', scale_factor=2)
output = self.l7(output)
return output
def get_inputs():
return [torch.rand([4, 2, 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
assert_size_stride = torch._C._dynamo.guards.assert_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_relu_repeat_threshold_backward_0(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr3,
out_ptr4, out_ptr5, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 8
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)
x0 = xindex
r3 = rindex
x1 = xindex % 2
tmp0 = tl.load(in_ptr0 + x0 % 2, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 64 * x0), xmask, other=0.0)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tl.where(xmask, tmp4, 0)
tmp7 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp12 = tmp11.to(tl.float32)
tmp13 = tmp10 / tmp12
tmp14 = tmp4 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.where(xmask, tmp16, 0)
tmp19 = tl.sum(tmp18, 1)[:, None]
tmp20 = tmp3 - tmp13
tmp21 = 64.0
tmp22 = tmp19 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.rsqrt(tmp24)
tmp26 = tmp20 * tmp25
tmp27 = tmp26 * tmp0
tmp29 = tmp27 + tmp28
tmp30 = tl.full([1, 1], 0, tl.int32)
tmp31 = triton_helpers.maximum(tmp30, tmp29)
tmp32 = 0.0
tmp33 = tmp31 <= tmp32
tl.store(out_ptr0 + x0, tmp0, xmask)
tl.store(in_out_ptr0 + (r3 + 64 * x0), tmp3, xmask)
tl.store(out_ptr3 + (r3 + 64 * x0), tmp31, xmask)
tl.store(out_ptr4 + (r3 + 64 * x0), tmp33, xmask)
tl.store(out_ptr5 + x0, tmp25, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_1(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_2(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = tl.full([1], 31, tl.int64)
tmp12 = triton_helpers.minimum(tmp10, tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_3(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_mean_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 8
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
tmp22 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp0 = r1
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.load(in_ptr0 + (2 * tmp8 + 64 * x0), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * tmp8 + 64 * x0), xmask,
eviction_policy='evict_last')
tmp11 = tmp10 + tmp9
tmp12 = tmp11 * tmp2
tmp13 = tl.full([1, 1], 1, tl.int64)
tmp14 = tmp8 + tmp13
tmp15 = tl.full([1, 1], 31, tl.int64)
tmp16 = triton_helpers.minimum(tmp14, tmp15)
tmp17 = tl.load(in_ptr0 + (2 * tmp16 + 64 * x0), xmask, eviction_policy
='evict_last')
tmp18 = tl.load(in_ptr0 + (1 + 2 * tmp16 + 64 * x0), xmask,
eviction_policy='evict_last')
tmp19 = tmp18 + tmp17
tmp20 = tmp19 * tmp2
tmp21 = tmp20 - tmp12
tmp23 = tmp21 * tmp22
tmp24 = tmp12 + tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.where(xmask, tmp25, 0)
tmp28 = tl.sum(tmp27, 1)[:, None]
tmp29 = 64.0
tmp30 = tmp28 / tmp29
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp30, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (2, 2, 1), (2, 1, 1))
assert_size_stride(primals_2, (2,), (1,))
assert_size_stride(primals_3, (4, 2, 64), (128, 64, 1))
assert_size_stride(primals_4, (2,), (1,))
assert_size_stride(primals_5, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 2, 64), (128, 64, 1))
buf2 = empty_strided_cuda((8,), (1,), torch.float32)
buf1 = buf0
del buf0
buf3 = empty_strided_cuda((1, 8, 1), (8, 1, 8), torch.float32)
buf7 = empty_strided_cuda((4, 2, 64), (128, 64, 1), torch.float32)
buf13 = empty_strided_cuda((4, 2, 64), (128, 64, 1), torch.bool)
buf6 = empty_strided_cuda((1, 8, 1), (8, 1, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_convolution_relu_repeat_threshold_backward_0[
grid(8)](buf1, primals_4, primals_2, primals_5, buf2, buf3,
buf7, buf13, buf6, 8, 64, XBLOCK=1, num_warps=2, num_stages=1)
del primals_2
del primals_4
del primals_5
buf8 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_1[grid(64)](buf8,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused_add_clamp_2[grid(64)](buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf10 = empty_strided_cuda((64,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_3[grid(64)](buf10,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
buf12 = buf11
del buf11
triton_per_fused_mean_4[grid(8)](buf12, buf7, buf10, 8, 64, XBLOCK=
1, num_warps=2, num_stages=1)
return reinterpret_tensor(buf12, (4, 2, 1), (2, 1, 1), 0
), primals_1, primals_3, buf1, buf2, reinterpret_tensor(buf6, (8,),
(1,), 0), reinterpret_tensor(buf7, (4, 2, 1, 64), (128, 64, 64, 1), 0
), buf8, buf9, buf10, buf13, reinterpret_tensor(buf3, (1, 8, 1), (8,
1, 1), 0)
class RefModel1dNew(torch.nn.Module):
"""The 3D reference model."""
def __init__(self):
super().__init__()
self.l1 = torch.nn.Conv1d(2, 2, 1, bias=True)
self.l2 = torch.nn.InstanceNorm1d(2, affine=True)
self.l3 = torch.nn.ReLU()
self.l4 = torch.nn.Dropout(0.2)
self.l5 = torch.nn.AvgPool1d(2)
self.l7 = torch.nn.AdaptiveAvgPool1d(1)
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_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
shuohan/pytorch-layers
|
RefModel1d
| false
| 4,335
|
[
"MIT"
] | 0
|
020846fd02d501cf477552179c19ba4b5e9a0695
|
https://github.com/shuohan/pytorch-layers/tree/020846fd02d501cf477552179c19ba4b5e9a0695
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.