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
Normalize
import torch import torch.nn as nn from itertools import product as product import torch.onnx class Normalize(nn.Module): def __init__(self, n_channels, scale=1.0): super(Normalize, self).__init__() self.n_channels = n_channels self.scale = scale self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(self.n_channels)) self.weight.data *= 0.0 self.weight.data += self.scale self.register_parameter('bias', None) def __repr__(self): return 'Normalize(channels=%d, scale=%f)' % (self.n_channels, self. scale) def forward(self, x): norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps x = x / norm * self.weight.view(1, -1, 1, 1) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'n_channels': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn from itertools import product as product import torch.onnx assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_mul_pow_sqrt_sum_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 x3 = xindex x0 = xindex % 16 x2 = xindex // 64 x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp16 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-10 tmp14 = tmp12 + tmp13 tmp15 = tmp0 / tmp14 tmp17 = tmp15 * tmp16 tl.store(out_ptr0 + x3, tmp17, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_mul_pow_sqrt_sum_0[grid(256)](primals_1, primals_2, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 return buf0, primals_1 class NormalizeNew(nn.Module): def __init__(self, n_channels, scale=1.0): super(NormalizeNew, self).__init__() self.n_channels = n_channels self.scale = scale self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(self.n_channels)) self.weight.data *= 0.0 self.weight.data += self.scale self.register_parameter('bias', None) def __repr__(self): return 'Normalize(channels=%d, scale=%f)' % (self.n_channels, self. scale) def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
Janus1984/Msnhnet
Normalize
false
13,872
[ "MIT" ]
546
4e09f2501ba8db789f0a20441a357de3ba468f10
https://github.com/Janus1984/Msnhnet/tree/4e09f2501ba8db789f0a20441a357de3ba468f10
GeLU
from torch.nn import Module import functools import math import torch import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init class GeLU(Module): def forward(self, x): return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) class PrePostInitMeta(type): """A metaclass that calls optional `__pre_init__` and `__post_init__` methods""" def __new__(cls, name, bases, dct): x = super().__new__(cls, name, bases, dct) old_init = x.__init__ def _pass(self): pass @functools.wraps(old_init) def _init(self, *args, **kwargs): self.__pre_init__() old_init(self, *args, **kwargs) self.__post_init__() x.__init__ = _init if not hasattr(x, '__pre_init__'): x.__pre_init__ = _pass if not hasattr(x, '__post_init__'): x.__post_init__ = _pass return x class Module(nn.Module, metaclass=PrePostInitMeta): """Same as `nn.Module`, but no need for subclasses to call `super().__init__`""" def __pre_init__(self): super().__init__() def __init__(self): pass 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.nn import Module import functools import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_mul_pow_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(Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0] class PrePostInitMeta(type): """A metaclass that calls optional `__pre_init__` and `__post_init__` methods""" def __new__(cls, name, bases, dct): x = super().__new__(cls, name, bases, dct) old_init = x.__init__ def _pass(self): pass @functools.wraps(old_init) def _init(self, *args, **kwargs): self.__pre_init__() old_init(self, *args, **kwargs) self.__post_init__() x.__init__ = _init if not hasattr(x, '__pre_init__'): x.__pre_init__ = _pass if not hasattr(x, '__post_init__'): x.__post_init__ = _pass return x class Module(nn.Module, metaclass=PrePostInitMeta): """Same as `nn.Module`, but no need for subclasses to call `super().__init__`""" def __pre_init__(self): super().__init__() def __init__(self): pass
JiahuaWU/fastai
GeLU
false
13,873
[ "Apache-2.0" ]
59
13a2df812d875abf0558004283392ab40d9bdea1
https://github.com/JiahuaWU/fastai/tree/13a2df812d875abf0558004283392ab40d9bdea1
Scale
import torch import torch.nn as nn from torch.nn.parameter import Parameter from itertools import product as product import torch.onnx class Scale(nn.Module): def __init__(self, channels): super(Scale, self).__init__() self.weight = Parameter(torch.Tensor(channels)) self.bias = Parameter(torch.Tensor(channels)) self.channels = channels def __repr__(self): return 'Scale(channels = %d)' % self.channels def forward(self, x): if x.dim() == 2: nB = x.size(0) nC = x.size(1) x = x * self.weight.view(1, nC).expand(nB, nC) + self.bias.view( 1, nC).expand(nB, nC) else: nB = x.size(0) nC = x.size(1) nH = x.size(2) nW = x.size(3) x = x * self.weight.view(1, nC, 1, 1).expand(nB, nC, nH, nW ) + self.bias.view(1, nC, 1, 1).expand(nB, nC, nH, nW) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channels': 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 from torch.nn.parameter import Parameter from itertools import product as product import torch.onnx assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tmp4 = tmp2 + tmp3 tl.store(out_ptr0 + x3, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (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_add_mul_0[grid(256)](primals_1, primals_2, primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 del primals_3 return buf0, primals_1 class ScaleNew(nn.Module): def __init__(self, channels): super(ScaleNew, self).__init__() self.weight = Parameter(torch.Tensor(channels)) self.bias = Parameter(torch.Tensor(channels)) self.channels = channels def __repr__(self): return 'Scale(channels = %d)' % self.channels 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]
Janus1984/Msnhnet
Scale
false
13,874
[ "MIT" ]
546
4e09f2501ba8db789f0a20441a357de3ba468f10
https://github.com/Janus1984/Msnhnet/tree/4e09f2501ba8db789f0a20441a357de3ba468f10
Ecgclient
import torch import torch.nn as nn class Ecgclient(nn.Module): def __init__(self): super(Ecgclient, self).__init__() self.conv1 = nn.Conv1d(1, 16, 7, padding=3) self.relu1 = nn.LeakyReLU() self.pool1 = nn.MaxPool1d(2) self.conv2 = nn.Conv1d(16, 16, 5, padding=2) self.relu2 = nn.LeakyReLU() def forward(self, x): x = self.conv1(x) x = self.relu1(x) x = self.pool1(x) x = self.conv2(x) x = self.relu2(x) return x def get_inputs(): return [torch.rand([4, 1, 64])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_convolution_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 64 % 16 tmp0 = tl.load(in_ptr0 + x3, None) tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.01 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(out_ptr0 + x3, tmp4, None) tl.store(out_ptr1 + x3, tmp7, 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 tmp0 = tl.load(in_ptr0 + 2 * x0, None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0), None, eviction_policy='evict_last') tmp2 = tmp1 > tmp0 tmp3 = tl.full([1], 1, tl.int8) tmp4 = tl.full([1], 0, tl.int8) tmp5 = tl.where(tmp2, tmp3, tmp4) tmp6 = triton_helpers.maximum(tmp1, tmp0) tl.store(out_ptr0 + x0, tmp5, None) tl.store(out_ptr1 + x0, tmp6, None) @triton.jit def triton_poi_fused_convolution_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 32 % 16 tmp0 = tl.load(in_ptr0 + x3, None) tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.01 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(out_ptr0 + x3, tmp4, None) tl.store(out_ptr1 + x3, tmp7, None) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (16, 1, 7), (7, 7, 1)) assert_size_stride(primals_2, (16,), (1,)) assert_size_stride(primals_3, (4, 1, 64), (64, 64, 1)) assert_size_stride(primals_4, (16, 16, 5), (80, 5, 1)) assert_size_stride(primals_5, (16,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,), padding=(3,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf0, (4, 16, 64), (1024, 64, 1)) buf1 = empty_strided_cuda((4, 16, 64), (1024, 64, 1), torch.bool) buf2 = empty_strided_cuda((4, 16, 64), (1024, 64, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_leaky_relu_0[grid(4096)](buf0, primals_2, buf1, buf2, 4096, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_2 buf3 = empty_strided_cuda((4, 16, 1, 32), (512, 32, 32, 1), torch.int8) buf4 = empty_strided_cuda((4, 16, 1, 32), (512, 32, 32, 1), torch. float32) triton_poi_fused_max_pool2d_with_indices_1[grid(2048)](buf2, buf3, buf4, 2048, XBLOCK=256, num_warps=4, num_stages=1) buf5 = extern_kernels.convolution(reinterpret_tensor(buf4, (4, 16, 32), (512, 32, 1), 0), primals_4, stride=(1,), padding=(2,), dilation=(1,), transposed=False, output_padding=(0,), groups=1, bias=None) assert_size_stride(buf5, (4, 16, 32), (512, 32, 1)) buf6 = empty_strided_cuda((4, 16, 32), (512, 32, 1), torch.bool) buf7 = empty_strided_cuda((4, 16, 32), (512, 32, 1), torch.float32) triton_poi_fused_convolution_leaky_relu_2[grid(2048)](buf5, primals_5, buf6, buf7, 2048, XBLOCK=256, num_warps=4, num_stages=1) del buf5 del primals_5 return buf7, primals_1, primals_3, primals_4, buf1, reinterpret_tensor(buf2 , (4, 16, 1, 64), (1024, 64, 64, 1), 0), buf3, reinterpret_tensor(buf4, (4, 16, 32), (512, 32, 1), 0), buf6 class EcgclientNew(nn.Module): def __init__(self): super(EcgclientNew, self).__init__() self.conv1 = nn.Conv1d(1, 16, 7, padding=3) self.relu1 = nn.LeakyReLU() self.pool1 = nn.MaxPool1d(2) self.conv2 = nn.Conv1d(16, 16, 5, padding=2) self.relu2 = nn.LeakyReLU() 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]
JayDigvijay/Federated-Learning-and-Split-Learning-with-raspberry-pi
Ecgclient
false
13,875
[ "MIT" ]
48
314a9618fc6be2ba1b9b7bdf93b126d49a2519ee
https://github.com/JayDigvijay/Federated-Learning-and-Split-Learning-with-raspberry-pi/tree/314a9618fc6be2ba1b9b7bdf93b126d49a2519ee
CELoss
import torch import torch.nn.functional as F from torch import nn def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Avarage factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None): """Calculate the CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. label (torch.Tensor): The gt label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. reduction (str): The method used to reduce the loss. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. Returns: torch.Tensor: The calculated loss """ loss = F.cross_entropy(pred, label, reduction='none') if weight is not None: weight = weight.float() loss = weight_reduce_loss(loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss class CELoss(nn.Module): def __init__(self, reduction='mean', loss_weight=1.0): super(CELoss, self).__init__() self.reduction = reduction self.loss_weight = loss_weight self.cls_criterion = cross_entropy def forward(self, cls_score, label, weight=None, avg_factor=None, reduction_override=None, **kwargs): assert reduction_override in (None, 'none', 'mean', 'sum') reduction = (reduction_override if reduction_override else self. reduction) n_pred_ch, n_target_ch = cls_score.shape[1], label.shape[1] if n_pred_ch == n_target_ch: label = torch.argmax(label, dim=1) else: label = torch.squeeze(label, dim=1) label = label.long() loss_cls = self.loss_weight * self.cls_criterion(cls_score, label, weight, reduction=reduction, avg_factor=avg_factor, **kwargs) return loss_cls def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn.functional 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 @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused_argmax_mean_mul_nll_loss2d_forward_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp17 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp32 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp56 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp58 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp61 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp64 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) 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, 1], 0, tl.int64) tmp11 = tl.full([1, 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, 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, 1], 3, tl.int64) tmp42 = tmp31 < tmp41 tmp43 = tmp40 & tmp42 tmp44 = tmp38 | tmp43 tl.where(tmp44, tmp30, tmp32) tmp46 = tl.where(tmp44, tmp31, tmp41) tmp47 = tl.full([1, 1], -100, tl.int64) tmp48 = tmp46 != tmp47 tmp49 = tl.where(tmp48, tmp46, tmp10) tmp50 = tl.full([XBLOCK, RBLOCK], 4, tl.int32) tmp51 = tmp49 + tmp50 tmp52 = tmp49 < 0 tmp53 = tl.where(tmp52, tmp51, tmp49) tl.device_assert((0 <= tmp53) & (tmp53 < 4), 'index out of bounds: 0 <= tmp53 < 4') tmp55 = tl.load(in_ptr1 + (r0 + 16 * tmp53 + 64 * r1), None) tmp57 = tl_math.exp(tmp56) tmp59 = tl_math.exp(tmp58) tmp60 = tmp57 + tmp59 tmp62 = tl_math.exp(tmp61) tmp63 = tmp60 + tmp62 tmp65 = tl_math.exp(tmp64) tmp66 = tmp63 + tmp65 tmp67 = tl_math.log(tmp66) tmp68 = tmp55 - tmp67 tmp69 = -tmp68 tmp70 = 0.0 tmp71 = tl.where(tmp48, tmp69, tmp70) tmp72 = tl.broadcast_to(tmp71, [XBLOCK, RBLOCK]) tmp74 = tl.sum(tmp72, 1)[:, None] tmp75 = 64.0 tmp76 = tmp74 / tmp75 tmp77 = 1.0 tmp78 = tmp76 * tmp77 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp78, 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((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 triton_per_fused_argmax_mean_mul_nll_loss2d_forward_1[grid(1)](buf3, arg1_1, buf1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg1_1 del buf1 return buf3, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Avarage factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None): """Calculate the CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. label (torch.Tensor): The gt label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. reduction (str): The method used to reduce the loss. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. Returns: torch.Tensor: The calculated loss """ loss = F.cross_entropy(pred, label, reduction='none') if weight is not None: weight = weight.float() loss = weight_reduce_loss(loss, weight=weight, reduction=reduction, avg_factor=avg_factor) return loss class CELossNew(nn.Module): def __init__(self, reduction='mean', loss_weight=1.0): super(CELossNew, self).__init__() self.reduction = reduction self.loss_weight = loss_weight self.cls_criterion = cross_entropy def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
JiYuanFeng/MCTrans
CELoss
false
13,876
[ "Apache-2.0" ]
84
9b8b5677eef584b423d5e1630680a4b667cbe823
https://github.com/JiYuanFeng/MCTrans/tree/9b8b5677eef584b423d5e1630680a4b667cbe823
EdgeFeaturesLayer
import torch import torch.nn as nn class EdgeFeaturesLayer(nn.Module): def __init__(self, d_model, d_edge, h, dropout): super(EdgeFeaturesLayer, self).__init__() assert d_model % h == 0 d_model // h self.linear = nn.Linear(d_edge, 1, bias=False) with torch.no_grad(): self.linear.weight.fill_(0.25) def forward(self, x): p_edge = x.permute(0, 2, 3, 1) p_edge = self.linear(p_edge).permute(0, 3, 1, 2) return torch.relu(p_edge) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'d_model': 4, 'd_edge': 4, 'h': 4, 'dropout': 0.5}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 64 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 16 y1 = yindex // 16 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_relu_threshold_backward_1(in_out_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.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = 0.0 tmp4 = tmp2 <= tmp3 tl.store(in_out_ptr0 + x0, tmp2, xmask) tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 1), (1, 4), 0), out=buf1) del primals_2 buf2 = reinterpret_tensor(buf1, (4, 1, 4, 4), (16, 1, 4, 1), 0) del buf1 buf3 = empty_strided_cuda((4, 1, 4, 4), (16, 1, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(64)](buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) return buf2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf3 class EdgeFeaturesLayerNew(nn.Module): def __init__(self, d_model, d_edge, h, dropout): super(EdgeFeaturesLayerNew, self).__init__() assert d_model % h == 0 d_model // h self.linear = nn.Linear(d_edge, 1, bias=False) with torch.no_grad(): self.linear.weight.fill_(0.25) def forward(self, input_0): primals_2 = self.linear.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
Jh-SYSU/MolRep
EdgeFeaturesLayer
false
13,877
[ "MIT" ]
57
b2c802d18d41d7db26c19c6dd644098f945e48a1
https://github.com/Jh-SYSU/MolRep/tree/b2c802d18d41d7db26c19c6dd644098f945e48a1
PositionGenerator
import torch import torch.nn as nn class LayerNorm(nn.Module): def __init__(self, hidden_size, variance_epsilon=1e-12): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(hidden_size)) self.beta = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = variance_epsilon def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.gamma * x + self.beta class PositionGenerator(nn.Module): """Define standard linear + softmax generation step.""" def __init__(self, d_model): super(PositionGenerator, self).__init__() self.norm = LayerNorm(d_model) self.proj = nn.Linear(d_model, 3) def forward(self, x, mask): mask = mask.unsqueeze(-1).float() out_masked = self.norm(x) * mask projected = self.proj(out_masked) return projected def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'d_model': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.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_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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = 4.0 tmp9 = tmp7 / tmp8 tmp10 = tmp0 - tmp9 tl.store(out_ptr0 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_add_div_mean_mul_pow_sqrt_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 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) @triton.jit def triton_poi_fused_add_div_mean_mul_pow_sqrt_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex % 256 x4 = xindex // 4 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, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (3, 4), (4, 1)) assert_size_stride(primals_6, (3,), (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_2, 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_3, buf0, primals_4, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_3 del primals_4 buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_add_div_mean_mul_pow_sqrt_2[grid(1024)](buf1, primals_1, buf2, 1024, XBLOCK=256, num_warps=4, num_stages=1) del buf1 buf3 = empty_strided_cuda((256, 3), (3, 1), torch.float32) extern_kernels.addmm(primals_6, reinterpret_tensor(buf2, (256, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 3), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_6 return reinterpret_tensor(buf3, (4, 4, 4, 4, 3), (192, 48, 12, 3, 1), 0 ), primals_1, primals_2, reinterpret_tensor(buf2, (256, 4), (4, 1), 0 ), primals_5 class LayerNorm(nn.Module): def __init__(self, hidden_size, variance_epsilon=1e-12): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(hidden_size)) self.beta = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = variance_epsilon def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.gamma * x + self.beta class PositionGeneratorNew(nn.Module): """Define standard linear + softmax generation step.""" def __init__(self, d_model): super(PositionGeneratorNew, self).__init__() self.norm = LayerNorm(d_model) self.proj = nn.Linear(d_model, 3) def forward(self, input_0, input_1): primals_3 = self.norm.gamma primals_4 = self.norm.beta primals_5 = self.proj.weight primals_6 = self.proj.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
Jh-SYSU/MolRep
PositionGenerator
false
13,878
[ "MIT" ]
57
b2c802d18d41d7db26c19c6dd644098f945e48a1
https://github.com/Jh-SYSU/MolRep/tree/b2c802d18d41d7db26c19c6dd644098f945e48a1
LNN
import math import torch import torch.utils.data import torch.nn.functional as F class LNN(torch.nn.Module): """ A pytorch implementation of LNN layer Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``. Arguments - **in_features** : Embedding of feature. - **num_fields**: int.The field size of feature. - **LNN_dim**: int.The number of Logarithmic neuron. - **bias**: bool.Whether or not use bias in LNN. """ def __init__(self, num_fields, embed_dim, LNN_dim, bias=False): super(LNN, self).__init__() self.num_fields = num_fields self.embed_dim = embed_dim self.LNN_dim = LNN_dim self.lnn_output_dim = LNN_dim * embed_dim self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): stdv = 1.0 / math.sqrt(self.weight.size(1)) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, x): """ :param x: Long tensor of size ``(batch_size, num_fields, embedding_size)`` """ embed_x_abs = torch.abs(x) embed_x_afn = torch.add(embed_x_abs, 1e-07) embed_x_log = torch.log1p(embed_x_afn) lnn_out = torch.matmul(self.weight, embed_x_log) if self.bias is not None: lnn_out += self.bias lnn_exp = torch.expm1(lnn_out) output = F.relu(lnn_exp).contiguous().view(-1, self.lnn_output_dim) return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_fields': 4, 'embed_dim': 4, 'LNN_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import math import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 64 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tmp1 = tl_math.abs(tmp0) tmp2 = 1e-07 tmp3 = tmp1 + tmp2 tmp4 = libdevice.log1p(tmp3) tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask) @triton.jit def triton_poi_fused_clone_expm1_relu_threshold_backward_1(in_ptr0, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl. constexpr): ynumel = 64 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tmp1 = libdevice.expm1(tmp0) tmp2 = tl.full([1, 1], 0, tl.int32) tmp3 = triton_helpers.maximum(tmp2, tmp1) tmp4 = 0.0 tmp5 = tmp3 <= tmp4 tl.store(out_ptr0 + (x2 + 4 * y3), tmp3, xmask & ymask) tl.store(out_ptr1 + (x2 + 4 * y3), tmp5, xmask & ymask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1) del primals_2 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_clone_expm1_relu_threshold_backward_1[grid(64, 4)]( buf1, buf2, buf3, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) return reinterpret_tensor(buf2, (16, 16), (16, 1), 0), reinterpret_tensor( buf0, (64, 4), (4, 1), 0), buf1, buf3 class LNNNew(torch.nn.Module): """ A pytorch implementation of LNN layer Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``. Arguments - **in_features** : Embedding of feature. - **num_fields**: int.The field size of feature. - **LNN_dim**: int.The number of Logarithmic neuron. - **bias**: bool.Whether or not use bias in LNN. """ def __init__(self, num_fields, embed_dim, LNN_dim, bias=False): super(LNNNew, self).__init__() self.num_fields = num_fields self.embed_dim = embed_dim self.LNN_dim = LNN_dim self.lnn_output_dim = LNN_dim * embed_dim self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): stdv = 1.0 / math.sqrt(self.weight.size(1)) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
JazonJiao/pytorch-fm
LNN
false
13,879
[ "MIT" ]
734
7192e7861fa54341d5b2df995f92858f583ea09e
https://github.com/JazonJiao/pytorch-fm/tree/7192e7861fa54341d5b2df995f92858f583ea09e
FactorizationMachine
import torch import torch.utils.data class FactorizationMachine(torch.nn.Module): def __init__(self, reduce_sum=True): super().__init__() self.reduce_sum = reduce_sum def forward(self, x): """ :param x: Float tensor of size ``(batch_size, num_fields, embed_dim)`` """ square_of_sum = torch.sum(x, dim=1) ** 2 sum_of_square = torch.sum(x ** 2, dim=1) ix = square_of_sum - sum_of_square if self.reduce_sum: ix = torch.sum(ix, dim=1, keepdim=True) return 0.5 * ix def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mul_pow_sub_sum_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp16 = tl.load(in_ptr0 + (4 + x0 + 64 * x1), xmask) tmp17 = tl.load(in_ptr0 + (20 + x0 + 64 * x1), xmask) tmp19 = tl.load(in_ptr0 + (36 + x0 + 64 * x1), xmask) tmp21 = tl.load(in_ptr0 + (52 + x0 + 64 * x1), xmask) tmp33 = tl.load(in_ptr0 + (8 + x0 + 64 * x1), xmask) tmp34 = tl.load(in_ptr0 + (24 + x0 + 64 * x1), xmask) tmp36 = tl.load(in_ptr0 + (40 + x0 + 64 * x1), xmask) tmp38 = tl.load(in_ptr0 + (56 + x0 + 64 * x1), xmask) tmp50 = tl.load(in_ptr0 + (12 + x0 + 64 * x1), xmask) tmp51 = tl.load(in_ptr0 + (28 + x0 + 64 * x1), xmask) tmp53 = tl.load(in_ptr0 + (44 + x0 + 64 * x1), xmask) tmp55 = tl.load(in_ptr0 + (60 + x0 + 64 * x1), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = tmp6 * tmp6 tmp8 = tmp0 * tmp0 tmp9 = tmp1 * tmp1 tmp10 = tmp8 + tmp9 tmp11 = tmp3 * tmp3 tmp12 = tmp10 + tmp11 tmp13 = tmp5 * tmp5 tmp14 = tmp12 + tmp13 tmp15 = tmp7 - tmp14 tmp18 = tmp16 + tmp17 tmp20 = tmp18 + tmp19 tmp22 = tmp20 + tmp21 tmp23 = tmp22 * tmp22 tmp24 = tmp16 * tmp16 tmp25 = tmp17 * tmp17 tmp26 = tmp24 + tmp25 tmp27 = tmp19 * tmp19 tmp28 = tmp26 + tmp27 tmp29 = tmp21 * tmp21 tmp30 = tmp28 + tmp29 tmp31 = tmp23 - tmp30 tmp32 = tmp15 + tmp31 tmp35 = tmp33 + tmp34 tmp37 = tmp35 + tmp36 tmp39 = tmp37 + tmp38 tmp40 = tmp39 * tmp39 tmp41 = tmp33 * tmp33 tmp42 = tmp34 * tmp34 tmp43 = tmp41 + tmp42 tmp44 = tmp36 * tmp36 tmp45 = tmp43 + tmp44 tmp46 = tmp38 * tmp38 tmp47 = tmp45 + tmp46 tmp48 = tmp40 - tmp47 tmp49 = tmp32 + tmp48 tmp52 = tmp50 + tmp51 tmp54 = tmp52 + tmp53 tmp56 = tmp54 + tmp55 tmp57 = tmp56 * tmp56 tmp58 = tmp50 * tmp50 tmp59 = tmp51 * tmp51 tmp60 = tmp58 + tmp59 tmp61 = tmp53 * tmp53 tmp62 = tmp60 + tmp61 tmp63 = tmp55 * tmp55 tmp64 = tmp62 + tmp63 tmp65 = tmp57 - tmp64 tmp66 = tmp49 + tmp65 tmp67 = 0.5 tmp68 = tmp66 * tmp67 tl.store(in_out_ptr0 + x2, tmp68, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32) buf1 = reinterpret_tensor(buf0, (4, 1, 4), (4, 4, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_mul_pow_sub_sum_0[grid(16)](buf1, arg0_1, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return buf1, class FactorizationMachineNew(torch.nn.Module): def __init__(self, reduce_sum=True): super().__init__() self.reduce_sum = reduce_sum def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
JazonJiao/pytorch-fm
FactorizationMachine
false
13,880
[ "MIT" ]
734
7192e7861fa54341d5b2df995f92858f583ea09e
https://github.com/JazonJiao/pytorch-fm/tree/7192e7861fa54341d5b2df995f92858f583ea09e
Linear_2L_KFRA
import torch import torch.nn as nn import torch.utils.data def sample_K_laplace_MN(MAP, upper_Qinv, lower_HHinv): Z = MAP.data.new(MAP.size()).normal_(mean=0, std=1) all_mtx_sample = MAP + torch.matmul(torch.matmul(lower_HHinv, Z), upper_Qinv) weight_mtx_sample = all_mtx_sample[:, :-1] bias_mtx_sample = all_mtx_sample[:, -1] return weight_mtx_sample, bias_mtx_sample class Linear_2L_KFRA(nn.Module): def __init__(self, input_dim, output_dim, n_hid): super(Linear_2L_KFRA, self).__init__() self.n_hid = n_hid self.input_dim = input_dim self.output_dim = output_dim self.fc1 = nn.Linear(input_dim, self.n_hid) self.fc2 = nn.Linear(self.n_hid, self.n_hid) self.fc3 = nn.Linear(self.n_hid, output_dim) self.act = nn.ReLU(inplace=True) self.one = None self.a2 = None self.h2 = None self.a1 = None self.h1 = None self.a0 = None def forward(self, x): self.one = x.new(x.shape[0], 1).fill_(1) a0 = x.view(-1, self.input_dim) self.a0 = torch.cat((a0.data, self.one), dim=1) h1 = self.fc1(a0) self.h1 = h1.data a1 = self.act(h1) self.a1 = torch.cat((a1.data, self.one), dim=1) h2 = self.fc2(a1) self.h2 = h2.data a2 = self.act(h2) self.a2 = torch.cat((a2.data, self.one), dim=1) h3 = self.fc3(a2) return h3 def sample_predict(self, x, Nsamples, Qinv1, HHinv1, MAP1, Qinv2, HHinv2, MAP2, Qinv3, HHinv3, MAP3): predictions = x.data.new(Nsamples, x.shape[0], self.output_dim) x = x.view(-1, self.input_dim) for i in range(Nsamples): w1, b1 = sample_K_laplace_MN(MAP1, Qinv1, HHinv1) a = torch.matmul(x, torch.t(w1)) + b1.unsqueeze(0) a = self.act(a) w2, b2 = sample_K_laplace_MN(MAP2, Qinv2, HHinv2) a = torch.matmul(a, torch.t(w2)) + b2.unsqueeze(0) a = self.act(a) w3, b3 = sample_K_laplace_MN(MAP3, Qinv3, HHinv3) y = torch.matmul(a, torch.t(w3)) + b3.unsqueeze(0) predictions[i] = y return predictions def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'input_dim': 4, 'output_dim': 4, 'n_hid': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = 1.0 tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 20 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 5 x1 = xindex // 5 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 5, tl.int64) tmp9 = 1.0 tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp6, tmp9, tmp10) tmp12 = tl.where(tmp4, tmp5, tmp11) tl.store(out_ptr0 + x2, tmp12, xmask) @triton.jit def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_fill_0[grid(4)](buf0, 4, XBLOCK=4, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 5), (5, 1), torch.float32) triton_poi_fused_cat_1[grid(20)](primals_1, buf1, 20, XBLOCK=32, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf2) del primals_2 buf3 = buf2 del buf2 triton_poi_fused_relu_2[grid(16)](buf3, primals_3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf4 = empty_strided_cuda((4, 5), (5, 1), torch.float32) triton_poi_fused_cat_1[grid(20)](buf3, buf4, 20, XBLOCK=32, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf3, reinterpret_tensor(primals_4, (4, 4), (1, 4 ), 0), out=buf5) buf6 = buf5 del buf5 triton_poi_fused_relu_2[grid(16)](buf6, primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf7 = empty_strided_cuda((4, 5), (5, 1), torch.float32) triton_poi_fused_cat_1[grid(20)](buf6, buf7, 20, XBLOCK=32, num_warps=1, num_stages=1) buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, buf6, reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf8) del primals_7 return (buf8, buf7, buf6, buf4, buf3, buf1, buf0, primals_1, buf3, buf6, primals_6, primals_4) def sample_K_laplace_MN(MAP, upper_Qinv, lower_HHinv): Z = MAP.data.new(MAP.size()).normal_(mean=0, std=1) all_mtx_sample = MAP + torch.matmul(torch.matmul(lower_HHinv, Z), upper_Qinv) weight_mtx_sample = all_mtx_sample[:, :-1] bias_mtx_sample = all_mtx_sample[:, -1] return weight_mtx_sample, bias_mtx_sample class Linear_2L_KFRANew(nn.Module): def __init__(self, input_dim, output_dim, n_hid): super(Linear_2L_KFRANew, self).__init__() self.n_hid = n_hid self.input_dim = input_dim self.output_dim = output_dim self.fc1 = nn.Linear(input_dim, self.n_hid) self.fc2 = nn.Linear(self.n_hid, self.n_hid) self.fc3 = nn.Linear(self.n_hid, output_dim) self.act = nn.ReLU(inplace=True) self.one = None self.a2 = None self.h2 = None self.a1 = None self.h1 = None self.a0 = None def sample_predict(self, x, Nsamples, Qinv1, HHinv1, MAP1, Qinv2, HHinv2, MAP2, Qinv3, HHinv3, MAP3): predictions = x.data.new(Nsamples, x.shape[0], self.output_dim) x = x.view(-1, self.input_dim) for i in range(Nsamples): w1, b1 = sample_K_laplace_MN(MAP1, Qinv1, HHinv1) a = torch.matmul(x, torch.t(w1)) + b1.unsqueeze(0) a = self.act(a) w2, b2 = sample_K_laplace_MN(MAP2, Qinv2, HHinv2) a = torch.matmul(a, torch.t(w2)) + b2.unsqueeze(0) a = self.act(a) w3, b3 = sample_K_laplace_MN(MAP3, Qinv3, HHinv3) y = torch.matmul(a, torch.t(w3)) + b3.unsqueeze(0) predictions[i] = y return predictions def forward(self, input_0): primals_1 = self.fc1.weight primals_3 = self.fc1.bias primals_2 = self.fc2.weight primals_5 = self.fc2.bias primals_4 = self.fc3.weight primals_7 = self.fc3.bias primals_6 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
JavierAntoran/Bayesain-Neural-Networks
Linear_2L_KFRA
false
13,881
[ "MIT" ]
1,299
1f867a5bcbd1abfecede99807eb0b5f97ed8be7c
https://github.com/JavierAntoran/Bayesain-Neural-Networks/tree/1f867a5bcbd1abfecede99807eb0b5f97ed8be7c
ScaleNorm
import math import torch import torch.nn as nn class ScaleNorm(nn.Module): """ScaleNorm""" """All g’s in SCALE NORM are initialized to sqrt(d)""" def __init__(self, scale, eps=1e-05): super(ScaleNorm, self).__init__() self.scale = nn.Parameter(torch.tensor(math.sqrt(scale))) self.eps = eps def forward(self, x): norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min= self.eps) return x * norm def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'scale': 1.0}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice import math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_clamp_div_linalg_vector_norm_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 + 0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK]) tmp2 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr1 + (3 + 4 * 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 = libdevice.sqrt(tmp12) tmp14 = 1e-05 tmp15 = triton_helpers.maximum(tmp13, tmp14) tmp16 = tmp1 / tmp15 tl.store(out_ptr0 + x0, tmp16, xmask) @triton.jit def triton_poi_fused_clamp_div_linalg_vector_norm_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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (), ()) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) get_raw_stream(0) triton_poi_fused_clamp_div_linalg_vector_norm_0[grid(64)](primals_1, primals_2, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_clamp_div_linalg_vector_norm_mul_1[grid(256)]( primals_2, buf0, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf0 return buf1, primals_2 class ScaleNormNew(nn.Module): """ScaleNorm""" """All g’s in SCALE NORM are initialized to sqrt(d)""" def __init__(self, scale, eps=1e-05): super(ScaleNormNew, self).__init__() self.scale = nn.Parameter(torch.tensor(math.sqrt(scale))) self.eps = eps def forward(self, input_0): primals_1 = self.scale primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
Jh-SYSU/MolRep
ScaleNorm
false
13,882
[ "MIT" ]
57
b2c802d18d41d7db26c19c6dd644098f945e48a1
https://github.com/Jh-SYSU/MolRep/tree/b2c802d18d41d7db26c19c6dd644098f945e48a1
AsymmetricLoss
import torch import torch.nn as nn import torch.nn.functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Average factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def asymmetric_loss(pred, target, weight=None, gamma_pos=1.0, gamma_neg=4.0, clip=0.05, reduction='mean', avg_factor=None, use_sigmoid=True, eps=1e-08): """asymmetric loss. Please refer to the `paper <https://arxiv.org/abs/2009.14119>`__ for details. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, ). Defaults to None. gamma_pos (float): positive focusing parameter. Defaults to 0.0. gamma_neg (float): Negative focusing parameter. We usually set gamma_neg > gamma_pos. Defaults to 4.0. clip (float, optional): Probability margin. Defaults to 0.05. reduction (str): The method used to reduce the loss. Options are "none", "mean" and "sum". If reduction is 'none' , loss is same shape as pred and label. Defaults to 'mean'. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. use_sigmoid (bool): Whether the prediction uses sigmoid instead of softmax. Defaults to True. eps (float): The minimum value of the argument of logarithm. Defaults to 1e-8. Returns: torch.Tensor: Loss. """ assert pred.shape == target.shape, 'pred and target should be in the same shape.' if use_sigmoid: pred_sigmoid = pred.sigmoid() else: pred_sigmoid = nn.functional.softmax(pred, dim=-1) target = target.type_as(pred) if clip and clip > 0: pt = (1 - pred_sigmoid + clip).clamp(max=1) * (1 - target ) + pred_sigmoid * target else: pt = (1 - pred_sigmoid) * (1 - target) + pred_sigmoid * target asymmetric_weight = (1 - pt).pow(gamma_pos * target + gamma_neg * (1 - target)) loss = -torch.log(pt.clamp(min=eps)) * asymmetric_weight if weight is not None: assert weight.dim() == 1 weight = weight.float() if pred.dim() > 1: weight = weight.reshape(-1, 1) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss def convert_to_one_hot(targets: 'torch.Tensor', classes) ->torch.Tensor: """This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (Tensor): The ground truth label of the prediction with shape (N, 1) classes (int): the number of classes. Returns: Tensor: Processed loss values. """ assert torch.max(targets).item( ) < classes, 'Class Index must be less than number of classes' one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch. long, device=targets.device) one_hot_targets.scatter_(1, targets.long(), 1) return one_hot_targets class AsymmetricLoss(nn.Module): """asymmetric loss. Args: gamma_pos (float): positive focusing parameter. Defaults to 0.0. gamma_neg (float): Negative focusing parameter. We usually set gamma_neg > gamma_pos. Defaults to 4.0. clip (float, optional): Probability margin. Defaults to 0.05. reduction (str): The method used to reduce the loss into a scalar. loss_weight (float): Weight of loss. Defaults to 1.0. use_sigmoid (bool): Whether the prediction uses sigmoid instead of softmax. Defaults to True. eps (float): The minimum value of the argument of logarithm. Defaults to 1e-8. """ def __init__(self, gamma_pos=0.0, gamma_neg=4.0, clip=0.05, reduction= 'mean', loss_weight=1.0, use_sigmoid=True, eps=1e-08): super(AsymmetricLoss, self).__init__() self.gamma_pos = gamma_pos self.gamma_neg = gamma_neg self.clip = clip self.reduction = reduction self.loss_weight = loss_weight self.use_sigmoid = use_sigmoid self.eps = eps def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None): """asymmetric loss. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*), N or (N,1). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, \\*). Defaults to None. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. reduction_override (str, optional): The method used to reduce the loss into a scalar. Options are "none", "mean" and "sum". Defaults to None. Returns: torch.Tensor: Loss. """ assert reduction_override in (None, 'none', 'mean', 'sum') reduction = (reduction_override if reduction_override else self. reduction) if target.dim() == 1 or target.dim() == 2 and target.shape[1] == 1: target = convert_to_one_hot(target.view(-1, 1), pred.shape[-1]) loss_cls = self.loss_weight * asymmetric_loss(pred, target, weight, gamma_pos=self.gamma_pos, gamma_neg=self.gamma_neg, clip=self. clip, reduction=reduction, avg_factor=avg_factor, use_sigmoid= self.use_sigmoid, eps=self.eps) return loss_cls def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import torch.nn as nn import torch.nn.functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_clamp_log_mean_mul_neg_pow_rsub_sigmoid_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp7 = tl.load(in_ptr1 + r0, None) tmp1 = tl.sigmoid(tmp0) tmp2 = 1.0 tmp3 = tmp2 - tmp1 tmp4 = 0.05 tmp5 = tmp3 + tmp4 tmp6 = triton_helpers.minimum(tmp5, tmp2) tmp8 = tmp2 - tmp7 tmp9 = tmp6 * tmp8 tmp10 = tmp1 * tmp7 tmp11 = tmp9 + tmp10 tmp12 = 1e-08 tmp13 = triton_helpers.maximum(tmp11, tmp12) tmp14 = tl_math.log(tmp13) tmp15 = -tmp14 tmp16 = tmp2 - tmp11 tmp17 = 0.0 tmp18 = tmp7 * tmp17 tmp19 = 4.0 tmp20 = tmp8 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = libdevice.pow(tmp16, tmp21) tmp23 = tmp15 * tmp22 tmp24 = tl.broadcast_to(tmp23, [RBLOCK]) tmp26 = triton_helpers.promote_to_tensor(tl.sum(tmp24, 0)) tmp27 = 256.0 tmp28 = tmp26 / tmp27 tmp29 = tmp28 * tmp2 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp29, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_clamp_log_mean_mul_neg_pow_rsub_sigmoid_0[grid(1) ](buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Average factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def asymmetric_loss(pred, target, weight=None, gamma_pos=1.0, gamma_neg=4.0, clip=0.05, reduction='mean', avg_factor=None, use_sigmoid=True, eps=1e-08): """asymmetric loss. Please refer to the `paper <https://arxiv.org/abs/2009.14119>`__ for details. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, ). Defaults to None. gamma_pos (float): positive focusing parameter. Defaults to 0.0. gamma_neg (float): Negative focusing parameter. We usually set gamma_neg > gamma_pos. Defaults to 4.0. clip (float, optional): Probability margin. Defaults to 0.05. reduction (str): The method used to reduce the loss. Options are "none", "mean" and "sum". If reduction is 'none' , loss is same shape as pred and label. Defaults to 'mean'. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. use_sigmoid (bool): Whether the prediction uses sigmoid instead of softmax. Defaults to True. eps (float): The minimum value of the argument of logarithm. Defaults to 1e-8. Returns: torch.Tensor: Loss. """ assert pred.shape == target.shape, 'pred and target should be in the same shape.' if use_sigmoid: pred_sigmoid = pred.sigmoid() else: pred_sigmoid = nn.functional.softmax(pred, dim=-1) target = target.type_as(pred) if clip and clip > 0: pt = (1 - pred_sigmoid + clip).clamp(max=1) * (1 - target ) + pred_sigmoid * target else: pt = (1 - pred_sigmoid) * (1 - target) + pred_sigmoid * target asymmetric_weight = (1 - pt).pow(gamma_pos * target + gamma_neg * (1 - target)) loss = -torch.log(pt.clamp(min=eps)) * asymmetric_weight if weight is not None: assert weight.dim() == 1 weight = weight.float() if pred.dim() > 1: weight = weight.reshape(-1, 1) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss def convert_to_one_hot(targets: 'torch.Tensor', classes) ->torch.Tensor: """This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (Tensor): The ground truth label of the prediction with shape (N, 1) classes (int): the number of classes. Returns: Tensor: Processed loss values. """ assert torch.max(targets).item( ) < classes, 'Class Index must be less than number of classes' one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch. long, device=targets.device) one_hot_targets.scatter_(1, targets.long(), 1) return one_hot_targets class AsymmetricLossNew(nn.Module): """asymmetric loss. Args: gamma_pos (float): positive focusing parameter. Defaults to 0.0. gamma_neg (float): Negative focusing parameter. We usually set gamma_neg > gamma_pos. Defaults to 4.0. clip (float, optional): Probability margin. Defaults to 0.05. reduction (str): The method used to reduce the loss into a scalar. loss_weight (float): Weight of loss. Defaults to 1.0. use_sigmoid (bool): Whether the prediction uses sigmoid instead of softmax. Defaults to True. eps (float): The minimum value of the argument of logarithm. Defaults to 1e-8. """ def __init__(self, gamma_pos=0.0, gamma_neg=4.0, clip=0.05, reduction= 'mean', loss_weight=1.0, use_sigmoid=True, eps=1e-08): super(AsymmetricLossNew, self).__init__() self.gamma_pos = gamma_pos self.gamma_neg = gamma_neg self.clip = clip self.reduction = reduction self.loss_weight = loss_weight self.use_sigmoid = use_sigmoid self.eps = eps def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
JiYuanFeng/mmclassification
AsymmetricLoss
false
13,883
[ "Apache-2.0" ]
1,190
b337ef1f11b85148cca4b6fb0c4da3f8cc2eede6
https://github.com/JiYuanFeng/mmclassification/tree/b337ef1f11b85148cca4b6fb0c4da3f8cc2eede6
Generator
import math import torch import torch.nn as nn class LayerNorm(nn.Module): def __init__(self, hidden_size, variance_epsilon=1e-12): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(hidden_size)) self.beta = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = variance_epsilon def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.gamma * x + self.beta class ScaleNorm(nn.Module): """ScaleNorm""" """All g’s in SCALE NORM are initialized to sqrt(d)""" def __init__(self, scale, eps=1e-05): super(ScaleNorm, self).__init__() self.scale = nn.Parameter(torch.tensor(math.sqrt(scale))) self.eps = eps def forward(self, x): norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min= self.eps) return x * norm class Generator(nn.Module): """Define standard linear + softmax generation step.""" def __init__(self, d_model, aggregation_type='mean', n_output=1, n_layers=1, leaky_relu_slope=0.01, dropout=0.0, scale_norm=False): super(Generator, self).__init__() if n_layers == 1: self.proj = nn.Linear(d_model, n_output) else: self.proj = [] for i in range(n_layers - 1): self.proj.append(nn.Linear(d_model, d_model)) self.proj.append(nn.LeakyReLU(leaky_relu_slope)) self.proj.append(ScaleNorm(d_model) if scale_norm else LayerNorm(d_model)) self.proj.append(nn.Dropout(dropout)) self.proj.append(nn.Linear(d_model, n_output)) self.proj = torch.nn.Sequential(*self.proj) self.aggregation_type = aggregation_type def forward(self, x, mask): mask = mask.unsqueeze(-1).float() out_masked = x * mask if self.aggregation_type == 'mean': out_sum = out_masked.sum(dim=1) mask_sum = mask.sum(dim=1) out_avg_pooling = out_sum / mask_sum elif self.aggregation_type == 'sum': out_sum = out_masked.sum(dim=1) out_avg_pooling = out_sum elif self.aggregation_type == 'dummy_node': out_avg_pooling = out_masked[:, 0] projected = self.proj(out_avg_pooling) return projected def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'d_model': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_div_mul_sum_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 x3 = xindex % 64 x1 = xindex // 4 % 16 x2 = xindex // 64 x4 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (64 + x3), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (16 + x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp7 = tl.load(in_ptr0 + (128 + x3), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (32 + x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp11 = tl.load(in_ptr0 + (192 + x3), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr1 + (48 + x1 + 64 * x2), 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 = tmp1 + tmp4 tmp16 = tmp15 + tmp8 tmp17 = tmp16 + tmp12 tmp18 = tmp14 / tmp17 tl.store(out_ptr0 + x4, tmp18, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (1, 4), (4, 1)) assert_size_stride(primals_4, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_mul_sum_0[grid(256)](primals_2, primals_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 del primals_2 buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_4, reinterpret_tensor(buf0, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_3, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf2) del primals_3 del primals_4 return reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(buf0, (64, 4), (4, 1), 0) class LayerNorm(nn.Module): def __init__(self, hidden_size, variance_epsilon=1e-12): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(hidden_size)) self.beta = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = variance_epsilon def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.gamma * x + self.beta class ScaleNorm(nn.Module): """ScaleNorm""" """All g’s in SCALE NORM are initialized to sqrt(d)""" def __init__(self, scale, eps=1e-05): super(ScaleNorm, self).__init__() self.scale = nn.Parameter(torch.tensor(math.sqrt(scale))) self.eps = eps def forward(self, x): norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min= self.eps) return x * norm class GeneratorNew(nn.Module): """Define standard linear + softmax generation step.""" def __init__(self, d_model, aggregation_type='mean', n_output=1, n_layers=1, leaky_relu_slope=0.01, dropout=0.0, scale_norm=False): super(GeneratorNew, self).__init__() if n_layers == 1: self.proj = nn.Linear(d_model, n_output) else: self.proj = [] for i in range(n_layers - 1): self.proj.append(nn.Linear(d_model, d_model)) self.proj.append(nn.LeakyReLU(leaky_relu_slope)) self.proj.append(ScaleNorm(d_model) if scale_norm else LayerNorm(d_model)) self.proj.append(nn.Dropout(dropout)) self.proj.append(nn.Linear(d_model, n_output)) self.proj = torch.nn.Sequential(*self.proj) self.aggregation_type = aggregation_type def forward(self, input_0, input_1): primals_3 = self.proj.weight primals_4 = self.proj.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
Jh-SYSU/MolRep
Generator
false
13,884
[ "MIT" ]
57
b2c802d18d41d7db26c19c6dd644098f945e48a1
https://github.com/Jh-SYSU/MolRep/tree/b2c802d18d41d7db26c19c6dd644098f945e48a1
CQAttention
import torch import torch.nn as nn import torch.utils.data import torch.backends.cudnn def mask_logits(inputs, mask, mask_value=-1e+30): mask = mask.type(torch.float32) return inputs + (1.0 - mask) * mask_value class Conv1D(nn.Module): def __init__(self, in_dim, out_dim, kernel_size=1, stride=1, padding=0, bias=True): super(Conv1D, self).__init__() self.conv1d = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=kernel_size, padding=padding, stride=stride, bias=bias) def forward(self, x): x = x.transpose(1, 2) x = self.conv1d(x) return x.transpose(1, 2) class CQAttention(nn.Module): def __init__(self, dim, drop_rate=0.0): super(CQAttention, self).__init__() w4C = torch.empty(dim, 1) w4Q = torch.empty(dim, 1) w4mlu = torch.empty(1, 1, dim) nn.init.xavier_uniform_(w4C) nn.init.xavier_uniform_(w4Q) nn.init.xavier_uniform_(w4mlu) self.w4C = nn.Parameter(w4C, requires_grad=True) self.w4Q = nn.Parameter(w4Q, requires_grad=True) self.w4mlu = nn.Parameter(w4mlu, requires_grad=True) self.dropout = nn.Dropout(p=drop_rate) self.cqa_linear = Conv1D(in_dim=4 * dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) def forward(self, context, query, c_mask, q_mask): score = self.trilinear_attention(context, query) score_ = nn.Softmax(dim=2)(mask_logits(score, q_mask.unsqueeze(1))) score_t = nn.Softmax(dim=1)(mask_logits(score, c_mask.unsqueeze(2))) score_t = score_t.transpose(1, 2) c2q = torch.matmul(score_, query) q2c = torch.matmul(torch.matmul(score_, score_t), context) output = torch.cat([context, c2q, torch.mul(context, c2q), torch. mul(context, q2c)], dim=2) output = self.cqa_linear(output) return output def trilinear_attention(self, context, query): _batch_size, c_seq_len, _dim = context.shape _batch_size, q_seq_len, _dim = query.shape context = self.dropout(context) query = self.dropout(query) subres0 = torch.matmul(context, self.w4C).expand([-1, -1, q_seq_len]) subres1 = torch.matmul(query, self.w4Q).transpose(1, 2).expand([-1, c_seq_len, -1]) subres2 = torch.matmul(context * self.w4mlu, query.transpose(1, 2)) res = subres0 + subres1 + subres2 return res def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4] ), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn import torch.utils.data import torch.backends.cudnn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused__softmax_add_mul_rsub_1(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + 4 * x2, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + 4 * x1, xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp13 = tl.load(in_ptr2 + (1 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp15 = tl.load(in_ptr3 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp20 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr2 + (2 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp24 = tl.load(in_ptr3 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp29 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp31 = tl.load(in_ptr2 + (3 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp33 = tl.load(in_ptr3 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = 1.0 tmp7 = tmp6 - tmp5 tmp8 = -1e+30 tmp9 = tmp7 * tmp8 tmp10 = tmp4 + tmp9 tmp12 = tmp0 + tmp11 tmp14 = tmp12 + tmp13 tmp16 = tmp6 - tmp15 tmp17 = tmp16 * tmp8 tmp18 = tmp14 + tmp17 tmp19 = triton_helpers.maximum(tmp10, tmp18) tmp21 = tmp0 + tmp20 tmp23 = tmp21 + tmp22 tmp25 = tmp6 - tmp24 tmp26 = tmp25 * tmp8 tmp27 = tmp23 + tmp26 tmp28 = triton_helpers.maximum(tmp19, tmp27) tmp30 = tmp0 + tmp29 tmp32 = tmp30 + tmp31 tmp34 = tmp6 - tmp33 tmp35 = tmp34 * tmp8 tmp36 = tmp32 + tmp35 tmp37 = triton_helpers.maximum(tmp28, tmp36) tl.store(out_ptr0 + x2, tmp37, xmask) @triton.jit def triton_poi_fused__softmax_add_mul_rsub_2(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 x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask) tmp5 = tl.load(in_ptr3 + 4 * x1, xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp13 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask) tmp15 = tl.load(in_ptr3 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp20 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask) tmp24 = tl.load(in_ptr3 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp29 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp31 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask) tmp33 = tl.load(in_ptr3 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = 1.0 tmp7 = tmp6 - tmp5 tmp8 = -1e+30 tmp9 = tmp7 * tmp8 tmp10 = tmp4 + tmp9 tmp12 = tmp11 + tmp1 tmp14 = tmp12 + tmp13 tmp16 = tmp6 - tmp15 tmp17 = tmp16 * tmp8 tmp18 = tmp14 + tmp17 tmp19 = triton_helpers.maximum(tmp10, tmp18) tmp21 = tmp20 + tmp1 tmp23 = tmp21 + tmp22 tmp25 = tmp6 - tmp24 tmp26 = tmp25 * tmp8 tmp27 = tmp23 + tmp26 tmp28 = triton_helpers.maximum(tmp19, tmp27) tmp30 = tmp29 + tmp1 tmp32 = tmp30 + tmp31 tmp34 = tmp6 - tmp33 tmp35 = tmp34 * tmp8 tmp36 = tmp32 + tmp35 tmp37 = triton_helpers.maximum(tmp28, tmp36) tl.store(out_ptr0 + x2, tmp37, xmask) @triton.jit def triton_poi_fused__softmax_add_mul_rsub_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, 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 x3 = xindex // 4 x0 = xindex % 4 x2 = xindex // 16 x4 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr2 + x4, xmask) tmp5 = tl.load(in_ptr3 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr4 + x3, xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr5 + x3, xmask, eviction_policy='evict_last') tmp18 = tl.load(in_ptr6 + (x0 + 4 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = 1.0 tmp7 = tmp6 - tmp5 tmp8 = -1e+30 tmp9 = tmp7 * tmp8 tmp10 = tmp4 + tmp9 tmp12 = tmp10 - tmp11 tmp13 = tl_math.exp(tmp12) tmp15 = tmp6 - tmp14 tmp16 = tmp15 * tmp8 tmp17 = tmp4 + tmp16 tmp19 = tmp17 - tmp18 tmp20 = tl_math.exp(tmp19) tl.store(out_ptr0 + x4, tmp13, xmask) tl.store(out_ptr1 + x4, tmp20, xmask) @triton.jit def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 4 x2 = xindex // 16 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_poi_fused_cat_6(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 % 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 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (4 * x1 + (-8 + x0)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.load(in_ptr1 + (4 * x1 + (-8 + x0)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp17 = tmp15 * tmp16 tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype) tmp19 = tl.where(tmp14, tmp17, tmp18) tmp20 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp23 = tl.load(in_ptr0 + (4 * x1 + (-12 + x0)), tmp20 & xmask, eviction_policy='evict_last', other=0.0) tmp24 = tl.load(in_ptr2 + (4 * x1 + (-12 + x0)), tmp20 & xmask, eviction_policy='evict_last', other=0.0) tmp25 = tmp23 * tmp24 tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype) tmp27 = tl.where(tmp20, tmp25, tmp26) tmp28 = tl.where(tmp14, tmp19, tmp27) tmp29 = tl.where(tmp9, tmp10, tmp28) tmp30 = tl.where(tmp4, tmp5, tmp29) tl.store(out_ptr0 + x2, tmp30, xmask) @triton.jit def triton_poi_fused_convolution_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 64 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 16 y1 = yindex // 16 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_8(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = 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), (1, 1)) assert_size_stride(primals_4, (4, 1), (1, 1)) assert_size_stride(primals_5, (1, 1, 4), (4, 4, 1)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4, 4), (4, 1)) assert_size_stride(primals_8, (4, 16, 1), (16, 1, 1)) assert_size_stride(primals_9, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), primals_3, out=buf0) del primals_3 buf1 = empty_strided_cuda((16, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0), primals_4, out=buf1) del primals_4 buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_0[grid(64)](primals_1, primals_5, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_5 buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf2, reinterpret_tensor(primals_2, (4, 4, 4), ( 16, 1, 4), 0), out=buf3) buf4 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused__softmax_add_mul_rsub_1[grid(16)](buf0, buf1, buf3, primals_6, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) buf7 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32) triton_poi_fused__softmax_add_mul_rsub_2[grid(16)](buf0, buf1, buf3, primals_7, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) buf5 = buf2 del buf2 buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_add_mul_rsub_3[grid(64)](buf0, buf1, buf3, primals_6, buf4, primals_7, buf7, buf5, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del buf1 del buf4 del buf7 del primals_6 del primals_7 buf6 = buf3 del buf3 triton_poi_fused__softmax_4[grid(64)](buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = buf5 del buf5 triton_poi_fused__softmax_5[grid(64)](buf8, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1) buf10 = buf8 del buf8 extern_kernels.bmm(buf6, primals_2, out=buf10) buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf9, (4, 4, 4), (16, 1, 4), 0), out=buf11) buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf11, primals_1, out=buf12) del buf11 buf13 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32) triton_poi_fused_cat_6[grid(256)](primals_1, buf10, buf12, buf13, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf10 del buf12 buf14 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32) triton_poi_fused_convolution_7[grid(64, 4)](buf13, buf14, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf15 = extern_kernels.convolution(buf14, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf15, (4, 4, 4), (16, 4, 1)) del buf14 buf16 = buf15 del buf15 triton_poi_fused_convolution_8[grid(64)](buf16, primals_9, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_9 return reinterpret_tensor(buf16, (4, 4, 4), (16, 1, 4), 0 ), primals_1, primals_2, primals_8, buf6, buf9, reinterpret_tensor( buf13, (4, 16, 4), (64, 1, 16), 0) def mask_logits(inputs, mask, mask_value=-1e+30): mask = mask.type(torch.float32) return inputs + (1.0 - mask) * mask_value class Conv1D(nn.Module): def __init__(self, in_dim, out_dim, kernel_size=1, stride=1, padding=0, bias=True): super(Conv1D, self).__init__() self.conv1d = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=kernel_size, padding=padding, stride=stride, bias=bias) def forward(self, x): x = x.transpose(1, 2) x = self.conv1d(x) return x.transpose(1, 2) class CQAttentionNew(nn.Module): def __init__(self, dim, drop_rate=0.0): super(CQAttentionNew, self).__init__() w4C = torch.empty(dim, 1) w4Q = torch.empty(dim, 1) w4mlu = torch.empty(1, 1, dim) nn.init.xavier_uniform_(w4C) nn.init.xavier_uniform_(w4Q) nn.init.xavier_uniform_(w4mlu) self.w4C = nn.Parameter(w4C, requires_grad=True) self.w4Q = nn.Parameter(w4Q, requires_grad=True) self.w4mlu = nn.Parameter(w4mlu, requires_grad=True) self.dropout = nn.Dropout(p=drop_rate) self.cqa_linear = Conv1D(in_dim=4 * dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) def trilinear_attention(self, context, query): _batch_size, c_seq_len, _dim = context.shape _batch_size, q_seq_len, _dim = query.shape context = self.dropout(context) query = self.dropout(query) subres0 = torch.matmul(context, self.w4C).expand([-1, -1, q_seq_len]) subres1 = torch.matmul(query, self.w4Q).transpose(1, 2).expand([-1, c_seq_len, -1]) subres2 = torch.matmul(context * self.w4mlu, query.transpose(1, 2)) res = subres0 + subres1 + subres2 return res def forward(self, input_0, input_1, input_2, input_3): primals_3 = self.w4C primals_4 = self.w4Q primals_5 = self.w4mlu primals_8 = self.cqa_linear.conv1d.weight primals_9 = self.cqa_linear.conv1d.bias primals_1 = input_0 primals_2 = input_1 primals_6 = input_2 primals_7 = input_3 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
IsaacChanghau/VSLNet
CQAttention
false
13,885
[ "MIT" ]
62
3793c625f2e251a5f19a0d59f0c83b12e386f808
https://github.com/IsaacChanghau/VSLNet/tree/3793c625f2e251a5f19a0d59f0c83b12e386f808
FusionLayer
import torch from torch import nn from torch.nn import init class FusionLayer(nn.Module): def __init__(self, nums=6): super(FusionLayer, self).__init__() self.weights = nn.Parameter(torch.randn(nums)) self.nums = nums self._reset_parameters() def _reset_parameters(self): init.constant_(self.weights, 1 / self.nums) def forward(self, x): for i in range(self.nums): out = self.weights[i] * x[i] if i == 0 else out + self.weights[i ] * x[i] return out def get_inputs(): return [torch.rand([6, 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 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_add_mul_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK]) tmp2 = tl.load(in_ptr1 + x0, xmask) tmp4 = tl.load(in_ptr0 + 1) tmp5 = tl.broadcast_to(tmp4, [XBLOCK]) tmp6 = tl.load(in_ptr1 + (64 + x0), xmask) tmp9 = tl.load(in_ptr0 + 2) tmp10 = tl.broadcast_to(tmp9, [XBLOCK]) tmp11 = tl.load(in_ptr1 + (128 + x0), xmask) tmp14 = tl.load(in_ptr0 + 3) tmp15 = tl.broadcast_to(tmp14, [XBLOCK]) tmp16 = tl.load(in_ptr1 + (192 + x0), xmask) tmp19 = tl.load(in_ptr0 + 4) tmp20 = tl.broadcast_to(tmp19, [XBLOCK]) tmp21 = tl.load(in_ptr1 + (256 + x0), xmask) tmp24 = tl.load(in_ptr0 + 5) tmp25 = tl.broadcast_to(tmp24, [XBLOCK]) tmp26 = tl.load(in_ptr1 + (320 + x0), xmask) tmp3 = tmp1 * tmp2 tmp7 = tmp5 * tmp6 tmp8 = tmp3 + tmp7 tmp12 = tmp10 * tmp11 tmp13 = tmp8 + tmp12 tmp17 = tmp15 * tmp16 tmp18 = tmp13 + tmp17 tmp22 = tmp20 * tmp21 tmp23 = tmp18 + tmp22 tmp27 = tmp25 * tmp26 tmp28 = tmp23 + tmp27 tl.store(in_out_ptr0 + x0, tmp28, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (6,), (1,)) assert_size_stride(primals_2, (6, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_add_mul_0[grid(64)](buf1, primals_1, primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 return buf1, reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 64 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 128 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 192 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 256 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 4, 1), 320) class FusionLayerNew(nn.Module): def __init__(self, nums=6): super(FusionLayerNew, self).__init__() self.weights = nn.Parameter(torch.randn(nums)) self.nums = nums self._reset_parameters() def _reset_parameters(self): init.constant_(self.weights, 1 / self.nums) def forward(self, input_0): primals_1 = self.weights primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
JasonLin1998/DSS-pytorch
FusionLayer
false
13,886
[ "MIT" ]
188
f249541bf7e5e479e050b562dd6024d6219f36f4
https://github.com/JasonLin1998/DSS-pytorch/tree/f249541bf7e5e479e050b562dd6024d6219f36f4
ConvToVector
import torch import torch.nn as nn import torch.nn.functional as F class ConvToVector(nn.Module): def __init__(self, in_channels, padding=1): super(ConvToVector, self).__init__() self.in_channels = in_channels self.conv1 = nn.Conv2d(in_channels, 3, kernel_size=3, padding=padding) self.conv2 = nn.Conv2d(3, 6, kernel_size=3, padding=padding) self.conv3 = nn.Conv2d(6, 12, kernel_size=3, padding=padding) self.conv8 = nn.Conv2d(12, 6, kernel_size=3, padding=0) self.conv9 = nn.Conv2d(6, 3, kernel_size=3, padding=0) self.conv10 = nn.Conv2d(3, 1, kernel_size=3, padding=0) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = F.relu(self.conv8(x)) x = F.relu(self.conv9(x)) x = self.conv10(x) return x def get_inputs(): return [torch.rand([4, 4, 64, 64])] 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 import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 4096 % 3 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) 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 // 4096 % 6 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 // 4096 % 12 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 92256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3844 % 6 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 43200 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3600 % 3 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_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 13456 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, primals_12, primals_13) = args args.clear() assert_size_stride(primals_1, (3, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (3,), (1,)) assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1)) assert_size_stride(primals_4, (6, 3, 3, 3), (27, 9, 3, 1)) assert_size_stride(primals_5, (6,), (1,)) assert_size_stride(primals_6, (12, 6, 3, 3), (54, 9, 3, 1)) assert_size_stride(primals_7, (12,), (1,)) assert_size_stride(primals_8, (6, 12, 3, 3), (108, 9, 3, 1)) assert_size_stride(primals_9, (6,), (1,)) assert_size_stride(primals_10, (3, 6, 3, 3), (54, 9, 3, 1)) assert_size_stride(primals_11, (3,), (1,)) assert_size_stride(primals_12, (1, 3, 3, 3), (27, 9, 3, 1)) assert_size_stride(primals_13, (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, 3, 64, 64), (12288, 4096, 64, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(49152)](buf1, primals_2, 49152, XBLOCK=512, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 6, 64, 64), (24576, 4096, 64, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_1[grid(98304)](buf3, primals_5, 98304, XBLOCK=512, num_warps=8, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 12, 64, 64), (49152, 4096, 64, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_2[grid(196608)](buf5, primals_7, 196608, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 6, 62, 62), (23064, 3844, 62, 1)) buf7 = buf6 del buf6 triton_poi_fused_convolution_relu_3[grid(92256)](buf7, primals_9, 92256, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 3, 60, 60), (10800, 3600, 60, 1)) buf9 = buf8 del buf8 triton_poi_fused_convolution_relu_4[grid(43200)](buf9, primals_11, 43200, XBLOCK=512, num_warps=4, num_stages=1) del primals_11 buf10 = extern_kernels.convolution(buf9, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 1, 58, 58), (3364, 3364, 58, 1)) buf11 = buf10 del buf10 triton_poi_fused_convolution_5[grid(13456)](buf11, primals_13, 13456, XBLOCK=256, num_warps=4, num_stages=1) del primals_13 return (buf11, primals_1, primals_3, primals_4, primals_6, primals_8, primals_10, primals_12, buf1, buf3, buf5, buf7, buf9) class ConvToVectorNew(nn.Module): def __init__(self, in_channels, padding=1): super(ConvToVectorNew, self).__init__() self.in_channels = in_channels self.conv1 = nn.Conv2d(in_channels, 3, kernel_size=3, padding=padding) self.conv2 = nn.Conv2d(3, 6, kernel_size=3, padding=padding) self.conv3 = nn.Conv2d(6, 12, kernel_size=3, padding=padding) self.conv8 = nn.Conv2d(12, 6, kernel_size=3, padding=0) self.conv9 = nn.Conv2d(6, 3, kernel_size=3, padding=0) self.conv10 = nn.Conv2d(3, 1, kernel_size=3, padding=0) 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.conv8.weight primals_9 = self.conv8.bias primals_10 = self.conv9.weight primals_11 = self.conv9.bias primals_12 = self.conv10.weight primals_13 = self.conv10.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]
JannerM/spatial-reasoning
ConvToVector
false
13,887
[ "MIT" ]
54
e163003a33177e41ca02d5feefee3fdfca5ba154
https://github.com/JannerM/spatial-reasoning/tree/e163003a33177e41ca02d5feefee3fdfca5ba154
MultiHeadAttention
import torch from torch import nn import torch.nn.functional as F import torch.utils.data class MultiHeadAttention(nn.Module): """ input: query --- [N, T_q, query_dim] key --- [N, T_k, key_dim] output: out --- [N, T_q, num_units] """ def __init__(self, query_dim, key_dim, num_units, num_heads): super().__init__() self.num_units = num_units self.num_heads = num_heads self.key_dim = key_dim self.W_query = nn.Linear(in_features=query_dim, out_features= num_units, bias=False) self.W_key = nn.Linear(in_features=key_dim, out_features=num_units, bias=False) self.W_value = nn.Linear(in_features=key_dim, out_features= num_units, bias=False) def forward(self, query, key): querys = self.W_query(query) keys = self.W_key(key) values = self.W_value(key) split_size = self.num_units // self.num_heads querys = torch.stack(torch.split(querys, split_size, dim=2), dim=0) keys = torch.stack(torch.split(keys, split_size, dim=2), dim=0) values = torch.stack(torch.split(values, split_size, dim=2), dim=0) scores = torch.matmul(querys, keys.transpose(2, 3)) scores = scores / self.key_dim ** 0.5 scores = F.softmax(scores, dim=3) out = torch.matmul(scores, values) out = torch.cat(torch.split(out, 1, dim=0), dim=3).squeeze(0) return out def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'query_dim': 4, 'key_dim': 4, 'num_units': 4, 'num_heads': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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 x3 = xindex // 4 x0 = xindex % 4 x1 = xindex // 4 % 4 x2 = xindex // 16 x4 = xindex tmp0 = x3 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x0 + 16 * (x1 + 4 * x2)), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * (-4 + x1 + 4 * x2)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * (-8 + x1 + 4 * x2)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp19 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * (-12 + x1 + 4 * x2)), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tmp23 = 0.7071067811865476 tmp24 = tmp22 * tmp23 tl.store(out_ptr0 + x4, tmp24, 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 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_stack_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 x1 = xindex // 4 x0 = xindex % 4 x2 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x0 + 16 * x1), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * (-4 + x1)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * (-8 + x1)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp19 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * (-12 + x1)), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tl.store(out_ptr0 + x2, tmp22, xmask) @triton.jit def triton_poi_fused_cat_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + x1, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 2, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr0 + (16 + x1), tmp9 & xmask, eviction_policy= 'evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 3, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (32 + x1), tmp14 & xmask, eviction_policy= 'evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 4, tl.int64) tmp19 = tl.load(in_ptr0 + (48 + x1), tmp16 & xmask, eviction_policy= 'evict_last', other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tl.store(out_ptr0 + x2, tmp22, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_5, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1) del primals_3 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(64)](buf0, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf0 triton_poi_fused_0[grid(64)](buf1, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5) buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_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, (16, 4, 1), (4, 1, 1), 0) del buf1 triton_poi_fused_stack_3[grid(64)](buf2, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9) buf10 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_cat_4[grid(64)](buf9, buf10, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf9 return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0 ), reinterpret_tensor(primals_4, (16, 4), (4, 1), 0 ), buf7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0) class MultiHeadAttentionNew(nn.Module): """ input: query --- [N, T_q, query_dim] key --- [N, T_k, key_dim] output: out --- [N, T_q, num_units] """ def __init__(self, query_dim, key_dim, num_units, num_heads): super().__init__() self.num_units = num_units self.num_heads = num_heads self.key_dim = key_dim self.W_query = nn.Linear(in_features=query_dim, out_features= num_units, bias=False) self.W_key = nn.Linear(in_features=key_dim, out_features=num_units, bias=False) self.W_value = nn.Linear(in_features=key_dim, out_features= num_units, bias=False) def forward(self, input_0, input_1): primals_1 = self.W_query.weight primals_3 = self.W_key.weight primals_5 = self.W_value.weight primals_2 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Jesse3692/ttskit
MultiHeadAttention
false
13,888
[ "MIT" ]
151
aa424cf46f5fbe67dc06e67d00c1d46c31a9974b
https://github.com/Jesse3692/ttskit/tree/aa424cf46f5fbe67dc06e67d00c1d46c31a9974b
DacBlock
import torch from torch import nn class DacBlock(nn.Module): def __init__(self, channel): super(DacBlock, self).__init__() self.dilate1 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 1, padding=1) self.dilate2 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 3, padding=3) self.dilate3 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 5, padding=5) self.conv1x1 = nn.Conv2d(channel, channel, kernel_size=1, dilation= 1, padding=0) self.relu = nn.ReLU(inplace=True) for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): if m.bias is not None: m.bias.data.zero_() def forward(self, x): dilate1_out = self.relu(self.dilate1(x)) dilate2_out = self.relu(self.conv1x1(self.dilate2(x))) dilate3_out = self.relu(self.conv1x1(self.dilate2(self.dilate1(x)))) dilate4_out = self.relu(self.conv1x1(self.dilate3(self.dilate2(self .dilate1(x))))) out = x + dilate1_out + dilate2_out + dilate3_out + dilate4_out return out 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 from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) @triton.jit def triton_poi_fused_convolution_1(in_out_ptr0, in_out_ptr1, 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') tmp3 = tl.load(in_out_ptr1 + x3, xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp3 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) tl.store(in_out_ptr1 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_add_convolution_relu_threshold_backward_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, 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 x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x3, xmask) tmp5 = tl.load(in_ptr2 + x3, xmask) tmp6 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x3, xmask) tmp14 = tl.load(in_ptr5 + x3, xmask) tmp2 = tl.full([1], 0, tl.int32) tmp3 = triton_helpers.maximum(tmp2, tmp1) tmp4 = tmp0 + tmp3 tmp7 = tmp5 + tmp6 tmp8 = triton_helpers.maximum(tmp2, tmp7) tmp9 = tmp4 + tmp8 tmp11 = tmp10 + tmp6 tmp12 = triton_helpers.maximum(tmp2, tmp11) tmp13 = tmp9 + tmp12 tmp15 = tmp14 + tmp6 tmp16 = triton_helpers.maximum(tmp2, tmp15) tmp17 = tmp13 + tmp16 tmp18 = 0.0 tmp19 = tmp16 <= tmp18 tmp20 = tmp12 <= tmp18 tmp21 = tmp8 <= tmp18 tl.store(out_ptr0 + x3, tmp17, xmask) tl.store(out_ptr1 + x3, tmp19, xmask) tl.store(out_ptr2 + x3, tmp20, xmask) tl.store(out_ptr3 + x3, tmp21, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_9, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(256)](buf1, primals_2, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1, 1), padding=(3, 3), dilation=(3, 3), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1)) buf5 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1), padding=(3, 3), dilation=(3, 3), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 4, 4, 4), (64, 16, 4, 1)) buf3 = buf2 del buf2 buf6 = buf5 del buf5 triton_poi_fused_convolution_1[grid(256)](buf3, buf6, primals_5, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1)) buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 4, 4, 4), (64, 16, 4, 1)) buf8 = extern_kernels.convolution(buf6, primals_8, stride=(1, 1), padding=(5, 5), dilation=(5, 5), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1)) buf9 = buf8 del buf8 triton_poi_fused_convolution_0[grid(256)](buf9, primals_9, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_9 buf10 = extern_kernels.convolution(buf9, primals_6, 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, 16, 4, 1)) buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_add_convolution_relu_threshold_backward_2[grid(256)]( primals_3, buf1, buf4, primals_7, buf7, buf10, buf11, buf12, buf13, buf14, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf10 del buf4 del buf7 del primals_7 return (buf11, primals_1, primals_3, primals_4, primals_6, primals_8, buf1, buf3, buf6, buf9, buf12, buf13, buf14) class DacBlockNew(nn.Module): def __init__(self, channel): super(DacBlockNew, self).__init__() self.dilate1 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 1, padding=1) self.dilate2 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 3, padding=3) self.dilate3 = nn.Conv2d(channel, channel, kernel_size=3, dilation= 5, padding=5) self.conv1x1 = nn.Conv2d(channel, channel, kernel_size=1, dilation= 1, padding=0) self.relu = nn.ReLU(inplace=True) for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): if m.bias is not None: m.bias.data.zero_() def forward(self, input_0): primals_1 = self.dilate1.weight primals_2 = self.dilate1.bias primals_4 = self.dilate2.weight primals_5 = self.dilate2.bias primals_8 = self.dilate3.weight primals_7 = self.dilate3.bias primals_6 = self.conv1x1.weight primals_9 = self.conv1x1.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]
JiYuanFeng/MCTrans
DacBlock
false
13,889
[ "Apache-2.0" ]
84
9b8b5677eef584b423d5e1630680a4b667cbe823
https://github.com/JiYuanFeng/MCTrans/tree/9b8b5677eef584b423d5e1630680a4b667cbe823
MultiHeadAttentionBlock
import math import torch import torch.nn as nn import torch.utils.data import torch.backends.cudnn def mask_logits(inputs, mask, mask_value=-1e+30): mask = mask.type(torch.float32) return inputs + (1.0 - mask) * mask_value class Conv1D(nn.Module): def __init__(self, in_dim, out_dim, kernel_size=1, stride=1, padding=0, bias=True): super(Conv1D, self).__init__() self.conv1d = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=kernel_size, padding=padding, stride=stride, bias=bias) def forward(self, x): x = x.transpose(1, 2) x = self.conv1d(x) return x.transpose(1, 2) class MultiHeadAttentionBlock(nn.Module): def __init__(self, dim, num_heads, drop_rate): super(MultiHeadAttentionBlock, self).__init__() assert dim % num_heads == 0, 'The channels (%d) is not a multiple of attention heads (%d)' % ( dim, num_heads) self.head_size, self.num_heads, self.dim = int(dim / num_heads ), num_heads, dim self.dropout = nn.Dropout(p=drop_rate) self.query = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride= 1, padding=0, bias=True) self.key = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) self.value = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride= 1, padding=0, bias=True) self.layer_norm1 = nn.LayerNorm(dim, eps=1e-06) self.layer_norm2 = nn.LayerNorm(dim, eps=1e-06) self.out_layer = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_heads, self.head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) @staticmethod def combine_last_two_dim(x): old_shape = list(x.size()) new_shape = old_shape[:-2] + [old_shape[-2] * old_shape[-1]] return x.reshape(shape=new_shape) def forward(self, x, mask=None): output = self.layer_norm1(x) output = self.dropout(output) query = self.transpose_for_scores(self.query(output)) key = self.transpose_for_scores(self.key(output)) value = self.transpose_for_scores(self.value(output)) attention_scores = torch.matmul(query, key.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.head_size) if mask is not None: mask = mask.unsqueeze(1).unsqueeze(2) attention_scores = mask_logits(attention_scores, mask) attention_probs = nn.Softmax(dim=-1)(attention_scores) attention_probs = self.dropout(attention_probs) value = torch.matmul(attention_probs, value) value = self.combine_last_two_dim(value.permute(0, 2, 1, 3)) output = self.dropout(value) residual = output + x output = self.layer_norm2(residual) output = self.dropout(output) output = self.out_layer(output) output = self.dropout(output) + residual return output def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dim': 4, 'num_heads': 4, 'drop_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 from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import torch.nn as nn import torch.utils.data import torch.backends.cudnn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-06 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_convolution_2(in_ptr0, out_ptr0, out_ptr1, out_ptr2, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex 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) tl.store(out_ptr1 + (x2 + 4 * y3), tmp0, xmask & ymask) tl.store(out_ptr2 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) 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_5(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_convolution_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask) tmp1 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask) tmp4 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask) tmp8 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask) tmp12 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 + tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = 4.0 tmp16 = tmp14 / tmp15 tmp17 = tmp2 - tmp16 tmp18 = tmp17 * tmp17 tmp19 = tmp5 - tmp16 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = tmp9 - tmp16 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp16 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = tmp27 / tmp15 tl.store(out_ptr0 + x2, tmp16, xmask) tl.store(out_ptr1 + x2, tmp28, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, 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 + (x2 + 4 * y3), xmask & ymask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr2 + y3, ymask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + y3, ymask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x2, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp6 = 1e-06 tmp7 = tmp5 + tmp6 tmp8 = libdevice.rsqrt(tmp7) tmp9 = tmp4 * tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + (x2 + 4 * y3), tmp13, xmask & ymask) @triton.jit def triton_poi_fused_convolution_9(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_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_out_ptr0 + (x2 + 4 * y3), xmask & ymask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + y0, ymask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + (x2 + 4 * y3), xmask & ymask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + (x2 + 4 * 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) = args args.clear() assert_size_stride(primals_1, (4,), (1,)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_4, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) get_raw_stream(0) triton_poi_fused_native_layer_norm_0[grid(16)](primals_3, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(64)](primals_3, buf0, buf1, primals_1, primals_2, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_2 buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_convolution_2[grid(16, 4)](buf2, buf3, buf5, buf7, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4), (16, 4, 1)) buf6 = extern_kernels.convolution(buf5, primals_6, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf6, (4, 4, 4), (16, 4, 1)) buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf8, (4, 4, 4), (16, 4, 1)) buf9 = reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf4 triton_poi_fused_3[grid(64)](buf9, primals_5, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_5 buf10 = reinterpret_tensor(buf6, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf6 triton_poi_fused_3[grid(64)](buf10, primals_7, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_7 buf11 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf10, (16, 1, 4), (4, 0, 1), 0), out=buf11) buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_4[grid(256)](buf11, buf12, 256, XBLOCK=128, num_warps=4, num_stages=1) buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_5[grid(256)](buf11, buf12, buf13, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf11 del buf12 buf14 = buf8 del buf8 triton_poi_fused_convolution_6[grid(64)](buf14, primals_9, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_9 buf15 = reinterpret_tensor(buf7, (16, 4, 1), (4, 1, 1), 0) del buf7 extern_kernels.bmm(reinterpret_tensor(buf13, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf14, (16, 4, 1), (4, 1, 0), 0), out=buf15) buf16 = buf1 del buf1 buf17 = buf0 del buf0 triton_poi_fused_add_native_layer_norm_7[grid(16)](buf15, primals_3, buf16, buf17, 16, XBLOCK=16, num_warps=1, num_stages=1) buf18 = buf5 del buf5 triton_poi_fused_add_native_layer_norm_8[grid(16, 4)](buf15, primals_3, buf16, buf17, primals_10, primals_11, buf18, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del buf16 del buf17 del primals_11 buf19 = buf3 del buf3 triton_poi_fused_convolution_9[grid(16, 4)](buf18, buf19, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf20 = extern_kernels.convolution(buf19, primals_12, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf20, (4, 4, 4), (16, 4, 1)) del buf19 buf21 = reinterpret_tensor(buf20, (4, 4, 4), (16, 1, 4), 0) del buf20 triton_poi_fused_add_10[grid(16, 4)](buf21, primals_13, buf15, primals_3, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del primals_13 return (buf21, primals_3, primals_4, primals_6, primals_8, primals_10, primals_12, reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), buf13, buf15, reinterpret_tensor(buf14, (16, 1, 4), (4, 4, 1), 0), reinterpret_tensor(buf9, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf10, (16, 4, 1), (4, 1, 4), 0), reinterpret_tensor(buf18, (4, 4, 4), (16, 1, 4), 0)) def mask_logits(inputs, mask, mask_value=-1e+30): mask = mask.type(torch.float32) return inputs + (1.0 - mask) * mask_value class Conv1D(nn.Module): def __init__(self, in_dim, out_dim, kernel_size=1, stride=1, padding=0, bias=True): super(Conv1D, self).__init__() self.conv1d = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=kernel_size, padding=padding, stride=stride, bias=bias) def forward(self, x): x = x.transpose(1, 2) x = self.conv1d(x) return x.transpose(1, 2) class MultiHeadAttentionBlockNew(nn.Module): def __init__(self, dim, num_heads, drop_rate): super(MultiHeadAttentionBlockNew, self).__init__() assert dim % num_heads == 0, 'The channels (%d) is not a multiple of attention heads (%d)' % ( dim, num_heads) self.head_size, self.num_heads, self.dim = int(dim / num_heads ), num_heads, dim self.dropout = nn.Dropout(p=drop_rate) self.query = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride= 1, padding=0, bias=True) self.key = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) self.value = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride= 1, padding=0, bias=True) self.layer_norm1 = nn.LayerNorm(dim, eps=1e-06) self.layer_norm2 = nn.LayerNorm(dim, eps=1e-06) self.out_layer = Conv1D(in_dim=dim, out_dim=dim, kernel_size=1, stride=1, padding=0, bias=True) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_heads, self.head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) @staticmethod def combine_last_two_dim(x): old_shape = list(x.size()) new_shape = old_shape[:-2] + [old_shape[-2] * old_shape[-1]] return x.reshape(shape=new_shape) def forward(self, input_0): primals_4 = self.query.conv1d.weight primals_1 = self.query.conv1d.bias primals_6 = self.key.conv1d.weight primals_2 = self.key.conv1d.bias primals_8 = self.value.conv1d.weight primals_5 = self.value.conv1d.bias primals_7 = self.layer_norm1.weight primals_9 = self.layer_norm1.bias primals_10 = self.layer_norm2.weight primals_11 = self.layer_norm2.bias primals_12 = self.out_layer.conv1d.weight primals_13 = self.out_layer.conv1d.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]
IsaacChanghau/VSLNet
MultiHeadAttentionBlock
false
13,890
[ "MIT" ]
62
3793c625f2e251a5f19a0d59f0c83b12e386f808
https://github.com/IsaacChanghau/VSLNet/tree/3793c625f2e251a5f19a0d59f0c83b12e386f808
WassersteinLoss
from torch.nn import Module import functools import torch import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init class WassersteinLoss(Module): """For WGAN.""" def forward(self, real, fake): return real.mean() - fake.mean() class PrePostInitMeta(type): """A metaclass that calls optional `__pre_init__` and `__post_init__` methods""" def __new__(cls, name, bases, dct): x = super().__new__(cls, name, bases, dct) old_init = x.__init__ def _pass(self): pass @functools.wraps(old_init) def _init(self, *args, **kwargs): self.__pre_init__() old_init(self, *args, **kwargs) self.__post_init__() x.__init__ = _init if not hasattr(x, '__pre_init__'): x.__pre_init__ = _pass if not hasattr(x, '__post_init__'): x.__post_init__ = _pass return x class Module(nn.Module, metaclass=PrePostInitMeta): """Same as `nn.Module`, but no need for subclasses to call `super().__init__`""" def __pre_init__(self): super().__init__() def __init__(self): pass 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.nn import Module import functools import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_mean_sub_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp4 = tl.load(in_ptr1 + r0, None) tmp1 = tl.broadcast_to(tmp0, [RBLOCK]) tmp3 = triton_helpers.promote_to_tensor(tl.sum(tmp1, 0)) tmp5 = tl.broadcast_to(tmp4, [RBLOCK]) tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0)) tmp8 = 256.0 tmp9 = tmp3 / tmp8 tmp10 = tmp7 / tmp8 tmp11 = tmp9 - tmp10 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_mean_sub_0[grid(1)](buf2, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf2, class WassersteinLossNew(Module): """For WGAN.""" def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0] class PrePostInitMeta(type): """A metaclass that calls optional `__pre_init__` and `__post_init__` methods""" def __new__(cls, name, bases, dct): x = super().__new__(cls, name, bases, dct) old_init = x.__init__ def _pass(self): pass @functools.wraps(old_init) def _init(self, *args, **kwargs): self.__pre_init__() old_init(self, *args, **kwargs) self.__post_init__() x.__init__ = _init if not hasattr(x, '__pre_init__'): x.__pre_init__ = _pass if not hasattr(x, '__post_init__'): x.__post_init__ = _pass return x class Module(nn.Module, metaclass=PrePostInitMeta): """Same as `nn.Module`, but no need for subclasses to call `super().__init__`""" def __pre_init__(self): super().__init__() def __init__(self): pass
JiahuaWU/fastai
WassersteinLoss
false
13,892
[ "Apache-2.0" ]
59
13a2df812d875abf0558004283392ab40d9bdea1
https://github.com/JiahuaWU/fastai/tree/13a2df812d875abf0558004283392ab40d9bdea1
FocalLoss
import torch import torch.nn as nn import torch.nn.functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Average factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def convert_to_one_hot(targets: 'torch.Tensor', classes) ->torch.Tensor: """This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (Tensor): The ground truth label of the prediction with shape (N, 1) classes (int): the number of classes. Returns: Tensor: Processed loss values. """ assert torch.max(targets).item( ) < classes, 'Class Index must be less than number of classes' one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch. long, device=targets.device) one_hot_targets.scatter_(1, targets.long(), 1) return one_hot_targets def sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): """Sigmoid focal loss. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, ). Defaults to None. gamma (float): The gamma for calculating the modulating factor. Defaults to 2.0. alpha (float): A balanced form for Focal Loss. Defaults to 0.25. reduction (str): The method used to reduce the loss. Options are "none", "mean" and "sum". If reduction is 'none' , loss is same shape as pred and label. Defaults to 'mean'. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. Returns: torch.Tensor: Loss. """ assert pred.shape == target.shape, 'pred and target should be in the same shape.' pred_sigmoid = pred.sigmoid() target = target.type_as(pred) pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target) focal_weight = (alpha * target + (1 - alpha) * (1 - target)) * pt.pow(gamma ) loss = F.binary_cross_entropy_with_logits(pred, target, reduction='none' ) * focal_weight if weight is not None: assert weight.dim() == 1 weight = weight.float() if pred.dim() > 1: weight = weight.reshape(-1, 1) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss class FocalLoss(nn.Module): """Focal loss. Args: gamma (float): Focusing parameter in focal loss. Defaults to 2.0. alpha (float): The parameter in balanced form of focal loss. Defaults to 0.25. reduction (str): The method used to reduce the loss into a scalar. Options are "none" and "mean". Defaults to 'mean'. loss_weight (float): Weight of loss. Defaults to 1.0. """ def __init__(self, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0 ): super(FocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha self.reduction = reduction self.loss_weight = loss_weight def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None): """Sigmoid focal loss. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*), N or (N,1). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, \\*). Defaults to None. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. reduction_override (str, optional): The method used to reduce the loss into a scalar. Options are "none", "mean" and "sum". Defaults to None. Returns: torch.Tensor: Loss. """ assert reduction_override in (None, 'none', 'mean', 'sum') reduction = (reduction_override if reduction_override else self. reduction) if target.dim() == 1 or target.dim() == 2 and target.shape[1] == 1: target = convert_to_one_hot(target.view(-1, 1), pred.shape[-1]) loss_cls = self.loss_weight * sigmoid_focal_loss(pred, target, weight, gamma=self.gamma, alpha=self.alpha, reduction=reduction, avg_factor=avg_factor) return loss_cls def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import torch.nn as nn import torch.nn.functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0( in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 1.0 tmp2 = tmp1 - tmp0 tmp4 = tmp2 * tmp3 tmp5 = 0.0 tmp6 = triton_helpers.minimum(tmp5, tmp3) tmp7 = tl_math.abs(tmp3) tmp8 = -tmp7 tmp9 = tl_math.exp(tmp8) tmp10 = libdevice.log1p(tmp9) tmp11 = tmp6 - tmp10 tmp12 = tmp4 - tmp11 tmp13 = 0.25 tmp14 = tmp0 * tmp13 tmp15 = 0.75 tmp16 = tmp2 * tmp15 tmp17 = tmp14 + tmp16 tmp18 = tl.sigmoid(tmp3) tmp19 = tmp1 - tmp18 tmp20 = tmp19 * tmp0 tmp21 = tmp18 * tmp2 tmp22 = tmp20 + tmp21 tmp23 = tmp22 * tmp22 tmp24 = tmp17 * tmp23 tmp25 = tmp12 * tmp24 tmp26 = tl.broadcast_to(tmp25, [RBLOCK]) tmp28 = triton_helpers.promote_to_tensor(tl.sum(tmp26, 0)) tmp29 = 256.0 tmp30 = tmp28 / tmp29 tmp31 = tmp30 * tmp1 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp31, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0[ grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, 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): Average factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def convert_to_one_hot(targets: 'torch.Tensor', classes) ->torch.Tensor: """This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (Tensor): The ground truth label of the prediction with shape (N, 1) classes (int): the number of classes. Returns: Tensor: Processed loss values. """ assert torch.max(targets).item( ) < classes, 'Class Index must be less than number of classes' one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch. long, device=targets.device) one_hot_targets.scatter_(1, targets.long(), 1) return one_hot_targets def sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): """Sigmoid focal loss. Args: pred (torch.Tensor): The prediction with shape (N, \\*). target (torch.Tensor): The ground truth label of the prediction with shape (N, \\*). weight (torch.Tensor, optional): Sample-wise loss weight with shape (N, ). Defaults to None. gamma (float): The gamma for calculating the modulating factor. Defaults to 2.0. alpha (float): A balanced form for Focal Loss. Defaults to 0.25. reduction (str): The method used to reduce the loss. Options are "none", "mean" and "sum". If reduction is 'none' , loss is same shape as pred and label. Defaults to 'mean'. avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. Returns: torch.Tensor: Loss. """ assert pred.shape == target.shape, 'pred and target should be in the same shape.' pred_sigmoid = pred.sigmoid() target = target.type_as(pred) pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target) focal_weight = (alpha * target + (1 - alpha) * (1 - target)) * pt.pow(gamma ) loss = F.binary_cross_entropy_with_logits(pred, target, reduction='none' ) * focal_weight if weight is not None: assert weight.dim() == 1 weight = weight.float() if pred.dim() > 1: weight = weight.reshape(-1, 1) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss class FocalLossNew(nn.Module): """Focal loss. Args: gamma (float): Focusing parameter in focal loss. Defaults to 2.0. alpha (float): The parameter in balanced form of focal loss. Defaults to 0.25. reduction (str): The method used to reduce the loss into a scalar. Options are "none" and "mean". Defaults to 'mean'. loss_weight (float): Weight of loss. Defaults to 1.0. """ def __init__(self, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0 ): super(FocalLossNew, self).__init__() self.gamma = gamma self.alpha = alpha self.reduction = reduction self.loss_weight = loss_weight def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
JiYuanFeng/mmclassification
FocalLoss
false
13,893
[ "Apache-2.0" ]
1,190
b337ef1f11b85148cca4b6fb0c4da3f8cc2eede6
https://github.com/JiYuanFeng/mmclassification/tree/b337ef1f11b85148cca4b6fb0c4da3f8cc2eede6
CrossEntropy2D
import torch import torch.nn as nn class CrossEntropy2D(nn.Module): """ 2D Cross-entropy loss implemented as negative log likelihood """ def __init__(self, weight=None, reduction='none'): super(CrossEntropy2D, self).__init__() self.nll_loss = nn.CrossEntropyLoss(weight=weight, reduction=reduction) def forward(self, inputs, targets): return self.nll_loss(inputs, targets) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_poi_fused__log_softmax_mul_neg_sum_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp5 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp8 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp13 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask) tmp16 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask) tmp20 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask) tmp24 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask) tmp1 = tl_math.exp(tmp0) tmp3 = tl_math.exp(tmp2) tmp4 = tmp1 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp14 = tmp12 * tmp13 tmp15 = tmp2 - tmp11 tmp17 = tmp15 * tmp16 tmp18 = tmp14 + tmp17 tmp19 = tmp5 - tmp11 tmp21 = tmp19 * tmp20 tmp22 = tmp18 + tmp21 tmp23 = tmp8 - tmp11 tmp25 = tmp23 * tmp24 tmp26 = tmp22 + tmp25 tmp27 = -tmp26 tl.store(out_ptr0 + x2, tmp27, 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_softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__log_softmax_mul_neg_sum_1[grid(64)](buf0, arg0_1, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 del buf0 return buf1, class CrossEntropy2DNew(nn.Module): """ 2D Cross-entropy loss implemented as negative log likelihood """ def __init__(self, weight=None, reduction='none'): super(CrossEntropy2DNew, self).__init__() self.nll_loss = nn.CrossEntropyLoss(weight=weight, reduction=reduction) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
Jinboasltw/FastSurfer
CrossEntropy2D
false
13,894
[ "Apache-2.0" ]
257
3c0330c459c221b85428d3ec2e95f5196aee3129
https://github.com/Jinboasltw/FastSurfer/tree/3c0330c459c221b85428d3ec2e95f5196aee3129
MaxPoolPad
import torch import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init class MaxPoolPad(nn.Module): def __init__(self): super(MaxPoolPad, self).__init__() self.pad = nn.ZeroPad2d((1, 0, 1, 0)) self.pool = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, x): x = self.pad(x) x = self.pool(x) x = x[:, :, 1:, 1:] return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.utils.data import torch.nn as nn from torchvision.models import * import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_constant_pad_nd_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 144 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 3 % 3 x0 = xindex % 3 x2 = xindex // 9 x4 = xindex tmp0 = -1 + 2 * x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 5, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = -1 + 2 * x0 tmp7 = tmp6 >= tmp1 tmp8 = tmp6 < tmp3 tmp9 = tmp7 & tmp8 tmp10 = tmp5 & tmp9 tmp11 = -2 + 2 * x1 tmp12 = tmp11 >= tmp1 tmp13 = -2 + 2 * x0 tmp14 = tmp13 >= tmp1 tmp15 = tmp12 & tmp14 tmp16 = tmp15 & tmp10 tmp17 = tl.load(in_ptr0 + (-10 + 2 * x0 + 8 * x1 + 16 * x2), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp18 = tl.full(tmp17.shape, float('-inf'), tmp17.dtype) tmp19 = tl.where(tmp10, tmp17, tmp18) tmp20 = 2 * x0 tmp21 = tmp20 >= tmp1 tmp22 = tmp20 < tmp3 tmp23 = tmp21 & tmp22 tmp24 = tmp5 & tmp23 tmp25 = tmp12 & tmp7 tmp26 = tmp25 & tmp24 tmp27 = tl.load(in_ptr0 + (-9 + 2 * x0 + 8 * x1 + 16 * x2), tmp26 & xmask, eviction_policy='evict_last', other=0.0) tmp28 = tl.full(tmp27.shape, float('-inf'), tmp27.dtype) tmp29 = tl.where(tmp24, tmp27, tmp28) tmp30 = triton_helpers.maximum(tmp29, tmp19) tmp31 = 1 + 2 * x0 tmp32 = tmp31 >= tmp1 tmp33 = tmp31 < tmp3 tmp34 = tmp32 & tmp33 tmp35 = tmp5 & tmp34 tmp36 = tmp12 & tmp21 tmp37 = tmp36 & tmp35 tmp38 = tl.load(in_ptr0 + (-8 + 2 * x0 + 8 * x1 + 16 * x2), tmp37 & xmask, eviction_policy='evict_last', other=0.0) tmp39 = tl.full(tmp38.shape, float('-inf'), tmp38.dtype) tmp40 = tl.where(tmp35, tmp38, tmp39) tmp41 = triton_helpers.maximum(tmp40, tmp30) tmp42 = 2 * x1 tmp43 = tmp42 >= tmp1 tmp44 = tmp42 < tmp3 tmp45 = tmp43 & tmp44 tmp46 = tmp45 & tmp9 tmp47 = tmp2 & tmp14 tmp48 = tmp47 & tmp46 tmp49 = tl.load(in_ptr0 + (-6 + 2 * x0 + 8 * x1 + 16 * x2), tmp48 & xmask, eviction_policy='evict_last', other=0.0) tmp50 = tl.full(tmp49.shape, float('-inf'), tmp49.dtype) tmp51 = tl.where(tmp46, tmp49, tmp50) tmp52 = triton_helpers.maximum(tmp51, tmp41) tmp53 = tmp45 & tmp23 tmp54 = tmp2 & tmp7 tmp55 = tmp54 & tmp53 tmp56 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x1 + 16 * x2), tmp55 & xmask, eviction_policy='evict_last', other=0.0) tmp57 = tl.full(tmp56.shape, float('-inf'), tmp56.dtype) tmp58 = tl.where(tmp53, tmp56, tmp57) tmp59 = triton_helpers.maximum(tmp58, tmp52) tmp60 = tmp45 & tmp34 tmp61 = tmp2 & tmp21 tmp62 = tmp61 & tmp60 tmp63 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x1 + 16 * x2), tmp62 & xmask, eviction_policy='evict_last', other=0.0) tmp64 = tl.full(tmp63.shape, float('-inf'), tmp63.dtype) tmp65 = tl.where(tmp60, tmp63, tmp64) tmp66 = triton_helpers.maximum(tmp65, tmp59) tmp67 = 1 + 2 * x1 tmp68 = tmp67 >= tmp1 tmp69 = tmp67 < tmp3 tmp70 = tmp68 & tmp69 tmp71 = tmp70 & tmp9 tmp72 = tmp43 & tmp14 tmp73 = tmp72 & tmp71 tmp74 = tl.load(in_ptr0 + (-2 + 2 * x0 + 8 * x1 + 16 * x2), tmp73 & xmask, eviction_policy='evict_last', other=0.0) tmp75 = tl.full(tmp74.shape, float('-inf'), tmp74.dtype) tmp76 = tl.where(tmp71, tmp74, tmp75) tmp77 = triton_helpers.maximum(tmp76, tmp66) tmp78 = tmp70 & tmp23 tmp79 = tmp43 & tmp7 tmp80 = tmp79 & tmp78 tmp81 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x1 + 16 * x2), tmp80 & xmask, eviction_policy='evict_last', other=0.0) tmp82 = tl.full(tmp81.shape, float('-inf'), tmp81.dtype) tmp83 = tl.where(tmp78, tmp81, tmp82) tmp84 = triton_helpers.maximum(tmp83, tmp77) tmp85 = tmp70 & tmp34 tmp86 = tmp43 & tmp21 tmp87 = tmp86 & tmp85 tmp88 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp87 & xmask, eviction_policy='evict_last', other=0.0) tmp89 = tl.full(tmp88.shape, float('-inf'), tmp88.dtype) tmp90 = tl.where(tmp85, tmp88, tmp89) tmp91 = triton_helpers.maximum(tmp90, tmp84) tl.store(out_ptr0 + x4, tmp91, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_max_pool2d_with_indices_0[grid(144)]( arg0_1, buf0, 144, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 4, 2, 2), (36, 9, 3, 1), 4), class MaxPoolPadNew(nn.Module): def __init__(self): super(MaxPoolPadNew, self).__init__() self.pad = nn.ZeroPad2d((1, 0, 1, 0)) self.pool = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
JiahuaWU/fastai
MaxPoolPad
false
13,895
[ "Apache-2.0" ]
59
13a2df812d875abf0558004283392ab40d9bdea1
https://github.com/JiahuaWU/fastai/tree/13a2df812d875abf0558004283392ab40d9bdea1
SoftQNetwork
import torch import torch.nn as nn import torch.nn.functional as F class SoftQNetwork(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, init_w=0.003): super(SoftQNetwork, self).__init__() self.linear1 = nn.Linear(num_inputs + num_actions, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear3 = nn.Linear(hidden_size, hidden_size) self.linear4 = nn.Linear(hidden_size, 1) self.linear4.weight.data.uniform_(-init_w, init_w) self.linear4.bias.data.uniform_(-init_w, init_w) def forward(self, state, action): x = torch.cat([state, action], 1) x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = F.relu(self.linear3(x)) x = self.linear4(x) return x def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'num_inputs': 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 import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4, 8), (8, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 4), (4, 1)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (4, 4), (4, 1)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (1, 4), (4, 1)) assert_size_stride(primals_10, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8 ), 0), out=buf1) del primals_3 buf2 = buf1 del buf1 triton_poi_fused_relu_1[grid(16)](buf2, primals_4, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_4 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4 ), 0), out=buf3) buf4 = buf3 del buf3 triton_poi_fused_relu_1[grid(16)](buf4, primals_6, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_6 buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf4, reinterpret_tensor(primals_7, (4, 4), (1, 4 ), 0), out=buf5) buf6 = buf5 del buf5 triton_poi_fused_relu_1[grid(16)](buf6, primals_8, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_8 buf8 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_10, buf6, reinterpret_tensor(primals_9, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf8) del primals_10 return buf8, buf0, buf2, buf4, buf6, primals_9, primals_7, primals_5 class SoftQNetworkNew(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, init_w=0.003): super(SoftQNetworkNew, self).__init__() self.linear1 = nn.Linear(num_inputs + num_actions, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear3 = nn.Linear(hidden_size, hidden_size) self.linear4 = nn.Linear(hidden_size, 1) self.linear4.weight.data.uniform_(-init_w, init_w) self.linear4.bias.data.uniform_(-init_w, init_w) def forward(self, input_0, input_1): primals_3 = self.linear1.weight primals_4 = self.linear1.bias primals_1 = self.linear2.weight primals_6 = self.linear2.bias primals_2 = self.linear3.weight primals_8 = self.linear3.bias primals_9 = self.linear4.weight primals_10 = self.linear4.bias primals_5 = input_0 primals_7 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10]) return output[0]
JieRen98/Popular-RL-Algorithms
SoftQNetwork
false
13,896
[ "Apache-2.0" ]
273
7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
https://github.com/JieRen98/Popular-RL-Algorithms/tree/7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
Attention
import torch import torch.nn as nn class Attention(nn.Module): """ Applies attention mechanism on the `context` using the `query`. **Thank you** to IBM for their initial implementation of :class:`Attention`. Here is their `License <https://github.com/IBM/pytorch-seq2seq/blob/master/LICENSE>`__. Args: dimensions (int): Dimensionality of the query and context. attention_type (str, optional): How to compute the attention score: * dot: :math:`score(H_j,q) = H_j^T q` * general: :math:`score(H_j, q) = H_j^T W_a q` Example: >>> attention = Attention(256) >>> query = torch.randn(5, 1, 256) >>> context = torch.randn(5, 5, 256) >>> output, weights = attention(query, context) >>> output.size() torch.Size([5, 1, 256]) >>> weights.size() torch.Size([5, 1, 5]) """ def __init__(self, dimensions, attention_type='general'): super(Attention, self).__init__() if attention_type not in ['dot', 'general']: raise ValueError('Invalid attention type selected.') self.attention_type = attention_type if self.attention_type == 'general': self.linear_in = nn.Linear(dimensions, dimensions, bias=False) self.linear_out = nn.Linear(dimensions * 2, dimensions, bias=False) self.softmax = nn.Softmax(dim=-1) self.tanh = nn.Tanh() def forward(self, query, context): """ Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data overwhich to apply the attention mechanism. Returns: :class:`tuple` with `output` and `weights`: * **output** (:class:`torch.LongTensor` [batch size, output length, dimensions]): Tensor containing the attended features. * **weights** (:class:`torch.FloatTensor` [batch size, output length, query length]): Tensor containing attention weights. """ batch_size, output_len, dimensions = query.size() query_len = context.size(1) if self.attention_type == 'general': query = query.view(batch_size * output_len, dimensions) query = self.linear_in(query) query = query.view(batch_size, output_len, dimensions) attention_scores = torch.bmm(query, context.transpose(1, 2). contiguous()) attention_scores = attention_scores.view(batch_size * output_len, query_len) attention_weights = self.softmax(attention_scores) attention_weights = attention_weights.view(batch_size, output_len, query_len) mix = torch.bmm(attention_weights, context) combined = torch.cat((mix, query), dim=2) combined = combined.view(batch_size * output_len, 2 * dimensions) output = self.linear_out(combined).view(batch_size, output_len, dimensions) output = self.tanh(output) return output, attention_weights def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dimensions': 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_clone_transpose_0(in_ptr0, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x1 = xindex y0 = yindex y2 = yindex % 4 y3 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x1 + 4 * y0), xmask & ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) tl.store(out_ptr1 + (y2 + 4 * x1 + 16 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_cat_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_tanh_4(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) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 8), (8, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf0) del primals_3 buf1 = empty_strided_cuda((4, 4, 4), (16, 1, 4), torch.float32) buf9 = empty_strided_cuda((4, 4, 4), (16, 1, 4), torch.float32) get_raw_stream(0) triton_poi_fused_clone_transpose_0[grid(16, 4)](primals_2, buf1, buf9, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0), buf1, out=buf2) buf3 = reinterpret_tensor(buf1, (16, 4), (4, 1), 0) del buf1 triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = reinterpret_tensor(buf2, (16, 4), (4, 1), 0) del buf2 triton_poi_fused__softmax_2[grid(64)](buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) buf5 = reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0) del buf3 extern_kernels.bmm(reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0), primals_2, out=buf5) buf6 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32) triton_poi_fused_cat_3[grid(128)](buf5, buf0, buf6, 128, XBLOCK=128, num_warps=4, num_stages=1) del buf0 buf7 = reinterpret_tensor(buf5, (16, 4), (4, 1), 0) del buf5 extern_kernels.mm(reinterpret_tensor(buf6, (16, 8), (8, 1), 0), reinterpret_tensor(primals_4, (8, 4), (1, 8), 0), out=buf7) buf8 = reinterpret_tensor(buf7, (4, 4, 4), (16, 4, 1), 0) del buf7 triton_poi_fused_tanh_4[grid(64)](buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) return buf8, reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0 ), reinterpret_tensor(primals_2, (4, 4, 4), (16, 1, 4), 0 ), buf4, reinterpret_tensor(buf6, (16, 8), (8, 1), 0 ), buf8, primals_4, buf9 class AttentionNew(nn.Module): """ Applies attention mechanism on the `context` using the `query`. **Thank you** to IBM for their initial implementation of :class:`Attention`. Here is their `License <https://github.com/IBM/pytorch-seq2seq/blob/master/LICENSE>`__. Args: dimensions (int): Dimensionality of the query and context. attention_type (str, optional): How to compute the attention score: * dot: :math:`score(H_j,q) = H_j^T q` * general: :math:`score(H_j, q) = H_j^T W_a q` Example: >>> attention = Attention(256) >>> query = torch.randn(5, 1, 256) >>> context = torch.randn(5, 5, 256) >>> output, weights = attention(query, context) >>> output.size() torch.Size([5, 1, 256]) >>> weights.size() torch.Size([5, 1, 5]) """ def __init__(self, dimensions, attention_type='general'): super(AttentionNew, self).__init__() if attention_type not in ['dot', 'general']: raise ValueError('Invalid attention type selected.') self.attention_type = attention_type if self.attention_type == 'general': self.linear_in = nn.Linear(dimensions, dimensions, bias=False) self.linear_out = nn.Linear(dimensions * 2, dimensions, bias=False) self.softmax = nn.Softmax(dim=-1) self.tanh = nn.Tanh() def forward(self, input_0, input_1): primals_3 = self.linear_in.weight primals_4 = self.linear_out.weight primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0], output[1]
JiaqiLiu/PyTorch-NLP
Attention
false
13,897
[ "BSD-3-Clause" ]
2,125
71d2ce1e8b8da5ab4e7732d1ebf971150986e6c8
https://github.com/JiaqiLiu/PyTorch-NLP/tree/71d2ce1e8b8da5ab4e7732d1ebf971150986e6c8
CharbonnierLoss
import functools import torch import torch.nn as nn from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def charbonnier_loss(pred, target, eps=1e-12): """Charbonnier loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated Charbonnier loss. """ return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierLoss(nn.Module): """Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss). Described in "Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution". Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False, eps=1e-12): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise self.eps = eps def forward(self, pred, target, weight=None, **kwargs): """Forward Function. Args: pred (Tensor): of shape (N, C, H, W). Predicted tensor. target (Tensor): of shape (N, C, H, W). Ground truth tensor. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ return self.loss_weight * charbonnier_loss(pred, target, weight, eps=self.eps, reduction=self.reduction, sample_wise=self. sample_wise) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice import functools import torch.nn as nn from torch.nn import functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_mean_mul_pow_sqrt_sub_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = 1e-12 tmp5 = tmp3 + tmp4 tmp6 = libdevice.sqrt(tmp5) tmp7 = tl.broadcast_to(tmp6, [RBLOCK]) tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0)) tmp10 = 256.0 tmp11 = tmp9 / tmp10 tmp12 = 1.0 tmp13 = tmp11 * tmp12 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp13, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_mean_mul_pow_sqrt_sub_0[grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def charbonnier_loss(pred, target, eps=1e-12): """Charbonnier loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated Charbonnier loss. """ return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierLossNew(nn.Module): """Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss). Described in "Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution". Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False, eps=1e-12): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise self.eps = eps def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
Juggernaut93/mmediting
CharbonnierLoss
false
13,898
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
CharbonnierCompLoss
import functools import torch import torch.nn as nn from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def charbonnier_loss(pred, target, eps=1e-12): """Charbonnier loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated Charbonnier loss. """ return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierCompLoss(nn.Module): """Charbonnier composition loss. Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False, eps=1e-12): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise self.eps = eps def forward(self, pred_alpha, fg, bg, ori_merged, weight=None, **kwargs): """ Args: pred_alpha (Tensor): of shape (N, 1, H, W). Predicted alpha matte. fg (Tensor): of shape (N, 3, H, W). Tensor of foreground object. bg (Tensor): of shape (N, 3, H, W). Tensor of background object. ori_merged (Tensor): of shape (N, 3, H, W). Tensor of origin merged image before normalized by ImageNet mean and std. weight (Tensor, optional): of shape (N, 1, H, W). It is an indicating matrix: weight[trimap == 128] = 1. Default: None. """ pred_merged = pred_alpha * fg + (1.0 - pred_alpha) * bg if weight is not None: weight = weight.expand(-1, 3, -1, -1) return self.loss_weight * charbonnier_loss(pred_merged, ori_merged, weight, eps=self.eps, reduction=self.reduction, sample_wise= self.sample_wise) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice import functools import torch.nn as nn from torch.nn import functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_mean_mul_pow_rsub_sqrt_sub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp5 = tl.load(in_ptr2 + r0, None) tmp8 = tl.load(in_ptr3 + r0, None) tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp3 - tmp0 tmp6 = tmp4 * tmp5 tmp7 = tmp2 + tmp6 tmp9 = tmp7 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = 1e-12 tmp12 = tmp10 + tmp11 tmp13 = libdevice.sqrt(tmp12) tmp14 = tl.broadcast_to(tmp13, [RBLOCK]) tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0)) tmp17 = 256.0 tmp18 = tmp16 / tmp17 tmp19 = tmp18 * tmp3 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp19, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_mean_mul_pow_rsub_sqrt_sub_0[grid(1)](buf1, arg0_1, arg1_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def charbonnier_loss(pred, target, eps=1e-12): """Charbonnier loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated Charbonnier loss. """ return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierCompLossNew(nn.Module): """Charbonnier composition loss. Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False, eps=1e-12): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise self.eps = eps 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]
Juggernaut93/mmediting
CharbonnierCompLoss
false
13,899
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
L1CompositionLoss
import functools import torch import torch.nn as nn from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def l1_loss(pred, target): """L1 loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated L1 loss. """ return F.l1_loss(pred, target, reduction='none') class L1CompositionLoss(nn.Module): """L1 composition loss. Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise def forward(self, pred_alpha, fg, bg, ori_merged, weight=None, **kwargs): """ Args: pred_alpha (Tensor): of shape (N, 1, H, W). Predicted alpha matte. fg (Tensor): of shape (N, 3, H, W). Tensor of foreground object. bg (Tensor): of shape (N, 3, H, W). Tensor of background object. ori_merged (Tensor): of shape (N, 3, H, W). Tensor of origin merged image before normalized by ImageNet mean and std. weight (Tensor, optional): of shape (N, 1, H, W). It is an indicating matrix: weight[trimap == 128] = 1. Default: None. """ pred_merged = pred_alpha * fg + (1.0 - pred_alpha) * bg if weight is not None: weight = weight.expand(-1, 3, -1, -1) return self.loss_weight * l1_loss(pred_merged, ori_merged, weight, reduction=self.reduction, sample_wise=self.sample_wise) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import functools import torch.nn as nn from torch.nn import functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_abs_add_mean_mul_rsub_sub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp5 = tl.load(in_ptr2 + r0, None) tmp8 = tl.load(in_ptr3 + r0, None) tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp3 - tmp0 tmp6 = tmp4 * tmp5 tmp7 = tmp2 + tmp6 tmp9 = tmp7 - tmp8 tmp10 = tl_math.abs(tmp9) tmp11 = tl.broadcast_to(tmp10, [RBLOCK]) tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0)) tmp14 = 256.0 tmp15 = tmp13 / tmp14 tmp16 = tmp15 * tmp3 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp16, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_add_mean_mul_rsub_sub_0[grid(1)](buf1, arg0_1, arg1_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def l1_loss(pred, target): """L1 loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated L1 loss. """ return F.l1_loss(pred, target, reduction='none') class L1CompositionLossNew(nn.Module): """L1 composition loss. Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise 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]
Juggernaut93/mmediting
L1CompositionLoss
false
13,900
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
FocalLoss
import torch import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.nn.functional as F def focal_loss(input_values, gamma): """Computes the focal loss""" p = torch.exp(-input_values) loss = (1 - p) ** gamma * input_values return loss.mean() class FocalLoss(nn.Module): def __init__(self, weight=None, gamma=0.0): super(FocalLoss, self).__init__() assert gamma >= 0 self.gamma = gamma self.weight = weight def forward(self, input, target): return focal_loss(F.cross_entropy(input, target, reduction='none', weight=self.weight), self.gamma) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn import torch.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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp13 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp20 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp24 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = tl_math.exp(tmp0) tmp3 = tl_math.exp(tmp2) tmp4 = tmp1 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp14 = tmp12 * tmp13 tmp15 = tmp2 - tmp11 tmp17 = tmp15 * tmp16 tmp18 = tmp14 + tmp17 tmp19 = tmp5 - tmp11 tmp21 = tmp19 * tmp20 tmp22 = tmp18 + tmp21 tmp23 = tmp8 - tmp11 tmp25 = tmp23 * tmp24 tmp26 = tmp22 + tmp25 tmp27 = -tmp26 tmp28 = -tmp27 tmp29 = tl_math.exp(tmp28) tmp30 = 1.0 tmp30 - tmp29 tmp32 = tmp30 * tmp27 tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK]) tmp35 = tl.sum(tmp33, 1)[:, None] tmp36 = 64.0 tmp37 = tmp35 / tmp36 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp37, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1[grid(1)]( buf3, buf0, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf0 return buf3, def focal_loss(input_values, gamma): """Computes the focal loss""" p = torch.exp(-input_values) loss = (1 - p) ** gamma * input_values return loss.mean() class FocalLossNew(nn.Module): def __init__(self, weight=None, gamma=0.0): super(FocalLossNew, self).__init__() assert gamma >= 0 self.gamma = gamma self.weight = 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]
Jianf-Wang/RSG
FocalLoss
false
13,901
[ "MIT" ]
108
3c5074511455428d81af89e1621493dcdb5db6ce
https://github.com/Jianf-Wang/RSG/tree/3c5074511455428d81af89e1621493dcdb5db6ce
NormedLinear
import torch import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.nn.functional as F from torch.nn import Parameter class NormedLinear(nn.Module): def __init__(self, in_features, out_features): super(NormedLinear, self).__init__() self.weight = Parameter(torch.Tensor(in_features, out_features)) self.weight.data.uniform_(-1, 1).renorm_(2, 1, 1e-05).mul_(100000.0) def forward(self, x): out = F.normalize(x, dim=1).mm(F.normalize(self.weight, dim=0)) return out def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_features': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data from torch.nn import Parameter assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-12 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = tmp0 / tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused_div_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (8 + x0), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (12 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-12 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = tmp0 / tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_div_1[grid(16)](primals_2, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf0, buf1, out=buf2) del buf1 return buf2, primals_2, reinterpret_tensor(buf0, (4, 4), (1, 4), 0) class NormedLinearNew(nn.Module): def __init__(self, in_features, out_features): super(NormedLinearNew, self).__init__() self.weight = Parameter(torch.Tensor(in_features, out_features)) self.weight.data.uniform_(-1, 1).renorm_(2, 1, 1e-05).mul_(100000.0) def forward(self, input_0): primals_1 = self.weight primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
Jianf-Wang/RSG
NormedLinear
false
13,902
[ "MIT" ]
108
3c5074511455428d81af89e1621493dcdb5db6ce
https://github.com/Jianf-Wang/RSG/tree/3c5074511455428d81af89e1621493dcdb5db6ce
ComponentConditionBlock
import torch import torch.nn as nn import torch.utils.data.distributed class ComponentConditionBlock(nn.Module): def __init__(self, in_shape, n_comps): super().__init__() self.in_shape = in_shape self.bias = nn.Parameter(torch.zeros(n_comps, in_shape[0], 1, 1), requires_grad=True) def forward(self, x, comp_id): b = self.bias[comp_id] out = x + b return out def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.ones([4], dtype=torch.int64)] def get_init_inputs(): return [[], {'in_shape': [4, 4], 'n_comps': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn import torch.utils.data.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_index_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 x2 = xindex // 64 x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last') tmp2 = tl.full([XBLOCK], 4, tl.int32) tmp3 = tmp1 + tmp2 tmp4 = tmp1 < 0 tmp5 = tl.where(tmp4, tmp3, tmp1) tl.device_assert((0 <= tmp5) & (tmp5 < 4) | ~xmask, 'index out of bounds: 0 <= tmp5 < 4') tmp7 = tl.load(in_ptr2 + (x1 + 4 * tmp5), xmask, eviction_policy= 'evict_last') tmp8 = tmp0 + tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) 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_index_0[grid(256)](primals_3, primals_2, primals_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 del primals_3 return buf0, primals_2 class ComponentConditionBlockNew(nn.Module): def __init__(self, in_shape, n_comps): super().__init__() self.in_shape = in_shape self.bias = nn.Parameter(torch.zeros(n_comps, in_shape[0], 1, 1), requires_grad=True) def forward(self, input_0, input_1): primals_1 = self.bias primals_3 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3]) return output[0]
Johnson-yue/lffont
ComponentConditionBlock
false
13,903
[ "MIT" ]
98
f31f5a1cd6a075449a0f18aaafd945d373121e15
https://github.com/Johnson-yue/lffont/tree/f31f5a1cd6a075449a0f18aaafd945d373121e15
TwoLayerNet
import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F class TwoLayerNet(nn.Module): def __init__(self, D_in: 'int', H: 'int', D_out: 'int') ->None: """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. D_in: input dimension H: dimension of hidden layer D_out: output dimension """ super(TwoLayerNet, self).__init__() self.linear1 = nn.Linear(D_in, H) self.linear2 = nn.Linear(H, D_out) def forward(self, x) ->Tensor: """ In the forward function we accept a Variable of input data and we must return a Variable of output data. We can use Modules defined in the constructor as well as arbitrary operators on Variables. """ h_relu = F.relu(self.linear1(x)) y_pred = self.linear2(h_relu) return F.log_softmax(y_pred, 1) 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 from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused__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') 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_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') 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, 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 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1, primals_2, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_1[grid(256)](buf2, buf3, 256, XBLOCK= 256, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused__log_softmax_2[grid(256)](buf3, buf4, 256, XBLOCK= 256, num_warps=4, num_stages=1) del buf3 return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf4, primals_4, buf5 class TwoLayerNetNew(nn.Module): def __init__(self, D_in: 'int', H: 'int', D_out: 'int') ->None: """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. D_in: input dimension H: dimension of hidden layer D_out: output dimension """ super(TwoLayerNetNew, 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]
JohnlNguyen/FLSim
TwoLayerNet
false
13,904
[ "BSD-3-Clause" ]
79
a5ed7c0b84499cd9dbc5fe95f8bcb4ba8ab5a5cb
https://github.com/JohnlNguyen/FLSim/tree/a5ed7c0b84499cd9dbc5fe95f8bcb4ba8ab5a5cb
Get_gradient_nopadding
import torch import torch.nn as nn import torch.nn.functional as F class Get_gradient_nopadding(nn.Module): def __init__(self): super(Get_gradient_nopadding, self).__init__() kernel_v = [[0, -1, 0], [0, 0, 0], [0, 1, 0]] kernel_h = [[0, 0, 0], [-1, 0, 1], [0, 0, 0]] kernel_h = torch.FloatTensor(kernel_h).unsqueeze(0).unsqueeze(0) kernel_v = torch.FloatTensor(kernel_v).unsqueeze(0).unsqueeze(0) self.weight_h = nn.Parameter(data=kernel_h, requires_grad=False) self.weight_v = nn.Parameter(data=kernel_v, requires_grad=False) def forward(self, x): x_list = [] for i in range(x.shape[1]): x_i = x[:, i] x_i_v = F.conv2d(x_i.unsqueeze(1), self.weight_v, padding=1) x_i_h = F.conv2d(x_i.unsqueeze(1), self.weight_h, padding=1) x_i = torch.sqrt(torch.pow(x_i_v, 2) + torch.pow(x_i_h, 2) + 1e-06) x_list.append(x_i) x = torch.cat(x_list, dim=1) 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.triton_helpers import libdevice import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, 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], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x2), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp5 * tmp5 tmp7 = tl.load(in_ptr1 + (x0 + 16 * x2), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp8 = tmp7 * tmp7 tmp9 = tmp6 + tmp8 tmp10 = 1e-06 tmp11 = tmp9 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype) tmp14 = tl.where(tmp4, tmp12, tmp13) tmp15 = tmp0 >= tmp3 tmp16 = tl.full([1], 2, tl.int64) tmp17 = tmp0 < tmp16 tmp18 = tmp15 & tmp17 tmp19 = tl.load(in_ptr2 + (x0 + 16 * x2), tmp18 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tmp19 * tmp19 tmp21 = tl.load(in_ptr3 + (x0 + 16 * x2), tmp18 & xmask, eviction_policy='evict_last', other=0.0) tmp22 = tmp21 * tmp21 tmp23 = tmp20 + tmp22 tmp24 = tmp23 + tmp10 tmp25 = libdevice.sqrt(tmp24) tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype) tmp27 = tl.where(tmp18, tmp25, tmp26) tmp28 = tmp0 >= tmp16 tmp29 = tl.full([1], 3, tl.int64) tmp30 = tmp0 < tmp29 tmp31 = tmp28 & tmp30 tmp32 = tl.load(in_ptr4 + (x0 + 16 * x2), tmp31 & xmask, eviction_policy='evict_last', other=0.0) tmp33 = tmp32 * tmp32 tmp34 = tl.load(in_ptr5 + (x0 + 16 * x2), tmp31 & xmask, eviction_policy='evict_last', other=0.0) tmp35 = tmp34 * tmp34 tmp36 = tmp33 + tmp35 tmp37 = tmp36 + tmp10 tmp38 = libdevice.sqrt(tmp37) tmp39 = tl.full(tmp38.shape, 0.0, tmp38.dtype) tmp40 = tl.where(tmp31, tmp38, tmp39) tmp41 = tmp0 >= tmp29 tl.full([1], 4, tl.int64) tmp44 = tl.load(in_ptr6 + (x0 + 16 * x2), tmp41 & xmask, eviction_policy='evict_last', other=0.0) tmp45 = tmp44 * tmp44 tmp46 = tl.load(in_ptr7 + (x0 + 16 * x2), tmp41 & xmask, eviction_policy='evict_last', other=0.0) tmp47 = tmp46 * tmp46 tmp48 = tmp45 + tmp47 tmp49 = tmp48 + tmp10 tmp50 = libdevice.sqrt(tmp49) tmp51 = tl.full(tmp50.shape, 0.0, tmp50.dtype) tmp52 = tl.where(tmp41, tmp50, tmp51) tmp53 = tl.where(tmp31, tmp40, tmp52) tmp54 = tl.where(tmp18, tmp27, tmp53) tmp55 = tl.where(tmp4, tmp14, tmp54) tl.store(out_ptr0 + x3, tmp55, xmask) def call(args): arg0_1, arg1_1, arg2_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (1, 1, 3, 3), (9, 9, 3, 1)) assert_size_stride(arg2_1, (1, 1, 3, 3), (9, 9, 3, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 0), arg1_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, 1, 4, 4), (16, 16, 4, 1)) buf1 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 0), arg2_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 1, 4, 4), (16, 16, 4, 1)) buf2 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 16), arg1_1, 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, 4, 4), (16, 16, 4, 1)) buf3 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 16), arg2_1, stride=(1, 1), padding=(1, 1 ), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 1, 4, 4), (16, 16, 4, 1)) buf4 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 32), arg1_1, stride=(1, 1), padding=(1, 1 ), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 1, 4, 4), (16, 16, 4, 1)) buf5 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 32), arg2_1, stride=(1, 1), padding=(1, 1 ), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 1, 4, 4), (16, 16, 4, 1)) buf6 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 48), arg1_1, stride=(1, 1), padding=(1, 1 ), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 1, 4, 4), (16, 16, 4, 1)) del arg1_1 buf7 = extern_kernels.convolution(reinterpret_tensor(arg0_1, (4, 1, 4, 4), (64, 0, 4, 1), 48), arg2_1, stride=(1, 1), padding=(1, 1 ), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 1, 4, 4), (16, 16, 4, 1)) del arg0_1 del arg2_1 buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(256)](buf0, buf1, buf2, buf3, buf4, buf5, buf6, buf7, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del buf1 del buf2 del buf3 del buf4 del buf5 del buf6 del buf7 return buf8, class Get_gradient_nopaddingNew(nn.Module): def __init__(self): super(Get_gradient_nopaddingNew, self).__init__() kernel_v = [[0, -1, 0], [0, 0, 0], [0, 1, 0]] kernel_h = [[0, 0, 0], [-1, 0, 1], [0, 0, 0]] kernel_h = torch.FloatTensor(kernel_h).unsqueeze(0).unsqueeze(0) kernel_v = torch.FloatTensor(kernel_v).unsqueeze(0).unsqueeze(0) self.weight_h = nn.Parameter(data=kernel_h, requires_grad=False) self.weight_v = nn.Parameter(data=kernel_v, requires_grad=False) def forward(self, input_0): arg1_1 = self.weight_h arg2_1 = self.weight_v arg0_1 = input_0 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
JoeyBallentine/ESRGAN
Get_gradient_nopadding
false
13,905
[ "Apache-2.0" ]
95
9000b43e3acf8709626f45951bb91ace1d983359
https://github.com/JoeyBallentine/ESRGAN/tree/9000b43e3acf8709626f45951bb91ace1d983359
LinearRegression
import torch import torch.nn as nn class LinearRegression(nn.Module): def __init__(self): super().__init__() self.a = nn.Parameter(torch.randn(1, requires_grad=True, dtype= torch.float)) self.b = nn.Parameter(torch.randn(1, requires_grad=True, dtype= torch.float)) def forward(self, x): return self.a + self.b * x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK]) tmp2 = tl.load(in_ptr1 + 0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK]) tmp4 = tl.load(in_ptr2 + x0, xmask) tmp5 = tmp3 * tmp4 tmp6 = tmp1 + tmp5 tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (1,), (1,)) assert_size_stride(primals_2, (1,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_0[grid(256)](primals_1, primals_2, primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 return buf0, primals_3 class LinearRegressionNew(nn.Module): def __init__(self): super().__init__() self.a = nn.Parameter(torch.randn(1, requires_grad=True, dtype= torch.float)) self.b = nn.Parameter(torch.randn(1, requires_grad=True, dtype= torch.float)) def forward(self, input_0): primals_1 = self.a primals_2 = self.b primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
JohnlNguyen/FLSim
LinearRegression
false
13,906
[ "BSD-3-Clause" ]
79
a5ed7c0b84499cd9dbc5fe95f8bcb4ba8ab5a5cb
https://github.com/JohnlNguyen/FLSim/tree/a5ed7c0b84499cd9dbc5fe95f8bcb4ba8ab5a5cb
ModMBStddevLayer
import torch import torch.nn as nn class ModMBStddevLayer(nn.Module): """Modified MiniBatch Stddev Layer. This layer is modified from ``MiniBatchStddevLayer`` used in PGGAN. In StyleGAN2, the authors add a new feature, `channel_groups`, into this layer. """ def __init__(self, group_size=4, channel_groups=1, sync_groups=None, eps=1e-08): super(ModMBStddevLayer, self).__init__() self.group_size = group_size self.eps = eps self.channel_groups = channel_groups self.sync_groups = group_size if sync_groups is None else sync_groups def forward(self, x): assert x.shape[0] <= self.group_size or x.shape[0 ] % self.group_size == 0, f'Batch size be smaller than or equal to group size. Otherwise, batch size should be divisible by the group size.But got batch size {x.shape[0]}, group size {self.group_size}' assert x.shape[1 ] % self.channel_groups == 0, f'"channel_groups" must be divided by the feature channels. channel_groups: {self.channel_groups}, feature channels: {x.shape[1]}' n, c, h, w = x.shape group_size = min(n, self.group_size) y = torch.reshape(x, (group_size, -1, self.channel_groups, c // self.channel_groups, h, w)) y = torch.var(y, dim=0, unbiased=False) y = torch.sqrt(y + self.eps) y = y.mean(dim=(2, 3, 4), keepdim=True).squeeze(2) y = y.repeat(group_size, 1, h, w) return torch.cat([x, y], dim=1) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_per_fused_add_mean_repeat_sqrt_var_0(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex r1 = rindex % 16 r2 = rindex // 16 tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr0 + (64 + r0), None) tmp3 = tl.load(in_ptr0 + (128 + r0), None) tmp5 = tl.load(in_ptr0 + (192 + r0), None) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-08 tmp22 = tmp20 + tmp21 tmp23 = libdevice.sqrt(tmp22) tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp26 = tl.sum(tmp24, 1)[:, None] tmp27 = 64.0 tmp28 = tmp26 / tmp27 tl.store(out_ptr1 + tl.broadcast_to(r1 + 80 * r2, [XBLOCK, RBLOCK]), tmp28, None) @triton.jit def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 x1 = xindex // 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tl.store(out_ptr0 + (x0 + 80 * x1), tmp0, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf3 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32) buf2 = reinterpret_tensor(buf3, (4, 1, 4, 4), (80, 16, 4, 1), 64) get_raw_stream(0) triton_per_fused_add_mean_repeat_sqrt_var_0[grid(1)](arg0_1, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) buf1 = reinterpret_tensor(buf3, (4, 4, 4, 4), (80, 16, 4, 1), 0) triton_poi_fused_cat_1[grid(256)](arg0_1, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf3, class ModMBStddevLayerNew(nn.Module): """Modified MiniBatch Stddev Layer. This layer is modified from ``MiniBatchStddevLayer`` used in PGGAN. In StyleGAN2, the authors add a new feature, `channel_groups`, into this layer. """ def __init__(self, group_size=4, channel_groups=1, sync_groups=None, eps=1e-08): super(ModMBStddevLayerNew, self).__init__() self.group_size = group_size self.eps = eps self.channel_groups = channel_groups self.sync_groups = group_size if sync_groups is None else sync_groups def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Juggernaut93/mmediting
ModMBStddevLayer
false
13,907
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
ValueNetwork
import torch import torch.nn as nn import torch.nn.functional as F class ValueNetwork(nn.Module): def __init__(self, state_dim, hidden_dim, init_w=0.003): super(ValueNetwork, self).__init__() self.linear1 = nn.Linear(state_dim, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, hidden_dim) self.linear4 = nn.Linear(hidden_dim, 1) self.linear4.weight.data.uniform_(-init_w, init_w) self.linear4.bias.data.uniform_(-init_w, init_w) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) x = F.relu(self.linear3(x)) x = self.linear4(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'state_dim': 4, 'hidden_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime 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 = 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) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (1, 4), (4, 1)) assert_size_stride(primals_9, (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 buf10 = 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, buf10, 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 buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3, primals_5, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf5, primals_7, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 buf7 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_8, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf7) del primals_9 return reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor( buf3, (64, 4), (4, 1), 0), reinterpret_tensor(buf5, (64, 4), (4, 1), 0 ), primals_8, buf8, primals_6, buf9, primals_4, buf10 class ValueNetworkNew(nn.Module): def __init__(self, state_dim, hidden_dim, init_w=0.003): super(ValueNetworkNew, self).__init__() self.linear1 = nn.Linear(state_dim, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, hidden_dim) self.linear4 = nn.Linear(hidden_dim, 1) self.linear4.weight.data.uniform_(-init_w, init_w) self.linear4.bias.data.uniform_(-init_w, init_w) def forward(self, input_0): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_4 = self.linear2.weight primals_5 = self.linear2.bias primals_6 = self.linear3.weight primals_7 = self.linear3.bias primals_8 = self.linear4.weight primals_9 = self.linear4.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]
JieRen98/Popular-RL-Algorithms
ValueNetwork
false
13,908
[ "Apache-2.0" ]
273
7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
https://github.com/JieRen98/Popular-RL-Algorithms/tree/7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
MSECompositionLoss
import functools import torch import torch.nn as nn from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def mse_loss(pred, target): """MSE loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated MSE loss. """ return F.mse_loss(pred, target, reduction='none') class MSECompositionLoss(nn.Module): """MSE (L2) composition loss. Args: loss_weight (float): Loss weight for MSE loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise def forward(self, pred_alpha, fg, bg, ori_merged, weight=None, **kwargs): """ Args: pred_alpha (Tensor): of shape (N, 1, H, W). Predicted alpha matte. fg (Tensor): of shape (N, 3, H, W). Tensor of foreground object. bg (Tensor): of shape (N, 3, H, W). Tensor of background object. ori_merged (Tensor): of shape (N, 3, H, W). Tensor of origin merged image before normalized by ImageNet mean and std. weight (Tensor, optional): of shape (N, 1, H, W). It is an indicating matrix: weight[trimap == 128] = 1. Default: None. """ pred_merged = pred_alpha * fg + (1.0 - pred_alpha) * bg if weight is not None: weight = weight.expand(-1, 3, -1, -1) return self.loss_weight * mse_loss(pred_merged, ori_merged, weight, reduction=self.reduction, sample_wise=self.sample_wise) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import functools import torch.nn as nn from torch.nn import functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_mean_mse_loss_mul_rsub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp5 = tl.load(in_ptr2 + r0, None) tmp8 = tl.load(in_ptr3 + r0, None) tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp3 - tmp0 tmp6 = tmp4 * tmp5 tmp7 = tmp2 + tmp6 tmp9 = tmp7 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tl.broadcast_to(tmp10, [RBLOCK]) tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0)) tmp14 = 256.0 tmp15 = tmp13 / tmp14 tmp16 = tmp15 * tmp3 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp16, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_mean_mse_loss_mul_rsub_0[grid(1)](buf1, arg0_1, arg1_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss if reduction_enum == 1: return loss.mean() return loss.sum() def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are "none", "mean" and "sum". Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) == 1: weight = weight.expand_as(loss) eps = 1e-12 if sample_wise: weight = weight.sum(dim=[1, 2, 3], keepdim=True) loss = (loss / (weight + eps)).sum() / weight.size(0) else: loss = loss.sum() / (weight.sum() + eps) return loss def masked_loss(loss_func): """Create a masked version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @masked_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', sample_wise= False, **kwargs): loss = loss_func(pred, target, **kwargs) loss = mask_reduce_loss(loss, weight, reduction, sample_wise) return loss return wrapper @masked_loss def mse_loss(pred, target): """MSE loss. Args: pred (Tensor): Prediction Tensor with shape (n, c, h, w). target ([type]): Target Tensor with shape (n, c, h, w). Returns: Tensor: Calculated MSE loss. """ return F.mse_loss(pred, target, reduction='none') class MSECompositionLossNew(nn.Module): """MSE (L2) composition loss. Args: loss_weight (float): Loss weight for MSE loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. sample_wise (bool): Whether calculate the loss sample-wise. This argument only takes effect when `reduction` is 'mean' and `weight` (argument of `forward()`) is not None. It will first reduces loss with 'mean' per-sample, and then it means over all the samples. Default: False. """ def __init__(self, loss_weight=1.0, reduction='mean', sample_wise=False): super().__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.sample_wise = sample_wise 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]
Juggernaut93/mmediting
MSECompositionLoss
false
13,909
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
PlainRefiner
import torch import torch.nn as nn class PlainRefiner(nn.Module): """Simple refiner from Deep Image Matting. Args: conv_channels (int): Number of channels produced by the three main convolutional layer. loss_refine (dict): Config of the loss of the refiner. Default: None. pretrained (str): Name of pretrained model. Default: None. """ def __init__(self, conv_channels=64, pretrained=None): super().__init__() assert pretrained is None, 'pretrained not supported yet' self.refine_conv1 = nn.Conv2d(4, conv_channels, kernel_size=3, padding=1) self.refine_conv2 = nn.Conv2d(conv_channels, conv_channels, kernel_size=3, padding=1) self.refine_conv3 = nn.Conv2d(conv_channels, conv_channels, kernel_size=3, padding=1) self.refine_pred = nn.Conv2d(conv_channels, 1, kernel_size=3, padding=1 ) self.relu = nn.ReLU(inplace=True) def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): xavier_init(m) def forward(self, x, raw_alpha): """Forward function. Args: x (Tensor): The input feature map of refiner. raw_alpha (Tensor): The raw predicted alpha matte. Returns: Tensor: The refined alpha matte. """ out = self.relu(self.refine_conv1(x)) out = self.relu(self.refine_conv2(out)) out = self.relu(self.refine_conv3(out)) raw_refine = self.refine_pred(out) pred_refine = torch.sigmoid(raw_alpha + raw_refine) return pred_refine def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 16 % 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_add_convolution_sigmoid_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr2 + 0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK]) tmp4 = tmp1 + tmp3 tmp5 = tmp0 + tmp4 tmp6 = tl.sigmoid(tmp5) tl.store(out_ptr0 + x3, tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10) = args args.clear() assert_size_stride(primals_1, (64, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (64,), (1,)) assert_size_stride(primals_8, (1, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_9, (1,), (1,)) assert_size_stride(primals_10, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 64, 4, 4), (1024, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(4096)](buf1, primals_2, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 64, 4, 4), (1024, 16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_0[grid(4096)](buf3, primals_5, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 64, 4, 4), (1024, 16, 4, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_0[grid(4096)](buf5, primals_7, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 1, 4, 4), (16, 16, 4, 1)) buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_convolution_sigmoid_1[grid(256)](primals_10, buf6, primals_9, buf7, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf6 del primals_10 del primals_9 return (buf7, primals_1, primals_3, primals_4, primals_6, primals_8, buf1, buf3, buf5, buf7) class PlainRefinerNew(nn.Module): """Simple refiner from Deep Image Matting. Args: conv_channels (int): Number of channels produced by the three main convolutional layer. loss_refine (dict): Config of the loss of the refiner. Default: None. pretrained (str): Name of pretrained model. Default: None. """ def __init__(self, conv_channels=64, pretrained=None): super().__init__() assert pretrained is None, 'pretrained not supported yet' self.refine_conv1 = nn.Conv2d(4, conv_channels, kernel_size=3, padding=1) self.refine_conv2 = nn.Conv2d(conv_channels, conv_channels, kernel_size=3, padding=1) self.refine_conv3 = nn.Conv2d(conv_channels, conv_channels, kernel_size=3, padding=1) self.refine_pred = nn.Conv2d(conv_channels, 1, kernel_size=3, padding=1 ) self.relu = nn.ReLU(inplace=True) def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): xavier_init(m) def forward(self, input_0, input_1): primals_1 = self.refine_conv1.weight primals_2 = self.refine_conv1.bias primals_4 = self.refine_conv2.weight primals_5 = self.refine_conv2.bias primals_6 = self.refine_conv3.weight primals_7 = self.refine_conv3.bias primals_8 = self.refine_pred.weight primals_9 = self.refine_pred.bias primals_3 = input_0 primals_10 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10]) return output[0]
Juggernaut93/mmediting
PlainRefiner
false
13,910
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
Transformer
import torch from torch import nn import torch.nn.functional as F import torch.utils.data class Transformer(nn.Module): def __init__(self, in_channels, out_channels): super(Transformer, self).__init__() self.T_sigma = nn.Linear(in_channels, out_channels) self.T_gamma = nn.Linear(in_channels, out_channels) def forward(self, sigma, gamma): sigma_out = self.T_sigma(sigma) gamma_out = self.T_gamma(gamma) return F.softplus(sigma_out), F.softplus(gamma_out) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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) tl.store(out_ptr0 + x0, tmp5, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_softplus_0[grid(256)](buf0, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_softplus_0[grid(256)](buf1, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf2, buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf0, reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), buf1 class TransformerNew(nn.Module): def __init__(self, in_channels, out_channels): super(TransformerNew, self).__init__() self.T_sigma = nn.Linear(in_channels, out_channels) self.T_gamma = nn.Linear(in_channels, out_channels) def forward(self, input_0, input_1): primals_1 = self.T_sigma.weight primals_2 = self.T_sigma.bias primals_4 = self.T_gamma.weight primals_5 = self.T_gamma.bias primals_3 = input_0 primals_6 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0], output[1]
JunLi-Galios/PGGAN
Transformer
false
13,911
[ "Apache-2.0" ]
58
b8bd3dc44c71a985315fb82070e911378cf210db
https://github.com/JunLi-Galios/PGGAN/tree/b8bd3dc44c71a985315fb82070e911378cf210db
ReLUHyperSolver
import torch import torch.nn as nn class ReLUHyperSolver(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = nn.ReLU() self.a2 = nn.ReLU() def forward(self, x): x = self.a1(self.fc1(x)) x = self.a2(self.fc2(x)) x = self.fc3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_dim': 4, 'out_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._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 % 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) 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, (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, (4, 32), (32, 1)) assert_size_stride(primals_7, (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 buf6 = 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, buf6, 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 buf5 = 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, buf5, 2048, 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, 32), (32, 1), 0), reinterpret_tensor(primals_6, (32, 4), (1, 32), 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, 32), (32, 1), 0), reinterpret_tensor( buf3, (64, 32), (32, 1), 0), primals_6, buf5, primals_4, buf6 class ReLUHyperSolverNew(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = nn.ReLU() self.a2 = nn.ReLU() def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_6 = self.fc3.weight primals_7 = self.fc3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
Juju-botu/diffeqml-research
ReLUHyperSolver
false
13,912
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
DilatedModel
import torch from torch import nn import torch.nn.functional as F class DilatedModel(nn.Module): def __init__(self, k=16): super(DilatedModel, self).__init__() self.conv1 = nn.Conv2d(1, k, 3, stride=1, dilation=1, padding=1) self.conv2 = nn.Conv2d(k, k, 3, stride=1, dilation=1, padding=1) self.conv3 = nn.Conv2d(k, k, 3, stride=1, dilation=2, padding=2) self.conv4 = nn.Conv2d(k, k, 3, stride=1, dilation=4, padding=4) self.conv5 = nn.Conv2d(k, k, 3, stride=1, dilation=8, padding=8) self.conv6 = nn.Conv2d(k, k, 3, stride=1, dilation=16, padding=16) self.conv7 = nn.Conv2d(k, k, 3, stride=1, dilation=1, padding=1) self.conv8 = nn.Conv2d(k, 1, 1, stride=1, dilation=1, padding=0) def forward(self, x): h = x h = F.relu(self.conv1(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv2(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv3(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv3(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv4(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv5(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv6(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv7(h)) assert h.shape[2:] == x.shape[2:] h = F.relu(self.conv8(h)) assert h.shape == x.shape return h def get_inputs(): return [torch.rand([4, 1, 64, 64])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @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_convolution_relu_threshold_backward_1(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) 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.full([1], 0, tl.int32) tmp5 = triton_helpers.maximum(tmp4, tmp3) tmp6 = 0.0 tmp7 = tmp5 <= tmp6 tl.store(in_out_ptr0 + x0, tmp5, None) tl.store(out_ptr0 + x0, tmp7, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17) = args args.clear() assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1)) assert_size_stride(primals_2, (16, 1, 3, 3), (9, 9, 3, 1)) assert_size_stride(primals_3, (16,), (1,)) assert_size_stride(primals_4, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_5, (16,), (1,)) assert_size_stride(primals_6, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_7, (16,), (1,)) assert_size_stride(primals_8, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_9, (16,), (1,)) assert_size_stride(primals_10, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_11, (16,), (1,)) assert_size_stride(primals_12, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_13, (16,), (1,)) assert_size_stride(primals_14, (16, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_15, (16,), (1,)) assert_size_stride(primals_16, (1, 16, 1, 1), (16, 1, 1, 1)) assert_size_stride(primals_17, (1,), (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, 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_3, 262144, XBLOCK=1024, 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, 64, 64), (65536, 4096, 64, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_0[grid(262144)](buf3, primals_5, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(2, 2), dilation=(2, 2), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_0[grid(262144)](buf5, primals_7, 262144, XBLOCK=1024, num_warps=4, num_stages=1) buf6 = extern_kernels.convolution(buf5, primals_6, stride=(1, 1), padding=(2, 2), dilation=(2, 2), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf7 = buf6 del buf6 triton_poi_fused_convolution_relu_0[grid(262144)](buf7, primals_7, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1), padding=(4, 4), dilation=(4, 4), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf9 = buf8 del buf8 triton_poi_fused_convolution_relu_0[grid(262144)](buf9, primals_9, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 buf10 = extern_kernels.convolution(buf9, primals_10, stride=(1, 1), padding=(8, 8), dilation=(8, 8), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_0[grid(262144)](buf11, primals_11, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_11 buf12 = extern_kernels.convolution(buf11, primals_12, stride=(1, 1), padding=(16, 16), dilation=(16, 16), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf13 = buf12 del buf12 triton_poi_fused_convolution_relu_0[grid(262144)](buf13, primals_13, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_13 buf14 = extern_kernels.convolution(buf13, primals_14, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf14, (4, 16, 64, 64), (65536, 4096, 64, 1)) buf15 = buf14 del buf14 triton_poi_fused_convolution_relu_0[grid(262144)](buf15, primals_15, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_15 buf16 = extern_kernels.convolution(buf15, primals_16, stride=(1, 1), padding=(0, 0), 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 buf18 = empty_strided_cuda((4, 1, 64, 64), (4096, 4096, 64, 1), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_1[grid(16384)]( buf17, primals_17, buf18, 16384, XBLOCK=128, num_warps=4, num_stages=1) del primals_17 return (buf17, primals_1, primals_2, primals_4, primals_6, primals_8, primals_10, primals_12, primals_14, primals_16, buf1, buf3, buf5, buf7, buf9, buf11, buf13, buf15, buf18) class DilatedModelNew(nn.Module): def __init__(self, k=16): super(DilatedModelNew, self).__init__() self.conv1 = nn.Conv2d(1, k, 3, stride=1, dilation=1, padding=1) self.conv2 = nn.Conv2d(k, k, 3, stride=1, dilation=1, padding=1) self.conv3 = nn.Conv2d(k, k, 3, stride=1, dilation=2, padding=2) self.conv4 = nn.Conv2d(k, k, 3, stride=1, dilation=4, padding=4) self.conv5 = nn.Conv2d(k, k, 3, stride=1, dilation=8, padding=8) self.conv6 = nn.Conv2d(k, k, 3, stride=1, dilation=16, padding=16) self.conv7 = nn.Conv2d(k, k, 3, stride=1, dilation=1, padding=1) self.conv8 = nn.Conv2d(k, 1, 1, stride=1, dilation=1, padding=0) 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.conv4.weight primals_9 = self.conv4.bias primals_10 = self.conv5.weight primals_11 = self.conv5.bias primals_12 = self.conv6.weight primals_13 = self.conv6.bias primals_14 = self.conv7.weight primals_15 = self.conv7.bias primals_16 = self.conv8.weight primals_17 = self.conv8.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17]) return output[0]
JulianYu123456/icnn
DilatedModel
false
13,913
[ "Apache-2.0" ]
258
0aaf4b5cd13d71d98b0d05f367e1f71657ea6eb8
https://github.com/JulianYu123456/icnn/tree/0aaf4b5cd13d71d98b0d05f367e1f71657ea6eb8
PolicyNetwork
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal class PolicyNetwork(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, action_range= 1.0, init_w=0.003, log_std_min=-20, log_std_max=2): super(PolicyNetwork, self).__init__() self.log_std_min = log_std_min self.log_std_max = log_std_max self.linear1 = nn.Linear(num_inputs, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear3 = nn.Linear(hidden_size, hidden_size) self.linear4 = nn.Linear(hidden_size, hidden_size) self.mean_linear = nn.Linear(hidden_size, num_actions) self.mean_linear.weight.data.uniform_(-init_w, init_w) self.mean_linear.bias.data.uniform_(-init_w, init_w) self.log_std_linear = nn.Linear(hidden_size, num_actions) self.log_std_linear.weight.data.uniform_(-init_w, init_w) self.log_std_linear.bias.data.uniform_(-init_w, init_w) self.action_range = action_range self.num_actions = num_actions def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) x = F.relu(self.linear3(x)) x = F.relu(self.linear4(x)) mean = F.tanh(self.mean_linear(x)) log_std = self.log_std_linear(x) log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max) return mean, log_std def evaluate(self, state, deterministic, eval_noise_scale, epsilon=1e-06): """ generate action with state as input wrt the policy network, for calculating gradients """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(0, 1) z = normal.sample() action_0 = torch.tanh(mean + std * z) action = (self.action_range * mean if deterministic else self. action_range * action_0) log_prob = Normal(mean, std).log_prob(mean + std * z) - torch.log( 1.0 - action_0.pow(2) + epsilon) - np.log(self.action_range) log_prob = log_prob.sum(dim=1, keepdim=True) """ add noise """ eval_noise_clip = 2 * eval_noise_scale noise = normal.sample(action.shape) * eval_noise_scale noise = torch.clamp(noise, -eval_noise_clip, eval_noise_clip) action = action + noise return action, log_prob, z, mean, log_std def get_action(self, state, deterministic, explore_noise_scale): """ generate action for interaction with env """ state = torch.FloatTensor(state).unsqueeze(0) mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(0, 1) z = normal.sample() action = mean.detach().cpu().numpy()[0 ] if deterministic else torch.tanh(mean + std * z).detach().cpu( ).numpy()[0] """ add noise """ noise = normal.sample(action.shape) * explore_noise_scale action = self.action_range * action + noise.numpy() return action def sample_action(self): a = torch.FloatTensor(self.num_actions).uniform_(-1, 1) return self.action_range * a.numpy() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_inputs': 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 libdevice import numpy as np import torch.nn as nn from torch.distributions import Normal assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 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_tanh_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 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) @triton.jit def triton_poi_fused_clamp_ge_le_logical_and_2(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 = -20.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 2.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp2 >= tmp3 tmp8 = tmp2 <= tmp5 tmp9 = tmp7 & tmp8 tl.store(out_ptr0 + x2, tmp6, xmask) tl.store(out_ptr1 + x2, tmp9, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 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, (4, 4), (4, 1)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4, 4), (4, 1)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((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 buf16 = 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, buf16, 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 buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3, primals_5, buf15, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf5, primals_7, buf14, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (64, 4), (4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf6) buf7 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf6 buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf7, primals_9, buf13, 256, 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, 4), (4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf8) buf9 = reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf8 triton_poi_fused_tanh_1[grid(256)](buf9, primals_11, 256, XBLOCK= 256, num_warps=4, num_stages=1) del primals_11 buf10 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf7, (64, 4), (4, 1), 0), reinterpret_tensor(primals_12, (4, 4), (1, 4), 0), out=buf10) buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_clamp_ge_le_logical_and_2[grid(256)](buf10, primals_13, buf11, buf12, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf10 del primals_13 return (buf9, buf11, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor( buf3, (64, 4), (4, 1), 0), reinterpret_tensor(buf5, (64, 4), (4, 1), 0), reinterpret_tensor(buf7, (64, 4), (4, 1), 0), buf9, buf12, primals_12, primals_10, buf13, primals_8, buf14, primals_6, buf15, primals_4, buf16) class PolicyNetworkNew(nn.Module): def __init__(self, num_inputs, num_actions, hidden_size, action_range= 1.0, init_w=0.003, log_std_min=-20, log_std_max=2): super(PolicyNetworkNew, self).__init__() self.log_std_min = log_std_min self.log_std_max = log_std_max self.linear1 = nn.Linear(num_inputs, hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.linear3 = nn.Linear(hidden_size, hidden_size) self.linear4 = nn.Linear(hidden_size, hidden_size) self.mean_linear = nn.Linear(hidden_size, num_actions) self.mean_linear.weight.data.uniform_(-init_w, init_w) self.mean_linear.bias.data.uniform_(-init_w, init_w) self.log_std_linear = nn.Linear(hidden_size, num_actions) self.log_std_linear.weight.data.uniform_(-init_w, init_w) self.log_std_linear.bias.data.uniform_(-init_w, init_w) self.action_range = action_range self.num_actions = num_actions def evaluate(self, state, deterministic, eval_noise_scale, epsilon=1e-06): """ generate action with state as input wrt the policy network, for calculating gradients """ mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(0, 1) z = normal.sample() action_0 = torch.tanh(mean + std * z) action = (self.action_range * mean if deterministic else self. action_range * action_0) log_prob = Normal(mean, std).log_prob(mean + std * z) - torch.log( 1.0 - action_0.pow(2) + epsilon) - np.log(self.action_range) log_prob = log_prob.sum(dim=1, keepdim=True) """ add noise """ eval_noise_clip = 2 * eval_noise_scale noise = normal.sample(action.shape) * eval_noise_scale noise = torch.clamp(noise, -eval_noise_clip, eval_noise_clip) action = action + noise return action, log_prob, z, mean, log_std def get_action(self, state, deterministic, explore_noise_scale): """ generate action for interaction with env """ state = torch.FloatTensor(state).unsqueeze(0) mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(0, 1) z = normal.sample() action = mean.detach().cpu().numpy()[0 ] if deterministic else torch.tanh(mean + std * z).detach().cpu( ).numpy()[0] """ add noise """ noise = normal.sample(action.shape) * explore_noise_scale action = self.action_range * action + noise.numpy() return action def sample_action(self): a = torch.FloatTensor(self.num_actions).uniform_(-1, 1) return self.action_range * a.numpy() def forward(self, input_0): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_4 = self.linear2.weight primals_5 = self.linear2.bias primals_6 = self.linear3.weight primals_7 = self.linear3.bias primals_8 = self.linear4.weight primals_9 = self.linear4.bias primals_10 = self.mean_linear.weight primals_11 = self.mean_linear.bias primals_12 = self.log_std_linear.weight primals_13 = self.log_std_linear.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13]) return output[0], output[1]
JieRen98/Popular-RL-Algorithms
PolicyNetwork
false
13,914
[ "Apache-2.0" ]
273
7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
https://github.com/JieRen98/Popular-RL-Algorithms/tree/7f2bb74a51cf9cbde92a6ccfa42e97dc129dd145
DiscShiftLoss
import torch import torch.nn as nn class DiscShiftLoss(nn.Module): """Disc shift loss. Args: loss_weight (float, optional): Loss weight. Defaults to 1.0. """ def __init__(self, loss_weight=0.1): super().__init__() self.loss_weight = loss_weight def forward(self, x): """Forward function. Args: x (Tensor): Tensor with shape (n, c, h, w) Returns: Tensor: Loss. """ loss = torch.mean(x ** 2) return loss * self.loss_weight def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_mean_mul_pow_0(in_out_ptr0, in_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [RBLOCK]) tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0)) tmp5 = 256.0 tmp6 = tmp4 / tmp5 tmp7 = 0.1 tmp8 = tmp6 * tmp7 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp8, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_mean_mul_pow_0[grid(1)](buf1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf1, class DiscShiftLossNew(nn.Module): """Disc shift loss. Args: loss_weight (float, optional): Loss weight. Defaults to 1.0. """ def __init__(self, loss_weight=0.1): super().__init__() self.loss_weight = loss_weight def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Juggernaut93/mmediting
DiscShiftLoss
false
13,915
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
EqualLinearActModule
import torch import torch.nn as nn from copy import deepcopy from functools import partial from torch.nn.init import _calculate_correct_fan def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul) return module class EqualizedLR: """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. """ def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0 ): self.name = name self.mode = mode self.gain = gain self.lr_mul = lr_mul def compute_weight(self, module): """Compute weight with equalized learning rate. Args: module (nn.Module): A module that is wrapped with equalized lr. Returns: torch.Tensor: Updated weight. """ weight = getattr(module, self.name + '_orig') if weight.ndim == 5: fan = _calculate_correct_fan(weight[0], self.mode) else: assert weight.ndim <= 4 fan = _calculate_correct_fan(weight, self.mode) weight = weight * torch.tensor(self.gain, device=weight.device ) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device) ) * self.lr_mul return weight def __call__(self, module, inputs): """Standard interface for forward pre hooks.""" setattr(module, self.name, self.compute_weight(module)) @staticmethod def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Apply function. This function is to register an equalized learning rate hook in an ``nn.Module``. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ for _, hook in module._forward_pre_hooks.items(): if isinstance(hook, EqualizedLR): raise RuntimeError( f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.' ) fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul) weight = module._parameters[name] delattr(module, name) module.register_parameter(name + '_orig', weight) setattr(module, name, weight.data) module.register_forward_pre_hook(fn) return fn class EqualizedLRLinearModule(nn.Linear): """Equalized LR LinearModule. In this module, we adopt equalized lr in ``nn.Linear``. The equalized learning rate is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation Note that, the initialization of ``self.weight`` will be overwritten as :math:`\\mathcal{N}(0, 1)`. Args: equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``. If ``None``, equalized learning rate is ignored. Defaults to dict(mode='fan_in'). """ def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs): super(EqualizedLRLinearModule, self).__init__(*args, **kwargs) self.with_equlized_lr = equalized_lr_cfg is not None if self.with_equlized_lr: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if self.with_equlized_lr: equalized_lr(self, **equalized_lr_cfg) self._init_linear_weights() def _init_linear_weights(self): """Initialize linear weights as described in PGGAN.""" nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul) if self.bias is not None: nn.init.constant_(self.bias, 0.0) class EqualLinearActModule(nn.Module): """Equalized LR Linear Module with Activation Layer. Args: nn ([type]): [description] """ def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0), bias=True, bias_init=0.0, act_cfg=None, **kwargs): super(EqualLinearActModule, self).__init__() self.with_activation = act_cfg is not None self.linear = EqualizedLRLinearModule(*args, bias=False, equalized_lr_cfg=equalized_lr_cfg, **kwargs) if equalized_lr_cfg is not None: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if bias: self.bias = nn.Parameter(torch.zeros(self.linear.out_features). fill_(bias_init)) else: self.bias = None if self.with_activation: act_cfg = deepcopy(act_cfg) if act_cfg['type'] == 'fused_bias': self.act_type = act_cfg.pop('type') assert self.bias is not None self.activate = partial(fused_bias_leakyrelu, **act_cfg) else: self.act_type = 'normal' self.activate = build_activation_layer(act_cfg) else: self.act_type = None def forward(self, x): if x.ndim >= 3: x = x.reshape(x.size(0), -1) x = self.linear(x) if self.with_activation and self.act_type == 'fused_bias': x = self.activate(x, self.bias * self.lr_mul) elif self.bias is not None and self.with_activation: x = self.activate(x + self.bias * self.lr_mul) elif self.bias is not None: x = x + self.bias * self.lr_mul elif self.with_activation: x = self.activate(x) return x def get_inputs(): return [torch.rand([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 import torch.nn as nn from copy import deepcopy from functools import partial from torch.nn.init import _calculate_correct_fan assert_size_stride = torch._C._dynamo.guards.assert_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_sqrt_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.5 tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sqrt_0[grid(16)](primals_2, buf0, 16, XBLOCK= 16, num_warps=1, num_stages=1) del primals_2 buf1 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_3 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(buf1, primals_1, reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del buf1 return buf2, buf0, primals_1 def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul) return module class EqualizedLR: """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. """ def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0 ): self.name = name self.mode = mode self.gain = gain self.lr_mul = lr_mul def compute_weight(self, module): """Compute weight with equalized learning rate. Args: module (nn.Module): A module that is wrapped with equalized lr. Returns: torch.Tensor: Updated weight. """ weight = getattr(module, self.name + '_orig') if weight.ndim == 5: fan = _calculate_correct_fan(weight[0], self.mode) else: assert weight.ndim <= 4 fan = _calculate_correct_fan(weight, self.mode) weight = weight * torch.tensor(self.gain, device=weight.device ) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device) ) * self.lr_mul return weight def __call__(self, module, inputs): """Standard interface for forward pre hooks.""" setattr(module, self.name, self.compute_weight(module)) @staticmethod def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Apply function. This function is to register an equalized learning rate hook in an ``nn.Module``. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ for _, hook in module._forward_pre_hooks.items(): if isinstance(hook, EqualizedLR): raise RuntimeError( f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.' ) fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul) weight = module._parameters[name] delattr(module, name) module.register_parameter(name + '_orig', weight) setattr(module, name, weight.data) module.register_forward_pre_hook(fn) return fn class EqualizedLRLinearModule(nn.Linear): """Equalized LR LinearModule. In this module, we adopt equalized lr in ``nn.Linear``. The equalized learning rate is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation Note that, the initialization of ``self.weight`` will be overwritten as :math:`\\mathcal{N}(0, 1)`. Args: equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``. If ``None``, equalized learning rate is ignored. Defaults to dict(mode='fan_in'). """ def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs): super(EqualizedLRLinearModule, self).__init__(*args, **kwargs) self.with_equlized_lr = equalized_lr_cfg is not None if self.with_equlized_lr: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if self.with_equlized_lr: equalized_lr(self, **equalized_lr_cfg) self._init_linear_weights() def _init_linear_weights(self): """Initialize linear weights as described in PGGAN.""" nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul) if self.bias is not None: nn.init.constant_(self.bias, 0.0) class EqualLinearActModuleNew(nn.Module): """Equalized LR Linear Module with Activation Layer. Args: nn ([type]): [description] """ def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0), bias=True, bias_init=0.0, act_cfg=None, **kwargs): super(EqualLinearActModuleNew, self).__init__() self.with_activation = act_cfg is not None self.linear = EqualizedLRLinearModule(*args, bias=False, equalized_lr_cfg=equalized_lr_cfg, **kwargs) if equalized_lr_cfg is not None: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if bias: self.bias = nn.Parameter(torch.zeros(self.linear.out_features). fill_(bias_init)) else: self.bias = None if self.with_activation: act_cfg = deepcopy(act_cfg) if act_cfg['type'] == 'fused_bias': self.act_type = act_cfg.pop('type') assert self.bias is not None self.activate = partial(fused_bias_leakyrelu, **act_cfg) else: self.act_type = 'normal' self.activate = build_activation_layer(act_cfg) else: self.act_type = None def forward(self, input_0): primals_3 = self.bias primals_1 = self.linear.weight_orig primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Juggernaut93/mmediting
EqualLinearActModule
false
13,916
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
AvgPoolHead
import torch import torch.nn as nn import torch.optim class AvgPoolHead(nn.Module): def __init__(self, in_channels, out_channels, fea_map_size): super(AvgPoolHead, self).__init__() self.avgpool = nn.AvgPool2d(fea_map_size, stride=1) self.fc = nn.Linear(in_channels, out_channels) def forward(self, x): x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'fea_map_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn import torch.optim assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp9 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp13 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp17 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp21 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp25 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp27 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp29 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp18 = tmp17 + tmp16 tmp20 = tmp19 + tmp18 tmp22 = tmp21 + tmp20 tmp24 = tmp23 + tmp22 tmp26 = tmp25 + tmp24 tmp28 = tmp27 + tmp26 tmp30 = tmp29 + tmp28 tmp31 = 0.0625 tmp32 = tmp30 * tmp31 tl.store(out_ptr0 + x0, tmp32, xmask) def call(args): 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, 1, 1), (4, 1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(16)](primals_1, buf0, 16, XBLOCK =16, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (4, 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 buf1, reinterpret_tensor(buf0, (4, 4), (4, 1), 0) class AvgPoolHeadNew(nn.Module): def __init__(self, in_channels, out_channels, fea_map_size): super(AvgPoolHeadNew, self).__init__() self.avgpool = nn.AvgPool2d(fea_map_size, stride=1) self.fc = nn.Linear(in_channels, out_channels) def forward(self, input_0): primals_2 = self.fc.weight primals_3 = self.fc.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
KGMSFT/integral-human-pose
AvgPoolHead
false
13,917
[ "MIT" ]
472
d3ad4117ed71c580d2ab17987e15f9b2c3318a3b
https://github.com/KGMSFT/integral-human-pose/tree/d3ad4117ed71c580d2ab17987e15f9b2c3318a3b
PositioningCost
import torch import torch.nn as nn class PositioningCost(nn.Module): def __init__(self, target, Q=1, R=0, P=0): super().__init__() self.target = target self.Q, self.R, self.P = Q, R, P def forward(self, traj, u=None, mesh_p=None): cost = 0.1 * torch.norm(traj[..., -1, :3] - self.target ) + 1 * torch.norm(traj[..., :3] - self.target ) + 0.01 * torch.norm(traj[..., 3:6]) + 0.01 * torch.norm(traj[ ..., 6:9]) + 0.01 * torch.norm(traj[..., 9:12]) return cost def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'target': 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_per_fused_linalg_vector_norm_sub_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): rnumel = 48 RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel r0 = rindex % 3 r1 = rindex // 3 tmp0 = tl.load(in_ptr0 + (12 + r0 + 16 * r1), rmask, other=0.0) tmp1 = 4.0 tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp6 = tl.where(rmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None) @triton.jit def triton_per_fused_linalg_vector_norm_sub_1(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): rnumel = 192 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel r0 = rindex % 3 r1 = rindex // 3 tmp0 = tl.load(in_ptr0 + (r0 + 4 * r1), rmask, other=0.0) tmp1 = 4.0 tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp6 = tl.where(rmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None) @triton.jit def triton_per_fused_add_linalg_vector_norm_mul_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last') tmp5 = tl.load(in_out_ptr0 + 0) tmp6 = tl.broadcast_to(tmp5, [XBLOCK, 1]) tmp10 = tl.load(in_ptr1 + 0) tmp11 = tl.broadcast_to(tmp10, [XBLOCK, 1]) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp7 = libdevice.sqrt(tmp6) tmp8 = 0.1 tmp9 = tmp7 * tmp8 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1.0 tmp14 = tmp12 * tmp13 tmp15 = tmp9 + tmp14 tmp16 = libdevice.sqrt(tmp4) tmp17 = 0.01 tmp18 = tmp16 * tmp17 tmp19 = tmp15 + tmp18 tmp20 = 0.0 tmp21 = libdevice.sqrt(tmp20) tmp22 = tmp21 * tmp17 tmp23 = tmp19 + tmp22 tmp24 = tmp23 + tmp22 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp24, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused_linalg_vector_norm_sub_0[grid(1)](arg0_1, buf0, 1, 48, XBLOCK=1, num_warps=2, num_stages=1) buf1 = empty_strided_cuda((), (), torch.float32) triton_per_fused_linalg_vector_norm_sub_1[grid(1)](arg0_1, buf1, 1, 192, XBLOCK=1, num_warps=2, num_stages=1) buf3 = buf0 del buf0 triton_per_fused_add_linalg_vector_norm_mul_2[grid(1)](buf3, arg0_1, buf1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf1 return buf3, class PositioningCostNew(nn.Module): def __init__(self, target, Q=1, R=0, P=0): super().__init__() self.target = target self.Q, self.R, self.P = Q, R, P def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Juju-botu/diffeqml-research
PositioningCost
false
13,918
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
TanhHyperSolver
import torch import torch.nn as nn class TanhHyperSolver(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = nn.Tanh() self.a2 = nn.Tanh() def forward(self, x): x = self.a1(self.fc1(x)) x = self.a2(self.fc2(x)) x = self.fc3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_dim': 4, 'out_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._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 ): 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 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, 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, (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, (4, 32), (32, 1)) assert_size_stride(primals_7, (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 get_raw_stream(0) triton_poi_fused_tanh_0[grid(2048)](buf1, primals_2, 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 triton_poi_fused_tanh_0[grid(2048)](buf3, primals_5, 2048, 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, 32), (32, 1), 0), reinterpret_tensor(primals_6, (32, 4), (1, 32), 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 ), buf1, buf3, primals_6, primals_4 class TanhHyperSolverNew(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = nn.Tanh() self.a2 = nn.Tanh() 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]
Juju-botu/diffeqml-research
TanhHyperSolver
false
13,919
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
NeuralArray
import torch import torch.utils.data import torch import torch.nn as nn class NeuralArray(nn.Module): def __init__(self, dim, random_init=False): super(NeuralArray, self).__init__() self.dim = dim if random_init: self.register_parameter('data', torch.nn.Parameter(torch.randn( self.dim, requires_grad=True))) else: self.register_parameter('data', torch.nn.Parameter(torch.zeros( self.dim, requires_grad=True))) def forward(self, id): return self.data[id] def regularizer_zero(self): return torch.mean(torch.pow(self.data, 2.0)) def get_inputs(): return [torch.ones([4], dtype=torch.int64)] def get_init_inputs(): return [[], {'dim': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.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 @triton.jit def triton_poi_fused_index_0(in_ptr0, in_ptr1, 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.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 + tmp4, xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4,), (1,)) assert_size_stride(primals_2, (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_index_0[grid(4)](primals_2, primals_1, buf0, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_1 return buf0, primals_2 class NeuralArrayNew(nn.Module): def __init__(self, dim, random_init=False): super(NeuralArrayNew, self).__init__() self.dim = dim if random_init: self.register_parameter('data', torch.nn.Parameter(torch.randn( self.dim, requires_grad=True))) else: self.register_parameter('data', torch.nn.Parameter(torch.zeros( self.dim, requires_grad=True))) def regularizer_zero(self): return torch.mean(torch.pow(self.data, 2.0)) def forward(self, input_0): primals_1 = self.data primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
JustusThies/NeuralTexGen
NeuralArray
false
13,920
[ "BSD-3-Clause" ]
49
008a6596cf54db3dab2d73f6248e243ca9a46e32
https://github.com/JustusThies/NeuralTexGen/tree/008a6596cf54db3dab2d73f6248e243ca9a46e32
Downsample
import torch import torchvision.transforms.functional as F import torch.nn as nn import torch.nn.functional as F class Downsample(nn.Module): def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False, fir_kernel=(1, 3, 3, 1)): super().__init__() out_ch = out_ch if out_ch else in_ch if not fir: if with_conv: self.Conv_0 = conv3x3(in_ch, out_ch, stride=2, padding=0) elif with_conv: self.Conv2d_0 = up_or_down_sampling.Conv2d(in_ch, out_ch, kernel=3, down=True, resample_kernel=fir_kernel, use_bias= True, kernel_init=default_init()) self.fir = fir self.fir_kernel = fir_kernel self.with_conv = with_conv self.out_ch = out_ch def forward(self, x): _B, _C, _H, _W = x.shape if not self.fir: if self.with_conv: x = F.pad(x, (0, 1, 0, 1)) x = self.Conv_0(x) else: x = F.avg_pool2d(x, 2, stride=2) elif not self.with_conv: x = up_or_down_sampling.downsample_2d(x, self.fir_kernel, factor=2) else: x = self.Conv2d_0(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_avg_pool2d_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 % 2 x1 = xindex // 2 x2 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp7 = 0.25 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): 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, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 return buf0, class DownsampleNew(nn.Module): def __init__(self, in_ch=None, out_ch=None, with_conv=False, fir=False, fir_kernel=(1, 3, 3, 1)): super().__init__() out_ch = out_ch if out_ch else in_ch if not fir: if with_conv: self.Conv_0 = conv3x3(in_ch, out_ch, stride=2, padding=0) elif with_conv: self.Conv2d_0 = up_or_down_sampling.Conv2d(in_ch, out_ch, kernel=3, down=True, resample_kernel=fir_kernel, use_bias= True, kernel_init=default_init()) self.fir = fir self.fir_kernel = fir_kernel self.with_conv = with_conv self.out_ch = out_ch def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
DeepTitan/PNDM
Downsample
false
13,921
[ "Apache-2.0" ]
61
4037a4f40011c9a0d47b92303e64d47fcc7ed56a
https://github.com/DeepTitan/PNDM/tree/4037a4f40011c9a0d47b92303e64d47fcc7ed56a
WeightShareConv1d
import torch import torch.nn as nn import torch.nn import torch.nn.functional import torch.jit import torch.nn.functional as F import torch.utils.data import torch.nn.utils class VariationalHidDropout(nn.Module): def __init__(self, dropout=0.0): """ Hidden-to-hidden (VD-based) dropout that applies the same mask at every time step and every layer of TrellisNet :param dropout: The dropout rate (0 means no dropout is applied) :param temporal: Whether the dropout mask is the same across the temporal dimension (or only the depth dimension) """ super(VariationalHidDropout, self).__init__() self.dropout = dropout self.mask = None def reset_mask(self, x): dropout = self.dropout m = torch.zeros_like(x[:, :, :1]).bernoulli_(1 - dropout) mask = m.requires_grad_(False) / (1 - dropout) self.mask = mask return mask def forward(self, x): if not self.training or self.dropout == 0: return x assert self.mask is not None, 'You need to reset mask before using VariationalHidDropout' mask = self.mask.expand_as(x) return mask * x class WeightShareConv1d(nn.Module): def __init__(self, n_hid, n_out, kernel_size, dropouth=0.0): """ The weight-tied 1D convolution used in TrellisNet. :param n_hid: The dim of hidden input :param n_out: The dim of the pre-activation (i.e. convolutional) output :param kernel_size: The size of the convolutional kernel :param dropouth: Hidden-to-hidden dropout """ super(WeightShareConv1d, self).__init__() self.kernel_size = kernel_size conv = nn.Conv1d(n_hid, n_out, kernel_size) self.weight = conv.weight self.bias = conv.bias self.init_weights() self.dict = dict() self.drop = VariationalHidDropout(dropout=dropouth) def init_weights(self): bound = 0.01 self.weight.data.normal_(0, bound) self.bias.data.normal_(0, bound) def copy(self, func): self.weight.data = func.weight.data.clone().detach() self.bias.data = func.bias.data.clone().detach() self.drop.mask = func.drop.mask.clone().detach() def forward(self, x, dilation=1, hid=None): k = self.kernel_size padding = (k - 1) * dilation x = F.pad(x, (padding, 0)) if hid is not None: x[:, :, :padding] = hid.repeat(1, 1, padding) res = F.conv1d(self.drop(x), self.weight, self.bias, dilation=dilation) return res def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'n_hid': 4, 'n_out': 4, 'kernel_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn import torch.nn import torch.nn.functional import torch.jit import torch.utils.data import torch.nn.utils assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 28 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 7 x1 = xindex // 7 x2 = xindex tmp0 = -3 + x0 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.load(in_ptr0 + (-3 + x0 + 4 * x1), tmp2 & xmask, other=0.0) tl.store(out_ptr0 + x2, tmp3, xmask) @triton.jit def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 7), (7, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(28)](primals_1, buf0, 28, XBLOCK=32, num_warps=1, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (1, 4, 7 ), (0, 7, 1), 0), primals_2, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=(0,), groups=1, bias=None) assert_size_stride(buf1, (1, 4, 4), (16, 4, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(16)](buf2, primals_3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 return reinterpret_tensor(buf2, (4, 4), (4, 1), 0 ), primals_2, reinterpret_tensor(buf0, (1, 4, 7), (28, 7, 1), 0) class VariationalHidDropout(nn.Module): def __init__(self, dropout=0.0): """ Hidden-to-hidden (VD-based) dropout that applies the same mask at every time step and every layer of TrellisNet :param dropout: The dropout rate (0 means no dropout is applied) :param temporal: Whether the dropout mask is the same across the temporal dimension (or only the depth dimension) """ super(VariationalHidDropout, self).__init__() self.dropout = dropout self.mask = None def reset_mask(self, x): dropout = self.dropout m = torch.zeros_like(x[:, :, :1]).bernoulli_(1 - dropout) mask = m.requires_grad_(False) / (1 - dropout) self.mask = mask return mask def forward(self, x): if not self.training or self.dropout == 0: return x assert self.mask is not None, 'You need to reset mask before using VariationalHidDropout' mask = self.mask.expand_as(x) return mask * x class WeightShareConv1dNew(nn.Module): def __init__(self, n_hid, n_out, kernel_size, dropouth=0.0): """ The weight-tied 1D convolution used in TrellisNet. :param n_hid: The dim of hidden input :param n_out: The dim of the pre-activation (i.e. convolutional) output :param kernel_size: The size of the convolutional kernel :param dropouth: Hidden-to-hidden dropout """ super(WeightShareConv1dNew, self).__init__() self.kernel_size = kernel_size conv = nn.Conv1d(n_hid, n_out, kernel_size) self.weight = conv.weight self.bias = conv.bias self.init_weights() self.dict = dict() self.drop = VariationalHidDropout(dropout=dropouth) def init_weights(self): bound = 0.01 self.weight.data.normal_(0, bound) self.bias.data.normal_(0, bound) def copy(self, func): self.weight.data = func.weight.data.clone().detach() self.bias.data = func.bias.data.clone().detach() self.drop.mask = func.drop.mask.clone().detach() 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]
JunLi-Galios/deq
WeightShareConv1d
false
13,922
[ "MIT" ]
548
80eb6b598357e8e01ad419126465fa3ed53b12c7
https://github.com/JunLi-Galios/deq/tree/80eb6b598357e8e01ad419126465fa3ed53b12c7
DropConnect
import torch class DropConnect(torch.nn.Module): def __init__(self, p): super(DropConnect, self).__init__() self.p = p def forward(self, inputs): batch_size = inputs.shape[0] inputs.shape[2] inputs.shape[3] channel_size = inputs.shape[1] keep_prob = 1 - self.p random_tensor = keep_prob random_tensor += torch.rand([batch_size, channel_size, 1, 1], dtype =inputs.dtype, device=inputs.device) binary_tensor = torch.floor(random_tensor) output = inputs / keep_prob * binary_tensor return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'p': 4}]
import torch from torch import device import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.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_floor_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp1 = -0.3333333333333333 tmp2 = tmp0 * tmp1 tmp4 = -3.0 tmp5 = tmp3 + tmp4 tmp6 = libdevice.floor(tmp5) tmp7 = tmp2 * tmp6 tl.store(out_ptr0 + x2, 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 = torch.ops.aten.rand.default([4, 4, 1, 1], dtype=torch. float32, device=device(type='cuda', index=0), pin_memory=False) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_floor_mul_0[grid(256)](arg0_1, buf1, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del buf1 return buf2, class DropConnectNew(torch.nn.Module): def __init__(self, p): super(DropConnectNew, self).__init__() self.p = p def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KelvinYang0320/nas-without-training
DropConnect
false
13,923
[ "MIT" ]
385
5ed77a06726a73233a5a93b8f70a7172ce570029
https://github.com/KelvinYang0320/nas-without-training/tree/5ed77a06726a73233a5a93b8f70a7172ce570029
AuxiliaryConvolutions
import torch from torch import nn import torch.nn.functional as F class AuxiliaryConvolutions(nn.Module): """ Additional convolutions to produce higher-level feature maps. """ def __init__(self): super(AuxiliaryConvolutions, self).__init__() self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0) self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1) self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0) self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1) self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.init_conv2d() def init_conv2d(self): """ Initialize convolution parameters. """ for c in self.children(): if isinstance(c, nn.Conv2d): nn.init.xavier_uniform_(c.weight) nn.init.constant_(c.bias, 0.0) def forward(self, conv7_feats): """ Forward propagation. :param conv7_feats: lower-level conv7 feature map, a tensor of dimensions (N, 1024, 19, 19) :return: higher-level feature maps conv8_2, conv9_2, conv10_2, and conv11_2 """ out = F.relu(self.conv8_1(conv7_feats)) out = F.relu(self.conv8_2(out)) conv8_2_feats = out out = F.relu(self.conv9_1(out)) out = F.relu(self.conv9_2(out)) conv9_2_feats = out out = F.relu(self.conv10_1(out)) out = F.relu(self.conv10_2(out)) conv10_2_feats = out out = F.relu(self.conv11_1(out)) conv11_2_feats = F.relu(self.conv11_2(out)) return conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats def get_inputs(): return [torch.rand([4, 1024, 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 @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 % 1024 y1 = yindex // 1024 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None) tl.store(out_ptr0 + (y0 + 1024 * x2 + 4194304 * y1), tmp0, None) @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 % 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_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 % 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_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 256 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_4(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 1024 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 512 y1 = yindex // 512 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 512 * x2 + 524288 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 1024 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 512 * x2 + 524288 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 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_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 256 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 65536 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 256 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 65536 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 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_8(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 196 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 50176 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 196 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 50176 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_threshold_backward_10(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 144 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 36864 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(out_ptr0 + (x2 + 144 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 36864 * y1), tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17) = args args.clear() assert_size_stride(primals_1, (256, 1024, 1, 1), (1024, 1, 1, 1)) assert_size_stride(primals_2, (256,), (1,)) assert_size_stride(primals_3, (4, 1024, 64, 64), (4194304, 4096, 64, 1)) assert_size_stride(primals_4, (512, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_5, (512,), (1,)) assert_size_stride(primals_6, (128, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_9, (256,), (1,)) assert_size_stride(primals_10, (128, 256, 1, 1), (256, 1, 1, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_13, (256,), (1,)) assert_size_stride(primals_14, (128, 256, 1, 1), (256, 1, 1, 1)) assert_size_stride(primals_15, (128,), (1,)) assert_size_stride(primals_16, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_17, (256,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1024, 64, 64), (4194304, 1, 65536, 1024), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(4096, 4096)](primals_3, buf0, 4096, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del primals_3 buf1 = empty_strided_cuda((512, 256, 3, 3), (2304, 1, 768, 256), torch.float32) triton_poi_fused_1[grid(131072, 9)](primals_4, buf1, 131072, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_4 buf2 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_8, buf2, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_8 buf3 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_12, buf3, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_12 buf4 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_16, buf4, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_16 buf5 = 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(buf5, (4, 256, 64, 64), (1048576, 1, 16384, 256)) buf6 = buf5 del buf5 triton_poi_fused_convolution_relu_3[grid(4194304)](buf6, primals_2, 4194304, XBLOCK=1024, num_warps=4, num_stages=1) del primals_2 buf7 = extern_kernels.convolution(buf6, buf1, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 512, 32, 32), (524288, 1, 16384, 512)) buf8 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1), torch.float32) buf9 = empty_strided_cuda((4, 512, 32, 32), (524288, 1, 16384, 512), torch.float32) triton_poi_fused_convolution_relu_4[grid(2048, 1024)](buf7, primals_5, buf8, buf9, 2048, 1024, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1) del buf7 del primals_5 buf10 = extern_kernels.convolution(buf9, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 128, 32, 32), (131072, 1, 4096, 128)) del buf9 buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_5[grid(524288)](buf11, primals_7, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf12 = extern_kernels.convolution(buf11, buf2, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 256, 16, 16), (65536, 1, 4096, 256)) buf13 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1), torch.float32) buf14 = empty_strided_cuda((4, 256, 16, 16), (65536, 1, 4096, 256), torch.float32) triton_poi_fused_convolution_relu_6[grid(1024, 256)](buf12, primals_9, buf13, buf14, 1024, 256, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf12 del primals_9 buf15 = extern_kernels.convolution(buf14, 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, 128, 16, 16), (32768, 1, 2048, 128)) del buf14 buf16 = buf15 del buf15 triton_poi_fused_convolution_relu_7[grid(131072)](buf16, primals_11, 131072, XBLOCK=512, num_warps=8, num_stages=1) del primals_11 buf17 = extern_kernels.convolution(buf16, buf3, 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, 14, 14), (50176, 1, 3584, 256)) buf18 = empty_strided_cuda((4, 256, 14, 14), (50176, 196, 14, 1), torch.float32) buf19 = empty_strided_cuda((4, 256, 14, 14), (50176, 1, 3584, 256), torch.float32) triton_poi_fused_convolution_relu_8[grid(1024, 196)](buf17, primals_13, buf18, buf19, 1024, 196, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf17 del primals_13 buf20 = extern_kernels.convolution(buf19, primals_14, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf20, (4, 128, 14, 14), (25088, 1, 1792, 128)) del buf19 buf21 = buf20 del buf20 triton_poi_fused_convolution_relu_9[grid(100352)](buf21, primals_15, 100352, XBLOCK=1024, num_warps=4, num_stages=1) del primals_15 buf22 = extern_kernels.convolution(buf21, buf4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf22, (4, 256, 12, 12), (36864, 1, 3072, 256)) buf23 = empty_strided_cuda((4, 256, 12, 12), (36864, 144, 12, 1), torch.float32) buf24 = empty_strided_cuda((4, 256, 12, 12), (36864, 1, 3072, 256), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_10[grid(1024, 144) ](buf22, primals_17, buf23, buf24, 1024, 144, XBLOCK=64, YBLOCK =64, num_warps=8, num_stages=1) del buf22 del primals_17 return (buf8, buf13, buf18, buf23, primals_1, buf0, buf1, primals_6, buf2, primals_10, buf3, primals_14, buf4, buf6, buf8, buf11, buf13, buf16, buf18, buf21, buf24) class AuxiliaryConvolutionsNew(nn.Module): """ Additional convolutions to produce higher-level feature maps. """ def __init__(self): super(AuxiliaryConvolutionsNew, self).__init__() self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0) self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1) self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0) self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1) self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.init_conv2d() def init_conv2d(self): """ Initialize convolution parameters. """ for c in self.children(): if isinstance(c, nn.Conv2d): nn.init.xavier_uniform_(c.weight) nn.init.constant_(c.bias, 0.0) def forward(self, input_0): primals_1 = self.conv8_1.weight primals_2 = self.conv8_1.bias primals_4 = self.conv8_2.weight primals_5 = self.conv8_2.bias primals_6 = self.conv9_1.weight primals_7 = self.conv9_1.bias primals_8 = self.conv9_2.weight primals_9 = self.conv9_2.bias primals_10 = self.conv10_1.weight primals_11 = self.conv10_1.bias primals_12 = self.conv10_2.weight primals_13 = self.conv10_2.bias primals_14 = self.conv11_1.weight primals_15 = self.conv11_1.bias primals_16 = self.conv11_2.weight primals_17 = self.conv11_2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17]) return output[0], output[1], output[2], output[3]
HFAiLab/ffrecord
AuxiliaryConvolutions
false
13,924
[ "MIT" ]
47
e916dc715ffa38a304a673ade7c5aa1efff5936d
https://github.com/HFAiLab/ffrecord/tree/e916dc715ffa38a304a673ade7c5aa1efff5936d
Linear_Q
from torch.autograd import Function import torch import torch.utils.data.distributed import torch.nn as nn import torch.nn.functional as F import torch.utils.data def quantize(input, nbit): return Quantizer.apply(input, nbit) def dorefa_a(input, nbit_a): return quantize(torch.clamp(0.1 * input, 0, 1), nbit_a) def scale_sign(input): return ScaleSigner.apply(input) def dorefa_w(w, nbit_w): if nbit_w == 1: w = scale_sign(w) else: w = torch.tanh(w) w = w / (2 * torch.max(torch.abs(w))) + 0.5 w = 2 * quantize(w, nbit_w) - 1 return w class Quantizer(Function): @staticmethod def forward(ctx, input, nbit): scale = 2 ** nbit - 1 return torch.round(input * scale) / scale @staticmethod def backward(ctx, grad_output): return grad_output, None class ScaleSigner(Function): """take a real value x, output sign(x)*E(|x|)""" @staticmethod def forward(ctx, input): return torch.sign(input) * torch.mean(torch.abs(input)) @staticmethod def backward(ctx, grad_output): return grad_output class Linear_Q(nn.Linear): def __init__(self, in_features, out_features, bias=True, quan_name_w= 'dorefa', quan_name_a='dorefa', nbit_w=1, nbit_a=1): super(Linear_Q, self).__init__(in_features, out_features, bias) self.nbit_w = nbit_w self.nbit_a = nbit_a name_w_dict = {'dorefa': dorefa_w} name_a_dict = {'dorefa': dorefa_a} self.quan_w = name_w_dict[quan_name_w] self.quan_a = name_a_dict[quan_name_a] def forward(self, input): if self.nbit_w < 32: w = self.quan_w(self.weight, self.nbit_w) else: w = self.weight if self.nbit_a < 32: x = self.quan_a(input, self.nbit_a) else: x = input output = F.linear(x, w, self.bias) return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_features': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math from torch.autograd import Function import torch.utils.data.distributed 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_per_fused_abs_mean_mul_sign_0(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl_math.abs(tmp0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = tl.full([1, 1], 0, tl.int32) tmp6 = tmp5 < tmp0 tmp7 = tmp6.to(tl.int8) tmp8 = tmp0 < tmp5 tmp9 = tmp8.to(tl.int8) tmp10 = tmp7 - tmp9 tmp11 = tmp10.to(tmp0.dtype) tmp12 = 16.0 tmp13 = tmp4 / tmp12 tmp14 = tmp11 * tmp13 tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp14, None) @triton.jit def triton_poi_fused_clamp_div_mul_round_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.1 tmp2 = tmp0 * tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 1.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp6 * tmp5 tmp8 = libdevice.nearbyint(tmp7) tmp9 = tmp8 * tmp5 tl.store(out_ptr0 + x0, tmp9, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_per_fused_abs_mean_mul_sign_0[grid(1)](primals_1, buf2, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_clamp_div_mul_round_1[grid(256)](primals_2, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(buf1, (64, 4), ( 4, 1), 0), reinterpret_tensor(buf2, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del buf2 del primals_3 return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0) def quantize(input, nbit): return Quantizer.apply(input, nbit) def dorefa_a(input, nbit_a): return quantize(torch.clamp(0.1 * input, 0, 1), nbit_a) def scale_sign(input): return ScaleSigner.apply(input) def dorefa_w(w, nbit_w): if nbit_w == 1: w = scale_sign(w) else: w = torch.tanh(w) w = w / (2 * torch.max(torch.abs(w))) + 0.5 w = 2 * quantize(w, nbit_w) - 1 return w class Quantizer(Function): @staticmethod def forward(ctx, input, nbit): scale = 2 ** nbit - 1 return torch.round(input * scale) / scale @staticmethod def backward(ctx, grad_output): return grad_output, None class ScaleSigner(Function): """take a real value x, output sign(x)*E(|x|)""" @staticmethod def forward(ctx, input): return torch.sign(input) * torch.mean(torch.abs(input)) @staticmethod def backward(ctx, grad_output): return grad_output class Linear_QNew(nn.Linear): def __init__(self, in_features, out_features, bias=True, quan_name_w= 'dorefa', quan_name_a='dorefa', nbit_w=1, nbit_a=1): super(Linear_QNew, self).__init__(in_features, out_features, bias) self.nbit_w = nbit_w self.nbit_a = nbit_a name_w_dict = {'dorefa': dorefa_w} name_a_dict = {'dorefa': dorefa_a} self.quan_w = name_w_dict[quan_name_w] self.quan_a = name_a_dict[quan_name_a] def forward(self, input_0): primals_1 = self.weight primals_3 = self.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Jzz24/pytorch_quantization
Linear_Q
false
13,925
[ "MIT" ]
71
0c2d93c8ce4f85dd2c34ea6f36c58d14db21bf8e
https://github.com/Jzz24/pytorch_quantization/tree/0c2d93c8ce4f85dd2c34ea6f36c58d14db21bf8e
TransformerNet
import torch import numpy as np import torch.nn as nn class ConvLayer(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride): super(ConvLayer, self).__init__() reflection_padding = int(np.floor(kernel_size / 2)) self.reflection_pad = nn.ReflectionPad2d(reflection_padding) self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride) def forward(self, x): out = self.reflection_pad(x) out = self.conv2d(out) return out class InstanceNormalization(torch.nn.Module): """InstanceNormalization Improves convergence of neural-style. ref: https://arxiv.org/pdf/1607.08022.pdf """ def __init__(self, dim, eps=1e-09): super(InstanceNormalization, self).__init__() self.scale = nn.Parameter(torch.FloatTensor(dim)) self.shift = nn.Parameter(torch.FloatTensor(dim)) self.eps = eps self._reset_parameters() def _reset_parameters(self): self.scale.data.uniform_() self.shift.data.zero_() def forward(self, x): n = x.size(2) * x.size(3) t = x.view(x.size(0), x.size(1), n) mean = torch.mean(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x) var = torch.var(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x) * ((n - 1) / float(n)) scale_broadcast = self.scale.unsqueeze(1).unsqueeze(1).unsqueeze(0) scale_broadcast = scale_broadcast.expand_as(x) shift_broadcast = self.shift.unsqueeze(1).unsqueeze(1).unsqueeze(0) shift_broadcast = shift_broadcast.expand_as(x) out = (x - mean) / torch.sqrt(var + self.eps) out = out * scale_broadcast + shift_broadcast return out class ResidualBlock(torch.nn.Module): """ResidualBlock introduced in: https://arxiv.org/abs/1512.03385 recommended architecture: http://torch.ch/blog/2016/02/04/resnets.html """ def __init__(self, channels): super(ResidualBlock, self).__init__() self.conv1 = ConvLayer(channels, channels, kernel_size=3, stride=1) self.in1 = InstanceNormalization(channels) self.conv2 = ConvLayer(channels, channels, kernel_size=3, stride=1) self.in2 = InstanceNormalization(channels) self.relu = nn.ReLU() def forward(self, x): residual = x out = self.relu(self.in1(self.conv1(x))) out = self.in2(self.conv2(out)) out = out + residual return out class UpsampleConvLayer(torch.nn.Module): """UpsampleConvLayer Upsamples the input and then does a convolution. This method gives better results compared to ConvTranspose2d. ref: http://distill.pub/2016/deconv-checkerboard/ """ def __init__(self, in_channels, out_channels, kernel_size, stride, upsample=None): super(UpsampleConvLayer, self).__init__() self.upsample = upsample if upsample: self.upsample_layer = torch.nn.Upsample(scale_factor=upsample) reflection_padding = int(np.floor(kernel_size / 2)) self.reflection_pad = nn.ReflectionPad2d(reflection_padding) self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride) def forward(self, x): x_in = x if self.upsample: x_in = self.upsample_layer(x_in) out = self.reflection_pad(x_in) out = self.conv2d(out) return out class TransformerNet(torch.nn.Module): def __init__(self): super(TransformerNet, self).__init__() self.conv1 = ConvLayer(3, 32, kernel_size=9, stride=1) self.in1 = InstanceNormalization(32) self.conv2 = ConvLayer(32, 64, kernel_size=3, stride=2) self.in2 = InstanceNormalization(64) self.conv3 = ConvLayer(64, 128, kernel_size=3, stride=2) self.in3 = InstanceNormalization(128) self.res1 = ResidualBlock(128) self.res2 = ResidualBlock(128) self.res3 = ResidualBlock(128) self.res4 = ResidualBlock(128) self.res5 = ResidualBlock(128) self.deconv1 = UpsampleConvLayer(128, 64, kernel_size=3, stride=1, upsample=2) self.in4 = InstanceNormalization(64) self.deconv2 = UpsampleConvLayer(64, 32, kernel_size=3, stride=1, upsample=2) self.in5 = InstanceNormalization(32) self.deconv3 = ConvLayer(32, 3, kernel_size=9, stride=1) self.relu = nn.ReLU() def forward(self, X): in_X = X y = self.relu(self.in1(self.conv1(in_X))) y = self.relu(self.in2(self.conv2(y))) y = self.relu(self.in3(self.conv3(y))) y = self.res1(y) y = self.res2(y) y = self.res3(y) y = self.res4(y) y = self.res5(y) y = self.relu(self.in4(self.deconv1(y))) y = self.relu(self.in5(self.deconv2(y))) y = self.deconv3(y) return y def get_inputs(): return [torch.rand([4, 3, 64, 64])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import numpy as np import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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_convolution_mean_var_1(in_out_ptr0, in_out_ptr1, in_out_ptr2, in_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 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) tmp6_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32) tmp6_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32) tmp6_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]) tmp5 = _tmp4 + tmp3 _tmp4 = tl.where(rmask & xmask, tmp5, _tmp4) tmp6_mean_next, tmp6_m2_next, tmp6_weight_next = (triton_helpers. welford_reduce(tmp3, tmp6_mean, tmp6_m2, tmp6_weight, roffset == 0) ) tmp6_mean = tl.where(rmask & xmask, tmp6_mean_next, tmp6_mean) tmp6_m2 = tl.where(rmask & xmask, tmp6_m2_next, tmp6_m2) tmp6_weight = tl.where(rmask & xmask, tmp6_weight_next, tmp6_weight) tl.store(in_out_ptr0 + (r2 + 4096 * x3), tmp2, rmask & xmask) tmp4 = tl.sum(_tmp4, 1)[:, None] tmp6_tmp, tmp7_tmp, tmp8_tmp = triton_helpers.welford(tmp6_mean, tmp6_m2, tmp6_weight, 1) tmp6_tmp[:, None] tmp7 = tmp7_tmp[:, None] tmp8_tmp[:, None] tmp9 = 4096.0 tmp10 = tmp4 / tmp9 tmp11 = 4095.0 tmp12 = tmp7 / tmp11 tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp10, xmask) tl.debug_barrier() tl.store(in_out_ptr2 + x3, tmp12, xmask) @triton.jit def triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_2(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 x4 = xindex // 4356 x2 = xindex // 4356 % 32 x6 = 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 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = 0.999755859375 tmp5 = tmp3 * tmp4 tmp6 = 1e-09 tmp7 = tmp5 + tmp6 tmp8 = libdevice.sqrt(tmp7) tmp9 = tmp2 / tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tmp14 = tl.full([1], 0, tl.int32) tmp15 = triton_helpers.maximum(tmp14, tmp13) tl.store(out_ptr0 + x6, tmp15, xmask) @triton.jit def triton_per_fused_convolution_mean_var_3(in_out_ptr0, in_out_ptr1, in_out_ptr2, in_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 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0)) tmp7 = tl.broadcast_to(tmp3, [RBLOCK]) tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0)) tmp10 = tl.full([1], 1024, tl.int32) tmp11 = tmp10.to(tl.float32) tmp12 = tmp9 / tmp11 tmp13 = tmp3 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = 1024.0 tmp19 = tmp5 / tmp18 tmp20 = 1023.0 tmp21 = tmp17 / tmp20 tl.store(in_out_ptr0 + (r2 + 1024 * x3), tmp2, None) tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp19, None) tl.debug_barrier() tl.store(in_out_ptr2 + x3, tmp21, None) @triton.jit def triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_4(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 x4 = xindex // 1156 x2 = xindex // 1156 % 64 x6 = 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 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = 0.9990234375 tmp5 = tmp3 * tmp4 tmp6 = 1e-09 tmp7 = tmp5 + tmp6 tmp8 = libdevice.sqrt(tmp7) tmp9 = tmp2 / tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tmp14 = tl.full([1], 0, tl.int32) tmp15 = triton_helpers.maximum(tmp14, tmp13) tl.store(out_ptr0 + x6, tmp15, xmask) @triton.jit def triton_per_fused_add_convolution_div_mean_mul_relu_sqrt_sub_var_5( in_out_ptr0, in_out_ptr1, in_out_ptr2, in_ptr0, in_ptr1, in_ptr2, 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') tmp29 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last') tmp31 = tl.load(in_ptr2 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.broadcast_to(tmp2, [RBLOCK]) tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0)) tmp7 = tl.broadcast_to(tmp3, [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 = tmp3 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = 256.0 tmp19 = tmp5 / tmp18 tmp20 = 255.0 tmp21 = tmp17 / tmp20 tmp22 = tmp2 - tmp19 tmp23 = 0.99609375 tmp24 = tmp21 * tmp23 tmp25 = 1e-09 tmp26 = tmp24 + tmp25 tmp27 = libdevice.sqrt(tmp26) tmp28 = tmp22 / tmp27 tmp30 = tmp28 * tmp29 tmp32 = tmp30 + tmp31 tmp33 = tl.full([1], 0, tl.int32) tmp34 = triton_helpers.maximum(tmp33, tmp32) tl.store(in_out_ptr0 + (r2 + 256 * x3), tmp2, None) tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp19, None) tl.debug_barrier() tl.store(in_out_ptr2 + x3, tmp21, None) tl.store(out_ptr0 + (r2 + 256 * x3), tmp34, None) @triton.jit def triton_poi_fused_reflection_pad2d_6(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_convolution_mean_var_7(in_out_ptr0, in_out_ptr1, in_out_ptr2, in_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 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0)) tmp7 = tl.broadcast_to(tmp3, [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 = tmp3 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = 256.0 tmp19 = tmp5 / tmp18 tmp20 = 255.0 tmp21 = tmp17 / tmp20 tl.store(in_out_ptr0 + (r2 + 256 * x3), tmp2, None) tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp19, None) tl.debug_barrier() tl.store(in_out_ptr2 + x3, tmp21, None) @triton.jit def triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8(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 x4 = xindex // 324 x2 = xindex // 324 % 128 x6 = 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 * x4), None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x4, None, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, None, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last') tmp12 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = 0.99609375 tmp5 = tmp3 * tmp4 tmp6 = 1e-09 tmp7 = tmp5 + tmp6 tmp8 = libdevice.sqrt(tmp7) tmp9 = tmp2 / tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tmp14 = tl.full([1], 0, tl.int32) tmp15 = triton_helpers.maximum(tmp14, tmp13) tl.store(out_ptr0 + x6, tmp15, None) @triton.jit def triton_per_fused_add_convolution_div_mean_mul_sqrt_sub_var_9(in_out_ptr0, in_out_ptr1, in_out_ptr2, in_out_ptr3, in_ptr0, in_ptr1, in_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) 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') tmp29 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last') tmp31 = tl.load(in_ptr2 + x0, None, eviction_policy='evict_last') tmp33 = tl.load(in_out_ptr3 + (r2 + 256 * x3), None) tmp2 = tmp0 + tmp1 tmp3 = tl.broadcast_to(tmp2, [RBLOCK]) tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0)) tmp7 = tl.broadcast_to(tmp3, [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 = tmp3 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = 256.0 tmp19 = tmp5 / tmp18 tmp20 = 255.0 tmp21 = tmp17 / tmp20 tmp22 = tmp2 - tmp19 tmp23 = 0.99609375 tmp24 = tmp21 * tmp23 tmp25 = 1e-09 tmp26 = tmp24 + tmp25 tmp27 = libdevice.sqrt(tmp26) tmp28 = tmp22 / tmp27 tmp30 = tmp28 * tmp29 tmp32 = tmp30 + tmp31 tmp34 = tmp32 + tmp33 tl.store(in_out_ptr0 + (r2 + 256 * x3), tmp2, None) tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp19, None) tl.debug_barrier() tl.store(in_out_ptr2 + x3, tmp21, None) tl.store(in_out_ptr3 + (r2 + 256 * x3), tmp34, None) @triton.jit def triton_poi_fused_arange_10(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_11(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_add_div_mul_reflection_pad2d_sqrt_sub_12( in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, 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 x4 = xindex // 1156 x2 = xindex // 1156 % 128 x7 = 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') tmp10 = tl.load(in_ptr2 + x4, None, eviction_policy='evict_last') tmp12 = tl.load(in_ptr3 + x4, None, eviction_policy='evict_last') tmp19 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last') tmp21 = tl.load(in_ptr5 + x2, 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 * x4), None, eviction_policy='evict_last') tmp11 = tmp9 - tmp10 tmp13 = 0.99609375 tmp14 = tmp12 * tmp13 tmp15 = 1e-09 tmp16 = tmp14 + tmp15 tmp17 = libdevice.sqrt(tmp16) tmp18 = tmp11 / tmp17 tmp20 = tmp18 * tmp19 tmp22 = tmp20 + tmp21 tmp23 = tl.load(in_ptr6 + (tmp8 + 16 * tmp4 + 256 * x4), None, eviction_policy='evict_last') tmp24 = tmp22 + tmp23 tl.store(out_ptr0 + x7, tmp24, None) @triton.jit def triton_poi_fused_arange_13(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_14(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_add_div_mul_reflection_pad2d_relu_sqrt_sub_15( 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 x4 = xindex // 4356 x2 = xindex // 4356 % 64 x7 = 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 + x4, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last') tmp19 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last') tmp21 = 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 * x4), xmask, eviction_policy='evict_last') tmp11 = tmp9 - tmp10 tmp13 = 0.9990234375 tmp14 = tmp12 * tmp13 tmp15 = 1e-09 tmp16 = tmp14 + tmp15 tmp17 = libdevice.sqrt(tmp16) tmp18 = tmp11 / tmp17 tmp20 = tmp18 * tmp19 tmp22 = tmp20 + tmp21 tmp23 = tl.full([1], 0, tl.int32) tmp24 = triton_helpers.maximum(tmp23, tmp22) tl.store(out_ptr0 + x7, tmp24, xmask) @triton.jit def triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_16(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 x4 = xindex // 5184 x2 = xindex // 5184 % 32 x6 = 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 * x4), None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x4, None, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, None, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last') tmp12 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = 0.999755859375 tmp5 = tmp3 * tmp4 tmp6 = 1e-09 tmp7 = tmp5 + tmp6 tmp8 = libdevice.sqrt(tmp7) tmp9 = tmp2 / tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tmp14 = tl.full([1], 0, tl.int32) tmp15 = triton_helpers.maximum(tmp14, tmp13) tl.store(out_ptr0 + x6, tmp15, None) @triton.jit def triton_poi_fused_convolution_17(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 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, (4, 3, 64, 64), (12288, 4096, 64, 1)) assert_size_stride(primals_2, (32, 3, 9, 9), (243, 81, 9, 1)) assert_size_stride(primals_3, (32,), (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_1, buf0, 62208, XBLOCK=256, 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, 32, 64, 64), (131072, 4096, 64, 1)) buf2 = buf1 del buf1 buf3 = empty_strided_cuda((4, 32), (32, 1), torch.float32) buf6 = empty_strided_cuda((4, 32), (32, 1), torch.float32) buf4 = buf3 del buf3 buf8 = buf6 del buf6 triton_red_fused_convolution_mean_var_1[grid(128)](buf2, buf4, buf8, primals_3, 128, 4096, XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1) del primals_3 buf9 = empty_strided_cuda((4, 32, 66, 66), (139392, 4356, 66, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_2[grid( 557568)](buf2, buf4, buf8, primals_4, primals_5, 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 buf12 = empty_strided_cuda((4, 64), (64, 1), torch.float32) buf15 = empty_strided_cuda((4, 64), (64, 1), torch.float32) buf13 = buf12 del buf12 buf17 = buf15 del buf15 triton_per_fused_convolution_mean_var_3[grid(256)](buf11, buf13, buf17, primals_7, 256, 1024, num_warps=8, num_stages=1) del primals_7 buf18 = empty_strided_cuda((4, 64, 34, 34), (73984, 1156, 34, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_4[grid( 295936)](buf11, buf13, buf17, primals_8, primals_9, 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)) buf20 = buf19 del buf19 buf21 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf24 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf22 = buf21 del buf21 buf26 = buf24 del buf24 buf27 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1), torch.float32) triton_per_fused_add_convolution_div_mean_mul_relu_sqrt_sub_var_5[grid (512)](buf20, buf22, buf26, primals_11, primals_12, primals_13, buf27, 512, 256, num_warps=2, num_stages=1) del primals_11 buf28 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_reflection_pad2d_6[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 buf31 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf34 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf32 = buf31 del buf31 buf36 = buf34 del buf34 triton_per_fused_convolution_mean_var_7[grid(512)](buf30, buf32, buf36, primals_15, 512, 256, num_warps=2, num_stages=1) del primals_15 buf37 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8[grid( 165888)](buf30, buf32, buf36, primals_16, primals_17, buf37, 165888, XBLOCK=512, num_warps=8, 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)) buf39 = buf38 del buf38 buf40 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf43 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf41 = buf40 del buf40 buf45 = buf43 del buf43 buf46 = buf27 del buf27 triton_per_fused_add_convolution_div_mean_mul_sqrt_sub_var_9[grid(512) ](buf39, buf41, buf45, buf46, primals_19, primals_20, primals_21, 512, 256, num_warps=2, num_stages=1) del primals_19 del primals_21 buf47 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_reflection_pad2d_6[grid(165888)](buf46, buf47, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf48 = extern_kernels.convolution(buf47, primals_22, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf48, (4, 128, 16, 16), (32768, 256, 16, 1)) buf49 = buf48 del buf48 buf50 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf53 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf51 = buf50 del buf50 buf55 = buf53 del buf53 triton_per_fused_convolution_mean_var_7[grid(512)](buf49, buf51, buf55, primals_23, 512, 256, num_warps=2, num_stages=1) del primals_23 buf56 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8[grid( 165888)](buf49, buf51, buf55, primals_24, primals_25, buf56, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf57 = extern_kernels.convolution(buf56, primals_26, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf57, (4, 128, 16, 16), (32768, 256, 16, 1)) buf58 = buf57 del buf57 buf59 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf62 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf60 = buf59 del buf59 buf64 = buf62 del buf62 buf65 = buf46 del buf46 triton_per_fused_add_convolution_div_mean_mul_sqrt_sub_var_9[grid(512) ](buf58, buf60, buf64, buf65, primals_27, primals_28, primals_29, 512, 256, num_warps=2, num_stages=1) del primals_27 del primals_29 buf66 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_reflection_pad2d_6[grid(165888)](buf65, buf66, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf67 = extern_kernels.convolution(buf66, primals_30, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf67, (4, 128, 16, 16), (32768, 256, 16, 1)) buf68 = buf67 del buf67 buf69 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf72 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf70 = buf69 del buf69 buf74 = buf72 del buf72 triton_per_fused_convolution_mean_var_7[grid(512)](buf68, buf70, buf74, primals_31, 512, 256, num_warps=2, num_stages=1) del primals_31 buf75 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8[grid( 165888)](buf68, buf70, buf74, primals_32, primals_33, buf75, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf76 = extern_kernels.convolution(buf75, primals_34, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf76, (4, 128, 16, 16), (32768, 256, 16, 1)) buf77 = buf76 del buf76 buf78 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf81 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf79 = buf78 del buf78 buf83 = buf81 del buf81 buf84 = buf65 del buf65 triton_per_fused_add_convolution_div_mean_mul_sqrt_sub_var_9[grid(512) ](buf77, buf79, buf83, buf84, primals_35, primals_36, primals_37, 512, 256, num_warps=2, num_stages=1) del primals_35 del primals_37 buf85 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_reflection_pad2d_6[grid(165888)](buf84, buf85, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf86 = extern_kernels.convolution(buf85, primals_38, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf86, (4, 128, 16, 16), (32768, 256, 16, 1)) buf87 = buf86 del buf86 buf88 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf91 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf89 = buf88 del buf88 buf93 = buf91 del buf91 triton_per_fused_convolution_mean_var_7[grid(512)](buf87, buf89, buf93, primals_39, 512, 256, num_warps=2, num_stages=1) del primals_39 buf94 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8[grid( 165888)](buf87, buf89, buf93, primals_40, primals_41, buf94, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf95 = extern_kernels.convolution(buf94, primals_42, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf95, (4, 128, 16, 16), (32768, 256, 16, 1)) buf96 = buf95 del buf95 buf97 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf100 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf98 = buf97 del buf97 buf102 = buf100 del buf100 buf103 = buf84 del buf84 triton_per_fused_add_convolution_div_mean_mul_sqrt_sub_var_9[grid(512) ](buf96, buf98, buf102, buf103, primals_43, primals_44, primals_45, 512, 256, num_warps=2, num_stages=1) del primals_43 del primals_45 buf104 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_reflection_pad2d_6[grid(165888)](buf103, buf104, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf105 = extern_kernels.convolution(buf104, primals_46, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf105, (4, 128, 16, 16), (32768, 256, 16, 1)) buf106 = buf105 del buf105 buf107 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf110 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf108 = buf107 del buf107 buf112 = buf110 del buf110 triton_per_fused_convolution_mean_var_7[grid(512)](buf106, buf108, buf112, primals_47, 512, 256, num_warps=2, num_stages=1) del primals_47 buf113 = empty_strided_cuda((4, 128, 18, 18), (41472, 324, 18, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_8[grid( 165888)](buf106, buf108, buf112, primals_48, primals_49, buf113, 165888, XBLOCK=512, num_warps=8, num_stages=1) buf114 = extern_kernels.convolution(buf113, primals_50, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf114, (4, 128, 16, 16), (32768, 256, 16, 1)) buf115 = buf114 del buf114 buf116 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf119 = empty_strided_cuda((4, 128), (128, 1), torch.float32) buf117 = buf116 del buf116 buf121 = buf119 del buf119 triton_per_fused_convolution_mean_var_7[grid(512)](buf115, buf117, buf121, primals_51, 512, 256, num_warps=2, num_stages=1) del primals_51 buf122 = empty_strided_cuda((32,), (1,), torch.int64) triton_poi_fused_arange_10[grid(32)](buf122, 32, XBLOCK=32, num_warps=1, num_stages=1) buf123 = empty_strided_cuda((32,), (1,), torch.int64) triton_poi_fused__to_copy_add_arange_mul_11[grid(32)](buf123, 32, XBLOCK=32, num_warps=1, num_stages=1) buf124 = empty_strided_cuda((4, 128, 34, 34), (147968, 1156, 34, 1), torch.float32) triton_poi_fused__unsafe_index_add_div_mul_reflection_pad2d_sqrt_sub_12[ grid(591872)](buf123, buf115, buf117, buf121, primals_52, primals_53, buf103, buf124, 591872, XBLOCK=512, num_warps=8, num_stages=1) del buf103 del primals_53 buf125 = extern_kernels.convolution(buf124, primals_54, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf125, (4, 64, 32, 32), (65536, 1024, 32, 1)) buf126 = buf125 del buf125 buf127 = empty_strided_cuda((4, 64), (64, 1), torch.float32) buf130 = empty_strided_cuda((4, 64), (64, 1), torch.float32) buf128 = buf127 del buf127 buf132 = buf130 del buf130 triton_per_fused_convolution_mean_var_3[grid(256)](buf126, buf128, buf132, primals_55, 256, 1024, num_warps=8, num_stages=1) del primals_55 buf133 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused_arange_13[grid(64)](buf133, 64, XBLOCK=64, num_warps=1, num_stages=1) buf134 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused__to_copy_add_arange_mul_14[grid(64)](buf134, 64, XBLOCK=64, num_warps=1, num_stages=1) buf135 = empty_strided_cuda((4, 64, 66, 66), (278784, 4356, 66, 1), torch.float32) triton_poi_fused__unsafe_index_add_div_mul_reflection_pad2d_relu_sqrt_sub_15[ grid(1115136)](buf134, buf126, buf128, buf132, primals_56, primals_57, buf135, 1115136, XBLOCK=512, num_warps=8, num_stages=1) buf136 = extern_kernels.convolution(buf135, primals_58, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf136, (4, 32, 64, 64), (131072, 4096, 64, 1)) buf137 = buf136 del buf136 buf138 = empty_strided_cuda((4, 32), (32, 1), torch.float32) buf141 = empty_strided_cuda((4, 32), (32, 1), torch.float32) buf139 = buf138 del buf138 buf143 = buf141 del buf141 triton_red_fused_convolution_mean_var_1[grid(128)](buf137, buf139, buf143, primals_59, 128, 4096, XBLOCK=1, RBLOCK=2048, num_warps =16, num_stages=1) del primals_59 buf144 = empty_strided_cuda((4, 32, 72, 72), (165888, 5184, 72, 1), torch.float32) triton_poi_fused_add_div_mul_reflection_pad2d_relu_sqrt_sub_16[grid (663552)](buf137, buf139, buf143, primals_60, primals_61, buf144, 663552, XBLOCK=512, num_warps=8, num_stages=1) buf145 = extern_kernels.convolution(buf144, primals_62, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf145, (4, 3, 64, 64), (12288, 4096, 64, 1)) buf146 = buf145 del buf145 triton_poi_fused_convolution_17[grid(49152)](buf146, primals_63, 49152, XBLOCK=256, num_warps=4, num_stages=1) del primals_63 return (buf146, primals_2, primals_4, primals_5, primals_6, primals_8, primals_9, primals_10, primals_12, primals_13, primals_14, primals_16, primals_17, primals_18, primals_20, primals_22, primals_24, primals_25, primals_26, primals_28, primals_30, primals_32, primals_33, primals_34, primals_36, primals_38, primals_40, primals_41, primals_42, primals_44, primals_46, primals_48, primals_49, primals_50, primals_52, primals_54, primals_56, primals_57, primals_58, primals_60, primals_61, primals_62, buf0, buf2, reinterpret_tensor(buf4, (4, 32, 1, 1), (32, 1, 1, 1), 0), reinterpret_tensor(buf8, (4, 32, 1, 1), (32, 1, 1, 1), 0), buf9, buf11, reinterpret_tensor(buf13, (4, 64, 1, 1), (64, 1, 1, 1), 0), reinterpret_tensor(buf17, (4, 64, 1, 1), (64, 1, 1, 1), 0), buf18, buf20, reinterpret_tensor(buf22, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf26, (4, 128, 1, 1), (128, 1, 1, 1), 0 ), buf28, buf30, reinterpret_tensor(buf32, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf36, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf37, buf39, reinterpret_tensor(buf41, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf45, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf47, buf49, reinterpret_tensor(buf51, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf55, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf56, buf58, reinterpret_tensor(buf60, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf64, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf66, buf68, reinterpret_tensor(buf70, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf74, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf75, buf77, reinterpret_tensor(buf79, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf83, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf85, buf87, reinterpret_tensor(buf89, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf93, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf94, buf96, reinterpret_tensor(buf98, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf102, (4, 128, 1, 1), (128, 1, 1, 1 ), 0), buf104, buf106, reinterpret_tensor(buf108, (4, 128, 1, 1), ( 128, 1, 1, 1), 0), reinterpret_tensor(buf112, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf113, buf115, reinterpret_tensor(buf117, (4, 128, 1, 1), (128, 1, 1, 1), 0), reinterpret_tensor(buf121, (4, 128, 1, 1), (128, 1, 1, 1), 0), buf122, buf123, buf124, buf126, reinterpret_tensor(buf128, (4, 64, 1, 1), (64, 1, 1, 1), 0), reinterpret_tensor(buf132, (4, 64, 1, 1), (64, 1, 1, 1), 0), buf133, buf134, buf135, buf137, reinterpret_tensor(buf139, (4, 32, 1, 1), ( 32, 1, 1, 1), 0), reinterpret_tensor(buf143, (4, 32, 1, 1), (32, 1, 1, 1), 0), buf144) class ConvLayer(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride): super(ConvLayer, self).__init__() reflection_padding = int(np.floor(kernel_size / 2)) self.reflection_pad = nn.ReflectionPad2d(reflection_padding) self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride) def forward(self, x): out = self.reflection_pad(x) out = self.conv2d(out) return out class InstanceNormalization(torch.nn.Module): """InstanceNormalization Improves convergence of neural-style. ref: https://arxiv.org/pdf/1607.08022.pdf """ def __init__(self, dim, eps=1e-09): super(InstanceNormalization, self).__init__() self.scale = nn.Parameter(torch.FloatTensor(dim)) self.shift = nn.Parameter(torch.FloatTensor(dim)) self.eps = eps self._reset_parameters() def _reset_parameters(self): self.scale.data.uniform_() self.shift.data.zero_() def forward(self, x): n = x.size(2) * x.size(3) t = x.view(x.size(0), x.size(1), n) mean = torch.mean(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x) var = torch.var(t, 2).unsqueeze(2).unsqueeze(3).expand_as(x) * ((n - 1) / float(n)) scale_broadcast = self.scale.unsqueeze(1).unsqueeze(1).unsqueeze(0) scale_broadcast = scale_broadcast.expand_as(x) shift_broadcast = self.shift.unsqueeze(1).unsqueeze(1).unsqueeze(0) shift_broadcast = shift_broadcast.expand_as(x) out = (x - mean) / torch.sqrt(var + self.eps) out = out * scale_broadcast + shift_broadcast return out class ResidualBlock(torch.nn.Module): """ResidualBlock introduced in: https://arxiv.org/abs/1512.03385 recommended architecture: http://torch.ch/blog/2016/02/04/resnets.html """ def __init__(self, channels): super(ResidualBlock, self).__init__() self.conv1 = ConvLayer(channels, channels, kernel_size=3, stride=1) self.in1 = InstanceNormalization(channels) self.conv2 = ConvLayer(channels, channels, kernel_size=3, stride=1) self.in2 = InstanceNormalization(channels) self.relu = nn.ReLU() def forward(self, x): residual = x out = self.relu(self.in1(self.conv1(x))) out = self.in2(self.conv2(out)) out = out + residual return out class UpsampleConvLayer(torch.nn.Module): """UpsampleConvLayer Upsamples the input and then does a convolution. This method gives better results compared to ConvTranspose2d. ref: http://distill.pub/2016/deconv-checkerboard/ """ def __init__(self, in_channels, out_channels, kernel_size, stride, upsample=None): super(UpsampleConvLayer, self).__init__() self.upsample = upsample if upsample: self.upsample_layer = torch.nn.Upsample(scale_factor=upsample) reflection_padding = int(np.floor(kernel_size / 2)) self.reflection_pad = nn.ReflectionPad2d(reflection_padding) self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride) def forward(self, x): x_in = x if self.upsample: x_in = self.upsample_layer(x_in) out = self.reflection_pad(x_in) out = self.conv2d(out) return out class TransformerNetNew(torch.nn.Module): def __init__(self): super(TransformerNetNew, self).__init__() self.conv1 = ConvLayer(3, 32, kernel_size=9, stride=1) self.in1 = InstanceNormalization(32) self.conv2 = ConvLayer(32, 64, kernel_size=3, stride=2) self.in2 = InstanceNormalization(64) self.conv3 = ConvLayer(64, 128, kernel_size=3, stride=2) self.in3 = InstanceNormalization(128) self.res1 = ResidualBlock(128) self.res2 = ResidualBlock(128) self.res3 = ResidualBlock(128) self.res4 = ResidualBlock(128) self.res5 = ResidualBlock(128) self.deconv1 = UpsampleConvLayer(128, 64, kernel_size=3, stride=1, upsample=2) self.in4 = InstanceNormalization(64) self.deconv2 = UpsampleConvLayer(64, 32, kernel_size=3, stride=1, upsample=2) self.in5 = InstanceNormalization(32) self.deconv3 = ConvLayer(32, 3, kernel_size=9, stride=1) self.relu = nn.ReLU() def forward(self, input_0): primals_2 = self.conv1.conv2d.weight primals_3 = self.conv1.conv2d.bias primals_4 = self.in1.scale primals_5 = self.in1.shift primals_6 = self.conv2.conv2d.weight primals_7 = self.conv2.conv2d.bias primals_8 = self.in2.scale primals_9 = self.in2.shift primals_10 = self.conv3.conv2d.weight primals_11 = self.conv3.conv2d.bias primals_12 = self.in3.scale primals_13 = self.in3.shift primals_14 = self.res1.conv1.conv2d.weight primals_15 = self.res1.conv1.conv2d.bias primals_16 = self.res1.in1.scale primals_17 = self.res1.in1.shift primals_18 = self.res1.conv2.conv2d.weight primals_19 = self.res1.conv2.conv2d.bias primals_20 = self.res1.in2.scale primals_21 = self.res1.in2.shift primals_22 = self.res2.conv1.conv2d.weight primals_23 = self.res2.conv1.conv2d.bias primals_24 = self.res2.in1.scale primals_25 = self.res2.in1.shift primals_26 = self.res2.conv2.conv2d.weight primals_27 = self.res2.conv2.conv2d.bias primals_28 = self.res2.in2.scale primals_29 = self.res2.in2.shift primals_30 = self.res3.conv1.conv2d.weight primals_31 = self.res3.conv1.conv2d.bias primals_32 = self.res3.in1.scale primals_33 = self.res3.in1.shift primals_34 = self.res3.conv2.conv2d.weight primals_35 = self.res3.conv2.conv2d.bias primals_36 = self.res3.in2.scale primals_37 = self.res3.in2.shift primals_38 = self.res4.conv1.conv2d.weight primals_39 = self.res4.conv1.conv2d.bias primals_40 = self.res4.in1.scale primals_41 = self.res4.in1.shift primals_42 = self.res4.conv2.conv2d.weight primals_43 = self.res4.conv2.conv2d.bias primals_44 = self.res4.in2.scale primals_45 = self.res4.in2.shift primals_46 = self.res5.conv1.conv2d.weight primals_47 = self.res5.conv1.conv2d.bias primals_48 = self.res5.in1.scale primals_49 = self.res5.in1.shift primals_50 = self.res5.conv2.conv2d.weight primals_51 = self.res5.conv2.conv2d.bias primals_52 = self.res5.in2.scale primals_53 = self.res5.in2.shift primals_54 = self.deconv1.conv2d.weight primals_55 = self.deconv1.conv2d.bias primals_56 = self.in4.scale primals_57 = self.in4.shift primals_58 = self.deconv2.conv2d.weight primals_59 = self.deconv2.conv2d.bias primals_60 = self.in5.scale primals_61 = self.in5.shift primals_62 = self.deconv3.conv2d.weight primals_63 = self.deconv3.conv2d.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19, primals_20, primals_21, primals_22, primals_23, primals_24, primals_25, primals_26, primals_27, 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]
ImageProcessingCentraleLille2021/fast-neural-style
TransformerNet
false
13,926
[ "MIT" ]
350
e77456c35c2a49f90227119d158828a0964c7e13
https://github.com/ImageProcessingCentraleLille2021/fast-neural-style/tree/e77456c35c2a49f90227119d158828a0964c7e13
QNetwork
import torch from torch import nn class QNetwork(nn.Module): def __init__(self, num_states, num_actions): super().__init__() self._num_states = num_states self._num_actions = num_actions self._fc1 = nn.Linear(self._num_states, 100) self._relu1 = nn.ReLU(inplace=True) self._fc2 = nn.Linear(100, 60) self._relu2 = nn.ReLU(inplace=True) self._fc_final = nn.Linear(60, self._num_actions) nn.init.zeros_(self._fc1.bias) nn.init.zeros_(self._fc2.bias) nn.init.zeros_(self._fc_final.bias) nn.init.uniform_(self._fc_final.weight, a=-1e-06, b=1e-06) def forward(self, state): h = self._relu1(self._fc1(state)) h = self._relu2(self._fc2(h)) q_values = self._fc_final(h) return q_values def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_states': 4, 'num_actions': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch 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 = 6400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x4 = xindex x0 = xindex % 100 x3 = xindex // 1600 x5 = 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 + (x5 + 1664 * x3), tmp6, xmask) @triton.jit def triton_poi_fused_view_1(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 x0 = xindex % 100 x1 = xindex // 100 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 100 * x1 + 400 * (x1 % 4 // 4) + 1600 * ((4 * (x1 // 4 % 4) + x1 % 4) // 16)), xmask) tl.store(out_ptr0 + x2, tmp0, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 3840 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x4 = xindex x0 = xindex % 60 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 + x4, tmp6, xmask) @triton.jit def triton_poi_fused_view_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 3840 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 60 x1 = xindex // 60 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 60 * x1 + 240 * (x1 % 4 // 4) + 960 * (( 4 * (x1 // 4 % 4) + x1 % 4) // 16)), xmask) tl.store(out_ptr0 + x2, 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, (100, 4), (4, 1)) assert_size_stride(primals_2, (100,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (60, 100), (100, 1)) assert_size_stride(primals_5, (60,), (1,)) assert_size_stride(primals_6, (4, 60), (60, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 100), (100, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 100), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 100), (1600, 400, 100, 1), 0) del buf0 buf8 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(6400)](buf1, primals_2, buf8, 6400, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 100), (100, 1), torch.float32) triton_poi_fused_view_1[grid(6400)](buf1, buf2, 6400, XBLOCK=128, num_warps=4, num_stages=1) del buf1 buf3 = empty_strided_cuda((64, 60), (60, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (100, 60), (1, 100), 0), out=buf3) buf4 = reinterpret_tensor(buf3, (4, 4, 4, 60), (960, 240, 60, 1), 0) del buf3 buf7 = empty_strided_cuda((4, 4, 4, 60), (960, 240, 60, 1), torch.bool) triton_poi_fused_relu_threshold_backward_2[grid(3840)](buf4, primals_5, buf7, 3840, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf5 = empty_strided_cuda((64, 60), (60, 1), torch.float32) triton_poi_fused_view_3[grid(3840)](buf4, buf5, 3840, XBLOCK=256, num_warps=4, num_stages=1) del buf4 buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, buf5, reinterpret_tensor(primals_6, (60, 4), (1, 60), 0), alpha=1, beta=1, out=buf6) del primals_7 return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf2, buf5, primals_6, buf7, primals_4, buf8 class QNetworkNew(nn.Module): def __init__(self, num_states, num_actions): super().__init__() self._num_states = num_states self._num_actions = num_actions self._fc1 = nn.Linear(self._num_states, 100) self._relu1 = nn.ReLU(inplace=True) self._fc2 = nn.Linear(100, 60) self._relu2 = nn.ReLU(inplace=True) self._fc_final = nn.Linear(60, self._num_actions) nn.init.zeros_(self._fc1.bias) nn.init.zeros_(self._fc2.bias) nn.init.zeros_(self._fc_final.bias) nn.init.uniform_(self._fc_final.weight, a=-1e-06, b=1e-06) 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._fc_final.weight primals_7 = self._fc_final.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
JulianoLagana/deep-machine-learning
QNetwork
false
13,927
[ "MIT" ]
49
0135a84067be357c8bc3d3a4298b60dcaf7d53d5
https://github.com/JulianoLagana/deep-machine-learning/tree/0135a84067be357c8bc3d3a4298b60dcaf7d53d5
SRCNN
import logging import torch import torch.nn as nn def get_root_logger(log_file=None, log_level=logging.INFO): """Get the root logger. The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If `log_file` is specified, a FileHandler will also be added. The name of the root logger is the top-level package name, e.g., "mmedit". Args: log_file (str | None): The log filename. If specified, a FileHandler will be added to the root logger. log_level (int): The root logger level. Note that only the process of rank 0 is affected, while other processes will set the level to "Error" and be silent most of the time. Returns: logging.Logger: The root logger. """ logger = get_logger(__name__.split('.')[0], log_file, log_level) return logger class SRCNN(nn.Module): """SRCNN network structure for image super resolution. SRCNN has three conv layers. For each layer, we can define the `in_channels`, `out_channels` and `kernel_size`. The input image will first be upsampled with a bicubic upsampler, and then super-resolved in the HR spatial size. Paper: Learning a Deep Convolutional Network for Image Super-Resolution. Args: channels (tuple[int]): A tuple of channel numbers for each layer including channels of input and output . Default: (3, 64, 32, 3). kernel_sizes (tuple[int]): A tuple of kernel sizes for each conv layer. Default: (9, 1, 5). upscale_factor (int): Upsampling factor. Default: 4. """ def __init__(self, channels=(3, 64, 32, 3), kernel_sizes=(9, 1, 5), upscale_factor=4): super().__init__() assert len(channels ) == 4, f'The length of channel tuple should be 4, but got {len(channels)}' assert len(kernel_sizes ) == 3, f'The length of kernel tuple should be 3, but got {len(kernel_sizes)}' self.upscale_factor = upscale_factor self.img_upsampler = nn.Upsample(scale_factor=self.upscale_factor, mode='bicubic', align_corners=False) self.conv1 = nn.Conv2d(channels[0], channels[1], kernel_size= kernel_sizes[0], padding=kernel_sizes[0] // 2) self.conv2 = nn.Conv2d(channels[1], channels[2], kernel_size= kernel_sizes[1], padding=kernel_sizes[1] // 2) self.conv3 = nn.Conv2d(channels[2], channels[3], kernel_size= kernel_sizes[2], padding=kernel_sizes[2] // 2) self.relu = nn.ReLU() def forward(self, x): """Forward function. Args: x (Tensor): Input tensor with shape (n, c, h, w). Returns: Tensor: Forward results. """ x = self.img_upsampler(x) out = self.relu(self.conv1(x)) out = self.relu(self.conv2(out)) out = self.conv3(out) return out def init_weights(self, pretrained=None, strict=True): """Init weights for models. Args: pretrained (str, optional): Path for pretrained weights. If given None, pretrained weights will not be loaded. Defaults to None. strict (boo, optional): Whether strictly load the pretrained model. Defaults to True. """ if isinstance(pretrained, str): logger = get_root_logger() load_checkpoint(self, pretrained, strict=strict, logger=logger) elif pretrained is None: pass else: raise TypeError( f'"pretrained" must be a str or None. But received {type(pretrained)}.' ) def get_inputs(): return [torch.rand([4, 3, 4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice import logging import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_0( in_out_ptr1, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 3072 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 16 % 16 x0 = xindex % 16 x2 = xindex // 256 x3 = xindex tmp0 = x1 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = 0.25 tmp5 = tmp3 * tmp4 tmp6 = tmp5 - tmp2 tmp7 = libdevice.floor(tmp6) tmp8 = tmp7.to(tl.int32) tmp9 = tl.full([1], 1, tl.int64) tmp10 = tmp8 - tmp9 tmp11 = tl.full([1], 0, tl.int64) tmp12 = triton_helpers.maximum(tmp10, tmp11) tmp13 = tl.full([1], 3, tl.int64) tmp14 = triton_helpers.minimum(tmp12, tmp13) tmp15 = x0 tmp16 = tmp15.to(tl.float32) tmp17 = tmp16 + tmp2 tmp18 = tmp17 * tmp4 tmp19 = tmp18 - tmp2 tmp20 = libdevice.floor(tmp19) tmp21 = tmp20.to(tl.int32) tmp22 = tmp21 - tmp9 tmp23 = triton_helpers.maximum(tmp22, tmp11) tmp24 = triton_helpers.minimum(tmp23, tmp13) tmp25 = tl.load(in_ptr0 + (tmp24 + 4 * tmp14 + 16 * x2), xmask, eviction_policy='evict_last') tmp26 = tmp19 - tmp20 tmp27 = 0.0 tmp28 = triton_helpers.maximum(tmp26, tmp27) tmp29 = 1.0 tmp30 = triton_helpers.minimum(tmp28, tmp29) tmp31 = tmp30 + tmp29 tmp32 = -0.75 tmp33 = tmp31 * tmp32 tmp34 = -3.75 tmp35 = tmp33 - tmp34 tmp36 = tmp35 * tmp31 tmp37 = -6.0 tmp38 = tmp36 + tmp37 tmp39 = tmp38 * tmp31 tmp40 = -3.0 tmp41 = tmp39 - tmp40 tmp42 = tmp25 * tmp41 tmp43 = triton_helpers.maximum(tmp21, tmp11) tmp44 = triton_helpers.minimum(tmp43, tmp13) tmp45 = tl.load(in_ptr0 + (tmp44 + 4 * tmp14 + 16 * x2), xmask, eviction_policy='evict_last') tmp46 = 1.25 tmp47 = tmp30 * tmp46 tmp48 = 2.25 tmp49 = tmp47 - tmp48 tmp50 = tmp49 * tmp30 tmp51 = tmp50 * tmp30 tmp52 = tmp51 + tmp29 tmp53 = tmp45 * tmp52 tmp54 = tmp21 + tmp9 tmp55 = triton_helpers.maximum(tmp54, tmp11) tmp56 = triton_helpers.minimum(tmp55, tmp13) tmp57 = tl.load(in_ptr0 + (tmp56 + 4 * tmp14 + 16 * x2), xmask, eviction_policy='evict_last') tmp58 = tmp29 - tmp30 tmp59 = tmp58 * tmp46 tmp60 = tmp59 - tmp48 tmp61 = tmp60 * tmp58 tmp62 = tmp61 * tmp58 tmp63 = tmp62 + tmp29 tmp64 = tmp57 * tmp63 tmp65 = triton_helpers.maximum(tmp8, tmp11) tmp66 = triton_helpers.minimum(tmp65, tmp13) tmp67 = tl.load(in_ptr0 + (tmp24 + 4 * tmp66 + 16 * x2), xmask, eviction_policy='evict_last') tmp68 = tmp67 * tmp41 tmp69 = tl.full([1], 2, tl.int64) tmp70 = tmp21 + tmp69 tmp71 = triton_helpers.maximum(tmp70, tmp11) tmp72 = triton_helpers.minimum(tmp71, tmp13) tmp73 = tl.load(in_ptr0 + (tmp72 + 4 * tmp14 + 16 * x2), xmask, eviction_policy='evict_last') tmp74 = 2.0 tmp75 = tmp74 - tmp30 tmp76 = tmp75 * tmp32 tmp77 = tmp76 - tmp34 tmp78 = tmp77 * tmp75 tmp79 = tmp78 + tmp37 tmp80 = tmp79 * tmp75 tmp81 = tmp80 - tmp40 tmp82 = tmp73 * tmp81 tmp83 = tl.load(in_ptr0 + (tmp44 + 4 * tmp66 + 16 * x2), xmask, eviction_policy='evict_last') tmp84 = tmp83 * tmp52 tmp85 = tl.load(in_ptr0 + (tmp56 + 4 * tmp66 + 16 * x2), xmask, eviction_policy='evict_last') tmp86 = tmp85 * tmp63 tmp87 = tmp8 + tmp9 tmp88 = triton_helpers.maximum(tmp87, tmp11) tmp89 = triton_helpers.minimum(tmp88, tmp13) tmp90 = tl.load(in_ptr0 + (tmp24 + 4 * tmp89 + 16 * x2), xmask, eviction_policy='evict_last') tmp91 = tmp90 * tmp41 tmp92 = tl.load(in_ptr0 + (tmp72 + 4 * tmp66 + 16 * x2), xmask, eviction_policy='evict_last') tmp93 = tmp92 * tmp81 tmp94 = tl.load(in_ptr0 + (tmp44 + 4 * tmp89 + 16 * x2), xmask, eviction_policy='evict_last') tmp95 = tmp94 * tmp52 tmp96 = tl.load(in_ptr0 + (tmp56 + 4 * tmp89 + 16 * x2), xmask, eviction_policy='evict_last') tmp97 = tmp96 * tmp63 tmp98 = tmp8 + tmp69 tmp99 = triton_helpers.maximum(tmp98, tmp11) tmp100 = triton_helpers.minimum(tmp99, tmp13) tmp101 = tl.load(in_ptr0 + (tmp24 + 4 * tmp100 + 16 * x2), xmask, eviction_policy='evict_last') tmp102 = tmp101 * tmp41 tmp103 = tl.load(in_ptr0 + (tmp72 + 4 * tmp89 + 16 * x2), xmask, eviction_policy='evict_last') tmp104 = tmp103 * tmp81 tmp105 = tl.load(in_ptr0 + (tmp44 + 4 * tmp100 + 16 * x2), xmask, eviction_policy='evict_last') tmp106 = tmp105 * tmp52 tmp107 = tl.load(in_ptr0 + (tmp56 + 4 * tmp100 + 16 * x2), xmask, eviction_policy='evict_last') tmp108 = tmp107 * tmp63 tmp109 = tl.load(in_ptr0 + (tmp72 + 4 * tmp100 + 16 * x2), xmask, eviction_policy='evict_last') tmp110 = tmp109 * tmp81 tmp111 = tmp42 + tmp53 tmp112 = tmp111 + tmp64 tmp113 = tmp112 + tmp82 tmp114 = tmp6 - tmp7 tmp115 = triton_helpers.maximum(tmp114, tmp27) tmp116 = triton_helpers.minimum(tmp115, tmp29) tmp117 = tmp116 + tmp29 tmp118 = tmp117 * tmp32 tmp119 = tmp118 - tmp34 tmp120 = tmp119 * tmp117 tmp121 = tmp120 + tmp37 tmp122 = tmp121 * tmp117 tmp123 = tmp122 - tmp40 tmp124 = tmp113 * tmp123 tmp125 = tmp68 + tmp84 tmp126 = tmp125 + tmp86 tmp127 = tmp126 + tmp93 tmp128 = tmp116 * tmp46 tmp129 = tmp128 - tmp48 tmp130 = tmp129 * tmp116 tmp131 = tmp130 * tmp116 tmp132 = tmp131 + tmp29 tmp133 = tmp127 * tmp132 tmp134 = tmp124 + tmp133 tmp135 = tmp91 + tmp95 tmp136 = tmp135 + tmp97 tmp137 = tmp136 + tmp104 tmp138 = tmp29 - tmp116 tmp139 = tmp138 * tmp46 tmp140 = tmp139 - tmp48 tmp141 = tmp140 * tmp138 tmp142 = tmp141 * tmp138 tmp143 = tmp142 + tmp29 tmp144 = tmp137 * tmp143 tmp145 = tmp134 + tmp144 tmp146 = tmp102 + tmp106 tmp147 = tmp146 + tmp108 tmp148 = tmp147 + tmp110 tmp149 = tmp74 - tmp116 tmp150 = tmp149 * tmp32 tmp151 = tmp150 - tmp34 tmp152 = tmp151 * tmp149 tmp153 = tmp152 + tmp37 tmp154 = tmp153 * tmp149 tmp155 = tmp154 - tmp40 tmp156 = tmp148 * tmp155 tmp157 = tmp145 + tmp156 tl.store(in_out_ptr1 + x3, tmp157, xmask) @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 % 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_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 // 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_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 3072 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 256 % 3 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4, 3, 4, 4), (48, 16, 4, 1)) assert_size_stride(primals_2, (64, 3, 9, 9), (243, 81, 9, 1)) assert_size_stride(primals_3, (64,), (1,)) assert_size_stride(primals_4, (32, 64, 1, 1), (64, 1, 1, 1)) assert_size_stride(primals_5, (32,), (1,)) assert_size_stride(primals_6, (3, 32, 5, 5), (800, 25, 5, 1)) assert_size_stride(primals_7, (3,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf10 = empty_strided_cuda((4, 3, 16, 16), (768, 256, 16, 1), torch .float32) buf18 = buf10 del buf10 buf20 = buf18 del buf18 get_raw_stream(0) triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_floor_mul_rsub_sub_0[ grid(3072)](buf20, primals_1, 3072, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf21 = extern_kernels.convolution(buf20, primals_2, stride=(1, 1), padding=(4, 4), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf21, (4, 64, 16, 16), (16384, 256, 16, 1)) buf22 = buf21 del buf21 triton_poi_fused_convolution_relu_1[grid(65536)](buf22, primals_3, 65536, XBLOCK=256, num_warps=4, num_stages=1) del primals_3 buf23 = extern_kernels.convolution(buf22, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf23, (4, 32, 16, 16), (8192, 256, 16, 1)) buf24 = buf23 del buf23 triton_poi_fused_convolution_relu_2[grid(32768)](buf24, primals_5, 32768, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf25 = extern_kernels.convolution(buf24, primals_6, stride=(1, 1), padding=(2, 2), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf25, (4, 3, 16, 16), (768, 256, 16, 1)) buf26 = buf25 del buf25 triton_poi_fused_convolution_3[grid(3072)](buf26, primals_7, 3072, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 return buf26, primals_2, primals_4, primals_6, buf20, buf22, buf24 def get_root_logger(log_file=None, log_level=logging.INFO): """Get the root logger. The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If `log_file` is specified, a FileHandler will also be added. The name of the root logger is the top-level package name, e.g., "mmedit". Args: log_file (str | None): The log filename. If specified, a FileHandler will be added to the root logger. log_level (int): The root logger level. Note that only the process of rank 0 is affected, while other processes will set the level to "Error" and be silent most of the time. Returns: logging.Logger: The root logger. """ logger = get_logger(__name__.split('.')[0], log_file, log_level) return logger class SRCNNNew(nn.Module): """SRCNN network structure for image super resolution. SRCNN has three conv layers. For each layer, we can define the `in_channels`, `out_channels` and `kernel_size`. The input image will first be upsampled with a bicubic upsampler, and then super-resolved in the HR spatial size. Paper: Learning a Deep Convolutional Network for Image Super-Resolution. Args: channels (tuple[int]): A tuple of channel numbers for each layer including channels of input and output . Default: (3, 64, 32, 3). kernel_sizes (tuple[int]): A tuple of kernel sizes for each conv layer. Default: (9, 1, 5). upscale_factor (int): Upsampling factor. Default: 4. """ def __init__(self, channels=(3, 64, 32, 3), kernel_sizes=(9, 1, 5), upscale_factor=4): super().__init__() assert len(channels ) == 4, f'The length of channel tuple should be 4, but got {len(channels)}' assert len(kernel_sizes ) == 3, f'The length of kernel tuple should be 3, but got {len(kernel_sizes)}' self.upscale_factor = upscale_factor self.img_upsampler = nn.Upsample(scale_factor=self.upscale_factor, mode='bicubic', align_corners=False) self.conv1 = nn.Conv2d(channels[0], channels[1], kernel_size= kernel_sizes[0], padding=kernel_sizes[0] // 2) self.conv2 = nn.Conv2d(channels[1], channels[2], kernel_size= kernel_sizes[1], padding=kernel_sizes[1] // 2) self.conv3 = nn.Conv2d(channels[2], channels[3], kernel_size= kernel_sizes[2], padding=kernel_sizes[2] // 2) self.relu = nn.ReLU() def init_weights(self, pretrained=None, strict=True): """Init weights for models. Args: pretrained (str, optional): Path for pretrained weights. If given None, pretrained weights will not be loaded. Defaults to None. strict (boo, optional): Whether strictly load the pretrained model. Defaults to True. """ if isinstance(pretrained, str): logger = get_root_logger() load_checkpoint(self, pretrained, strict=strict, logger=logger) elif pretrained is None: pass else: raise TypeError( f'"pretrained" must be a str or None. But received {type(pretrained)}.' ) 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_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
Juggernaut93/mmediting
SRCNN
false
13,928
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
SnakeHyperSolver
import torch import torch.nn as nn from torch import sin from torch import pow from torch.nn import Parameter from torch.distributions.exponential import Exponential class Snake(nn.Module): """ Implementation of the serpentine-like sine-based periodic activation function .. math:: Snake_a := x + rac{1}{a} sin^2(ax) = x - rac{1}{2a}cos{2ax} + rac{1}{2a} Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - a - trainable parameter References: - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: https://arxiv.org/abs/2006.08195 Examples: >>> a1 = snake(256) >>> x = torch.randn(256) >>> x = a1(x) """ def __init__(self, in_features, a=None, trainable=True): """ Initialization. Args: in_features: shape of the input a: trainable parameter trainable: sets `a` as a trainable parameter `a` is initialized to 1 by default, higher values = higher-frequency, 5-50 is a good starting point if you already think your data is periodic, consider starting lower e.g. 0.5 if you think not, but don't worry, `a` will be trained along with the rest of your model. """ super(Snake, self).__init__() self.in_features = in_features if isinstance(in_features, list) else [ in_features] if a is not None: self.a = Parameter(torch.ones(self.in_features) * a) else: m = Exponential(torch.tensor([0.1])) self.a = Parameter(m.rsample(self.in_features).squeeze()) self.a.requiresGrad = trainable def forward(self, x): """ Forward pass of the function. Applies the function to the input elementwise. Snake ∶= x + 1/a* sin^2 (xa) """ return x + 1.0 / self.a * pow(sin(x * self.a), 2) class SnakeHyperSolver(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = Snake(hidden_dim) self.a2 = Snake(hidden_dim) def forward(self, x): x = self.a1(self.fc1(x)) x = self.a2(self.fc2(x)) x = self.fc3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_dim': 4, 'out_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn from torch import sin from torch import pow from torch.nn import Parameter from torch.distributions.exponential import Exponential assert_size_stride = torch._C._dynamo.guards.assert_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_pow_reciprocal_sin_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 32 tmp0 = tl.load(in_ptr0 + x2, None) tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last') tmp2 = tl.full([1], 1, tl.int32) tmp3 = tmp2 / tmp1 tmp4 = 1.0 tmp5 = tmp3 * tmp4 tmp6 = tmp0 * tmp1 tmp7 = tl_math.sin(tmp6) tmp8 = tmp7 * tmp7 tmp9 = tmp5 * tmp8 tmp10 = tmp0 + tmp9 tl.store(out_ptr0 + x2, tmp10, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (32, 4), (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,), (1,)) assert_size_stride(primals_5, (32, 32), (32, 1)) assert_size_stride(primals_6, (32,), (1,)) assert_size_stride(primals_7, (32,), (1,)) assert_size_stride(primals_8, (4, 32), (32, 1)) assert_size_stride(primals_9, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 32), (32, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 32), (1, 4), 0), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch. float32) get_raw_stream(0) triton_poi_fused_add_mul_pow_reciprocal_sin_0[grid(2048)](buf0, primals_4, buf1, 2048, XBLOCK=256, num_warps=4, num_stages=1) buf2 = empty_strided_cuda((64, 32), (32, 1), torch.float32) extern_kernels.addmm(primals_6, reinterpret_tensor(buf1, (64, 32), (32, 1), 0), reinterpret_tensor(primals_5, (32, 32), (1, 32), 0 ), alpha=1, beta=1, out=buf2) del primals_6 buf3 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch. float32) triton_poi_fused_add_mul_pow_reciprocal_sin_0[grid(2048)](buf2, primals_7, buf3, 2048, XBLOCK=256, num_warps=4, num_stages=1) buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_9, reinterpret_tensor(buf3, (64, 32), (32, 1), 0), reinterpret_tensor(primals_8, (32, 4), (1, 32), 0), alpha=1, beta=1, out=buf4) del primals_9 return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), primals_4, primals_7, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0, reinterpret_tensor(buf1, (64, 32), (32, 1), 0 ), buf2, reinterpret_tensor(buf3, (64, 32), (32, 1), 0 ), primals_8, primals_5 class Snake(nn.Module): """ Implementation of the serpentine-like sine-based periodic activation function .. math:: Snake_a := x + rac{1}{a} sin^2(ax) = x - rac{1}{2a}cos{2ax} + rac{1}{2a} Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - a - trainable parameter References: - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: https://arxiv.org/abs/2006.08195 Examples: >>> a1 = snake(256) >>> x = torch.randn(256) >>> x = a1(x) """ def __init__(self, in_features, a=None, trainable=True): """ Initialization. Args: in_features: shape of the input a: trainable parameter trainable: sets `a` as a trainable parameter `a` is initialized to 1 by default, higher values = higher-frequency, 5-50 is a good starting point if you already think your data is periodic, consider starting lower e.g. 0.5 if you think not, but don't worry, `a` will be trained along with the rest of your model. """ super(Snake, self).__init__() self.in_features = in_features if isinstance(in_features, list) else [ in_features] if a is not None: self.a = Parameter(torch.ones(self.in_features) * a) else: m = Exponential(torch.tensor([0.1])) self.a = Parameter(m.rsample(self.in_features).squeeze()) self.a.requiresGrad = trainable def forward(self, x): """ Forward pass of the function. Applies the function to the input elementwise. Snake ∶= x + 1/a* sin^2 (xa) """ return x + 1.0 / self.a * pow(sin(x * self.a), 2) class SnakeHyperSolverNew(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim=32): super().__init__() self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, out_dim) self.a1 = Snake(hidden_dim) self.a2 = Snake(hidden_dim) def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_5 = self.fc2.weight primals_4 = self.fc2.bias primals_8 = self.fc3.weight primals_9 = self.fc3.bias primals_6 = self.a1.a primals_7 = self.a2.a 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]
Juju-botu/diffeqml-research
SnakeHyperSolver
false
13,929
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
RLFeatPreprocessNet
import torch from torch import nn import torch.nn.parallel class RLFeatPreprocessNet(nn.Module): def __init__(self, feature_size, embed_size, box_info_size, overlap_info_size, output_size): super(RLFeatPreprocessNet, self).__init__() self.feature_size = feature_size self.embed_size = embed_size self.box_info_size = box_info_size self.overlap_info_size = overlap_info_size self.output_size = output_size self.resize_feat = nn.Linear(self.feature_size, int(output_size / 4)) self.resize_embed = nn.Linear(self.embed_size, int(output_size / 4)) self.resize_box = nn.Linear(self.box_info_size, int(output_size / 4)) self.resize_overlap = nn.Linear(self.overlap_info_size, int( output_size / 4)) self.resize_feat.weight.data.normal_(0, 0.001) self.resize_embed.weight.data.normal_(0, 0.01) self.resize_box.weight.data.normal_(0, 1) self.resize_overlap.weight.data.normal_(0, 1) self.resize_feat.bias.data.zero_() self.resize_embed.bias.data.zero_() self.resize_box.bias.data.zero_() self.resize_overlap.bias.data.zero_() def forward(self, obj_feat, obj_embed, box_info, overlap_info): resized_obj = self.resize_feat(obj_feat) resized_embed = self.resize_embed(obj_embed) resized_box = self.resize_box(box_info) resized_overlap = self.resize_overlap(overlap_info) output_feat = torch.cat((resized_obj, resized_embed, resized_box, resized_overlap), 1) return output_feat 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 [[], {'feature_size': 4, 'embed_size': 4, 'box_info_size': 4, 'overlap_info_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 import nn import torch.nn.parallel assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_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 x1 = xindex // 4 % 16 x0 = xindex % 4 x2 = xindex // 64 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr1 + (x0 + 4 * (-4 + x1) + 16 * x2), tmp9 & xmask, other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr2 + (x0 + 4 * (-8 + x1) + 16 * x2), tmp14 & xmask, other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp19 = tl.load(in_ptr3 + (x0 + 4 * (-12 + x1) + 16 * x2), tmp16 & xmask, other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tl.store(out_ptr0 + x3, tmp22, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12 ) = args args.clear() assert_size_stride(primals_1, (1, 4), (4, 1)) assert_size_stride(primals_2, (1,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (1, 4), (4, 1)) assert_size_stride(primals_5, (1,), (1,)) assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_7, (1, 4), (4, 1)) assert_size_stride(primals_8, (1,), (1,)) assert_size_stride(primals_9, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_10, (1, 4), (4, 1)) assert_size_stride(primals_11, (1,), (1,)) assert_size_stride(primals_12, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0 ), alpha=1, beta=1, out=buf1) del primals_1 del primals_2 buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (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 buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_8, reinterpret_tensor(primals_9, (64, 4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 1), (1, 4), 0 ), alpha=1, beta=1, out=buf5) del primals_7 del primals_8 buf7 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_11, reinterpret_tensor(primals_12, (64, 4), (4, 1), 0), reinterpret_tensor(primals_10, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf7) del primals_10 del primals_11 buf8 = empty_strided_cuda((4, 16, 4, 1), (64, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(256)](buf1, buf3, buf5, buf7, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf1 del buf3 del buf5 del buf7 return buf8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0 ), reinterpret_tensor(primals_9, (64, 4), (4, 1), 0 ), reinterpret_tensor(primals_12, (64, 4), (4, 1), 0) class RLFeatPreprocessNetNew(nn.Module): def __init__(self, feature_size, embed_size, box_info_size, overlap_info_size, output_size): super(RLFeatPreprocessNetNew, self).__init__() self.feature_size = feature_size self.embed_size = embed_size self.box_info_size = box_info_size self.overlap_info_size = overlap_info_size self.output_size = output_size self.resize_feat = nn.Linear(self.feature_size, int(output_size / 4)) self.resize_embed = nn.Linear(self.embed_size, int(output_size / 4)) self.resize_box = nn.Linear(self.box_info_size, int(output_size / 4)) self.resize_overlap = nn.Linear(self.overlap_info_size, int( output_size / 4)) self.resize_feat.weight.data.normal_(0, 0.001) self.resize_embed.weight.data.normal_(0, 0.01) self.resize_box.weight.data.normal_(0, 1) self.resize_overlap.weight.data.normal_(0, 1) self.resize_feat.bias.data.zero_() self.resize_embed.bias.data.zero_() self.resize_box.bias.data.zero_() self.resize_overlap.bias.data.zero_() def forward(self, input_0, input_1, input_2, input_3): primals_1 = self.resize_feat.weight primals_2 = self.resize_feat.bias primals_4 = self.resize_embed.weight primals_5 = self.resize_embed.bias primals_7 = self.resize_box.weight primals_8 = self.resize_box.bias primals_10 = self.resize_overlap.weight primals_11 = self.resize_overlap.bias primals_3 = input_0 primals_6 = input_1 primals_9 = input_2 primals_12 = input_3 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12]) return output[0]
KaihuaTang/VCTree-Scene-Graph-Generation
RLFeatPreprocessNet
false
13,930
[ "MIT" ]
109
75bc30543dbb5a869acff65b2183efa7ee4ac35d
https://github.com/KaihuaTang/VCTree-Scene-Graph-Generation/tree/75bc30543dbb5a869acff65b2183efa7ee4ac35d
Softplus
import torch import numpy as np from torch.utils.data import Dataset as Dataset import torch.nn as nn import torch.utils.data def activation_shifting(activation): def shifted_activation(x): return activation(x) - activation(torch.zeros_like(x)) return shifted_activation def cauchy_softplus(x): pi = np.pi return (x * pi - torch.log(x ** 2 + 1) + 2 * x * torch.atan(x)) / (2 * pi) def gaussian_softplus(x): z = np.sqrt(np.pi / 2) return (z * x * torch.erf(x / np.sqrt(2)) + torch.exp(-x ** 2 / 2) + z * x ) / (2 * z) def gaussian_softplus2(x): z = np.sqrt(np.pi / 2) return (z * x * torch.erf(x / np.sqrt(2)) + torch.exp(-x ** 2 / 2) + z * x ) / z def get_softplus(softplus_type='softplus', zero_softplus=False): if softplus_type == 'softplus': act = nn.functional.softplus elif softplus_type == 'gaussian_softplus': act = gaussian_softplus elif softplus_type == 'gaussian_softplus2': act = gaussian_softplus2 elif softplus_type == 'laplace_softplus': act = gaussian_softplus elif softplus_type == 'cauchy_softplus': act = cauchy_softplus else: raise NotImplementedError( f'softplus type {softplus_type} not supported.') if zero_softplus: act = activation_shifting(act) return act class Softplus(nn.Module): def __init__(self, softplus_type='softplus', zero_softplus=False): super(Softplus, self).__init__() self.softplus_type = softplus_type self.zero_softplus = zero_softplus def forward(self, x): return get_softplus(self.softplus_type, self.zero_softplus)(x) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import numpy as np from torch.utils.data import Dataset as Dataset 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_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) tl.store(out_ptr0 + x0, tmp5, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_softplus_0[grid(256)](arg0_1, buf0, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg0_1 return buf0, def activation_shifting(activation): def shifted_activation(x): return activation(x) - activation(torch.zeros_like(x)) return shifted_activation def cauchy_softplus(x): pi = np.pi return (x * pi - torch.log(x ** 2 + 1) + 2 * x * torch.atan(x)) / (2 * pi) def gaussian_softplus(x): z = np.sqrt(np.pi / 2) return (z * x * torch.erf(x / np.sqrt(2)) + torch.exp(-x ** 2 / 2) + z * x ) / (2 * z) def gaussian_softplus2(x): z = np.sqrt(np.pi / 2) return (z * x * torch.erf(x / np.sqrt(2)) + torch.exp(-x ** 2 / 2) + z * x ) / z def get_softplus(softplus_type='softplus', zero_softplus=False): if softplus_type == 'softplus': act = nn.functional.softplus elif softplus_type == 'gaussian_softplus': act = gaussian_softplus elif softplus_type == 'gaussian_softplus2': act = gaussian_softplus2 elif softplus_type == 'laplace_softplus': act = gaussian_softplus elif softplus_type == 'cauchy_softplus': act = cauchy_softplus else: raise NotImplementedError( f'softplus type {softplus_type} not supported.') if zero_softplus: act = activation_shifting(act) return act class SoftplusNew(nn.Module): def __init__(self, softplus_type='softplus', zero_softplus=False): super(SoftplusNew, self).__init__() self.softplus_type = softplus_type self.zero_softplus = zero_softplus def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KelvinKan/CP-Flow
Softplus
false
13,931
[ "MIT" ]
64
d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
https://github.com/KelvinKan/CP-Flow/tree/d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
MaxPool3x3
import torch import torch.nn as nn class MaxPool3x3(nn.Module): """3x3 max pool with no subsampling.""" def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super(MaxPool3x3, self).__init__() self.maxpool = nn.MaxPool2d(kernel_size, stride, padding) def forward(self, x): x = self.maxpool(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel 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=float('-inf')) tmp12 = x0 tmp13 = tmp12 >= tmp1 tmp14 = tmp12 < tmp3 tmp15 = tmp13 & tmp14 tmp16 = tmp5 & tmp15 tmp17 = tl.load(in_ptr0 + (-4 + x4), tmp16 & xmask, other=float('-inf')) tmp18 = triton_helpers.maximum(tmp17, tmp11) tmp19 = 1 + x0 tmp20 = tmp19 >= tmp1 tmp21 = tmp19 < tmp3 tmp22 = tmp20 & tmp21 tmp23 = tmp5 & tmp22 tmp24 = tl.load(in_ptr0 + (-3 + x4), tmp23 & xmask, other=float('-inf')) tmp25 = triton_helpers.maximum(tmp24, tmp18) tmp26 = x1 tmp27 = tmp26 >= tmp1 tmp28 = tmp26 < tmp3 tmp29 = tmp27 & tmp28 tmp30 = tmp29 & tmp9 tmp31 = tl.load(in_ptr0 + (-1 + x4), tmp30 & xmask, other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp25) tmp33 = tmp29 & tmp15 tmp34 = tl.load(in_ptr0 + x4, tmp33 & xmask, other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp29 & tmp22 tmp37 = tl.load(in_ptr0 + (1 + x4), tmp36 & xmask, other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = 1 + x1 tmp40 = tmp39 >= tmp1 tmp41 = tmp39 < tmp3 tmp42 = tmp40 & tmp41 tmp43 = tmp42 & tmp9 tmp44 = tl.load(in_ptr0 + (3 + x4), tmp43 & xmask, other=float('-inf')) tmp45 = triton_helpers.maximum(tmp44, tmp38) tmp46 = tmp42 & tmp15 tmp47 = tl.load(in_ptr0 + (4 + x4), tmp46 & xmask, other=float('-inf')) tmp48 = triton_helpers.maximum(tmp47, tmp45) tmp49 = tmp42 & tmp22 tmp50 = tl.load(in_ptr0 + (5 + x4), tmp49 & xmask, other=float('-inf')) tmp51 = triton_helpers.maximum(tmp50, tmp48) tl.store(out_ptr0 + x4, tmp51, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class MaxPool3x3New(nn.Module): """3x3 max pool with no subsampling.""" def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super(MaxPool3x3New, self).__init__() self.maxpool = nn.MaxPool2d(kernel_size, stride, padding) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KelvinYang0320/nas-without-training
MaxPool3x3
false
13,932
[ "MIT" ]
385
5ed77a06726a73233a5a93b8f70a7172ce570029
https://github.com/KelvinYang0320/nas-without-training/tree/5ed77a06726a73233a5a93b8f70a7172ce570029
PseudoCoord
import torch import torch.nn as nn import torch.utils.data class PseudoCoord(nn.Module): def __init__(self): super(PseudoCoord, self).__init__() def forward(self, b): """ Input: b: bounding box [batch, num_obj, 4] (x1,y1,x2,y2) Output: pseudo_coord [batch, num_obj, num_obj, 2] (rho, theta) """ batch_size, num_obj, _ = b.shape centers = (b[:, :, 2:] + b[:, :, :2]) * 0.5 relative_coord = centers.view(batch_size, num_obj, 1, 2 ) - centers.view(batch_size, 1, num_obj, 2) rho = torch.sqrt(relative_coord[:, :, :, 0] ** 2 + relative_coord[:, :, :, 1] ** 2) theta = torch.atan2(relative_coord[:, :, :, 0], relative_coord[:, :, :, 1]) new_coord = torch.cat((rho.unsqueeze(-1), theta.unsqueeze(-1)), dim=-1) return new_coord def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import 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 @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 2 x5 = xindex // 8 x1 = xindex // 2 % 4 x3 = xindex // 32 x6 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (2 + 4 * x5), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tl.load(in_ptr0 + 4 * x5, tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = 0.5 tmp9 = tmp7 * tmp8 tmp10 = tl.load(in_ptr0 + (2 + 4 * x1 + 16 * x3), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tl.load(in_ptr0 + (4 * x1 + 16 * x3), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp12 = tmp10 + tmp11 tmp13 = tmp12 * tmp8 tmp14 = tmp9 - tmp13 tmp15 = tmp14 * tmp14 tmp16 = tl.load(in_ptr0 + (3 + 4 * x5), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp17 = tl.load(in_ptr0 + (1 + 4 * x5), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp18 = tmp16 + tmp17 tmp19 = tmp18 * tmp8 tmp20 = tl.load(in_ptr0 + (3 + 4 * x1 + 16 * x3), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp21 = tl.load(in_ptr0 + (1 + 4 * x1 + 16 * x3), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp22 = tmp20 + tmp21 tmp23 = tmp22 * tmp8 tmp24 = tmp19 - tmp23 tmp25 = tmp24 * tmp24 tmp26 = tmp15 + tmp25 tmp27 = libdevice.sqrt(tmp26) tmp28 = tl.full(tmp27.shape, 0.0, tmp27.dtype) tmp29 = tl.where(tmp4, tmp27, tmp28) tmp30 = tmp0 >= tmp3 tl.full([1], 2, tl.int64) tmp33 = tl.load(in_ptr0 + (2 + 4 * x5), tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp34 = tl.load(in_ptr0 + 4 * x5, tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp35 = tmp33 + tmp34 tmp36 = tmp35 * tmp8 tmp37 = tl.load(in_ptr0 + (2 + 4 * x1 + 16 * x3), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp38 = tl.load(in_ptr0 + (4 * x1 + 16 * x3), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp39 = tmp37 + tmp38 tmp40 = tmp39 * tmp8 tmp41 = tmp36 - tmp40 tmp42 = tl.load(in_ptr0 + (3 + 4 * x5), tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp43 = tl.load(in_ptr0 + (1 + 4 * x5), tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp44 = tmp42 + tmp43 tmp45 = tmp44 * tmp8 tmp46 = tl.load(in_ptr0 + (3 + 4 * x1 + 16 * x3), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp47 = tl.load(in_ptr0 + (1 + 4 * x1 + 16 * x3), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp48 = tmp46 + tmp47 tmp49 = tmp48 * tmp8 tmp50 = tmp45 - tmp49 tmp51 = libdevice.atan2(tmp41, tmp50) tmp52 = tl.full(tmp51.shape, 0.0, tmp51.dtype) tmp53 = tl.where(tmp30, tmp51, tmp52) tmp54 = tl.where(tmp4, tmp29, tmp53) tl.store(out_ptr0 + x6, tmp54, 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, 4, 2), (32, 8, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(128)](arg0_1, buf0, 128, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class PseudoCoordNew(nn.Module): def __init__(self): super(PseudoCoordNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch
PseudoCoord
false
13,933
[ "MIT" ]
298
52e1ba5a7f3b88c617115ccc755e2e7868e8de2b
https://github.com/KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch/tree/52e1ba5a7f3b88c617115ccc755e2e7868e8de2b
Conv2d
from torch.autograd import Function import torch import numpy as np import torchvision.transforms.functional as F import torch.nn as nn import torch.nn.functional as F def _setup_kernel(k): k = np.asarray(k, dtype=np.float32) if k.ndim == 1: k = np.outer(k, k) k /= np.sum(k) assert k.ndim == 2 assert k.shape[0] == k.shape[1] return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def conv_downsample_2d(x, w, k=None, factor=2, gain=1): """Fused `tf.nn.conv2d()` followed by `downsample_2d()`. Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary order. Args: x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`. w: Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be performed by `inChannels = x.shape[0] // numGroups`. k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which corresponds to average pooling. factor: Integer downsampling factor (default: 2). gain: Scaling factor for signal magnitude (default: 1.0). Returns: Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same datatype as `x`. """ assert isinstance(factor, int) and factor >= 1 _outC, _inC, convH, convW = w.shape assert convW == convH if k is None: k = [1] * factor k = _setup_kernel(k) * gain p = k.shape[0] - factor + (convW - 1) s = [factor, factor] x = upfirdn2d(x, torch.tensor(k, device=x.device), pad=((p + 1) // 2, p // 2)) return F.conv2d(x, w, stride=s, padding=0) def _shape(x, dim): return x.shape[dim] def upsample_conv_2d(x, w, k=None, factor=2, gain=1): """Fused `upsample_2d()` followed by `tf.nn.conv2d()`. Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary order. Args: x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`. w: Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be performed by `inChannels = x.shape[0] // numGroups`. k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which corresponds to nearest-neighbor upsampling. factor: Integer upsampling factor (default: 2). gain: Scaling factor for signal magnitude (default: 1.0). Returns: Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same datatype as `x`. """ assert isinstance(factor, int) and factor >= 1 assert len(w.shape) == 4 convH = w.shape[2] convW = w.shape[3] inC = w.shape[1] w.shape[0] assert convW == convH if k is None: k = [1] * factor k = _setup_kernel(k) * (gain * factor ** 2) p = k.shape[0] - factor - (convW - 1) stride = factor, factor stride = [1, 1, factor, factor] output_shape = (_shape(x, 2) - 1) * factor + convH, (_shape(x, 3) - 1 ) * factor + convW output_padding = output_shape[0] - (_shape(x, 2) - 1) * stride[0 ] - convH, output_shape[1] - (_shape(x, 3) - 1) * stride[1] - convW assert output_padding[0] >= 0 and output_padding[1] >= 0 num_groups = _shape(x, 1) // inC w = torch.reshape(w, (num_groups, -1, inC, convH, convW)) w = w[..., ::-1, ::-1].permute(0, 2, 1, 3, 4) w = torch.reshape(w, (num_groups * inC, -1, convH, convW)) x = F.conv_transpose2d(x, w, stride=stride, output_padding= output_padding, padding=0) return upfirdn2d(x, torch.tensor(k, device=x.device), pad=((p + 1) // 2 + factor - 1, p // 2 + 1)) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class Conv2d(nn.Module): """Conv2d layer with optimal upsampling and downsampling (StyleGAN2).""" def __init__(self, in_ch, out_ch, kernel, up=False, down=False, resample_kernel=(1, 3, 3, 1), use_bias=True, kernel_init=None): super().__init__() assert not (up and down) assert kernel >= 1 and kernel % 2 == 1 self.weight = nn.Parameter(torch.zeros(out_ch, in_ch, kernel, kernel)) if kernel_init is not None: self.weight.data = kernel_init(self.weight.data.shape) if use_bias: self.bias = nn.Parameter(torch.zeros(out_ch)) self.up = up self.down = down self.resample_kernel = resample_kernel self.kernel = kernel self.use_bias = use_bias def forward(self, x): if self.up: x = upsample_conv_2d(x, self.weight, k=self.resample_kernel) elif self.down: x = conv_downsample_2d(x, self.weight, k=self.resample_kernel) else: x = F.conv2d(x, self.weight, stride=1, padding=self.kernel // 2) if self.use_bias: x = x + self.bias.reshape(1, -1, 1, 1) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_ch': 4, 'out_ch': 4, 'kernel': 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.autograd import Function import numpy as np import torchvision.transforms.functional as F import torch.nn as nn import torch.nn.functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride @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 x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_add_0[grid(256)](buf1, primals_3, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 return buf1, primals_1, primals_2 def _setup_kernel(k): k = np.asarray(k, dtype=np.float32) if k.ndim == 1: k = np.outer(k, k) k /= np.sum(k) assert k.ndim == 2 assert k.shape[0] == k.shape[1] return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def conv_downsample_2d(x, w, k=None, factor=2, gain=1): """Fused `tf.nn.conv2d()` followed by `downsample_2d()`. Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary order. Args: x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`. w: Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be performed by `inChannels = x.shape[0] // numGroups`. k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which corresponds to average pooling. factor: Integer downsampling factor (default: 2). gain: Scaling factor for signal magnitude (default: 1.0). Returns: Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same datatype as `x`. """ assert isinstance(factor, int) and factor >= 1 _outC, _inC, convH, convW = w.shape assert convW == convH if k is None: k = [1] * factor k = _setup_kernel(k) * gain p = k.shape[0] - factor + (convW - 1) s = [factor, factor] x = upfirdn2d(x, torch.tensor(k, device=x.device), pad=((p + 1) // 2, p // 2)) return F.conv2d(x, w, stride=s, padding=0) def _shape(x, dim): return x.shape[dim] def upsample_conv_2d(x, w, k=None, factor=2, gain=1): """Fused `upsample_2d()` followed by `tf.nn.conv2d()`. Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary order. Args: x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`. w: Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be performed by `inChannels = x.shape[0] // numGroups`. k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which corresponds to nearest-neighbor upsampling. factor: Integer upsampling factor (default: 2). gain: Scaling factor for signal magnitude (default: 1.0). Returns: Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same datatype as `x`. """ assert isinstance(factor, int) and factor >= 1 assert len(w.shape) == 4 convH = w.shape[2] convW = w.shape[3] inC = w.shape[1] w.shape[0] assert convW == convH if k is None: k = [1] * factor k = _setup_kernel(k) * (gain * factor ** 2) p = k.shape[0] - factor - (convW - 1) stride = factor, factor stride = [1, 1, factor, factor] output_shape = (_shape(x, 2) - 1) * factor + convH, (_shape(x, 3) - 1 ) * factor + convW output_padding = output_shape[0] - (_shape(x, 2) - 1) * stride[0 ] - convH, output_shape[1] - (_shape(x, 3) - 1) * stride[1] - convW assert output_padding[0] >= 0 and output_padding[1] >= 0 num_groups = _shape(x, 1) // inC w = torch.reshape(w, (num_groups, -1, inC, convH, convW)) w = w[..., ::-1, ::-1].permute(0, 2, 1, 3, 4) w = torch.reshape(w, (num_groups * inC, -1, convH, convW)) x = F.conv_transpose2d(x, w, stride=stride, output_padding= output_padding, padding=0) return upfirdn2d(x, torch.tensor(k, device=x.device), pad=((p + 1) // 2 + factor - 1, p // 2 + 1)) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class Conv2dNew(nn.Module): """Conv2d layer with optimal upsampling and downsampling (StyleGAN2).""" def __init__(self, in_ch, out_ch, kernel, up=False, down=False, resample_kernel=(1, 3, 3, 1), use_bias=True, kernel_init=None): super().__init__() assert not (up and down) assert kernel >= 1 and kernel % 2 == 1 self.weight = nn.Parameter(torch.zeros(out_ch, in_ch, kernel, kernel)) if kernel_init is not None: self.weight.data = kernel_init(self.weight.data.shape) if use_bias: self.bias = nn.Parameter(torch.zeros(out_ch)) self.up = up self.down = down self.resample_kernel = resample_kernel self.kernel = kernel self.use_bias = use_bias def forward(self, input_0): primals_1 = self.weight primals_3 = self.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
DeepTitan/PNDM
Conv2d
false
13,934
[ "Apache-2.0" ]
61
4037a4f40011c9a0d47b92303e64d47fcc7ed56a
https://github.com/DeepTitan/PNDM/tree/4037a4f40011c9a0d47b92303e64d47fcc7ed56a
SymmSoftplus
import torch from torch.utils.data import Dataset as Dataset import torch.utils.data def symm_softplus(x, softplus_=torch.nn.functional.softplus): return softplus_(x) - 0.5 * x class SymmSoftplus(torch.nn.Module): def forward(self, x): return symm_softplus(x) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math from torch.utils.data import Dataset as Dataset 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_softplus_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 = 20.0 tmp2 = tmp0 > tmp1 tmp3 = tl_math.exp(tmp0) tmp4 = libdevice.log1p(tmp3) tmp5 = tl.where(tmp2, tmp0, tmp4) tmp6 = 0.5 tmp7 = tmp0 * tmp6 tmp8 = tmp5 - tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_softplus_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, def symm_softplus(x, softplus_=torch.nn.functional.softplus): return softplus_(x) - 0.5 * x class SymmSoftplusNew(torch.nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KelvinKan/CP-Flow
SymmSoftplus
false
13,935
[ "MIT" ]
64
d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
https://github.com/KelvinKan/CP-Flow/tree/d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
UpBlock
import torch import torch.nn as nn class UpBlock(nn.Module): def __init__(self, in_f, out_f, stride=2, add_blur=False): super(UpBlock, self).__init__() self.shuffle = nn.ConvTranspose2d(in_f, out_f, kernel_size=3, stride=stride, padding=0) self.has_blur = add_blur if self.has_blur: self.blur = nn.AvgPool2d(2, 1) def forward(self, x): x = self.shuffle(x) if self.has_blur: x = self.blur(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_f': 4, 'out_f': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride @triton.jit def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 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 = 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=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 9, 9), (324, 81, 9, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(1296)](buf1, primals_2, 1296, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 return buf1, primals_1, primals_3 class UpBlockNew(nn.Module): def __init__(self, in_f, out_f, stride=2, add_blur=False): super(UpBlockNew, self).__init__() self.shuffle = nn.ConvTranspose2d(in_f, out_f, kernel_size=3, stride=stride, padding=0) self.has_blur = add_blur if self.has_blur: self.blur = nn.AvgPool2d(2, 1) def forward(self, input_0): primals_1 = self.shuffle.weight primals_2 = self.shuffle.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Kash6/AnimeBot
UpBlock
false
13,936
[ "MIT" ]
177
99c68bdb03501d6919669c4aabbb9fe5ea92ec8e
https://github.com/Kash6/AnimeBot/tree/99c68bdb03501d6919669c4aabbb9fe5ea92ec8e
FCNet
import torch import torch.nn as nn from torch.nn.utils import weight_norm import torch.utils.data class FCNet(nn.Module): def __init__(self, in_size, out_size, activate=None, drop=0.0): super(FCNet, self).__init__() self.lin = weight_norm(nn.Linear(in_size, out_size), dim=None) self.drop_value = drop self.drop = nn.Dropout(drop) self.activate = activate.lower() if activate is not None else None if activate == 'relu': self.ac_fn = nn.ReLU() elif activate == 'sigmoid': self.ac_fn = nn.Sigmoid() elif activate == 'tanh': self.ac_fn = nn.Tanh() def forward(self, x): if self.drop_value > 0: x = self.drop(x) x = self.lin(x) if self.activate is not None: x = self.ac_fn(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_size': 4, 'out_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn from torch.nn.utils import weight_norm 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_per_fused_div_mul_norm_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp6 = tl.load(in_ptr1 + 0) tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK]) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = libdevice.sqrt(tmp4) tmp8 = tmp7 / tmp5 tmp9 = tmp0 * tmp8 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp5, None) tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp9, None) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (), ()) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_per_fused_div_mul_norm_0[grid(1)](buf1, primals_2, primals_1, buf2, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0), reinterpret_tensor(buf2, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_3 return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), buf2, primals_1, primals_2, buf1, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0) class FCNetNew(nn.Module): def __init__(self, in_size, out_size, activate=None, drop=0.0): super(FCNetNew, self).__init__() self.lin = weight_norm(nn.Linear(in_size, out_size), dim=None) self.drop_value = drop self.drop = nn.Dropout(drop) self.activate = activate.lower() if activate is not None else None if activate == 'relu': self.ac_fn = nn.ReLU() elif activate == 'sigmoid': self.ac_fn = nn.Sigmoid() elif activate == 'tanh': self.ac_fn = nn.Tanh() def forward(self, input_0): primals_3 = self.lin.bias primals_1 = self.lin.weight_g primals_2 = self.lin.weight_v primals_4 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch
FCNet
false
13,937
[ "MIT" ]
298
52e1ba5a7f3b88c617115ccc755e2e7868e8de2b
https://github.com/KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch/tree/52e1ba5a7f3b88c617115ccc755e2e7868e8de2b
ModulatedToRGB
import torch import torch.nn as nn from copy import deepcopy from functools import partial from torch.nn import functional as F from torch.nn.init import _calculate_correct_fan def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul) return module def _make_kernel(k): k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k class EqualizedLR: """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. """ def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0 ): self.name = name self.mode = mode self.gain = gain self.lr_mul = lr_mul def compute_weight(self, module): """Compute weight with equalized learning rate. Args: module (nn.Module): A module that is wrapped with equalized lr. Returns: torch.Tensor: Updated weight. """ weight = getattr(module, self.name + '_orig') if weight.ndim == 5: fan = _calculate_correct_fan(weight[0], self.mode) else: assert weight.ndim <= 4 fan = _calculate_correct_fan(weight, self.mode) weight = weight * torch.tensor(self.gain, device=weight.device ) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device) ) * self.lr_mul return weight def __call__(self, module, inputs): """Standard interface for forward pre hooks.""" setattr(module, self.name, self.compute_weight(module)) @staticmethod def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Apply function. This function is to register an equalized learning rate hook in an ``nn.Module``. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ for _, hook in module._forward_pre_hooks.items(): if isinstance(hook, EqualizedLR): raise RuntimeError( f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.' ) fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul) weight = module._parameters[name] delattr(module, name) module.register_parameter(name + '_orig', weight) setattr(module, name, weight.data) module.register_forward_pre_hook(fn) return fn class EqualizedLRLinearModule(nn.Linear): """Equalized LR LinearModule. In this module, we adopt equalized lr in ``nn.Linear``. The equalized learning rate is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation Note that, the initialization of ``self.weight`` will be overwritten as :math:`\\mathcal{N}(0, 1)`. Args: equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``. If ``None``, equalized learning rate is ignored. Defaults to dict(mode='fan_in'). """ def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs): super(EqualizedLRLinearModule, self).__init__(*args, **kwargs) self.with_equlized_lr = equalized_lr_cfg is not None if self.with_equlized_lr: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if self.with_equlized_lr: equalized_lr(self, **equalized_lr_cfg) self._init_linear_weights() def _init_linear_weights(self): """Initialize linear weights as described in PGGAN.""" nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul) if self.bias is not None: nn.init.constant_(self.bias, 0.0) class EqualLinearActModule(nn.Module): """Equalized LR Linear Module with Activation Layer. Args: nn ([type]): [description] """ def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0), bias=True, bias_init=0.0, act_cfg=None, **kwargs): super(EqualLinearActModule, self).__init__() self.with_activation = act_cfg is not None self.linear = EqualizedLRLinearModule(*args, bias=False, equalized_lr_cfg=equalized_lr_cfg, **kwargs) if equalized_lr_cfg is not None: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if bias: self.bias = nn.Parameter(torch.zeros(self.linear.out_features). fill_(bias_init)) else: self.bias = None if self.with_activation: act_cfg = deepcopy(act_cfg) if act_cfg['type'] == 'fused_bias': self.act_type = act_cfg.pop('type') assert self.bias is not None self.activate = partial(fused_bias_leakyrelu, **act_cfg) else: self.act_type = 'normal' self.activate = build_activation_layer(act_cfg) else: self.act_type = None def forward(self, x): if x.ndim >= 3: x = x.reshape(x.size(0), -1) x = self.linear(x) if self.with_activation and self.act_type == 'fused_bias': x = self.activate(x, self.bias * self.lr_mul) elif self.bias is not None and self.with_activation: x = self.activate(x + self.bias * self.lr_mul) elif self.bias is not None: x = x + self.bias * self.lr_mul elif self.with_activation: x = self.activate(x) return x class Blur(nn.Module): def __init__(self, kernel, pad, upsample_factor=1): super(Blur, self).__init__() kernel = _make_kernel(kernel) if upsample_factor > 1: kernel = kernel * upsample_factor ** 2 self.register_buffer('kernel', kernel) self.pad = pad def forward(self, x): return upfirdn2d(x, self.kernel, pad=self.pad) class ModulatedConv2d(nn.Module): """Modulated Conv2d in StyleGANv2. Attention: #. ``style_bias`` is provided to check the difference between official TF implementation and other PyTorch implementation. In TF, Tero explicitly add the ``1.`` after style code, while unofficial implementation adopts bias initialization with ``1.``. Details can be found in: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py#L214 https://github.com/NVlabs/stylegan2/blob/master/training/networks_stylegan2.py#L99 """ def __init__(self, in_channels, out_channels, kernel_size, style_channels, demodulate=True, upsample=False, downsample=False, blur_kernel=[1, 3, 3, 1], equalized_lr_cfg=dict(mode='fan_in', lr_mul=1.0, gain=1.0), style_mod_cfg=dict(bias_init=1.0), style_bias=0.0, eps=1e-08): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.style_channels = style_channels self.demodulate = demodulate assert isinstance(self.kernel_size, int) and (self.kernel_size >= 1 and self.kernel_size % 2 == 1) self.upsample = upsample self.downsample = downsample self.style_bias = style_bias self.eps = eps style_mod_cfg = dict() if style_mod_cfg is None else style_mod_cfg self.style_modulation = EqualLinearActModule(style_channels, in_channels, **style_mod_cfg) lr_mul_ = 1.0 if equalized_lr_cfg is not None: lr_mul_ = equalized_lr_cfg.get('lr_mul', 1.0) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size).div_(lr_mul_)) if upsample: factor = 2 p = len(blur_kernel) - factor - (kernel_size - 1) pad0 = (p + 1) // 2 + factor - 1 pad1 = p // 2 + 1 self.blur = Blur(blur_kernel, (pad0, pad1), upsample_factor=factor) if downsample: factor = 2 p = len(blur_kernel) - factor + (kernel_size - 1) pad0 = (p + 1) // 2 pad1 = p // 2 self.blur = Blur(blur_kernel, pad=(pad0, pad1)) if equalized_lr_cfg is not None: equalized_lr(self, **equalized_lr_cfg) self.padding = kernel_size // 2 def forward(self, x, style): n, c, h, w = x.shape style = self.style_modulation(style).view(n, 1, c, 1, 1 ) + self.style_bias weight = self.weight * style if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(n, self.out_channels, 1, 1, 1) weight = weight.view(n * self.out_channels, c, self.kernel_size, self.kernel_size) if self.upsample: x = x.reshape(1, n * c, h, w) weight = weight.view(n, self.out_channels, c, self.kernel_size, self.kernel_size) weight = weight.transpose(1, 2).reshape(n * c, self. out_channels, self.kernel_size, self.kernel_size) x = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=n) x = x.reshape(n, self.out_channels, *x.shape[-2:]) x = self.blur(x) elif self.downsample: x = self.blur(x) x = x.view(1, n * self.in_channels, *x.shape[-2:]) x = F.conv2d(x, weight, stride=2, padding=0, groups=n) x = x.view(n, self.out_channels, *x.shape[-2:]) else: x = x.view(1, n * c, h, w) x = F.conv2d(x, weight, stride=1, padding=self.padding, groups=n) x = x.view(n, self.out_channels, *x.shape[-2:]) return x class UpsampleUpFIRDn(nn.Module): def __init__(self, kernel, factor=2): super(UpsampleUpFIRDn, self).__init__() self.factor = factor kernel = _make_kernel(kernel) * factor ** 2 self.register_buffer('kernel', kernel) p = kernel.shape[0] - factor pad0 = (p + 1) // 2 + factor - 1 pad1 = p // 2 self.pad = pad0, pad1 def forward(self, x): out = upfirdn2d(x, self.kernel, up=self.factor, down=1, pad=self.pad) return out class ModulatedToRGB(nn.Module): def __init__(self, in_channels, style_channels, out_channels=3, upsample=True, blur_kernel=[1, 3, 3, 1], style_mod_cfg=dict( bias_init=1.0), style_bias=0.0): super(ModulatedToRGB, self).__init__() if upsample: self.upsample = UpsampleUpFIRDn(blur_kernel) self.conv = ModulatedConv2d(in_channels, out_channels=out_channels, kernel_size=1, style_channels=style_channels, demodulate=False, style_mod_cfg=style_mod_cfg, style_bias=style_bias) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): out = self.conv(x, style) out = out + self.bias if skip is not None: skip = self.upsample(skip) out = out + skip return out def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'style_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 from copy import deepcopy from functools import partial from torch.nn import functional as F from torch.nn.init import _calculate_correct_fan assert_size_stride = torch._C._dynamo.guards.assert_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_sqrt_0(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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.5 tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_mul_sqrt_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.5 tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_add_mul_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 48 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex % 12 x0 = xindex % 4 x2 = xindex // 12 x4 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') 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 = 1.0 tmp4 = tmp2 * tmp3 tmp5 = tmp1 + tmp4 tmp6 = 0.0 tmp7 = tmp5 + tmp6 tmp8 = tmp0 * tmp7 tl.store(out_ptr0 + x4, tmp8, xmask) @triton.jit def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 3 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (1, 3, 4, 1, 1), (12, 4, 1, 1, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (1, 3, 1, 1), (3, 1, 1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((1, 3, 4, 1, 1), (12, 4, 1, 1, 1), torch. float32) get_raw_stream(0) triton_poi_fused_mul_sqrt_0[grid(12)](primals_1, buf0, 12, XBLOCK= 16, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sqrt_1[grid(16)](primals_4, buf1, 16, XBLOCK= 16, num_warps=1, num_stages=1) del primals_4 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(buf1, (4, 4), (1, 4 ), 0), out=buf2) buf3 = empty_strided_cuda((4, 3, 4, 1, 1), (12, 4, 1, 1, 1), torch. float32) triton_poi_fused_add_mul_2[grid(48)](buf0, buf2, primals_5, buf3, 48, XBLOCK=64, num_warps=1, num_stages=1) buf4 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1, 16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (12, 4, 1, 1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None) assert_size_stride(buf4, (1, 12, 4, 4), (192, 16, 4, 1)) buf5 = reinterpret_tensor(buf4, (4, 3, 4, 4), (48, 16, 4, 1), 0) del buf4 triton_poi_fused_add_3[grid(192)](buf5, primals_6, 192, XBLOCK=256, num_warps=4, num_stages=1) del primals_6 return (buf5, buf0, buf1, primals_3, primals_5, buf0, buf2, reinterpret_tensor(buf3, (12, 4, 1, 1), (4, 1, 1, 1), 0), reinterpret_tensor(primals_2, (1, 16, 4, 4), (256, 16, 4, 1), 0)) def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul) return module def _make_kernel(k): k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k class EqualizedLR: """Equalized Learning Rate. This trick is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation The general idea is to dynamically rescale the weight in training instead of in initializing so that the variance of the responses in each layer is guaranteed with some statistical properties. Note that this function is always combined with a convolution module which is initialized with :math:`\\mathcal{N}(0, 1)`. Args: name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. """ def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0 ): self.name = name self.mode = mode self.gain = gain self.lr_mul = lr_mul def compute_weight(self, module): """Compute weight with equalized learning rate. Args: module (nn.Module): A module that is wrapped with equalized lr. Returns: torch.Tensor: Updated weight. """ weight = getattr(module, self.name + '_orig') if weight.ndim == 5: fan = _calculate_correct_fan(weight[0], self.mode) else: assert weight.ndim <= 4 fan = _calculate_correct_fan(weight, self.mode) weight = weight * torch.tensor(self.gain, device=weight.device ) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device) ) * self.lr_mul return weight def __call__(self, module, inputs): """Standard interface for forward pre hooks.""" setattr(module, self.name, self.compute_weight(module)) @staticmethod def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0): """Apply function. This function is to register an equalized learning rate hook in an ``nn.Module``. Args: module (nn.Module): Module to be wrapped. name (str | optional): The name of weights. Defaults to 'weight'. mode (str, optional): The mode of computing ``fan`` which is the same as ``kaiming_init`` in pytorch. You can choose one from ['fan_in', 'fan_out']. Defaults to 'fan_in'. Returns: nn.Module: Module that is registered with equalized lr hook. """ for _, hook in module._forward_pre_hooks.items(): if isinstance(hook, EqualizedLR): raise RuntimeError( f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.' ) fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul) weight = module._parameters[name] delattr(module, name) module.register_parameter(name + '_orig', weight) setattr(module, name, weight.data) module.register_forward_pre_hook(fn) return fn class EqualizedLRLinearModule(nn.Linear): """Equalized LR LinearModule. In this module, we adopt equalized lr in ``nn.Linear``. The equalized learning rate is proposed in: Progressive Growing of GANs for Improved Quality, Stability, and Variation Note that, the initialization of ``self.weight`` will be overwritten as :math:`\\mathcal{N}(0, 1)`. Args: equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``. If ``None``, equalized learning rate is ignored. Defaults to dict(mode='fan_in'). """ def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs): super(EqualizedLRLinearModule, self).__init__(*args, **kwargs) self.with_equlized_lr = equalized_lr_cfg is not None if self.with_equlized_lr: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if self.with_equlized_lr: equalized_lr(self, **equalized_lr_cfg) self._init_linear_weights() def _init_linear_weights(self): """Initialize linear weights as described in PGGAN.""" nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul) if self.bias is not None: nn.init.constant_(self.bias, 0.0) class EqualLinearActModule(nn.Module): """Equalized LR Linear Module with Activation Layer. Args: nn ([type]): [description] """ def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0), bias=True, bias_init=0.0, act_cfg=None, **kwargs): super(EqualLinearActModule, self).__init__() self.with_activation = act_cfg is not None self.linear = EqualizedLRLinearModule(*args, bias=False, equalized_lr_cfg=equalized_lr_cfg, **kwargs) if equalized_lr_cfg is not None: self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0) else: self.lr_mul = 1.0 if bias: self.bias = nn.Parameter(torch.zeros(self.linear.out_features). fill_(bias_init)) else: self.bias = None if self.with_activation: act_cfg = deepcopy(act_cfg) if act_cfg['type'] == 'fused_bias': self.act_type = act_cfg.pop('type') assert self.bias is not None self.activate = partial(fused_bias_leakyrelu, **act_cfg) else: self.act_type = 'normal' self.activate = build_activation_layer(act_cfg) else: self.act_type = None def forward(self, x): if x.ndim >= 3: x = x.reshape(x.size(0), -1) x = self.linear(x) if self.with_activation and self.act_type == 'fused_bias': x = self.activate(x, self.bias * self.lr_mul) elif self.bias is not None and self.with_activation: x = self.activate(x + self.bias * self.lr_mul) elif self.bias is not None: x = x + self.bias * self.lr_mul elif self.with_activation: x = self.activate(x) return x class Blur(nn.Module): def __init__(self, kernel, pad, upsample_factor=1): super(Blur, self).__init__() kernel = _make_kernel(kernel) if upsample_factor > 1: kernel = kernel * upsample_factor ** 2 self.register_buffer('kernel', kernel) self.pad = pad def forward(self, x): return upfirdn2d(x, self.kernel, pad=self.pad) class ModulatedConv2d(nn.Module): """Modulated Conv2d in StyleGANv2. Attention: #. ``style_bias`` is provided to check the difference between official TF implementation and other PyTorch implementation. In TF, Tero explicitly add the ``1.`` after style code, while unofficial implementation adopts bias initialization with ``1.``. Details can be found in: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py#L214 https://github.com/NVlabs/stylegan2/blob/master/training/networks_stylegan2.py#L99 """ def __init__(self, in_channels, out_channels, kernel_size, style_channels, demodulate=True, upsample=False, downsample=False, blur_kernel=[1, 3, 3, 1], equalized_lr_cfg=dict(mode='fan_in', lr_mul=1.0, gain=1.0), style_mod_cfg=dict(bias_init=1.0), style_bias=0.0, eps=1e-08): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.style_channels = style_channels self.demodulate = demodulate assert isinstance(self.kernel_size, int) and (self.kernel_size >= 1 and self.kernel_size % 2 == 1) self.upsample = upsample self.downsample = downsample self.style_bias = style_bias self.eps = eps style_mod_cfg = dict() if style_mod_cfg is None else style_mod_cfg self.style_modulation = EqualLinearActModule(style_channels, in_channels, **style_mod_cfg) lr_mul_ = 1.0 if equalized_lr_cfg is not None: lr_mul_ = equalized_lr_cfg.get('lr_mul', 1.0) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size).div_(lr_mul_)) if upsample: factor = 2 p = len(blur_kernel) - factor - (kernel_size - 1) pad0 = (p + 1) // 2 + factor - 1 pad1 = p // 2 + 1 self.blur = Blur(blur_kernel, (pad0, pad1), upsample_factor=factor) if downsample: factor = 2 p = len(blur_kernel) - factor + (kernel_size - 1) pad0 = (p + 1) // 2 pad1 = p // 2 self.blur = Blur(blur_kernel, pad=(pad0, pad1)) if equalized_lr_cfg is not None: equalized_lr(self, **equalized_lr_cfg) self.padding = kernel_size // 2 def forward(self, x, style): n, c, h, w = x.shape style = self.style_modulation(style).view(n, 1, c, 1, 1 ) + self.style_bias weight = self.weight * style if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(n, self.out_channels, 1, 1, 1) weight = weight.view(n * self.out_channels, c, self.kernel_size, self.kernel_size) if self.upsample: x = x.reshape(1, n * c, h, w) weight = weight.view(n, self.out_channels, c, self.kernel_size, self.kernel_size) weight = weight.transpose(1, 2).reshape(n * c, self. out_channels, self.kernel_size, self.kernel_size) x = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=n) x = x.reshape(n, self.out_channels, *x.shape[-2:]) x = self.blur(x) elif self.downsample: x = self.blur(x) x = x.view(1, n * self.in_channels, *x.shape[-2:]) x = F.conv2d(x, weight, stride=2, padding=0, groups=n) x = x.view(n, self.out_channels, *x.shape[-2:]) else: x = x.view(1, n * c, h, w) x = F.conv2d(x, weight, stride=1, padding=self.padding, groups=n) x = x.view(n, self.out_channels, *x.shape[-2:]) return x class UpsampleUpFIRDn(nn.Module): def __init__(self, kernel, factor=2): super(UpsampleUpFIRDn, self).__init__() self.factor = factor kernel = _make_kernel(kernel) * factor ** 2 self.register_buffer('kernel', kernel) p = kernel.shape[0] - factor pad0 = (p + 1) // 2 + factor - 1 pad1 = p // 2 self.pad = pad0, pad1 def forward(self, x): out = upfirdn2d(x, self.kernel, up=self.factor, down=1, pad=self.pad) return out class ModulatedToRGBNew(nn.Module): def __init__(self, in_channels, style_channels, out_channels=3, upsample=True, blur_kernel=[1, 3, 3, 1], style_mod_cfg=dict( bias_init=1.0), style_bias=0.0): super(ModulatedToRGBNew, self).__init__() if upsample: self.upsample = UpsampleUpFIRDn(blur_kernel) self.conv = ModulatedConv2d(in_channels, out_channels=out_channels, kernel_size=1, style_channels=style_channels, demodulate=False, style_mod_cfg=style_mod_cfg, style_bias=style_bias) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, input_0, input_1): primals_6 = self.bias primals_1 = self.conv.weight_orig primals_5 = self.conv.style_modulation.bias primals_3 = self.conv.style_modulation.linear.weight_orig primals_2 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
Juggernaut93/mmediting
ModulatedToRGB
false
13,938
[ "Apache-2.0" ]
1,884
8ef46ace29756dd2df1d92f2f73a33646e33e007
https://github.com/Juggernaut93/mmediting/tree/8ef46ace29756dd2df1d92f2f73a33646e33e007
PosLinear
import torch from torch import Tensor from torch.utils.data import Dataset as Dataset import torch.nn as nn import torch.utils.data class PosLinear(torch.nn.Linear): def forward(self, x: 'Tensor') ->Tensor: gain = 1 / x.size(1) return nn.functional.linear(x, torch.nn.functional.softplus(self. weight), self.bias) * gain 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 libdevice, math as tl_math from torch.utils.data import Dataset as Dataset 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_softplus_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 20.0 tmp2 = tmp0 > tmp1 tmp3 = tl_math.exp(tmp0) tmp4 = libdevice.log1p(tmp3) tmp5 = tl.where(tmp2, tmp0, tmp4) tl.store(out_ptr0 + x0, tmp5, xmask) @triton.jit def triton_poi_fused_mul_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.25 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 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, 1), torch.float32) get_raw_stream(0) triton_poi_fused_softplus_0[grid(16)](primals_2, buf0, 16, XBLOCK= 16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), out=buf1) del buf0 buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf1 triton_poi_fused_mul_1[grid(256)](buf2, primals_3, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_3 return buf2, primals_2, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0) class PosLinearNew(torch.nn.Linear): 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]
KelvinKan/CP-Flow
PosLinear
false
13,939
[ "MIT" ]
64
d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
https://github.com/KelvinKan/CP-Flow/tree/d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
MeanDistLoss
import torch class MeanDistLoss(torch.nn.Module): def __init__(self, p=2): super().__init__() self.p = p def forward(self, x, y): return torch.mean(torch.cdist(x, y, p=self.p)) def extra_repr(self): return c_f.extra_repr(self, ['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 from torch._inductor.runtime import triton_helpers assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.broadcast_to(tmp0, [RBLOCK]) tmp3 = triton_helpers.promote_to_tensor(tl.sum(tmp1, 0)) tmp4 = 256.0 tmp5 = tmp3 / tmp4 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp5, 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 = torch.ops.aten._cdist_forward.default(arg1_1, arg0_1, 2.0, None) del arg0_1 del arg1_1 buf1 = buf0 del buf0 buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 get_raw_stream(0) triton_per_fused_mean_0[grid(1)](buf3, buf1, 1, 256, num_warps=2, num_stages=1) del buf1 return buf3, class MeanDistLossNew(torch.nn.Module): def __init__(self, p=2): super().__init__() self.p = p def extra_repr(self): return c_f.extra_repr(self, ['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]
KevinMusgrave/pytorch-adapt
MeanDistLoss
false
13,940
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
M2
import torch import torch.nn as nn import torch.nn.functional as F class Conv2D(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, same_padding =False, stride=1, relu=True, bn=False): super(Conv2D, self).__init__() padding = int((kernel_size - 1) / 2) if same_padding else 0 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding) self.bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0, affine=True) if bn else None self.relu = nn.ReLU(inplace=True) if relu else None def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) if self.relu is not None: x = self.relu(x) return x class M2(nn.Module): def __init__(self, in_channels): super(M2, self).__init__() self.m2_ssh_3x3 = Conv2D(in_channels, 256, 3, True, 1, False) self.m2_ssh_dimred = Conv2D(in_channels, 128, 3, True, 1, True) self.m2_ssh_5x5 = Conv2D(128, 128, 3, True, 1, False) self.m2_ssh_7x7_1 = Conv2D(128, 128, 3, True, 1, True) self.m2_ssh_7x7 = Conv2D(128, 128, 3, True, 1, False) self.m2_ssh_cls_score = Conv2D(128 * 2 + 256, 4, 1, False, 1, False) self.m2_ssh_bbox_pred = Conv2D(128 * 2 + 256, 8, 1, False, 1, False) def forward(self, conv5_3): m2_ssh_dimred = self.m2_ssh_dimred(conv5_3) m2_ssh_3x3 = self.m2_ssh_3x3(conv5_3) m2_ssh_5x5 = self.m2_ssh_5x5(m2_ssh_dimred) m2_ssh_7x7_1 = self.m2_ssh_7x7_1(m2_ssh_dimred) m2_ssh_7x7 = self.m2_ssh_7x7(m2_ssh_7x7_1) m2_ssh_output = F.relu(torch.cat((m2_ssh_3x3, m2_ssh_5x5, m2_ssh_7x7), dim=1)) m2_ssh_cls_score = self.m2_ssh_cls_score(m2_ssh_output) m2_ssh_bbox_pred = self.m2_ssh_bbox_pred(m2_ssh_output) return m2_ssh_cls_score, m2_ssh_bbox_pred 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 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 512 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 % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * 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): 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_cat_relu_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 512 x1 = xindex // 512 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 256, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (256 * x1 + x0), tmp4, eviction_policy= 'evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tmp11 = tl.full([1], 384, tl.int64) tmp12 = tmp0 < tmp11 tmp13 = tmp10 & tmp12 tmp14 = tl.load(in_ptr2 + (128 * x1 + (-256 + x0)), tmp13, eviction_policy='evict_last', other=0.0) tmp15 = tl.load(in_ptr3 + (-256 + x0), tmp13, eviction_policy= 'evict_last', other=0.0) tmp16 = tmp14 + tmp15 tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype) tmp18 = tl.where(tmp13, tmp16, tmp17) tmp19 = tmp0 >= tmp11 tl.full([1], 512, tl.int64) tmp22 = tl.load(in_ptr4 + (128 * x1 + (-384 + x0)), tmp19, eviction_policy='evict_last', other=0.0) tmp23 = tl.load(in_ptr5 + (-384 + x0), tmp19, eviction_policy= 'evict_last', other=0.0) tmp24 = tmp22 + tmp23 tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype) tmp26 = tl.where(tmp19, tmp24, tmp25) tmp27 = tl.where(tmp13, tmp18, tmp26) tmp28 = tl.where(tmp4, tmp9, tmp27) tmp29 = tl.full([1], 0, tl.int32) tmp30 = triton_helpers.maximum(tmp29, tmp28) tl.store(out_ptr0 + x2, tmp30, None) @triton.jit def triton_poi_fused_convolution_6(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 16 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 64 * y1), xmask & ymask) tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 16 * y3), tmp2, xmask & ymask) @triton.jit def triton_poi_fused_convolution_7(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 32 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 % 8 y1 = yindex // 8 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 8 * x2 + 128 * 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 + 16 * y3), tmp2, 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, (128, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (128,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (256, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (256,), (1,)) assert_size_stride(primals_6, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (4, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (8, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_15, (8,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((128, 4, 3, 3), (36, 1, 12, 4), torch.float32 ) get_raw_stream(0) triton_poi_fused_0[grid(512, 9)](primals_1, buf0, 512, 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((256, 4, 3, 3), (36, 1, 12, 4), torch.float32 ) triton_poi_fused_2[grid(1024, 9)](primals_4, buf2, 1024, 9, XBLOCK= 16, YBLOCK=64, num_warps=4, num_stages=1) del primals_4 buf3 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_6, buf3, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_6 buf4 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_8, buf4, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_8 buf5 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_10, buf5, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_10 buf6 = 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(buf6, (4, 128, 4, 4), (2048, 1, 512, 128)) buf7 = buf6 del buf6 triton_poi_fused_convolution_relu_4[grid(8192)](buf7, primals_2, 8192, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf8 = extern_kernels.convolution(buf1, buf2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 256, 4, 4), (4096, 1, 1024, 256)) buf9 = 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(buf9, (4, 128, 4, 4), (2048, 1, 512, 128)) buf10 = extern_kernels.convolution(buf7, buf4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 128, 4, 4), (2048, 1, 512, 128)) buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_4[grid(8192)](buf11, primals_9, 8192, XBLOCK=128, num_warps=4, num_stages=1) del primals_9 buf12 = extern_kernels.convolution(buf11, buf5, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 128, 4, 4), (2048, 1, 512, 128)) buf13 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512), torch.float32) triton_poi_fused_cat_relu_5[grid(32768)](buf8, primals_5, buf9, primals_7, buf12, primals_11, buf13, 32768, XBLOCK=256, num_warps=4, num_stages=1) del buf12 del buf8 del buf9 del primals_11 del primals_5 del primals_7 buf14 = extern_kernels.convolution(buf13, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf14, (4, 4, 4, 4), (64, 1, 16, 4)) buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_convolution_6[grid(16, 16)](buf14, primals_13, buf15, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del buf14 del primals_13 buf16 = extern_kernels.convolution(buf13, primals_14, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf16, (4, 8, 4, 4), (128, 1, 32, 8)) buf17 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32 ) triton_poi_fused_convolution_7[grid(32, 16)](buf16, primals_15, buf17, 32, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del buf16 del primals_15 return (buf15, buf17, buf0, buf1, buf2, buf3, buf4, buf5, primals_12, primals_14, buf7, buf11, buf13) class Conv2D(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, same_padding =False, stride=1, relu=True, bn=False): super(Conv2D, self).__init__() padding = int((kernel_size - 1) / 2) if same_padding else 0 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding) self.bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0, affine=True) if bn else None self.relu = nn.ReLU(inplace=True) if relu else None def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) if self.relu is not None: x = self.relu(x) return x class M2New(nn.Module): def __init__(self, in_channels): super(M2New, self).__init__() self.m2_ssh_3x3 = Conv2D(in_channels, 256, 3, True, 1, False) self.m2_ssh_dimred = Conv2D(in_channels, 128, 3, True, 1, True) self.m2_ssh_5x5 = Conv2D(128, 128, 3, True, 1, False) self.m2_ssh_7x7_1 = Conv2D(128, 128, 3, True, 1, True) self.m2_ssh_7x7 = Conv2D(128, 128, 3, True, 1, False) self.m2_ssh_cls_score = Conv2D(128 * 2 + 256, 4, 1, False, 1, False) self.m2_ssh_bbox_pred = Conv2D(128 * 2 + 256, 8, 1, False, 1, False) def forward(self, input_0): primals_4 = self.m2_ssh_3x3.conv.weight primals_5 = self.m2_ssh_3x3.conv.bias primals_1 = self.m2_ssh_dimred.conv.weight primals_2 = self.m2_ssh_dimred.conv.bias primals_6 = self.m2_ssh_5x5.conv.weight primals_7 = self.m2_ssh_5x5.conv.bias primals_8 = self.m2_ssh_7x7_1.conv.weight primals_9 = self.m2_ssh_7x7_1.conv.bias primals_10 = self.m2_ssh_7x7.conv.weight primals_11 = self.m2_ssh_7x7.conv.bias primals_12 = self.m2_ssh_cls_score.conv.weight primals_13 = self.m2_ssh_cls_score.conv.bias primals_14 = self.m2_ssh_bbox_pred.conv.weight primals_15 = self.m2_ssh_bbox_pred.conv.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], output[1]
Juggernaut93/SSH-pytorch
M2
false
13,941
[ "MIT" ]
63
8ea205fb1a3adfc32b5a4e35f68ed4d385ddbc31
https://github.com/Juggernaut93/SSH-pytorch/tree/8ea205fb1a3adfc32b5a4e35f68ed4d385ddbc31
AbsLoss
import torch class AbsLoss(torch.nn.Module): """ The mean absolute value. """ def forward(self, x): """""" return torch.mean(torch.abs(x)) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_abs_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl_math.abs(tmp0) tmp2 = tl.broadcast_to(tmp1, [RBLOCK]) tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0)) tmp5 = 256.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp6, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_mean_0[grid(1)](buf1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf1, class AbsLossNew(torch.nn.Module): """ The mean absolute value. """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
AbsLoss
false
13,942
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
M3
import torch import torch.nn as nn import torch.nn.functional as F class Conv2D(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, same_padding =False, stride=1, relu=True, bn=False): super(Conv2D, self).__init__() padding = int((kernel_size - 1) / 2) if same_padding else 0 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding) self.bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0, affine=True) if bn else None self.relu = nn.ReLU(inplace=True) if relu else None def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) if self.relu is not None: x = self.relu(x) return x class M3(nn.Module): def __init__(self, in_channels): super(M3, self).__init__() self.m3_ssh_3x3 = Conv2D(in_channels, 256, 3, True, 1, False) self.m3_ssh_dimred = Conv2D(in_channels, 128, 3, True, 1, True) self.m3_ssh_5x5 = Conv2D(128, 128, 3, True, 1, False) self.m3_ssh_7x7_1 = Conv2D(128, 128, 3, True, 1, True) self.m3_ssh_7x7 = Conv2D(128, 128, 3, True, 1, False) self.m3_ssh_cls_score = Conv2D(128 * 2 + 256, 4, 1, False, 1, False) self.m3_ssh_bbox_pred = Conv2D(128 * 2 + 256, 8, 1, False, 1, False) def forward(self, pool6): m3_ssh_3x3 = self.m3_ssh_3x3(pool6) m3_ssh_dimred = self.m3_ssh_dimred(pool6) m3_ssh_5x5 = self.m3_ssh_5x5(m3_ssh_dimred) m3_ssh_7x7_1 = self.m3_ssh_7x7_1(m3_ssh_dimred) m3_ssh_7x7 = self.m3_ssh_7x7(m3_ssh_7x7_1) m3_ssh_output = F.relu(torch.cat((m3_ssh_3x3, m3_ssh_5x5, m3_ssh_7x7), dim=1)) m3_ssh_cls_score = self.m3_ssh_cls_score(m3_ssh_output) m3_ssh_bbox_pred = self.m3_ssh_bbox_pred(m3_ssh_output) return m3_ssh_cls_score, m3_ssh_bbox_pred 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 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): xnumel = 9 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask) @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): ynumel = 512 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_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): 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_cat_relu_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 512 x1 = xindex // 512 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 256, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (256 * x1 + x0), tmp4, eviction_policy= 'evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tmp11 = tl.full([1], 384, tl.int64) tmp12 = tmp0 < tmp11 tmp13 = tmp10 & tmp12 tmp14 = tl.load(in_ptr2 + (128 * x1 + (-256 + x0)), tmp13, eviction_policy='evict_last', other=0.0) tmp15 = tl.load(in_ptr3 + (-256 + x0), tmp13, eviction_policy= 'evict_last', other=0.0) tmp16 = tmp14 + tmp15 tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype) tmp18 = tl.where(tmp13, tmp16, tmp17) tmp19 = tmp0 >= tmp11 tl.full([1], 512, tl.int64) tmp22 = tl.load(in_ptr4 + (128 * x1 + (-384 + x0)), tmp19, eviction_policy='evict_last', other=0.0) tmp23 = tl.load(in_ptr5 + (-384 + x0), tmp19, eviction_policy= 'evict_last', other=0.0) tmp24 = tmp22 + tmp23 tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype) tmp26 = tl.where(tmp19, tmp24, tmp25) tmp27 = tl.where(tmp13, tmp18, tmp26) tmp28 = tl.where(tmp4, tmp9, tmp27) tmp29 = tl.full([1], 0, tl.int32) tmp30 = triton_helpers.maximum(tmp29, tmp28) tl.store(out_ptr0 + x2, tmp30, None) @triton.jit def triton_poi_fused_convolution_6(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 16 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 64 * y1), xmask & ymask) tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 16 * y3), tmp2, xmask & ymask) @triton.jit def triton_poi_fused_convolution_7(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 32 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 % 8 y1 = yindex // 8 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 8 * x2 + 128 * 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 + 16 * y3), tmp2, 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, (256, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (256,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (128, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (128,), (1,)) assert_size_stride(primals_6, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (4, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (8, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_15, (8,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((256, 4, 3, 3), (36, 1, 12, 4), torch.float32 ) get_raw_stream(0) triton_poi_fused_0[grid(1024, 9)](primals_1, buf0, 1024, 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, 4, 3, 3), (36, 1, 12, 4), torch.float32 ) triton_poi_fused_2[grid(512, 9)](primals_4, buf2, 512, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_4 buf3 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_6, buf3, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_6 buf4 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_8, buf4, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_8 buf5 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_10, buf5, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_10 buf6 = 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(buf6, (4, 256, 4, 4), (4096, 1, 1024, 256)) buf7 = extern_kernels.convolution(buf1, buf2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 128, 4, 4), (2048, 1, 512, 128)) buf8 = buf7 del buf7 triton_poi_fused_convolution_relu_4[grid(8192)](buf8, primals_5, 8192, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf9 = extern_kernels.convolution(buf8, buf3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf9, (4, 128, 4, 4), (2048, 1, 512, 128)) buf10 = extern_kernels.convolution(buf8, buf4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 128, 4, 4), (2048, 1, 512, 128)) buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_4[grid(8192)](buf11, primals_9, 8192, XBLOCK=128, num_warps=4, num_stages=1) del primals_9 buf12 = extern_kernels.convolution(buf11, buf5, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 128, 4, 4), (2048, 1, 512, 128)) buf13 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512), torch.float32) triton_poi_fused_cat_relu_5[grid(32768)](buf6, primals_2, buf9, primals_7, buf12, primals_11, buf13, 32768, XBLOCK=256, num_warps=4, num_stages=1) del buf12 del buf6 del buf9 del primals_11 del primals_2 del primals_7 buf14 = extern_kernels.convolution(buf13, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf14, (4, 4, 4, 4), (64, 1, 16, 4)) buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_convolution_6[grid(16, 16)](buf14, primals_13, buf15, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del buf14 del primals_13 buf16 = extern_kernels.convolution(buf13, primals_14, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf16, (4, 8, 4, 4), (128, 1, 32, 8)) buf17 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32 ) triton_poi_fused_convolution_7[grid(32, 16)](buf16, primals_15, buf17, 32, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del buf16 del primals_15 return (buf15, buf17, buf0, buf1, buf2, buf3, buf4, buf5, primals_12, primals_14, buf8, buf11, buf13) class Conv2D(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, same_padding =False, stride=1, relu=True, bn=False): super(Conv2D, self).__init__() padding = int((kernel_size - 1) / 2) if same_padding else 0 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding) self.bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0, affine=True) if bn else None self.relu = nn.ReLU(inplace=True) if relu else None def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) if self.relu is not None: x = self.relu(x) return x class M3New(nn.Module): def __init__(self, in_channels): super(M3New, self).__init__() self.m3_ssh_3x3 = Conv2D(in_channels, 256, 3, True, 1, False) self.m3_ssh_dimred = Conv2D(in_channels, 128, 3, True, 1, True) self.m3_ssh_5x5 = Conv2D(128, 128, 3, True, 1, False) self.m3_ssh_7x7_1 = Conv2D(128, 128, 3, True, 1, True) self.m3_ssh_7x7 = Conv2D(128, 128, 3, True, 1, False) self.m3_ssh_cls_score = Conv2D(128 * 2 + 256, 4, 1, False, 1, False) self.m3_ssh_bbox_pred = Conv2D(128 * 2 + 256, 8, 1, False, 1, False) def forward(self, input_0): primals_1 = self.m3_ssh_3x3.conv.weight primals_2 = self.m3_ssh_3x3.conv.bias primals_4 = self.m3_ssh_dimred.conv.weight primals_5 = self.m3_ssh_dimred.conv.bias primals_6 = self.m3_ssh_5x5.conv.weight primals_7 = self.m3_ssh_5x5.conv.bias primals_8 = self.m3_ssh_7x7_1.conv.weight primals_9 = self.m3_ssh_7x7_1.conv.bias primals_10 = self.m3_ssh_7x7.conv.weight primals_11 = self.m3_ssh_7x7.conv.bias primals_12 = self.m3_ssh_cls_score.conv.weight primals_13 = self.m3_ssh_cls_score.conv.bias primals_14 = self.m3_ssh_bbox_pred.conv.weight primals_15 = self.m3_ssh_bbox_pred.conv.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], output[1]
Juggernaut93/SSH-pytorch
M3
false
13,943
[ "MIT" ]
63
8ea205fb1a3adfc32b5a4e35f68ed4d385ddbc31
https://github.com/Juggernaut93/SSH-pytorch/tree/8ea205fb1a3adfc32b5a4e35f68ed4d385ddbc31
AdaptiveFeatureNorm
import torch class AdaptiveFeatureNorm(torch.nn.Module): """ Implementation of the loss in [Larger Norm More Transferable: An Adaptive Feature Norm Approach for Unsupervised Domain Adaptation](https://arxiv.org/abs/1811.07456). Encourages features to gradually have larger and larger L2 norms. """ def __init__(self, step_size: 'float'=1): """ Arguments: step_size: The desired increase in L2 norm at each iteration. Note that the loss will always be equal to ```step_size``` because the goal is always to make the L2 norm ```step_size``` larger than whatever the current L2 norm is. """ super().__init__() self.step_size = step_size def forward(self, x): """""" l2_norm = x.norm(p=2, dim=1) radius = l2_norm.detach() + self.step_size return torch.mean((l2_norm - radius) ** 2) def extra_repr(self): """""" return c_f.extra_repr(self, ['step_size']) 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 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_linalg_vector_norm_mean_pow_sub_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp1 = tmp0 * tmp0 tmp3 = tmp2 * tmp2 tmp4 = tmp1 + tmp3 tmp6 = tmp5 * tmp5 tmp7 = tmp4 + tmp6 tmp9 = tmp8 * tmp8 tmp10 = tmp7 + tmp9 tmp11 = libdevice.sqrt(tmp10) tmp12 = 1.0 tmp13 = tmp11 + tmp12 tmp14 = tmp11 - tmp13 tmp15 = tmp14 * tmp14 tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK]) tmp18 = tl.sum(tmp16, 1)[:, None] tmp19 = 64.0 tmp20 = tmp18 / tmp19 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_linalg_vector_norm_mean_pow_sub_0[grid(1)](buf1, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 return buf1, class AdaptiveFeatureNormNew(torch.nn.Module): """ Implementation of the loss in [Larger Norm More Transferable: An Adaptive Feature Norm Approach for Unsupervised Domain Adaptation](https://arxiv.org/abs/1811.07456). Encourages features to gradually have larger and larger L2 norms. """ def __init__(self, step_size: 'float'=1): """ Arguments: step_size: The desired increase in L2 norm at each iteration. Note that the loss will always be equal to ```step_size``` because the goal is always to make the L2 norm ```step_size``` larger than whatever the current L2 norm is. """ super().__init__() self.step_size = step_size def extra_repr(self): """""" return c_f.extra_repr(self, ['step_size']) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
AdaptiveFeatureNorm
false
13,944
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
UniformDistributionLoss
import torch import torch.nn.functional as F class UniformDistributionLoss(torch.nn.Module): """ Implementation of the confusion loss from [Simultaneous Deep Transfer Across Domains and Tasks](https://arxiv.org/abs/1510.02192). """ def forward(self, x, *args): """""" probs = F.log_softmax(x, dim=1) avg_probs = torch.mean(probs, dim=1) return -torch.mean(avg_probs) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_mean_neg_1(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp1 = tl_math.exp(tmp0) tmp3 = tl_math.exp(tmp2) tmp4 = tmp1 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp13 = tmp2 - tmp11 tmp14 = tmp12 + tmp13 tmp15 = tmp5 - tmp11 tmp16 = tmp14 + tmp15 tmp17 = tmp8 - tmp11 tmp18 = tmp16 + tmp17 tmp19 = 4.0 tmp20 = tmp18 / tmp19 tmp21 = tl.broadcast_to(tmp20, [XBLOCK, RBLOCK]) tmp23 = tl.sum(tmp21, 1)[:, None] tmp24 = 64.0 tmp25 = tmp23 / tmp24 tmp26 = -tmp25 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp26, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused__log_softmax_mean_neg_1[grid(1)](buf2, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf0 return buf2, class UniformDistributionLossNew(torch.nn.Module): """ Implementation of the confusion loss from [Simultaneous Deep Transfer Across Domains and Tasks](https://arxiv.org/abs/1510.02192). """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
UniformDistributionLoss
false
13,945
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
BatchSpectralLoss
import torch def batch_spectral_loss(x, k): singular_values = torch.linalg.svdvals(x) return torch.sum(singular_values[:k] ** 2) class BatchSpectralLoss(torch.nn.Module): """ Implementation of the loss in [Transferability vs. Discriminability: Batch Spectral Penalization for Adversarial Domain Adaptation](http://proceedings.mlr.press/v97/chen19i.html). The loss is the sum of the squares of the first k singular values. """ def __init__(self, k: 'int'=1): """ Arguments: k: the number of singular values to include in the loss """ super().__init__() self.k = k def forward(self, x): """""" return batch_spectral_loss(x, self.k) def extra_repr(self): """""" return c_f.extra_repr(self, ['k']) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_pow_sum_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp4, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = torch.ops.aten._linalg_svd.default(arg0_1) del arg0_1 buf2 = buf0[1] del buf0 buf4 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused_pow_sum_0[grid(1)](buf2, buf4, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del buf2 return buf4, def batch_spectral_loss(x, k): singular_values = torch.linalg.svdvals(x) return torch.sum(singular_values[:k] ** 2) class BatchSpectralLossNew(torch.nn.Module): """ Implementation of the loss in [Transferability vs. Discriminability: Batch Spectral Penalization for Adversarial Domain Adaptation](http://proceedings.mlr.press/v97/chen19i.html). The loss is the sum of the squares of the first k singular values. """ def __init__(self, k: 'int'=1): """ Arguments: k: the number of singular values to include in the loss """ super().__init__() self.k = k def extra_repr(self): """""" return c_f.extra_repr(self, ['k']) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
BatchSpectralLoss
false
13,946
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
CORALLoss
import torch def covariance(x): batch_size = x.shape[0] mm1 = torch.mm(x.t(), x) cols_summed = torch.sum(x, dim=0) mm2 = torch.mm(cols_summed.unsqueeze(1), cols_summed.unsqueeze(0)) return 1.0 / (batch_size - 1) * (mm1 - 1.0 / batch_size * mm2) class CORALLoss(torch.nn.Module): """ Implementation of [Deep CORAL: Correlation Alignment for Deep Domain Adaptation](https://arxiv.org/abs/1607.01719) """ def forward(self, x: 'torch.Tensor', y: 'torch.Tensor'): """ Arguments: x: features from one domain y: features from the other domain """ embedding_size = x.shape[1] cx = covariance(x) cy = covariance(y) squared_fro_norm = torch.linalg.norm(cx - cy, ord='fro') ** 2 return squared_fro_norm / (4 * embedding_size ** 2) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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 + x0, xmask) tmp1 = tl.load(in_ptr0 + (4 + x0), xmask) tmp3 = tl.load(in_ptr0 + (8 + x0), xmask) tmp5 = tl.load(in_ptr0 + (12 + x0), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_per_fused_div_linalg_vector_norm_mul_pow_sub_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp7 = tl.load(in_ptr2 + r0, None) tmp8 = tl.load(in_ptr3 + r0, None) tmp2 = 0.25 tmp3 = tmp1 * tmp2 tmp4 = tmp0 - tmp3 tmp5 = 0.3333333333333333 tmp6 = tmp4 * tmp5 tmp9 = tmp8 * tmp2 tmp10 = tmp7 - tmp9 tmp11 = tmp10 * tmp5 tmp12 = tmp6 - tmp11 tmp13 = tmp12 * tmp12 tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK]) tmp16 = tl.sum(tmp14, 1)[:, None] tmp17 = libdevice.sqrt(tmp16) tmp18 = tmp17 * tmp17 tmp19 = 0.015625 tmp20 = tmp18 * tmp19 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) assert_size_stride(arg1_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(arg0_1, (4, 4), (1, 4), 0), arg0_1, out=buf0) buf1 = empty_strided_cuda((4,), (1,), torch.float32) get_raw_stream(0) triton_poi_fused_sum_0[grid(4)](arg0_1, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) del arg0_1 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (4, 1), (1, 0), 0), reinterpret_tensor(buf1, (1, 4), (0, 1), 0), out=buf2) buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(arg1_1, (4, 4), (1, 4), 0), arg1_1, out=buf3) buf4 = buf1 del buf1 triton_poi_fused_sum_0[grid(4)](arg1_1, buf4, 4, XBLOCK=4, num_warps=1, num_stages=1) del arg1_1 buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf4, (4, 1), (1, 0), 0), reinterpret_tensor(buf4, (1, 4), (0, 1), 0), out=buf5) del buf4 buf6 = empty_strided_cuda((), (), torch.float32) buf7 = buf6 del buf6 triton_per_fused_div_linalg_vector_norm_mul_pow_sub_1[grid(1)](buf7, buf0, buf2, buf3, buf5, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del buf0 del buf2 del buf3 del buf5 return buf7, def covariance(x): batch_size = x.shape[0] mm1 = torch.mm(x.t(), x) cols_summed = torch.sum(x, dim=0) mm2 = torch.mm(cols_summed.unsqueeze(1), cols_summed.unsqueeze(0)) return 1.0 / (batch_size - 1) * (mm1 - 1.0 / batch_size * mm2) class CORALLossNew(torch.nn.Module): """ Implementation of [Deep CORAL: Correlation Alignment for Deep Domain Adaptation](https://arxiv.org/abs/1607.01719) """ def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
KevinMusgrave/pytorch-adapt
CORALLoss
false
13,947
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
SumNormalizer
import torch def sum_normalizer(x, detach=False, scale_by_batch_size=False): y = torch.sum(x) if detach: y = y.detach() if scale_by_batch_size: x = x * x.shape[0] return x / y class SumNormalizer(torch.nn.Module): def __init__(self, detach=False, scale_by_batch_size=False): super().__init__() self.detach = detach self.scale_by_batch_size = scale_by_batch_size def forward(self, x): return sum_normalizer(x, detach=self.detach, scale_by_batch_size= self.scale_by_batch_size) def extra_repr(self): return c_f.extra_repr(self, ['detach', 'scale_by_batch_size']) 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 assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_div_sum_0(in_ptr0, 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.broadcast_to(tmp0, [RBLOCK]) tmp3 = triton_helpers.promote_to_tensor(tl.sum(tmp1, 0)) tmp4 = tmp0 / tmp3 tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp4, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_div_sum_0[grid(1)](arg0_1, buf1, 1, 256, num_warps =2, num_stages=1) del arg0_1 return buf1, def sum_normalizer(x, detach=False, scale_by_batch_size=False): y = torch.sum(x) if detach: y = y.detach() if scale_by_batch_size: x = x * x.shape[0] return x / y class SumNormalizerNew(torch.nn.Module): def __init__(self, detach=False, scale_by_batch_size=False): super().__init__() self.detach = detach self.scale_by_batch_size = scale_by_batch_size def extra_repr(self): return c_f.extra_repr(self, ['detach', 'scale_by_batch_size']) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
SumNormalizer
false
13,948
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
Encoder
import torch from torch import nn import torch.hub import torch.nn.functional as F class Encoder(nn.Module): """Estimation of the nonnegative mixture weight by a 1-D conv layer. """ def __init__(self, L, N, audio_channels): super(Encoder, self).__init__() self.L, self.N = L, N self.conv1d_U = nn.Conv1d(audio_channels, N, kernel_size=L, stride= L // 2, bias=False) def forward(self, mixture): """ Args: mixture: [M, T], M is batch size, T is #samples Returns: mixture_w: [M, N, K], where K = (T-L)/(L/2)+1 = 2T/L-1 """ mixture_w = F.relu(self.conv1d_U(mixture)) return mixture_w def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'L': 4, 'N': 4, 'audio_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 import nn import torch.hub assert_size_stride = torch._C._dynamo.guards.assert_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, 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_out_ptr0 + x0, xmask) tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = 0.0 tmp4 = tmp2 <= tmp3 tl.store(in_out_ptr0 + x0, tmp2, xmask) tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0), primals_1, stride=(2,), padding=(0,), dilation=(1,), transposed=False, output_padding=(0,), groups=1, bias=None) assert_size_stride(buf0, (1, 4, 1), (4, 1, 1)) buf1 = reinterpret_tensor(buf0, (4, 1), (1, 1), 0) del buf0 buf2 = empty_strided_cuda((4, 1), (1, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(4)](buf1, buf2, 4, XBLOCK=4, num_warps=1, num_stages=1) return buf1, primals_1, reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0), buf2 class EncoderNew(nn.Module): """Estimation of the nonnegative mixture weight by a 1-D conv layer. """ def __init__(self, L, N, audio_channels): super(EncoderNew, self).__init__() self.L, self.N = L, N self.conv1d_U = nn.Conv1d(audio_channels, N, kernel_size=L, stride= L // 2, bias=False) def forward(self, input_0): primals_1 = self.conv1d_U.weight primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
KilianRuiz2B/demucs
Encoder
false
13,949
[ "MIT" ]
3,013
a6fbf3806b018634f68563887feaee64c5e36600
https://github.com/KilianRuiz2B/demucs/tree/a6fbf3806b018634f68563887feaee64c5e36600
BNMLoss
import torch class BNMLoss(torch.nn.Module): """ Implementation of the loss in [Towards Discriminability and Diversity: Batch Nuclear-norm Maximization under Label Insufficient Situations](https://arxiv.org/abs/2003.12237). """ def forward(self, x): """""" x = torch.nn.functional.softmax(x, dim=1) return -torch.linalg.norm(x, 'nuc') / x.shape[0] def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 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_per_fused_div_neg_sum_2(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.sum(tmp1, 1)[:, None] tmp4 = -tmp3 tmp5 = 0.25 tmp6 = tmp4 * tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp6, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_1[grid(16)](buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf0 buf2 = torch.ops.aten._linalg_svd.default(buf1) del buf1 buf4 = buf2[1] del buf2 buf6 = empty_strided_cuda((), (), torch.float32) buf7 = buf6 del buf6 triton_per_fused_div_neg_sum_2[grid(1)](buf7, buf4, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf4 return buf7, class BNMLossNew(torch.nn.Module): """ Implementation of the loss in [Towards Discriminability and Diversity: Batch Nuclear-norm Maximization under Label Insufficient Situations](https://arxiv.org/abs/2003.12237). """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
BNMLoss
false
13,950
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
MinMaxNormalizer
import torch def min_max_normalizer(x, detach=False): x_min = torch.min(x) x_max = torch.max(x) if detach: x_min = x_min.detach() x_max = x_max.detach() return (x - x_min) / (x_max - x_min) class MinMaxNormalizer(torch.nn.Module): def __init__(self, detach=False): super().__init__() self.detach = detach def forward(self, x): return min_max_normalizer(x, detach=self.detach) def extra_repr(self): return c_f.extra_repr(self, ['detach']) 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 assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_div_max_min_sub_0(in_ptr0, out_ptr2, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.broadcast_to(tmp0, [RBLOCK]) tmp3 = triton_helpers.promote_to_tensor(triton_helpers.min2(tmp1, 0)) tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0)) tmp6 = tmp0 - tmp3 tmp7 = tmp5 - tmp3 tmp8 = tmp6 / tmp7 tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), tmp8, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_div_max_min_sub_0[grid(1)](arg0_1, buf2, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf2, def min_max_normalizer(x, detach=False): x_min = torch.min(x) x_max = torch.max(x) if detach: x_min = x_min.detach() x_max = x_max.detach() return (x - x_min) / (x_max - x_min) class MinMaxNormalizerNew(torch.nn.Module): def __init__(self, detach=False): super().__init__() self.detach = detach def extra_repr(self): return c_f.extra_repr(self, ['detach']) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KevinMusgrave/pytorch-adapt
MinMaxNormalizer
false
13,951
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
SineLayer
import torch import numpy as np import torch.nn as nn class SineLayer(nn.Module): def __init__(self, in_features, out_features, bias=True, is_first=False, omega_0=30): super().__init__() self.omega_0 = omega_0 self.is_first = is_first self.in_features = in_features self.linear = nn.Linear(in_features, out_features, bias=bias) self.init_weights() def init_weights(self): with torch.no_grad(): if self.is_first: self.linear.weight.uniform_(-1 / self.in_features, 1 / self .in_features) else: self.linear.weight.uniform_(-np.sqrt(6 / self.in_features) / self.omega_0, np.sqrt(6 / self.in_features) / self.omega_0) def forward(self, input): return torch.sin(self.omega_0 * self.linear(input)) def forward_with_intermediate(self, input): intermediate = self.omega_0 * self.linear(input) return torch.sin(intermediate), intermediate 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 import numpy as np import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mul_sin_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 = 30.0 tmp2 = tmp0 * tmp1 tmp3 = tl_math.sin(tmp2) tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sin_0[grid(256)](buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0 class SineLayerNew(nn.Module): def __init__(self, in_features, out_features, bias=True, is_first=False, omega_0=30): super().__init__() self.omega_0 = omega_0 self.is_first = is_first self.in_features = in_features self.linear = nn.Linear(in_features, out_features, bias=bias) self.init_weights() def init_weights(self): with torch.no_grad(): if self.is_first: self.linear.weight.uniform_(-1 / self.in_features, 1 / self .in_features) else: self.linear.weight.uniform_(-np.sqrt(6 / self.in_features) / self.omega_0, np.sqrt(6 / self.in_features) / self.omega_0) def forward_with_intermediate(self, input): intermediate = self.omega_0 * self.linear(input) return torch.sin(intermediate), intermediate def forward(self, input_0): primals_1 = self.linear.weight primals_2 = self.linear.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Juju-botu/diffeqml-research
SineLayer
false
13,952
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
LRN
import torch import torch.nn as nn class LRN(nn.Module): def __init__(self, local_size=1, alpha=0.0001, beta=0.75, ACROSS_CHANNELS=False): super(LRN, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if self.ACROSS_CHANNELS: self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1), stride=1, padding=(int((local_size - 1.0) / 2), 0, 0)) else: self.average = nn.AvgPool2d(kernel_size=local_size, stride=1, padding=int((local_size - 1.0) / 2)) self.alpha = alpha self.beta = beta def forward(self, x): if self.ACROSS_CHANNELS: div = x.pow(2).unsqueeze(1) div = self.average(div).squeeze(1) div = div.mul(self.alpha).add(2.0).pow(self.beta) else: div = x.pow(2) div = self.average(div) div = div.mul(self.alpha).add(2.0).pow(self.beta) x = x.div(div) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_avg_pool2d_div_mul_pow_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tmp0 * tmp0 tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = 0.0001 tmp5 = tmp3 * tmp4 tmp6 = 2.0 tmp7 = tmp5 + tmp6 tmp8 = 0.75 tmp9 = libdevice.pow(tmp7, tmp8) tmp10 = tmp0 / tmp9 tl.store(out_ptr0 + x0, tmp10, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_avg_pool2d_div_mul_pow_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class LRNNew(nn.Module): def __init__(self, local_size=1, alpha=0.0001, beta=0.75, ACROSS_CHANNELS=False): super(LRNNew, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if self.ACROSS_CHANNELS: self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1), stride=1, padding=(int((local_size - 1.0) / 2), 0, 0)) else: self.average = nn.AvgPool2d(kernel_size=local_size, stride=1, padding=int((local_size - 1.0) / 2)) self.alpha = alpha self.beta = beta def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Kitware/VAIME
LRN
false
13,953
[ "BSD-3-Clause" ]
127
47b24b9d8a208cf8c621e5bb1088c61fcf507af6
https://github.com/Kitware/VAIME/tree/47b24b9d8a208cf8c621e5bb1088c61fcf507af6
SDFNetwork
import torch import numpy as np import torch.nn as nn def get_embedder(multires, input_dims=3): embed_kwargs = {'include_input': True, 'input_dims': input_dims, 'max_freq_log2': multires - 1, 'num_freqs': multires, 'log_sampling': True, 'periodic_fns': [torch.sin, torch.cos]} embedder_obj = Embedder(**embed_kwargs) def embed(x, eo=embedder_obj): return eo.embed(x) return embed, embedder_obj.out_dim class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda x: x) out_dim += d max_freq = self.kwargs['max_freq_log2'] N_freqs = self.kwargs['num_freqs'] if self.kwargs['log_sampling']: freq_bands = 2.0 ** torch.linspace(0.0, max_freq, N_freqs) else: freq_bands = torch.linspace(2.0 ** 0.0, 2.0 ** max_freq, N_freqs) for freq in freq_bands: for p_fn in self.kwargs['periodic_fns']: embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq) ) out_dim += d self.embed_fns = embed_fns self.out_dim = out_dim def embed(self, inputs): return torch.cat([fn(inputs) for fn in self.embed_fns], -1) class SDFNetwork(nn.Module): def __init__(self, d_in, d_out, d_hidden, n_layers, skip_in=(4,), multires=0, bias=0.5, scale=1, geometric_init=True, weight_norm= True, inside_outside=False): super(SDFNetwork, self).__init__() dims = [d_in] + [d_hidden for _ in range(n_layers)] + [d_out] self.embed_fn_fine = None if multires > 0: embed_fn, input_ch = get_embedder(multires, input_dims=d_in) self.embed_fn_fine = embed_fn dims[0] = input_ch self.num_layers = len(dims) self.skip_in = skip_in self.scale = scale for l in range(0, self.num_layers - 1): if l + 1 in self.skip_in: out_dim = dims[l + 1] - dims[0] else: out_dim = dims[l + 1] lin = nn.Linear(dims[l], out_dim) if geometric_init: if l == self.num_layers - 2: if not inside_outside: torch.nn.init.normal_(lin.weight, mean=np.sqrt(np. pi) / np.sqrt(dims[l]), std=0.0001) torch.nn.init.constant_(lin.bias, -bias) else: torch.nn.init.normal_(lin.weight, mean=-np.sqrt(np. pi) / np.sqrt(dims[l]), std=0.0001) torch.nn.init.constant_(lin.bias, bias) elif multires > 0 and l == 0: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.constant_(lin.weight[:, 3:], 0.0) torch.nn.init.normal_(lin.weight[:, :3], 0.0, np.sqrt(2 ) / np.sqrt(out_dim)) elif multires > 0 and l in self.skip_in: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np. sqrt(out_dim)) torch.nn.init.constant_(lin.weight[:, -(dims[0] - 3):], 0.0 ) else: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np. sqrt(out_dim)) if weight_norm: lin = nn.utils.weight_norm(lin) setattr(self, 'lin' + str(l), lin) self.activation = nn.Softplus(beta=100) def forward(self, inputs): inputs = inputs * self.scale if self.embed_fn_fine is not None: inputs = self.embed_fn_fine(inputs) x = inputs for l in range(0, self.num_layers - 1): lin = getattr(self, 'lin' + str(l)) if l in self.skip_in: x = torch.cat([x, inputs], 1) / np.sqrt(2) x = lin(x) if l < self.num_layers - 2: x = self.activation(x) return torch.cat([x[:, :1] / self.scale, x[:, 1:]], dim=-1) def sdf(self, x): return self.forward(x)[:, :1] def sdf_hidden_appearance(self, x): return self.forward(x) def gradient(self, x): x.requires_grad_(True) y = self.sdf(x) d_output = torch.ones_like(y, requires_grad=False, device=y.device) gradients = torch.autograd.grad(outputs=y, inputs=x, grad_outputs= d_output, create_graph=True, retain_graph=True, only_inputs=True)[0 ] return gradients.unsqueeze(1) def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'d_in': 4, 'd_out': 4, 'd_hidden': 4, 'n_layers': 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 numpy as np import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused__weight_norm_interface_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp1 = tmp0 * tmp0 tmp3 = tmp2 * tmp2 tmp4 = tmp1 + tmp3 tmp6 = tmp5 * tmp5 tmp7 = tmp4 + tmp6 tmp9 = tmp8 * tmp8 tmp10 = tmp7 + tmp9 tmp11 = libdevice.sqrt(tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused__weight_norm_interface_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp3 = tmp1 / tmp2 tmp4 = tmp0 * tmp3 tl.store(out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_softplus_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 100.0 tmp2 = tmp0 * tmp1 tmp3 = 20.0 tmp4 = tmp2 > tmp3 tmp5 = tl_math.exp(tmp2) tmp6 = libdevice.log1p(tmp5) tmp7 = 0.01 tmp8 = tmp6 * tmp7 tmp9 = tl.where(tmp4, tmp0, tmp8) tl.store(out_ptr0 + x0, tmp9, xmask) @triton.jit def triton_poi_fused_cat_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 x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + 4 * x1, tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = 1.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_ptr0 + (1 + 4 * x1 + (-1 + x0)), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tl.store(out_ptr0 + x2, tmp14, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = 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, 4), (4, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 1), (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((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 1), (1, 1), torch.float32) triton_poi_fused__weight_norm_interface_1[grid(4)](primals_3, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__weight_norm_interface_2[grid(16)](primals_3, primals_2, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_4, buf0, reinterpret_tensor(buf2, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_4 buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_softplus_3[grid(16)](buf3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32) triton_poi_fused__weight_norm_interface_1[grid(4)](primals_6, buf5, 4, XBLOCK=4, num_warps=1, num_stages=1) buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__weight_norm_interface_2[grid(16)](primals_6, primals_5, buf5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, buf4, reinterpret_tensor(buf6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf7) del primals_7 buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_cat_4[grid(16)](buf7, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf7 return (buf8, buf2, buf6, primals_2, primals_3, primals_5, primals_6, buf0, buf1, buf3, buf4, buf5, buf6) def get_embedder(multires, input_dims=3): embed_kwargs = {'include_input': True, 'input_dims': input_dims, 'max_freq_log2': multires - 1, 'num_freqs': multires, 'log_sampling': True, 'periodic_fns': [torch.sin, torch.cos]} embedder_obj = Embedder(**embed_kwargs) def embed(x, eo=embedder_obj): return eo.embed(x) return embed, embedder_obj.out_dim class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda x: x) out_dim += d max_freq = self.kwargs['max_freq_log2'] N_freqs = self.kwargs['num_freqs'] if self.kwargs['log_sampling']: freq_bands = 2.0 ** torch.linspace(0.0, max_freq, N_freqs) else: freq_bands = torch.linspace(2.0 ** 0.0, 2.0 ** max_freq, N_freqs) for freq in freq_bands: for p_fn in self.kwargs['periodic_fns']: embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq) ) out_dim += d self.embed_fns = embed_fns self.out_dim = out_dim def embed(self, inputs): return torch.cat([fn(inputs) for fn in self.embed_fns], -1) class SDFNetworkNew(nn.Module): def __init__(self, d_in, d_out, d_hidden, n_layers, skip_in=(4,), multires=0, bias=0.5, scale=1, geometric_init=True, weight_norm= True, inside_outside=False): super(SDFNetworkNew, self).__init__() dims = [d_in] + [d_hidden for _ in range(n_layers)] + [d_out] self.embed_fn_fine = None if multires > 0: embed_fn, input_ch = get_embedder(multires, input_dims=d_in) self.embed_fn_fine = embed_fn dims[0] = input_ch self.num_layers = len(dims) self.skip_in = skip_in self.scale = scale for l in range(0, self.num_layers - 1): if l + 1 in self.skip_in: out_dim = dims[l + 1] - dims[0] else: out_dim = dims[l + 1] lin = nn.Linear(dims[l], out_dim) if geometric_init: if l == self.num_layers - 2: if not inside_outside: torch.nn.init.normal_(lin.weight, mean=np.sqrt(np. pi) / np.sqrt(dims[l]), std=0.0001) torch.nn.init.constant_(lin.bias, -bias) else: torch.nn.init.normal_(lin.weight, mean=-np.sqrt(np. pi) / np.sqrt(dims[l]), std=0.0001) torch.nn.init.constant_(lin.bias, bias) elif multires > 0 and l == 0: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.constant_(lin.weight[:, 3:], 0.0) torch.nn.init.normal_(lin.weight[:, :3], 0.0, np.sqrt(2 ) / np.sqrt(out_dim)) elif multires > 0 and l in self.skip_in: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np. sqrt(out_dim)) torch.nn.init.constant_(lin.weight[:, -(dims[0] - 3):], 0.0 ) else: torch.nn.init.constant_(lin.bias, 0.0) torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np. sqrt(out_dim)) if weight_norm: lin = nn.utils.weight_norm(lin) setattr(self, 'lin' + str(l), lin) self.activation = nn.Softplus(beta=100) def sdf(self, x): return self.forward(x)[:, :1] def sdf_hidden_appearance(self, x): return self.forward(x) def gradient(self, x): x.requires_grad_(True) y = self.sdf(x) d_output = torch.ones_like(y, requires_grad=False, device=y.device) gradients = torch.autograd.grad(outputs=y, inputs=x, grad_outputs= d_output, create_graph=True, retain_graph=True, only_inputs=True)[0 ] return gradients.unsqueeze(1) def forward(self, input_0): primals_4 = self.lin0.bias primals_2 = self.lin0.weight_g primals_1 = self.lin0.weight_v primals_7 = self.lin1.bias primals_5 = self.lin1.weight_g primals_3 = self.lin1.weight_v primals_6 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
Junlin-Yin/NeuS
SDFNetwork
false
13,954
[ "MIT" ]
345
b13dba90ba1c65d0ccaaca6b9d65225d5dfa8fe2
https://github.com/Junlin-Yin/NeuS/tree/b13dba90ba1c65d0ccaaca6b9d65225d5dfa8fe2
PosLinear2
import torch from torch import Tensor from torch.utils.data import Dataset as Dataset import torch.nn as nn import torch.utils.data class PosLinear2(torch.nn.Linear): def forward(self, x: 'Tensor') ->Tensor: return nn.functional.linear(x, torch.nn.functional.softmax(self. weight, 1), self.bias) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_features': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math from torch.utils.data import Dataset as Dataset 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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(16)](primals_1, buf0, 16, XBLOCK= 16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_1[grid(16)](buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf0 buf2 = 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(buf1, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del buf1 del primals_2 return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), primals_1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) class PosLinear2New(torch.nn.Linear): def forward(self, input_0): primals_1 = self.weight primals_2 = self.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
KelvinKan/CP-Flow
PosLinear2
false
13,955
[ "MIT" ]
64
d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
https://github.com/KelvinKan/CP-Flow/tree/d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1
UpsamplingBilinear2d
import torch import torch.nn as nn import torch.nn.functional as F class UpsamplingBilinear2d(nn.Module): def __init__(self, scale_factor=2.0): super().__init__() self.scale_factor = scale_factor def forward(self, x): return F.interpolate(x, scale_factor=self.scale_factor, mode= 'bilinear', align_corners=True) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_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 x1 = xindex // 8 % 8 x0 = xindex % 8 x2 = xindex // 64 x4 = xindex tmp0 = x1 tmp1 = tmp0.to(tl.float32) tmp2 = 0.42857142857142855 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 3, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tmp11 = x0 tmp12 = tmp11.to(tl.float32) tmp13 = tmp12 * tmp2 tmp14 = triton_helpers.maximum(tmp13, tmp4) tmp15 = tmp14.to(tl.int32) tmp16 = tl.load(in_ptr0 + (tmp15 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp17 = tmp15 + tmp7 tmp18 = triton_helpers.minimum(tmp17, tmp9) tmp19 = tl.load(in_ptr0 + (tmp18 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp20 = tmp19 - tmp16 tmp21 = tmp15.to(tl.float32) tmp22 = tmp14 - tmp21 tmp23 = triton_helpers.maximum(tmp22, tmp4) tmp24 = 1.0 tmp25 = triton_helpers.minimum(tmp23, tmp24) tmp26 = tmp20 * tmp25 tmp27 = tmp16 + tmp26 tmp28 = tl.load(in_ptr0 + (tmp15 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp29 = tl.load(in_ptr0 + (tmp18 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp30 = tmp29 - tmp28 tmp31 = tmp30 * tmp25 tmp32 = tmp28 + tmp31 tmp33 = tmp27 - tmp32 tmp34 = tmp6.to(tl.float32) tmp35 = tmp5 - tmp34 tmp36 = triton_helpers.maximum(tmp35, tmp4) tmp37 = triton_helpers.minimum(tmp36, tmp24) tmp38 = tmp33 * tmp37 tmp39 = tmp32 + tmp38 tl.store(in_out_ptr0 + x4, tmp39, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0[grid (1024)](buf1, arg0_1, 1024, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf1, class UpsamplingBilinear2dNew(nn.Module): def __init__(self, scale_factor=2.0): super().__init__() self.scale_factor = scale_factor def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KyleDavisSA/pde-surrogate
UpsamplingBilinear2d
false
13,956
[ "MIT" ]
62
41ad2c9eb73c323e389174080f4b3df6cbd3c900
https://github.com/KyleDavisSA/pde-surrogate/tree/41ad2c9eb73c323e389174080f4b3df6cbd3c900
RewardCriterion
import torch from torch import nn import torch.nn.init class RewardCriterion(nn.Module): def __init__(self): super(RewardCriterion, self).__init__() def forward(self, input, seq, reward): input = input.contiguous().view(-1) reward = reward.contiguous().view(-1) mask = (seq > 0).float() mask = torch.cat([mask.new(mask.size(0), 1).fill_(1), mask[:, :-1]], 1 ).contiguous().view(-1) output = -input * reward * mask output = torch.sum(output) / torch.sum(mask) return output def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch import nn import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_div_mul_neg_sum_0(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) tmp2 = tl.load(in_ptr1 + r0, None) tmp1 = -tmp0 tmp3 = tmp1 * tmp2 tmp4 = r0 % 4 tl.full([1, 1], 0, tl.int64) tmp7 = tl.full([1, 1], 1, tl.int64) tmp8 = tmp4 < tmp7 tmp9 = 1.0 tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp8, tmp9, tmp10) tmp12 = tmp4 >= tmp7 tl.full([1, 1], 4, tl.int64) tmp15 = tl.load(in_ptr2 + tl.broadcast_to(4 * (r0 // 4) + (-1 + r0 % 4), [XBLOCK, RBLOCK]), tmp12, eviction_policy='evict_last', other=0.0) tmp16 = 0.0 tmp17 = tmp15 > tmp16 tmp18 = tmp17.to(tl.float32) tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype) tmp20 = tl.where(tmp12, tmp18, tmp19) tmp21 = tl.where(tmp8, tmp11, tmp20) tmp22 = tmp3 * tmp21 tmp23 = tl.broadcast_to(tmp22, [XBLOCK, RBLOCK]) tmp25 = tl.sum(tmp23, 1)[:, None] tmp26 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK]) tmp28 = tl.sum(tmp26, 1)[:, None] tmp29 = tmp25 / tmp28 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp29, None) def call(args): arg0_1, arg1_1, arg2_1 = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) assert_size_stride(arg1_1, (4, 4), (4, 1)) assert_size_stride(arg2_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_div_mul_neg_sum_0[grid(1)](buf2, arg0_1, arg1_1, arg2_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 return buf2, class RewardCriterionNew(nn.Module): def __init__(self): super(RewardCriterionNew, self).__init__() def forward(self, input_0, input_1, input_2): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
KunpengLi1994/VSRN
RewardCriterion
false
13,957
[ "Apache-2.0" ]
238
777ae74326fdb6abe69dbd3911d0e545322520d1
https://github.com/KunpengLi1994/VSRN/tree/777ae74326fdb6abe69dbd3911d0e545322520d1
MVCRegularizer
import torch import torch.nn.parallel import torch.utils.data class MVCRegularizer(torch.nn.Module): """ penalize MVC with large absolute value and negative values alpha * large_weight^2 + beta * (negative_weight)^2 """ def __init__(self, alpha=1.0, beta=1.0, threshold=5.0): super().__init__() self.alpha = alpha self.beta = beta self.threshold = threshold def forward(self, weights): loss = 0 if self.alpha > 0: large_loss = torch.log(torch.nn.functional.relu(weights.abs() - self.threshold) + 1) loss += torch.mean(large_loss) * self.alpha if self.beta > 0: neg_loss = torch.nn.functional.relu(-weights) neg_loss = neg_loss ** 2 loss += torch.mean(neg_loss) * self.beta return loss def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn.parallel import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_abs_add_log_mean_mul_neg_pow_relu_sub_0(in_out_ptr0, in_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl_math.abs(tmp0) tmp2 = 5.0 tmp3 = tmp1 - tmp2 tmp4 = tl.full([1], 0, tl.int32) tmp5 = triton_helpers.maximum(tmp4, tmp3) tmp6 = 1.0 tmp7 = tmp5 + tmp6 tmp8 = tl_math.log(tmp7) tmp9 = tl.broadcast_to(tmp8, [RBLOCK]) tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0)) tmp12 = -tmp0 tmp13 = triton_helpers.maximum(tmp4, tmp12) tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = 256.0 tmp19 = tmp11 / tmp18 tmp20 = tmp19 * tmp6 tmp21 = 0.0 tmp22 = tmp20 + tmp21 tmp23 = tmp17 / tmp18 tmp24 = tmp23 * tmp6 tmp25 = tmp22 + tmp24 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp25, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_add_log_mean_mul_neg_pow_relu_sub_0[grid(1)](buf2, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf2, class MVCRegularizerNew(torch.nn.Module): """ penalize MVC with large absolute value and negative values alpha * large_weight^2 + beta * (negative_weight)^2 """ def __init__(self, alpha=1.0, beta=1.0, threshold=5.0): super().__init__() self.alpha = alpha self.beta = beta self.threshold = threshold def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
KunalMGupta/deep_cage
MVCRegularizer
false
13,958
[ "MIT" ]
123
d8454c40d650911341b7f594af2fcefcf26f3d1d
https://github.com/KunalMGupta/deep_cage/tree/d8454c40d650911341b7f594af2fcefcf26f3d1d
MultiplicativeIntegration
import torch import torch.nn as nn from typing import List class MultiplicativeIntegration(nn.Module): def __init__(self, inputs_sizes: 'List[int]', output_sizes: 'List[int]', bias: 'bool', bias_start: 'float'=0.0, alpha_start: 'float'=1.0, beta_start: 'float'=1.0): super().__init__() self.inputs_sizes = inputs_sizes self.output_sizes = output_sizes total_output_size = sum(output_sizes) total_input_size = sum(inputs_sizes) self.bias_start = bias_start self.alpha_start = alpha_start self.beta_start = beta_start self.weights = nn.Parameter(torch.empty(total_input_size, total_output_size)) self.alphas = nn.Parameter(torch.empty([total_output_size])) self.betas = nn.Parameter(torch.empty([2 * total_output_size])) self.biases = nn.Parameter(torch.empty([total_output_size]) ) if bias else None self.reset_parameters() def forward(self, input0, input1): w1, w2 = torch.split(self.weights, self.inputs_sizes, dim=0) b1, b2 = torch.split(self.betas, sum(self.output_sizes), dim=0) wx1, wx2 = input0 @ w1, input1 @ w2 res = self.alphas * wx1 * wx2 + b1 * wx1 + b2 * wx2 if self.biases is not None: res += self.biases return res def reset_parameters(self): nn.init.xavier_uniform_(self.weights, gain=1.0) nn.init.constant_(self.alphas, self.alpha_start) nn.init.constant_(self.betas, self.beta_start) if self.biases is not None: nn.init.constant_(self.biases, self.bias_start) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'inputs_sizes': [4, 4], 'output_sizes': [4, 4], 'bias': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn from typing import List assert_size_stride = torch._C._dynamo.guards.assert_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_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + x2, xmask) tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp5 * tmp1 tmp7 = tmp4 + tmp6 tmp9 = tmp8 * tmp3 tmp10 = tmp7 + tmp9 tmp12 = tmp10 + tmp11 tl.store(out_ptr0 + x2, tmp12, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (8, 8), (8, 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, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_5, (8,), (1,)) assert_size_stride(primals_6, (8,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 8), (8, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 8), (8, 1), 0), out=buf0) buf1 = empty_strided_cuda((64, 8), (8, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 8), (8, 1), 32), out=buf1) del primals_1 buf2 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_0[grid(512)](primals_5, buf0, buf1, primals_2, primals_6, buf2, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_6 return buf2, primals_5, reinterpret_tensor(primals_2, (8,), (1,), 0 ), reinterpret_tensor(primals_2, (8,), (1,), 8 ), buf0, buf1, reinterpret_tensor(primals_4, (4, 64), (1, 4), 0 ), reinterpret_tensor(primals_3, (4, 64), (1, 4), 0) class MultiplicativeIntegrationNew(nn.Module): def __init__(self, inputs_sizes: 'List[int]', output_sizes: 'List[int]', bias: 'bool', bias_start: 'float'=0.0, alpha_start: 'float'=1.0, beta_start: 'float'=1.0): super().__init__() self.inputs_sizes = inputs_sizes self.output_sizes = output_sizes total_output_size = sum(output_sizes) total_input_size = sum(inputs_sizes) self.bias_start = bias_start self.alpha_start = alpha_start self.beta_start = beta_start self.weights = nn.Parameter(torch.empty(total_input_size, total_output_size)) self.alphas = nn.Parameter(torch.empty([total_output_size])) self.betas = nn.Parameter(torch.empty([2 * total_output_size])) self.biases = nn.Parameter(torch.empty([total_output_size]) ) if bias else None self.reset_parameters() def reset_parameters(self): nn.init.xavier_uniform_(self.weights, gain=1.0) nn.init.constant_(self.alphas, self.alpha_start) nn.init.constant_(self.betas, self.beta_start) if self.biases is not None: nn.init.constant_(self.biases, self.bias_start) def forward(self, input_0, input_1): primals_1 = self.weights primals_5 = self.alphas primals_2 = self.betas primals_6 = self.biases 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]
KnowingNothing/FlexTensor
MultiplicativeIntegration
false
13,959
[ "MIT" ]
135
00f6cd7e038af7714b833fde7034d465fe2dc4a7
https://github.com/KnowingNothing/FlexTensor/tree/00f6cd7e038af7714b833fde7034d465fe2dc4a7
QuanConv
from torch.autograd import Function import torch import torch.utils.data.distributed import torch.nn as nn import torch.nn.functional as F import torch.utils.data def quantize(input, nbit): return Quantizer.apply(input, nbit) def dorefa_a(input, nbit_a): return quantize(torch.clamp(0.1 * input, 0, 1), nbit_a) def scale_sign(input): return ScaleSigner.apply(input) def dorefa_w(w, nbit_w): if nbit_w == 1: w = scale_sign(w) else: w = torch.tanh(w) w = w / (2 * torch.max(torch.abs(w))) + 0.5 w = 2 * quantize(w, nbit_w) - 1 return w class Quantizer(Function): @staticmethod def forward(ctx, input, nbit): scale = 2 ** nbit - 1 return torch.round(input * scale) / scale @staticmethod def backward(ctx, grad_output): return grad_output, None class ScaleSigner(Function): """take a real value x, output sign(x)*E(|x|)""" @staticmethod def forward(ctx, input): return torch.sign(input) * torch.mean(torch.abs(input)) @staticmethod def backward(ctx, grad_output): return grad_output class QuanConv(nn.Conv2d): """docstring for QuanConv""" def __init__(self, in_channels, out_channels, kernel_size, quan_name_w= 'dorefa', quan_name_a='dorefa', nbit_w=1, nbit_a=1, stride=1, padding=0, dilation=1, groups=1, bias=True): super(QuanConv, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) self.nbit_w = nbit_w self.nbit_a = nbit_a name_w_dict = {'dorefa': dorefa_w} name_a_dict = {'dorefa': dorefa_a} self.quan_w = name_w_dict[quan_name_w] self.quan_a = name_a_dict[quan_name_a] def forward(self, input): if self.nbit_w < 32: w = self.quan_w(self.weight, self.nbit_w) else: w = self.weight if self.nbit_a < 32: x = self.quan_a(input, self.nbit_a) else: x = input output = F.conv2d(x, w, self.bias, self.stride, self.padding, self. dilation, self.groups) return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math from torch.autograd import Function import torch.utils.data.distributed 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_per_fused_abs_mean_mul_sign_0(in_ptr0, 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_math.abs(tmp0) tmp2 = tl.broadcast_to(tmp1, [RBLOCK]) tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0)) tmp5 = tl.full([1], 0, tl.int32) tmp6 = tmp5 < tmp0 tmp7 = tmp6.to(tl.int8) tmp8 = tmp0 < tmp5 tmp9 = tmp8.to(tl.int8) tmp10 = tmp7 - tmp9 tmp11 = tmp10.to(tmp0.dtype) tmp12 = 256.0 tmp13 = tmp4 / tmp12 tmp14 = tmp11 * tmp13 tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp14, None) @triton.jit def triton_poi_fused_clamp_div_mul_round_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.1 tmp2 = tmp0 * tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 1.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp6 * tmp5 tmp8 = libdevice.nearbyint(tmp7) tmp9 = tmp8 * tmp5 tl.store(out_ptr0 + x0, tmp9, xmask) @triton.jit def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_abs_mean_mul_sign_0[grid(1)](primals_1, buf1, 1, 256, num_warps=2, num_stages=1) del primals_1 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_clamp_div_mul_round_1[grid(256)](primals_2, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf3 = extern_kernels.convolution(buf2, buf1, 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, 1, 1), (4, 1, 1, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_2[grid(16)](buf4, primals_3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 return buf4, buf1, buf2 def quantize(input, nbit): return Quantizer.apply(input, nbit) def dorefa_a(input, nbit_a): return quantize(torch.clamp(0.1 * input, 0, 1), nbit_a) def scale_sign(input): return ScaleSigner.apply(input) def dorefa_w(w, nbit_w): if nbit_w == 1: w = scale_sign(w) else: w = torch.tanh(w) w = w / (2 * torch.max(torch.abs(w))) + 0.5 w = 2 * quantize(w, nbit_w) - 1 return w class Quantizer(Function): @staticmethod def forward(ctx, input, nbit): scale = 2 ** nbit - 1 return torch.round(input * scale) / scale @staticmethod def backward(ctx, grad_output): return grad_output, None class ScaleSigner(Function): """take a real value x, output sign(x)*E(|x|)""" @staticmethod def forward(ctx, input): return torch.sign(input) * torch.mean(torch.abs(input)) @staticmethod def backward(ctx, grad_output): return grad_output class QuanConvNew(nn.Conv2d): """docstring for QuanConv""" def __init__(self, in_channels, out_channels, kernel_size, quan_name_w= 'dorefa', quan_name_a='dorefa', nbit_w=1, nbit_a=1, stride=1, padding=0, dilation=1, groups=1, bias=True): super(QuanConvNew, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) self.nbit_w = nbit_w self.nbit_a = nbit_a name_w_dict = {'dorefa': dorefa_w} name_a_dict = {'dorefa': dorefa_a} self.quan_w = name_w_dict[quan_name_w] self.quan_a = name_a_dict[quan_name_a] def forward(self, input_0): primals_1 = self.weight primals_3 = self.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Jzz24/pytorch_quantization
QuanConv
false
13,960
[ "MIT" ]
71
0c2d93c8ce4f85dd2c34ea6f36c58d14db21bf8e
https://github.com/Jzz24/pytorch_quantization/tree/0c2d93c8ce4f85dd2c34ea6f36c58d14db21bf8e
SlicedWasserstein
import torch class SlicedWasserstein(torch.nn.Module): """ Implementation of the loss used in [Sliced Wasserstein Discrepancy for Unsupervised Domain Adaptation](https://arxiv.org/abs/1903.04064) """ def __init__(self, m: 'int'=128): """ Arguments: m: The dimensionality to project to. """ super().__init__() self.m = 128 def forward(self, x: 'torch.Tensor', y: 'torch.Tensor') ->torch.Tensor: """ Arguments: x: a batch of class predictions y: the other batch of class predictions Returns: The discrepancy between the two batches of class predictions. """ d = x.shape[1] proj = torch.randn(d, self.m, device=x.device) proj = torch.nn.functional.normalize(proj, dim=0) x = torch.matmul(x, proj) y = torch.matmul(y, proj) x, _ = torch.sort(x, dim=0) y, _ = torch.sort(y, dim=0) return torch.mean((x - y) ** 2) def extra_repr(self): """""" return c_f.extra_repr(self, ['m']) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch 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 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_poi_fused_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (256 + x0), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (384 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-12 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = tmp0 / tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_per_fused_sort_1(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl. constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xindex = 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) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 2048 * r1), None) tmp1 = r1 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 + 2048 * r1), tmp5, None) @triton.jit def triton_red_fused_mean_pow_sub_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr): rnumel = 8192 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rbase = tl.arange(0, RBLOCK)[None, :] _tmp5 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r0 = rindex tmp0 = tl.load(in_ptr0 + r0, rmask, eviction_policy='evict_first', other=0.0) tmp1 = tl.load(in_ptr1 + r0, rmask, eviction_policy='evict_first', other=0.0) tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp6 = _tmp5 + tmp4 _tmp5 = tl.where(rmask, tmp6, _tmp5) tmp5 = tl.sum(_tmp5, 1)[:, None] tmp7 = 8192.0 tmp8 = tmp5 / 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 = torch.ops.aten.randn.default([4, 128], device=device(type= 'cuda', index=0), pin_memory=False) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 128), (128, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(512)](buf1, buf2, 512, XBLOCK=256, num_warps=4, num_stages=1) del buf1 buf3 = empty_strided_cuda((64, 128), (128, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(arg0_1, (64, 4), (4, 1), 0), buf2, out=buf3) del arg0_1 buf4 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1), torch.float32) triton_per_fused_sort_1[grid(2048)](buf3, buf4, 2048, 4, XBLOCK=32, num_warps=2, num_stages=1) buf6 = buf3 del buf3 extern_kernels.mm(reinterpret_tensor(arg1_1, (64, 4), (4, 1), 0), buf2, out=buf6) del arg1_1 del buf2 buf7 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1), torch.float32) triton_per_fused_sort_1[grid(2048)](buf6, buf7, 2048, 4, XBLOCK=32, num_warps=2, num_stages=1) del buf6 buf9 = empty_strided_cuda((), (), torch.float32) buf10 = buf9 del buf9 triton_red_fused_mean_pow_sub_2[grid(1)](buf10, buf4, buf7, 1, 8192, XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1) del buf4 del buf7 return buf10, class SlicedWassersteinNew(torch.nn.Module): """ Implementation of the loss used in [Sliced Wasserstein Discrepancy for Unsupervised Domain Adaptation](https://arxiv.org/abs/1903.04064) """ def __init__(self, m: 'int'=128): """ Arguments: m: The dimensionality to project to. """ super().__init__() self.m = 128 def extra_repr(self): """""" return c_f.extra_repr(self, ['m']) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
KevinMusgrave/pytorch-adapt
SlicedWasserstein
false
13,961
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
EncoderImagePrecomp
import torch import numpy as np from torch import nn from collections import OrderedDict import torch.nn.init def l2norm(X): """L2-normalize columns of X """ norm = torch.pow(X, 2).sum(dim=1, keepdim=True).sqrt() X = torch.div(X, norm) return X class EncoderImagePrecomp(nn.Module): def __init__(self, img_dim, embed_size, use_abs=False, no_imgnorm=False): super(EncoderImagePrecomp, self).__init__() self.embed_size = embed_size self.no_imgnorm = no_imgnorm self.use_abs = use_abs self.fc = nn.Linear(img_dim, embed_size) self.init_weights() def init_weights(self): """Xavier initialization for the fully connected layer """ r = np.sqrt(6.0) / np.sqrt(self.fc.in_features + self.fc.out_features) self.fc.weight.data.uniform_(-r, r) self.fc.bias.data.fill_(0) def forward(self, images): """Extract image feature vectors.""" features = self.fc(images) if not self.no_imgnorm: features = l2norm(features) if self.use_abs: features = torch.abs(features) return features def load_state_dict(self, state_dict): """Copies parameters. overwritting the default one to accept state_dict from Full model """ own_state = self.state_dict() new_state = OrderedDict() for name, param in state_dict.items(): if name in own_state: new_state[name] = param super(EncoderImagePrecomp, self).load_state_dict(new_state) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'img_dim': 4, 'embed_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import numpy as np from torch import nn from collections import OrderedDict import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_div_pow_sqrt_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = tmp0 / tmp12 tl.store(out_ptr0 + x3, tmp13, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_pow_sqrt_sum_0[grid(256)](buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0 def l2norm(X): """L2-normalize columns of X """ norm = torch.pow(X, 2).sum(dim=1, keepdim=True).sqrt() X = torch.div(X, norm) return X class EncoderImagePrecompNew(nn.Module): def __init__(self, img_dim, embed_size, use_abs=False, no_imgnorm=False): super(EncoderImagePrecompNew, self).__init__() self.embed_size = embed_size self.no_imgnorm = no_imgnorm self.use_abs = use_abs self.fc = nn.Linear(img_dim, embed_size) self.init_weights() def init_weights(self): """Xavier initialization for the fully connected layer """ r = np.sqrt(6.0) / np.sqrt(self.fc.in_features + self.fc.out_features) self.fc.weight.data.uniform_(-r, r) self.fc.bias.data.fill_(0) def load_state_dict(self, state_dict): """Copies parameters. overwritting the default one to accept state_dict from Full model """ own_state = self.state_dict() new_state = OrderedDict() for name, param in state_dict.items(): if name in own_state: new_state[name] = param super(EncoderImagePrecompNew, self).load_state_dict(new_state) def forward(self, input_0): primals_1 = self.fc.weight primals_2 = self.fc.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
KunpengLi1994/VSRN
EncoderImagePrecomp
false
13,962
[ "Apache-2.0" ]
238
777ae74326fdb6abe69dbd3911d0e545322520d1
https://github.com/KunpengLi1994/VSRN/tree/777ae74326fdb6abe69dbd3911d0e545322520d1
SppBlock
import torch import torch.nn.functional as F from torch import nn class SppBlock(nn.Module): def __init__(self, in_channels): super(SppBlock, self).__init__() self.pool1 = nn.MaxPool2d(kernel_size=[2, 2], stride=2) self.pool2 = nn.MaxPool2d(kernel_size=[3, 3], stride=3) self.pool3 = nn.MaxPool2d(kernel_size=[5, 5], stride=5) self.pool4 = nn.MaxPool2d(kernel_size=[6, 6], stride=6) self.conv = nn.Conv2d(in_channels=in_channels, out_channels=1, kernel_size=1, padding=0) def forward(self, x): self.in_channels, h, w = x.size(1), x.size(2), x.size(3) self.layer1 = F.interpolate(self.conv(self.pool1(x)), size=(h, w), mode='bilinear', align_corners=True) self.layer2 = F.interpolate(self.conv(self.pool2(x)), size=(h, w), mode='bilinear', align_corners=True) self.layer3 = F.interpolate(self.conv(self.pool3(x)), size=(h, w), mode='bilinear', align_corners=True) self.layer4 = F.interpolate(self.conv(self.pool4(x)), size=(h, w), mode='bilinear', align_corners=True) out = torch.cat([self.layer1, self.layer2, self.layer3, self.layer4, x], 1) return out def get_inputs(): return [torch.rand([4, 4, 64, 64])] 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 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_max_pool2d_with_indices_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 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tl.store(out_ptr0 + x2, tmp6, None) @triton.jit def triton_poi_fused__to_copy_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.49206349206349204 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tl.store(out_ptr0 + x0, tmp6, 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.49206349206349204 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 31, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tl.store(out_ptr0 + x0, tmp10, xmask) @triton.jit def triton_poi_fused__to_copy_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.49206349206349204 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tmp6.to(tl.float32) tmp8 = tmp5 - tmp7 tmp9 = triton_helpers.maximum(tmp8, tmp4) tmp10 = 1.0 tmp11 = triton_helpers.minimum(tmp9, tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 7056 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 21 x1 = xindex // 21 % 21 x4 = xindex // 441 x3 = xindex // 1764 x5 = xindex % 1764 tmp0 = tl.load(in_ptr0 + (3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (64 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (65 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (66 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (128 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr0 + (129 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp15 = tl.load(in_ptr0 + (130 + 3 * x0 + 192 * x1 + 4096 * x4), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tmp8 = triton_helpers.maximum(tmp7, tmp6) tmp10 = triton_helpers.maximum(tmp9, tmp8) tmp12 = triton_helpers.maximum(tmp11, tmp10) tmp14 = triton_helpers.maximum(tmp13, tmp12) tmp16 = triton_helpers.maximum(tmp15, tmp14) tl.store(out_ptr0 + (x5 + 1792 * x3), tmp16, xmask) @triton.jit def triton_poi_fused__to_copy_5(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.31746031746031744 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_add_clamp_6(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.31746031746031744 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 20, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tl.store(out_ptr0 + x0, tmp10, xmask) @triton.jit def triton_poi_fused__to_copy_arange_clamp_mul_sub_7(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.31746031746031744 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tmp6.to(tl.float32) tmp8 = tmp5 - tmp7 tmp9 = triton_helpers.maximum(tmp8, tmp4) tmp10 = 1.0 tmp11 = triton_helpers.minimum(tmp9, tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_8(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2304 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 12 x1 = xindex // 12 % 12 x2 = xindex // 144 x3 = xindex tmp0 = tl.load(in_ptr0 + (5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (4 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (64 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (65 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr0 + (66 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp15 = tl.load(in_ptr0 + (67 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp17 = tl.load(in_ptr0 + (68 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp19 = tl.load(in_ptr0 + (128 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp21 = tl.load(in_ptr0 + (129 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp23 = tl.load(in_ptr0 + (130 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp25 = tl.load(in_ptr0 + (131 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp27 = tl.load(in_ptr0 + (132 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp29 = tl.load(in_ptr0 + (192 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp31 = tl.load(in_ptr0 + (193 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp33 = tl.load(in_ptr0 + (194 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp35 = tl.load(in_ptr0 + (195 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp37 = tl.load(in_ptr0 + (196 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp39 = tl.load(in_ptr0 + (256 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp41 = tl.load(in_ptr0 + (257 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp43 = tl.load(in_ptr0 + (258 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp45 = tl.load(in_ptr0 + (259 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp47 = tl.load(in_ptr0 + (260 + 5 * x0 + 320 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tmp8 = triton_helpers.maximum(tmp7, tmp6) tmp10 = triton_helpers.maximum(tmp9, tmp8) tmp12 = triton_helpers.maximum(tmp11, tmp10) tmp14 = triton_helpers.maximum(tmp13, tmp12) tmp16 = triton_helpers.maximum(tmp15, tmp14) tmp18 = triton_helpers.maximum(tmp17, tmp16) tmp20 = triton_helpers.maximum(tmp19, tmp18) tmp22 = triton_helpers.maximum(tmp21, tmp20) tmp24 = triton_helpers.maximum(tmp23, tmp22) tmp26 = triton_helpers.maximum(tmp25, tmp24) tmp28 = triton_helpers.maximum(tmp27, tmp26) tmp30 = triton_helpers.maximum(tmp29, tmp28) tmp32 = triton_helpers.maximum(tmp31, tmp30) tmp34 = triton_helpers.maximum(tmp33, tmp32) tmp36 = triton_helpers.maximum(tmp35, tmp34) tmp38 = triton_helpers.maximum(tmp37, tmp36) tmp40 = triton_helpers.maximum(tmp39, tmp38) tmp42 = triton_helpers.maximum(tmp41, tmp40) tmp44 = triton_helpers.maximum(tmp43, tmp42) tmp46 = triton_helpers.maximum(tmp45, tmp44) tmp48 = triton_helpers.maximum(tmp47, tmp46) tl.store(out_ptr0 + x3, tmp48, xmask) @triton.jit def triton_poi_fused__to_copy_9(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.1746031746031746 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_add_clamp_10(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.1746031746031746 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 11, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tl.store(out_ptr0 + x0, tmp10, xmask) @triton.jit def triton_poi_fused__to_copy_arange_clamp_mul_sub_11(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.1746031746031746 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tmp6.to(tl.float32) tmp8 = tmp5 - tmp7 tmp9 = triton_helpers.maximum(tmp8, tmp4) tmp10 = 1.0 tmp11 = triton_helpers.minimum(tmp9, tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused__to_copy_12(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.14285714285714285 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_add_clamp_13(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.14285714285714285 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 9, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tl.store(out_ptr0 + x0, tmp10, xmask) @triton.jit def triton_poi_fused__to_copy_arange_clamp_mul_sub_14(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.14285714285714285 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tmp6.to(tl.float32) tmp8 = tmp5 - tmp7 tmp9 = triton_helpers.maximum(tmp8, tmp4) tmp10 = 1.0 tmp11 = triton_helpers.minimum(tmp9, tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused__unsafe_index_add_convolution_mul_sub_15(in_out_ptr0, in_out_ptr1, in_out_ptr2, in_out_ptr3, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10, in_ptr11, in_ptr12, in_ptr13, in_ptr14, in_ptr15, in_ptr16, in_ptr17, in_ptr18, in_ptr19, in_ptr20, in_ptr21, in_ptr22, in_ptr23, in_ptr24, in_ptr25, in_ptr26, in_ptr27, in_ptr28, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x1 = xindex // 64 % 64 x0 = xindex % 64 x2 = xindex // 4096 x3 = xindex tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + 0) tmp11 = tl.broadcast_to(tmp10, [XBLOCK]) tmp13 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp20 = tl.load(in_ptr5 + x0, None, eviction_policy='evict_last') tmp23 = tl.load(in_ptr6 + x1, None, eviction_policy='evict_last') tmp35 = tl.load(in_ptr7 + x1, None, eviction_policy='evict_last') tmp38 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last') tmp43 = tl.load(in_ptr9 + x0, None, eviction_policy='evict_last') tmp49 = tl.load(in_ptr11 + x0, None, eviction_policy='evict_last') tmp56 = tl.load(in_ptr12 + x0, None, eviction_policy='evict_last') tmp59 = tl.load(in_ptr13 + x1, None, eviction_policy='evict_last') tmp71 = tl.load(in_ptr14 + x1, None, eviction_policy='evict_last') tmp74 = tl.load(in_ptr15 + x1, None, eviction_policy='evict_last') tmp79 = tl.load(in_ptr16 + x0, None, eviction_policy='evict_last') tmp85 = tl.load(in_ptr18 + x0, None, eviction_policy='evict_last') tmp92 = tl.load(in_ptr19 + x0, None, eviction_policy='evict_last') tmp95 = tl.load(in_ptr20 + x1, None, eviction_policy='evict_last') tmp107 = tl.load(in_ptr21 + x1, None, eviction_policy='evict_last') tmp110 = tl.load(in_ptr22 + x1, None, eviction_policy='evict_last') tmp115 = tl.load(in_ptr23 + x0, None, eviction_policy='evict_last') tmp121 = tl.load(in_ptr25 + x0, None, eviction_policy='evict_last') tmp128 = tl.load(in_ptr26 + x0, None, eviction_policy='evict_last') tmp131 = tl.load(in_ptr27 + x1, None, eviction_policy='evict_last') tmp143 = tl.load(in_ptr28 + x1, None, 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_ptr2 + (tmp8 + 32 * tmp4 + 1024 * x2), None, eviction_policy='evict_last') tmp12 = tmp9 + tmp11 tmp14 = tmp13 + tmp1 tmp15 = tmp13 < 0 tmp16 = tl.where(tmp15, tmp14, tmp13) tmp17 = tl.load(in_ptr2 + (tmp16 + 32 * tmp4 + 1024 * x2), None, eviction_policy='evict_last') tmp18 = tmp17 + tmp11 tmp19 = tmp18 - tmp12 tmp21 = tmp19 * tmp20 tmp22 = tmp12 + tmp21 tmp24 = tmp23 + tmp1 tmp25 = tmp23 < 0 tmp26 = tl.where(tmp25, tmp24, tmp23) tmp27 = tl.load(in_ptr2 + (tmp8 + 32 * tmp26 + 1024 * x2), None, eviction_policy='evict_last') tmp28 = tmp27 + tmp11 tmp29 = tl.load(in_ptr2 + (tmp16 + 32 * tmp26 + 1024 * x2), None, eviction_policy='evict_last') tmp30 = tmp29 + tmp11 tmp31 = tmp30 - tmp28 tmp32 = tmp31 * tmp20 tmp33 = tmp28 + tmp32 tmp34 = tmp33 - tmp22 tmp36 = tmp34 * tmp35 tmp37 = tmp22 + tmp36 tmp39 = tl.full([XBLOCK], 21, tl.int32) tmp40 = tmp38 + tmp39 tmp41 = tmp38 < 0 tmp42 = tl.where(tmp41, tmp40, tmp38) tmp44 = tmp43 + tmp39 tmp45 = tmp43 < 0 tmp46 = tl.where(tmp45, tmp44, tmp43) tmp47 = tl.load(in_ptr10 + (tmp46 + 21 * tmp42 + 441 * x2), None, eviction_policy='evict_last') tmp48 = tmp47 + tmp11 tmp50 = tmp49 + tmp39 tmp51 = tmp49 < 0 tmp52 = tl.where(tmp51, tmp50, tmp49) tmp53 = tl.load(in_ptr10 + (tmp52 + 21 * tmp42 + 441 * x2), None, eviction_policy='evict_last') tmp54 = tmp53 + tmp11 tmp55 = tmp54 - tmp48 tmp57 = tmp55 * tmp56 tmp58 = tmp48 + tmp57 tmp60 = tmp59 + tmp39 tmp61 = tmp59 < 0 tmp62 = tl.where(tmp61, tmp60, tmp59) tmp63 = tl.load(in_ptr10 + (tmp46 + 21 * tmp62 + 441 * x2), None, eviction_policy='evict_last') tmp64 = tmp63 + tmp11 tmp65 = tl.load(in_ptr10 + (tmp52 + 21 * tmp62 + 441 * x2), None, eviction_policy='evict_last') tmp66 = tmp65 + tmp11 tmp67 = tmp66 - tmp64 tmp68 = tmp67 * tmp56 tmp69 = tmp64 + tmp68 tmp70 = tmp69 - tmp58 tmp72 = tmp70 * tmp71 tmp73 = tmp58 + tmp72 tmp75 = tl.full([XBLOCK], 12, tl.int32) tmp76 = tmp74 + tmp75 tmp77 = tmp74 < 0 tmp78 = tl.where(tmp77, tmp76, tmp74) tmp80 = tmp79 + tmp75 tmp81 = tmp79 < 0 tmp82 = tl.where(tmp81, tmp80, tmp79) tmp83 = tl.load(in_ptr17 + (tmp82 + 12 * tmp78 + 144 * x2), None, eviction_policy='evict_last') tmp84 = tmp83 + tmp11 tmp86 = tmp85 + tmp75 tmp87 = tmp85 < 0 tmp88 = tl.where(tmp87, tmp86, tmp85) tmp89 = tl.load(in_ptr17 + (tmp88 + 12 * tmp78 + 144 * x2), None, eviction_policy='evict_last') tmp90 = tmp89 + tmp11 tmp91 = tmp90 - tmp84 tmp93 = tmp91 * tmp92 tmp94 = tmp84 + tmp93 tmp96 = tmp95 + tmp75 tmp97 = tmp95 < 0 tmp98 = tl.where(tmp97, tmp96, tmp95) tmp99 = tl.load(in_ptr17 + (tmp82 + 12 * tmp98 + 144 * x2), None, eviction_policy='evict_last') tmp100 = tmp99 + tmp11 tmp101 = tl.load(in_ptr17 + (tmp88 + 12 * tmp98 + 144 * x2), None, eviction_policy='evict_last') tmp102 = tmp101 + tmp11 tmp103 = tmp102 - tmp100 tmp104 = tmp103 * tmp92 tmp105 = tmp100 + tmp104 tmp106 = tmp105 - tmp94 tmp108 = tmp106 * tmp107 tmp109 = tmp94 + tmp108 tmp111 = tl.full([XBLOCK], 10, tl.int32) tmp112 = tmp110 + tmp111 tmp113 = tmp110 < 0 tmp114 = tl.where(tmp113, tmp112, tmp110) tmp116 = tmp115 + tmp111 tmp117 = tmp115 < 0 tmp118 = tl.where(tmp117, tmp116, tmp115) tmp119 = tl.load(in_ptr24 + (tmp118 + 10 * tmp114 + 100 * x2), None, eviction_policy='evict_last') tmp120 = tmp119 + tmp11 tmp122 = tmp121 + tmp111 tmp123 = tmp121 < 0 tmp124 = tl.where(tmp123, tmp122, tmp121) tmp125 = tl.load(in_ptr24 + (tmp124 + 10 * tmp114 + 100 * x2), None, eviction_policy='evict_last') tmp126 = tmp125 + tmp11 tmp127 = tmp126 - tmp120 tmp129 = tmp127 * tmp128 tmp130 = tmp120 + tmp129 tmp132 = tmp131 + tmp111 tmp133 = tmp131 < 0 tmp134 = tl.where(tmp133, tmp132, tmp131) tmp135 = tl.load(in_ptr24 + (tmp118 + 10 * tmp134 + 100 * x2), None, eviction_policy='evict_last') tmp136 = tmp135 + tmp11 tmp137 = tl.load(in_ptr24 + (tmp124 + 10 * tmp134 + 100 * x2), None, eviction_policy='evict_last') tmp138 = tmp137 + tmp11 tmp139 = tmp138 - tmp136 tmp140 = tmp139 * tmp128 tmp141 = tmp136 + tmp140 tmp142 = tmp141 - tmp130 tmp144 = tmp142 * tmp143 tmp145 = tmp130 + tmp144 tl.store(in_out_ptr0 + x3, tmp37, None) tl.store(in_out_ptr1 + x3, tmp73, None) tl.store(in_out_ptr2 + x3, tmp109, None) tl.store(in_out_ptr3 + x3, tmp145, None) @triton.jit def triton_poi_fused_cat_16(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) x1 = xindex // 4096 % 8 x0 = xindex % 4096 x2 = xindex // 32768 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 + 4096 * x2), tmp4, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 2, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr1 + (x0 + 4096 * x2), tmp9, eviction_policy= 'evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 3, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr2 + (x0 + 4096 * x2), tmp14, eviction_policy= 'evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tmp17 = tl.full([1], 4, tl.int64) tmp18 = tmp0 < tmp17 tmp19 = tmp16 & tmp18 tmp20 = tl.load(in_ptr3 + (x0 + 4096 * x2), tmp19, eviction_policy= 'evict_last', other=0.0) tmp21 = tmp0 >= tmp17 tl.full([1], 8, tl.int64) tmp24 = tl.load(in_ptr4 + (x0 + 4096 * (-4 + x1) + 16384 * x2), tmp21, other=0.0) tmp25 = tl.where(tmp19, tmp20, tmp24) tmp26 = tl.where(tmp14, tmp15, tmp25) tmp27 = tl.where(tmp9, tmp10, tmp26) tmp28 = tl.where(tmp4, tmp5, tmp27) tl.store(out_ptr0 + x3, tmp28, None) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 64, 64), (16384, 4096, 64, 1)) assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(16384)](primals_1, buf0, 16384, XBLOCK=128, num_warps=4, num_stages=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, 1, 32, 32), (1024, 1024, 32, 1)) buf2 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_1[grid(64)](buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_2[grid(64)](buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused__to_copy_1[grid(64)](buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused_add_clamp_2[grid(64)](buf5, 64, XBLOCK=64, num_warps=1, num_stages=1) buf6 = empty_strided_cuda((64,), (1,), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_3[grid(64)](buf6, 64, XBLOCK=64, num_warps=1, num_stages=1) buf11 = empty_strided_cuda((4, 4, 21, 21), (1792, 441, 21, 1), torch.float32) triton_poi_fused_max_pool2d_with_indices_4[grid(7056)](primals_1, buf11, 7056, XBLOCK=256, num_warps=4, num_stages=1) buf12 = extern_kernels.convolution(buf11, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 1, 21, 21), (441, 441, 21, 1)) buf13 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_5[grid(64)](buf13, 64, XBLOCK=64, num_warps=1, num_stages=1) buf14 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_6[grid(64)](buf14, 64, XBLOCK=64, num_warps=1, num_stages=1) buf15 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused__to_copy_5[grid(64)](buf15, 64, XBLOCK=64, num_warps=1, num_stages=1) buf16 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused_add_clamp_6[grid(64)](buf16, 64, XBLOCK=64, num_warps=1, num_stages=1) buf17 = empty_strided_cuda((64,), (1,), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_7[grid(64)](buf17, 64, XBLOCK=64, num_warps=1, num_stages=1) buf19 = empty_strided_cuda((64, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_7[grid(64)](buf19, 64, XBLOCK=64, num_warps=1, num_stages=1) buf22 = empty_strided_cuda((4, 4, 12, 12), (576, 144, 12, 1), torch .float32) triton_poi_fused_max_pool2d_with_indices_8[grid(2304)](primals_1, buf22, 2304, XBLOCK=128, num_warps=4, num_stages=1) buf23 = extern_kernels.convolution(buf22, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf23, (4, 1, 12, 12), (144, 144, 12, 1)) buf24 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_9[grid(64)](buf24, 64, XBLOCK=64, num_warps=1, num_stages=1) buf25 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_10[grid(64)](buf25, 64, XBLOCK=64, num_warps=1, num_stages=1) buf26 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused__to_copy_9[grid(64)](buf26, 64, XBLOCK=64, num_warps=1, num_stages=1) buf27 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused_add_clamp_10[grid(64)](buf27, 64, XBLOCK=64, num_warps=1, num_stages=1) buf28 = empty_strided_cuda((64,), (1,), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_11[grid(64)](buf28, 64, XBLOCK=64, num_warps=1, num_stages=1) buf30 = empty_strided_cuda((64, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_11[grid(64)](buf30, 64, XBLOCK=64, num_warps=1, num_stages=1) buf33 = torch.ops.aten.max_pool2d_with_indices.default(primals_1, [ 6, 6], [6, 6]) buf34 = buf33[0] del buf33 buf36 = extern_kernels.convolution(buf34, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf36, (4, 1, 10, 10), (100, 100, 10, 1)) buf37 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_12[grid(64)](buf37, 64, XBLOCK=64, num_warps=1, num_stages=1) buf38 = empty_strided_cuda((64, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_13[grid(64)](buf38, 64, XBLOCK=64, num_warps=1, num_stages=1) buf39 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused__to_copy_12[grid(64)](buf39, 64, XBLOCK=64, num_warps=1, num_stages=1) buf40 = empty_strided_cuda((64,), (1,), torch.int64) triton_poi_fused_add_clamp_13[grid(64)](buf40, 64, XBLOCK=64, num_warps=1, num_stages=1) buf41 = empty_strided_cuda((64,), (1,), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_14[grid(64)](buf41, 64, XBLOCK=64, num_warps=1, num_stages=1) buf43 = empty_strided_cuda((64, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_14[grid(64)](buf43, 64, XBLOCK=64, num_warps=1, num_stages=1) buf8 = empty_strided_cuda((64, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_arange_clamp_mul_sub_3[grid(64)](buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1), torch.float32) buf10 = reinterpret_tensor(buf9, (4, 1, 64, 64), (4096, 4096, 64, 1), 0 ) del buf9 buf20 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1), torch.float32) buf21 = reinterpret_tensor(buf20, (4, 1, 64, 64), (4096, 4096, 64, 1), 0) del buf20 buf31 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1), torch.float32) buf32 = reinterpret_tensor(buf31, (4, 1, 64, 64), (4096, 4096, 64, 1), 0) del buf31 buf44 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1), torch.float32) buf45 = reinterpret_tensor(buf44, (4, 1, 64, 64), (4096, 4096, 64, 1), 0) del buf44 triton_poi_fused__unsafe_index_add_convolution_mul_sub_15[grid(16384)]( buf10, buf21, buf32, buf45, buf2, buf4, buf1, primals_3, buf5, buf6, buf3, buf8, buf13, buf15, buf12, buf16, buf17, buf14, buf19, buf24, buf26, buf23, buf27, buf28, buf25, buf30, buf37, buf39, buf36, buf40, buf41, buf38, buf43, 16384, XBLOCK=256, num_warps=4, num_stages=1) del buf1 del buf12 del buf23 del buf36 del primals_3 buf46 = empty_strided_cuda((4, 8, 64, 64), (32768, 4096, 64, 1), torch.float32) triton_poi_fused_cat_16[grid(131072)](buf10, buf21, buf32, buf45, primals_1, buf46, 131072, XBLOCK=512, num_warps=8, num_stages=1) del primals_1 return (buf46, buf45, buf32, buf21, buf10, primals_2, buf0, buf2, buf3, buf4, buf5, buf6, buf8, buf11, buf13, buf14, buf15, buf16, buf17, buf19, buf22, buf24, buf25, buf26, buf27, buf28, buf30, buf34, buf37, buf38, buf39, buf40, buf41, buf43) class SppBlockNew(nn.Module): def __init__(self, in_channels): super(SppBlockNew, self).__init__() self.pool1 = nn.MaxPool2d(kernel_size=[2, 2], stride=2) self.pool2 = nn.MaxPool2d(kernel_size=[3, 3], stride=3) self.pool3 = nn.MaxPool2d(kernel_size=[5, 5], stride=5) self.pool4 = nn.MaxPool2d(kernel_size=[6, 6], stride=6) self.conv = nn.Conv2d(in_channels=in_channels, out_channels=1, kernel_size=1, padding=0) def forward(self, input_0): primals_2 = self.conv.weight primals_3 = self.conv.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
JiYuanFeng/MCTrans
SppBlock
false
13,963
[ "Apache-2.0" ]
84
9b8b5677eef584b423d5e1630680a4b667cbe823
https://github.com/JiYuanFeng/MCTrans/tree/9b8b5677eef584b423d5e1630680a4b667cbe823
SymNetsCategoryLoss
import torch import torch.nn.functional as F def split_half(x, dim): d = x.shape[dim] // 2 return torch.split(x, d, dim=dim) class ConcatSoftmax(torch.nn.Module): """ Applies softmax to the concatenation of a list of tensors. """ def __init__(self, dim: 'int'=1): """ Arguments: dim: a dimension along which softmax will be computed """ super().__init__() self.dim = dim def forward(self, *x: torch.Tensor): """ Arguments: *x: A sequence of tensors to be concatenated """ all_logits = torch.cat(x, dim=self.dim) return torch.nn.functional.softmax(all_logits, dim=self.dim) def extra_repr(self): """""" return c_f.extra_repr(self, ['dim']) class SymNetsCategoryLoss(torch.nn.Module): def __init__(self): super().__init__() self.softmax_fn = ConcatSoftmax() def forward(self, x, y, src_labels): x = self.softmax_fn(x, y) x, y = split_half(x, dim=1) x_loss = F.cross_entropy(x, src_labels) y_loss = F.cross_entropy(y, src_labels) return x_loss + y_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 math as tl_math assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused__log_softmax__softmax_cat_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 64 RBLOCK: tl.constexpr = 8 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r2 = rindex x0 = xindex % 16 x1 = xindex // 16 x3 = xindex tmp0 = r2 tmp1 = tl.full([1, 1], 0, tl.int64) tmp3 = tl.full([1, 1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1, 1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + r2) + 64 * x1), tmp6 & xmask, other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK]) tmp13 = tl.where(xmask, tmp11, float('-inf')) tmp14 = triton_helpers.max2(tmp13, 1)[:, None] tmp15 = tmp10 - tmp14 tmp16 = tl_math.exp(tmp15) tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK]) tmp19 = tl.where(xmask, tmp17, 0) tmp20 = tl.sum(tmp19, 1)[:, None] tmp22 = tmp1 < tmp3 tmp23 = tl.load(in_ptr0 + (x0 + 16 * 0 + 64 * x1), tmp22 & xmask, eviction_policy='evict_last', other=0.0) tmp24 = tmp1 >= tmp3 tmp26 = tl.load(in_ptr1 + (x0 + 16 * -4 + 64 * x1), tmp24 & xmask, eviction_policy='evict_last', other=0.0) tmp27 = tl.where(tmp22, tmp23, tmp26) tmp28 = tmp27 - tmp14 tmp29 = tl_math.exp(tmp28) tmp30 = tmp29 / tmp20 tmp31 = tl.full([1, 1], 1, tl.int64) tmp33 = tmp31 < tmp3 tmp34 = tl.load(in_ptr0 + (x0 + 16 * 1 + 64 * x1), tmp33 & xmask, eviction_policy='evict_last', other=0.0) tmp35 = tmp31 >= tmp3 tmp37 = tl.load(in_ptr1 + (x0 + 16 * -3 + 64 * x1), tmp35 & xmask, eviction_policy='evict_last', other=0.0) tmp38 = tl.where(tmp33, tmp34, tmp37) tmp39 = tmp38 - tmp14 tmp40 = tl_math.exp(tmp39) tmp41 = tmp40 / tmp20 tmp42 = triton_helpers.maximum(tmp30, tmp41) tmp43 = tl.full([1, 1], 2, tl.int64) tmp45 = tmp43 < tmp3 tmp46 = tl.load(in_ptr0 + (x0 + 16 * 2 + 64 * x1), tmp45 & xmask, eviction_policy='evict_last', other=0.0) tmp47 = tmp43 >= tmp3 tmp49 = tl.load(in_ptr1 + (x0 + 16 * -2 + 64 * x1), tmp47 & xmask, eviction_policy='evict_last', other=0.0) tmp50 = tl.where(tmp45, tmp46, tmp49) tmp51 = tmp50 - tmp14 tmp52 = tl_math.exp(tmp51) tmp53 = tmp52 / tmp20 tmp54 = triton_helpers.maximum(tmp42, tmp53) tmp55 = tl.full([1, 1], 3, tl.int64) tmp57 = tmp55 < tmp3 tmp58 = tl.load(in_ptr0 + (x0 + 16 * 3 + 64 * x1), tmp57 & xmask, eviction_policy='evict_last', other=0.0) tmp59 = tmp55 >= tmp3 tmp61 = tl.load(in_ptr1 + (x0 + 16 * -1 + 64 * x1), tmp59 & xmask, eviction_policy='evict_last', other=0.0) tmp62 = tl.where(tmp57, tmp58, tmp61) tmp63 = tmp62 - tmp14 tmp64 = tl_math.exp(tmp63) tmp65 = tmp64 / tmp20 tmp66 = triton_helpers.maximum(tmp54, tmp65) tmp68 = tmp3 < tmp3 tmp69 = tl.load(in_ptr0 + (x0 + 16 * 4 + 64 * x1), tmp68 & xmask, eviction_policy='evict_last', other=0.0) tmp70 = tmp3 >= tmp3 tmp72 = tl.load(in_ptr1 + (x0 + 16 * 0 + 64 * x1), tmp70 & xmask, eviction_policy='evict_last', other=0.0) tmp73 = tl.where(tmp68, tmp69, tmp72) tmp74 = tmp73 - tmp14 tmp75 = tl_math.exp(tmp74) tmp76 = tmp75 / tmp20 tmp77 = tl.full([1, 1], 5, tl.int64) tmp79 = tmp77 < tmp3 tmp80 = tl.load(in_ptr0 + (x0 + 16 * 5 + 64 * x1), tmp79 & xmask, eviction_policy='evict_last', other=0.0) tmp81 = tmp77 >= tmp3 tmp83 = tl.load(in_ptr1 + (x0 + 16 * 1 + 64 * x1), tmp81 & xmask, eviction_policy='evict_last', other=0.0) tmp84 = tl.where(tmp79, tmp80, tmp83) tmp85 = tmp84 - tmp14 tmp86 = tl_math.exp(tmp85) tmp87 = tmp86 / tmp20 tmp88 = triton_helpers.maximum(tmp76, tmp87) tmp89 = tl.full([1, 1], 6, tl.int64) tmp91 = tmp89 < tmp3 tmp92 = tl.load(in_ptr0 + (x0 + 16 * 6 + 64 * x1), tmp91 & xmask, eviction_policy='evict_last', other=0.0) tmp93 = tmp89 >= tmp3 tmp95 = tl.load(in_ptr1 + (x0 + 16 * 2 + 64 * x1), tmp93 & xmask, eviction_policy='evict_last', other=0.0) tmp96 = tl.where(tmp91, tmp92, tmp95) tmp97 = tmp96 - tmp14 tmp98 = tl_math.exp(tmp97) tmp99 = tmp98 / tmp20 tmp100 = triton_helpers.maximum(tmp88, tmp99) tmp101 = tl.full([1, 1], 7, tl.int64) tmp103 = tmp101 < tmp3 tmp104 = tl.load(in_ptr0 + (x0 + 16 * 7 + 64 * x1), tmp103 & xmask, eviction_policy='evict_last', other=0.0) tmp105 = tmp101 >= tmp3 tmp107 = tl.load(in_ptr1 + (x0 + 16 * 3 + 64 * x1), tmp105 & xmask, eviction_policy='evict_last', other=0.0) tmp108 = tl.where(tmp103, tmp104, tmp107) tmp109 = tmp108 - tmp14 tmp110 = tl_math.exp(tmp109) tmp111 = tmp110 / tmp20 tmp112 = triton_helpers.maximum(tmp100, tmp111) tl.store(out_ptr2 + x3, tmp66, xmask) tl.store(out_ptr3 + x3, tmp112, xmask) tl.store(out_ptr0 + x3, tmp14, xmask) tl.store(out_ptr1 + x3, tmp20, xmask) @triton.jit def triton_poi_fused__log_softmax_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 16 % 4 x0 = xindex % 16 x2 = xindex // 64 x3 = xindex tmp11 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp14 = tl.load(in_ptr3 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp16 = tl.load(in_ptr4 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp29 = tl.load(in_ptr5 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask, other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tmp12 = tmp10 - tmp11 tmp13 = tl_math.exp(tmp12) tmp15 = tmp13 / tmp14 tmp17 = tmp15 - tmp16 tmp18 = 4 + x1 tmp20 = tmp18 < tmp3 tmp21 = tl.load(in_ptr0 + (x0 + 16 * (4 + x1) + 64 * x2), tmp20 & xmask, other=0.0) tmp22 = tmp18 >= tmp3 tmp24 = tl.load(in_ptr1 + (x0 + 16 * x1 + 64 * x2), tmp22 & xmask, other=0.0) tmp25 = tl.where(tmp20, tmp21, tmp24) tmp26 = tmp25 - tmp11 tmp27 = tl_math.exp(tmp26) tmp28 = tmp27 / tmp14 tmp30 = tmp28 - tmp29 tl.store(out_ptr0 + x3, tmp17, xmask) tl.store(out_ptr1 + x3, tmp30, xmask) @triton.jit def triton_per_fused__log_softmax_add_div_mul_neg_sum_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r3 = rindex r0 = rindex % 16 r2 = rindex // 64 tmp0 = tl.load(in_ptr0 + r3, None) tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp14 = tl.load(in_ptr1 + r3, None) tmp19 = tl.load(in_ptr2 + r3, None) tmp20 = tl.load(in_ptr2 + (r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp22 = tl.load(in_ptr2 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp25 = tl.load(in_ptr2 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp28 = tl.load(in_ptr2 + (48 + r0 + 64 * r2), None, 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 tmp15 = tmp13 * tmp14 tmp16 = tl.broadcast_to(tmp15, [RBLOCK]) tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0)) tmp21 = tl_math.exp(tmp20) tmp23 = tl_math.exp(tmp22) tmp24 = tmp21 + tmp23 tmp26 = tl_math.exp(tmp25) tmp27 = tmp24 + tmp26 tmp29 = tl_math.exp(tmp28) tmp30 = tmp27 + tmp29 tmp31 = tl_math.log(tmp30) tmp32 = tmp19 - tmp31 tmp33 = tmp32 * tmp14 tmp34 = tl.broadcast_to(tmp33, [RBLOCK]) tmp36 = triton_helpers.promote_to_tensor(tl.sum(tmp34, 0)) tmp37 = -tmp18 tmp38 = 0.015625 tmp39 = tmp37 * tmp38 tmp40 = -tmp36 tmp41 = tmp40 * tmp38 tmp42 = tmp39 + tmp41 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp42, 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, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf1 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf2 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused__log_softmax__softmax_cat_0[grid(64)](arg0_1, arg1_1, buf0, buf1, buf2, buf5, 64, 8, XBLOCK=1, num_warps=2, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_1[grid(256)](arg0_1, arg1_1, buf0, buf1, buf2, buf5, buf3, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 del arg1_1 del buf0 del buf1 del buf2 del buf5 buf4 = empty_strided_cuda((), (), torch.float32) buf8 = buf4 del buf4 triton_per_fused__log_softmax_add_div_mul_neg_sum_2[grid(1)](buf8, buf3, arg2_1, buf6, 1, 256, num_warps=2, num_stages=1) del arg2_1 del buf3 del buf6 return buf8, def split_half(x, dim): d = x.shape[dim] // 2 return torch.split(x, d, dim=dim) class ConcatSoftmax(torch.nn.Module): """ Applies softmax to the concatenation of a list of tensors. """ def __init__(self, dim: 'int'=1): """ Arguments: dim: a dimension along which softmax will be computed """ super().__init__() self.dim = dim def forward(self, *x: torch.Tensor): """ Arguments: *x: A sequence of tensors to be concatenated """ all_logits = torch.cat(x, dim=self.dim) return torch.nn.functional.softmax(all_logits, dim=self.dim) def extra_repr(self): """""" return c_f.extra_repr(self, ['dim']) class SymNetsCategoryLossNew(torch.nn.Module): def __init__(self): super().__init__() self.softmax_fn = ConcatSoftmax() 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]
KevinMusgrave/pytorch-adapt
SymNetsCategoryLoss
false
13,964
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
Snake
import torch import torch.nn as nn from torch import sin from torch import pow from torch.nn import Parameter from torch.distributions.exponential import Exponential class Snake(nn.Module): """ Implementation of the serpentine-like sine-based periodic activation function .. math:: Snake_a := x + rac{1}{a} sin^2(ax) = x - rac{1}{2a}cos{2ax} + rac{1}{2a} Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - a - trainable parameter References: - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: https://arxiv.org/abs/2006.08195 Examples: >>> a1 = snake(256) >>> x = torch.randn(256) >>> x = a1(x) """ def __init__(self, in_features, a=None, trainable=True): """ Initialization. Args: in_features: shape of the input a: trainable parameter trainable: sets `a` as a trainable parameter `a` is initialized to 1 by default, higher values = higher-frequency, 5-50 is a good starting point if you already think your data is periodic, consider starting lower e.g. 0.5 if you think not, but don't worry, `a` will be trained along with the rest of your model. """ super(Snake, self).__init__() self.in_features = in_features if isinstance(in_features, list) else [ in_features] if a is not None: self.a = Parameter(torch.ones(self.in_features) * a) else: m = Exponential(torch.tensor([0.1])) self.a = Parameter(m.rsample(self.in_features).squeeze()) self.a.requiresGrad = trainable def forward(self, x): """ Forward pass of the function. Applies the function to the input elementwise. Snake ∶= x + 1/a* sin^2 (xa) """ return x + 1.0 / self.a * pow(sin(x * self.a), 2) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn from torch.nn import Parameter from torch.distributions.exponential import Exponential 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_reciprocal_sin_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tl.full([1], 1, tl.int32) tmp3 = tmp2 / tmp1 tmp4 = 1.0 tmp5 = tmp3 * tmp4 tmp6 = tmp0 * tmp1 tmp7 = tl_math.sin(tmp6) tmp8 = tmp7 * tmp7 tmp9 = tmp5 * tmp8 tmp10 = tmp0 + tmp9 tl.store(out_ptr0 + x2, tmp10, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4,), (1,)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_pow_reciprocal_sin_0[grid(256)](primals_2, primals_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf0, primals_1, primals_2 class SnakeNew(nn.Module): """ Implementation of the serpentine-like sine-based periodic activation function .. math:: Snake_a := x + rac{1}{a} sin^2(ax) = x - rac{1}{2a}cos{2ax} + rac{1}{2a} Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - a - trainable parameter References: - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: https://arxiv.org/abs/2006.08195 Examples: >>> a1 = snake(256) >>> x = torch.randn(256) >>> x = a1(x) """ def __init__(self, in_features, a=None, trainable=True): """ Initialization. Args: in_features: shape of the input a: trainable parameter trainable: sets `a` as a trainable parameter `a` is initialized to 1 by default, higher values = higher-frequency, 5-50 is a good starting point if you already think your data is periodic, consider starting lower e.g. 0.5 if you think not, but don't worry, `a` will be trained along with the rest of your model. """ super(SnakeNew, self).__init__() self.in_features = in_features if isinstance(in_features, list) else [ in_features] if a is not None: self.a = Parameter(torch.ones(self.in_features) * a) else: m = Exponential(torch.tensor([0.1])) self.a = Parameter(m.rsample(self.in_features).squeeze()) self.a.requiresGrad = trainable def forward(self, input_0): primals_1 = self.a primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
Juju-botu/diffeqml-research
Snake
false
13,965
[ "Apache-2.0" ]
49
aa796c87447e5299ec4f25a07fc4d032afb1f63e
https://github.com/Juju-botu/diffeqml-research/tree/aa796c87447e5299ec4f25a07fc4d032afb1f63e
MNISTFeatures
import torch import torch.nn.functional as F import torch.nn as nn class MNISTFeatures(nn.Module): """ A small convnet for extracting features from MNIST. """ def __init__(self): """ """ super().__init__() self.conv1 = nn.Conv2d(3, 32, 5, 1) self.conv2 = nn.Conv2d(32, 48, 5, 1) self.fc = nn.Identity() def forward(self, x): """ """ x = self.conv1(x) x = F.relu(x) x = F.max_pool2d(x, kernel_size=2, stride=2) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, kernel_size=2, stride=2) x = torch.flatten(x, start_dim=1) return self.fc(x) def get_inputs(): return [torch.rand([4, 3, 64, 64])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_convolution_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 3600 % 32 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_1(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 115200 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') tmp3 = tl.load(in_ptr0 + (60 + 2 * x0 + 120 * x1 + 3616 * x2), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (61 + 2 * x0 + 120 * x1 + 3616 * x2), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tmp7 = tmp1 > tmp0 tmp8 = tl.full([1], 1, tl.int8) tmp9 = tl.full([1], 0, tl.int8) tmp10 = tl.where(tmp7, tmp8, tmp9) tmp11 = tmp3 > tmp2 tmp12 = tl.full([1], 2, tl.int8) tmp13 = tl.where(tmp11, tmp12, tmp10) tmp14 = tmp5 > tmp4 tmp15 = tl.full([1], 3, tl.int8) tmp16 = tl.where(tmp14, tmp15, tmp13) tl.store(out_ptr0 + x3, tmp6, xmask) tl.store(out_ptr1 + x3, tmp16, xmask) @triton.jit def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 129792 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 676 % 48 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 32448 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 13 x3 = xindex // 13 x2 = xindex // 8112 x4 = xindex % 8112 x5 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 52 * x3), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 52 * x3), xmask, eviction_policy ='evict_last') tmp7 = tl.load(in_ptr0 + (26 + 2 * x0 + 52 * x3), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr0 + (27 + 2 * x0 + 52 * x3), xmask, eviction_policy='evict_last') tmp2 = tmp1 > tmp0 tmp3 = tl.full([1], 1, tl.int8) tmp4 = tl.full([1], 0, tl.int8) tmp5 = tl.where(tmp2, tmp3, tmp4) tmp6 = triton_helpers.maximum(tmp1, tmp0) tmp8 = tmp7 > tmp6 tmp9 = tl.full([1], 2, tl.int8) tmp10 = tl.where(tmp8, tmp9, tmp5) tmp11 = triton_helpers.maximum(tmp7, tmp6) tmp13 = tmp12 > tmp11 tmp14 = tl.full([1], 3, tl.int8) tmp15 = tl.where(tmp13, tmp14, tmp10) tmp16 = triton_helpers.maximum(tmp12, tmp11) tl.store(out_ptr0 + (x4 + 8192 * x2), tmp15, xmask) tl.store(out_ptr1 + x5, tmp16, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (32, 3, 5, 5), (75, 25, 5, 1)) assert_size_stride(primals_2, (32,), (1,)) assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1)) assert_size_stride(primals_4, (48, 32, 5, 5), (800, 25, 5, 1)) assert_size_stride(primals_5, (48,), (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, 60, 60), (115200, 3600, 60, 1)) buf1 = empty_strided_cuda((4, 32, 60, 60), (115712, 3616, 60, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(460800)](buf0, primals_2, buf1, 460800, XBLOCK=1024, num_warps=4, num_stages=1) del buf0 del primals_2 buf2 = empty_strided_cuda((4, 32, 30, 30), (28800, 900, 30, 1), torch.float32) buf3 = empty_strided_cuda((4, 32, 30, 30), (28800, 900, 30, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_1[grid(115200)](buf1, buf2, buf3, 115200, XBLOCK=512, num_warps=8, num_stages=1) buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 48, 26, 26), (32448, 676, 26, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_2[grid(129792)](buf5, primals_5, 129792, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf6 = empty_strided_cuda((4, 48, 13, 13), (8192, 169, 13, 1), torch.int8) buf7 = empty_strided_cuda((4, 48, 13, 13), (8112, 169, 13, 1), torch.float32) triton_poi_fused_max_pool2d_with_indices_3[grid(32448)](buf5, buf6, buf7, 32448, XBLOCK=128, num_warps=4, num_stages=1) return reinterpret_tensor(buf7, (4, 8112), (8112, 1), 0 ), primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5, buf6 class MNISTFeaturesNew(nn.Module): """ A small convnet for extracting features from MNIST. """ def __init__(self): """ """ super().__init__() self.conv1 = nn.Conv2d(3, 32, 5, 1) self.conv2 = nn.Conv2d(32, 48, 5, 1) self.fc = nn.Identity() 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]
KevinMusgrave/pytorch-adapt
MNISTFeatures
false
13,966
[ "MIT" ]
131
ff1491e1bfcc586afb8ee619712c8816ddf10358
https://github.com/KevinMusgrave/pytorch-adapt/tree/ff1491e1bfcc586afb8ee619712c8816ddf10358
MultiHeadAttention
import torch import numpy as np import torch.nn as nn def dot_product_attention(queries, keys, values, normalise=True): """ :param queries:[batch_size, N_target, key_size] :param keys:[batch_size, N_context, key_size] :param values: [] :param normalise: :return: """ key_size = keys.shape[-1] scale = np.sqrt(key_size) unnorm_weights = torch.matmul(queries, keys.transpose(-2, -1)) / scale if normalise: attention = torch.softmax(unnorm_weights, dim=-1) else: attention = torch.sigmoid(unnorm_weights) output = torch.matmul(attention, values) return output class MultiHeadAttention(nn.Module): """ Multi-head attention class """ def __init__(self, key_size, value_size, num_heads, key_hidden_size, normalise=True): """ :param num_heads: :param normalise: """ super().__init__() self._key_size = key_size self._value_size = value_size self._num_heads = num_heads self._key_hidden_size = key_hidden_size self._head_size = int(self._value_size / self._num_heads) self._normalise = normalise self._query_transform = nn.Linear(self._key_size, self._num_heads * self._key_hidden_size, bias=False) self._key_transform = nn.Linear(self._key_size, self._num_heads * self._key_hidden_size, bias=False) self._value_transform = nn.Linear(self._value_size, self._num_heads * self._head_size, bias=False) self._head_transform = nn.Linear(self._num_heads * self._head_size, self._value_size, bias=False) def forward(self, queries, keys=None, values=None): """ :param queries: [batch_size, N_target, key_size] :param keys: [batch_size, N_context, key_size] :param values: [batch_size, N_context, value_size] :return: """ if keys is None: keys = queries if values is None: values = queries self._batch_size = queries.shape[0] self._n_target = queries.shape[1] self._n_context = keys.shape[1] queries = self._query_transform(queries).view(self._batch_size, self._n_target, self._num_heads, self._key_hidden_size) keys = self._key_transform(keys).view(self._batch_size, self. _n_context, self._num_heads, self._key_hidden_size) values = self._value_transform(values).view(self._batch_size, self. _n_context, self._num_heads, self._head_size) queries = queries.transpose(1, 2) keys = keys.transpose(1, 2) values = values.transpose(1, 2) attention = dot_product_attention(queries, keys, values, normalise= self._normalise) attention = attention.transpose(1, 2) attention = attention.reshape(self._batch_size, self._n_target, -1) output = self._head_transform(attention) return output def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'key_size': 4, 'value_size': 4, 'num_heads': 4, 'key_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 numpy as np import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x1 = xindex // 4 % 4 x2 = xindex // 16 % 4 x3 = xindex // 64 x4 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask) tl.store(out_ptr0 + x4, tmp0, xmask) @triton.jit def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 64 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 16 y1 = yindex // 16 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused__softmax_sqrt_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp8 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp13 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp16 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp1 = tl.full([1], 2.0, tl.float64) tmp2 = tl.full([1], 0.0, tl.float64) tmp3 = tmp1 >= tmp2 tmp4 = 1.0 tmp5 = -1.0 tmp6 = tl.where(tmp3, tmp4, tmp5) tmp7 = tmp0 * tmp6 tmp9 = tmp8 * tmp6 tmp11 = tmp10 * tmp6 tmp12 = triton_helpers.maximum(tmp9, tmp11) tmp14 = tmp13 * tmp6 tmp15 = triton_helpers.maximum(tmp12, tmp14) tmp17 = tmp16 * tmp6 tmp18 = triton_helpers.maximum(tmp15, tmp17) tmp19 = tmp7 - tmp18 tmp20 = tmp6.to(tl.float64) tmp21 = tmp20 * tmp1 tmp22 = tmp21.to(tl.float32) tmp23 = tmp19 / tmp22 tmp24 = tl_math.exp(tmp23) tl.store(out_ptr0 + x2, tmp24, xmask) @triton.jit def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (16, 4), (4, 1)) assert_size_stride(primals_3, (16, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), out=buf0) del primals_2 buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 16), (1, 4), 0), out=buf1) del primals_3 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) del primals_4 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(256)](buf0, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 triton_poi_fused_clone_1[grid(64, 4)](buf1, buf4, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf5 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0) del buf1 extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0), out=buf5) buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_sqrt_2[grid(256)](buf5, buf6, 256, XBLOCK =128, num_warps=4, num_stages=1) buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf5 triton_poi_fused__softmax_3[grid(256)](buf6, buf7, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf6 buf8 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) triton_poi_fused_clone_4[grid(16, 4)](buf2, buf8, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9) buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 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.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf11) return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0 ), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0 ), primals_5, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0 ), reinterpret_tensor(buf4, (16, 4, 4), (16, 1, 4), 0) def dot_product_attention(queries, keys, values, normalise=True): """ :param queries:[batch_size, N_target, key_size] :param keys:[batch_size, N_context, key_size] :param values: [] :param normalise: :return: """ key_size = keys.shape[-1] scale = np.sqrt(key_size) unnorm_weights = torch.matmul(queries, keys.transpose(-2, -1)) / scale if normalise: attention = torch.softmax(unnorm_weights, dim=-1) else: attention = torch.sigmoid(unnorm_weights) output = torch.matmul(attention, values) return output class MultiHeadAttentionNew(nn.Module): """ Multi-head attention class """ def __init__(self, key_size, value_size, num_heads, key_hidden_size, normalise=True): """ :param num_heads: :param normalise: """ super().__init__() self._key_size = key_size self._value_size = value_size self._num_heads = num_heads self._key_hidden_size = key_hidden_size self._head_size = int(self._value_size / self._num_heads) self._normalise = normalise self._query_transform = nn.Linear(self._key_size, self._num_heads * self._key_hidden_size, bias=False) self._key_transform = nn.Linear(self._key_size, self._num_heads * self._key_hidden_size, bias=False) self._value_transform = nn.Linear(self._value_size, self._num_heads * self._head_size, bias=False) self._head_transform = nn.Linear(self._num_heads * self._head_size, self._value_size, bias=False) def forward(self, input_0): primals_2 = self._query_transform.weight primals_3 = self._key_transform.weight primals_4 = self._value_transform.weight primals_5 = self._head_transform.weight primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
JuliusSchwartz/FlowMO
MultiHeadAttention
false
13,967
[ "MIT" ]
53
e221d989914f906501e1ad19cd3629d88eac1785
https://github.com/JuliusSchwartz/FlowMO/tree/e221d989914f906501e1ad19cd3629d88eac1785
PerformanceModel
import torch import torch.nn as nn class PerformanceModel(nn.Module): def __init__(self, input_len): super(PerformanceModel, self).__init__() self.input_len = input_len self.linear1 = nn.Linear(self.input_len, 32, bias=True) self.dropout1 = nn.Dropout(p=0.01) self.activate1 = torch.relu self.linear2 = nn.Linear(32, 64, bias=True) self.dropout2 = nn.Dropout(p=0.01) self.activate2 = torch.relu self.linear3 = nn.Linear(64, 128, bias=True) self.dropout3 = nn.Dropout(p=0.01) self.activate3 = torch.relu self.linear4 = nn.Linear(128, 64, bias=True) self.dropout4 = nn.Dropout(p=0.01) self.activate4 = torch.relu self.linear5 = nn.Linear(64, 16, bias=True) self.activate5 = torch.relu self.linear6 = nn.Linear(16, 1, bias=True) self.activate6 = torch.relu def forward(self, inputs): output1 = self.activate1(self.dropout1(self.linear1(inputs))) output2 = self.activate2(self.dropout2(self.linear2(output1))) output3 = self.activate3(self.dropout3(self.linear3(output2))) output4 = self.activate4(self.dropout4(self.linear4(output3))) output5 = self.activate5(self.linear5(output4)) output6 = self.activate6(self.linear6(output5)) return output6 def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_len': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._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 % 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_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 % 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_2(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, None) tl.store(out_ptr0 + x2, tmp6, None) @triton.jit def triton_poi_fused_relu_threshold_backward_3(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 x2 = xindex x0 = xindex % 16 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_4(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 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 + tmp2 tmp4 = tl.full([1], 0, tl.int32) tmp5 = triton_helpers.maximum(tmp4, tmp3) tmp6 = 0.0 tmp7 = tmp5 <= tmp6 tl.store(in_out_ptr0 + x0, tmp5, xmask) tl.store(out_ptr0 + x0, tmp7, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13) = 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, (64, 32), (32, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (128, 64), (64, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (64, 128), (128, 1)) assert_size_stride(primals_9, (64,), (1,)) assert_size_stride(primals_10, (16, 64), (64, 1)) assert_size_stride(primals_11, (16,), (1,)) assert_size_stride(primals_12, (1, 16), (16, 1)) assert_size_stride(primals_13, (1,), (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 buf17 = 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, buf17, 2048, 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, 32), (32, 1), 0), reinterpret_tensor(primals_4, (32, 64), (1, 32), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf2 buf16 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch .bool) triton_poi_fused_relu_threshold_backward_1[grid(4096)](buf3, primals_5, buf16, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 128), (128, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 64), (64, 1), 0), reinterpret_tensor(primals_6, (64, 128), (1, 64), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 128), (2048, 512, 128, 1), 0) del buf4 buf15 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1), torch.bool) triton_poi_fused_relu_threshold_backward_2[grid(8192)](buf5, primals_7, buf15, 8192, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (64, 128), (128, 1), 0), reinterpret_tensor(primals_8, (128, 64), (1, 128), 0), out=buf6) buf7 = reinterpret_tensor(buf6, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf6 buf14 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch .bool) triton_poi_fused_relu_threshold_backward_1[grid(4096)](buf7, primals_9, buf14, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_9 buf8 = empty_strided_cuda((64, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf7, (64, 64), (64, 1), 0), reinterpret_tensor(primals_10, (64, 16), (1, 64), 0), out=buf8) buf9 = reinterpret_tensor(buf8, (4, 4, 4, 16), (256, 64, 16, 1), 0) del buf8 buf13 = empty_strided_cuda((4, 4, 4, 16), (256, 64, 16, 1), torch.bool) triton_poi_fused_relu_threshold_backward_3[grid(1024)](buf9, primals_11, buf13, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_11 buf10 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf9, (64, 16), (16, 1), 0), reinterpret_tensor(primals_12, (16, 1), (1, 16), 0), out=buf10) buf11 = reinterpret_tensor(buf10, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf10 buf12 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.bool) triton_poi_fused_relu_threshold_backward_4[grid(64)](buf11, primals_13, buf12, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_13 return (buf11, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(buf1, (64, 32), (32, 1), 0), reinterpret_tensor( buf3, (64, 64), (64, 1), 0), reinterpret_tensor(buf5, (64, 128), ( 128, 1), 0), reinterpret_tensor(buf7, (64, 64), (64, 1), 0), reinterpret_tensor(buf9, (64, 16), (16, 1), 0), buf12, primals_12, buf13, primals_10, buf14, primals_8, buf15, primals_6, buf16, primals_4, buf17) class PerformanceModelNew(nn.Module): def __init__(self, input_len): super(PerformanceModelNew, self).__init__() self.input_len = input_len self.linear1 = nn.Linear(self.input_len, 32, bias=True) self.dropout1 = nn.Dropout(p=0.01) self.activate1 = torch.relu self.linear2 = nn.Linear(32, 64, bias=True) self.dropout2 = nn.Dropout(p=0.01) self.activate2 = torch.relu self.linear3 = nn.Linear(64, 128, bias=True) self.dropout3 = nn.Dropout(p=0.01) self.activate3 = torch.relu self.linear4 = nn.Linear(128, 64, bias=True) self.dropout4 = nn.Dropout(p=0.01) self.activate4 = torch.relu self.linear5 = nn.Linear(64, 16, bias=True) self.activate5 = torch.relu self.linear6 = nn.Linear(16, 1, bias=True) self.activate6 = torch.relu def forward(self, input_0): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_4 = self.linear2.weight primals_5 = self.linear2.bias primals_6 = self.linear3.weight primals_7 = self.linear3.bias primals_8 = self.linear4.weight primals_9 = self.linear4.bias primals_10 = self.linear5.weight primals_11 = self.linear5.bias primals_12 = self.linear6.weight primals_13 = self.linear6.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]
KnowingNothing/FlexTensor
PerformanceModel
false
13,968
[ "MIT" ]
135
00f6cd7e038af7714b833fde7034d465fe2dc4a7
https://github.com/KnowingNothing/FlexTensor/tree/00f6cd7e038af7714b833fde7034d465fe2dc4a7
BinaryLoss
import torch import torch.nn as nn import torch.nn.functional as F class BinaryLoss(nn.Module): def __init__(self): super(BinaryLoss, self).__init__() def forward(self, pos_score, neg_score): pos_loss = -F.log_softmax(pos_score)[:, 1] neg_loss = -F.log_softmax(neg_score)[:, 0] loss = (pos_loss.sum() + neg_loss.sum()) / (pos_loss.size(0) + neg_loss.size(0)) 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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused_add_div_neg_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp1 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp17 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp19 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp22 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp25 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp2 = tl_math.exp(tmp1) tmp3 = tl_math.exp(tmp0) tmp4 = tmp2 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp13 = -tmp12 tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK]) tmp16 = tl.sum(tmp14, 1)[:, None] tmp18 = tl_math.exp(tmp17) tmp20 = tl_math.exp(tmp19) tmp21 = tmp18 + tmp20 tmp23 = tl_math.exp(tmp22) tmp24 = tmp21 + tmp23 tmp26 = tl_math.exp(tmp25) tmp27 = tmp24 + tmp26 tmp28 = tl_math.log(tmp27) tmp29 = tmp17 - tmp28 tmp30 = -tmp29 tmp31 = tl.broadcast_to(tmp30, [XBLOCK, RBLOCK]) tmp33 = tl.sum(tmp31, 1)[:, None] tmp34 = tmp16 + tmp33 tmp35 = 0.125 tmp36 = tmp34 * tmp35 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp36, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf4 = buf1 del buf1 triton_per_fused_add_div_neg_sum_1[grid(1)](buf4, buf0, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf0 del buf2 return buf4, class BinaryLossNew(nn.Module): def __init__(self): super(BinaryLossNew, 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]
Kitware/VAIME
BinaryLoss
false
13,969
[ "BSD-3-Clause" ]
127
47b24b9d8a208cf8c621e5bb1088c61fcf507af6
https://github.com/Kitware/VAIME/tree/47b24b9d8a208cf8c621e5bb1088c61fcf507af6
Conv2dZeros
import torch import torch.nn as nn class Conv2dZeros(nn.Module): """Normal conv2d for reparameterize the latent variable. - weight and bias initialized to zero - scale channel-wise after conv2d """ def __init__(self, in_channels, out_channels): super(Conv2dZeros, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True) self.conv.weight.data.zero_() self.conv.bias.data.zero_() self.scale = nn.Parameter(torch.zeros(1, out_channels, 1, 1)) def forward(self, x): x = self.conv(x) return x * torch.exp(self.scale * 3) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_exp_mul_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = 3.0 tmp5 = tmp3 * tmp4 tmp6 = tl_math.exp(tmp5) tmp7 = tmp2 * tmp6 tl.store(in_out_ptr0 + x3, tmp2, xmask) tl.store(out_ptr0 + x3, tmp7, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_exp_mul_0[grid(256)](buf1, primals_2, primals_4, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 return buf2, primals_1, primals_3, primals_4, buf1 class Conv2dZerosNew(nn.Module): """Normal conv2d for reparameterize the latent variable. - weight and bias initialized to zero - scale channel-wise after conv2d """ def __init__(self, in_channels, out_channels): super(Conv2dZerosNew, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True) self.conv.weight.data.zero_() self.conv.bias.data.zero_() self.scale = nn.Parameter(torch.zeros(1, out_channels, 1, 1)) def forward(self, input_0): primals_4 = self.scale primals_1 = self.conv.weight primals_2 = self.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
KyleDavisSA/pde-surrogate
Conv2dZeros
false
13,970
[ "MIT" ]
62
41ad2c9eb73c323e389174080f4b3df6cbd3c900
https://github.com/KyleDavisSA/pde-surrogate/tree/41ad2c9eb73c323e389174080f4b3df6cbd3c900
RingLoss
import torch import torch.nn as nn class RingLoss(nn.Module): """Ring loss. Reference: Zheng et al. Ring loss: Convex Feature Normalization for Face Recognition. CVPR 2018. """ def __init__(self, weight_ring=1.0): super(RingLoss, self).__init__() self.radius = nn.Parameter(torch.ones(1, dtype=torch.float)) self.weight_ring = weight_ring def forward(self, x): l = ((x.norm(p=2, dim=1) - self.radius) ** 2).mean() return l * self.weight_ring def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_linalg_vector_norm_mean_mul_pow_sub_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 r2 = rindex tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp12 = tl.load(in_ptr1 + 0) tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp1 = tmp0 * tmp0 tmp3 = tmp2 * tmp2 tmp4 = tmp1 + tmp3 tmp6 = tmp5 * tmp5 tmp7 = tmp4 + tmp6 tmp9 = tmp8 * tmp8 tmp10 = tmp7 + tmp9 tmp11 = libdevice.sqrt(tmp10) tmp14 = tmp11 - tmp13 tmp15 = 2.0 tmp16 = tmp14 * tmp15 tmp17 = tmp14 * tmp14 tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK]) tmp20 = tl.sum(tmp18, 1)[:, None] tmp21 = 64.0 tmp22 = tmp20 / tmp21 tmp23 = 1.0 tmp24 = tmp22 * tmp23 tl.store(out_ptr1 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp16, None) tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp24, None) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) buf1 = empty_strided_cuda((), (), torch.float32) buf3 = buf1 del buf1 get_raw_stream(0) triton_per_fused_linalg_vector_norm_mean_mul_pow_sub_0[grid(1)](buf3, primals_1, primals_2, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del primals_1 del primals_2 return buf3, buf2 class RingLossNew(nn.Module): """Ring loss. Reference: Zheng et al. Ring loss: Convex Feature Normalization for Face Recognition. CVPR 2018. """ def __init__(self, weight_ring=1.0): super(RingLossNew, self).__init__() self.radius = nn.Parameter(torch.ones(1, dtype=torch.float)) self.weight_ring = weight_ring def forward(self, input_0): primals_2 = self.radius primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
LT1st/ReID_Alined_beginer
RingLoss
false
13,971
[ "MIT" ]
370
1a12403a32d99900451ac05cd3623a9b770f6d24
https://github.com/LT1st/ReID_Alined_beginer/tree/1a12403a32d99900451ac05cd3623a9b770f6d24
_DenseBlockInput
import torch import torch.nn as nn class _DenseLayer(nn.Sequential): """One dense layer within dense block, with bottleneck design. Args: in_features (int): growth_rate (int): # out feature maps of every dense layer drop_rate (float): bn_size (int): Specifies maximum # features is `bn_size` * `growth_rate` bottleneck (bool, False): If True, enable bottleneck design """ def __init__(self, in_features, growth_rate, drop_rate=0.0, bn_size=8, bottleneck=False): super(_DenseLayer, self).__init__() if bottleneck and in_features > bn_size * growth_rate: self.add_module('norm1', nn.BatchNorm2d(in_features)) self.add_module('relu1', nn.ReLU(inplace=True)) self.add_module('conv1', nn.Conv2d(in_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)) self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)) self.add_module('relu2', nn.ReLU(inplace=True)) self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)) else: self.add_module('norm1', nn.BatchNorm2d(in_features)) self.add_module('relu1', nn.ReLU(inplace=True)) self.add_module('conv1', nn.Conv2d(in_features, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)) if drop_rate > 0: self.add_module('dropout', nn.Dropout2d(p=drop_rate)) def forward(self, x): y = super(_DenseLayer, self).forward(x) return torch.cat([x, y], 1) class _DenseBlockInput(nn.Sequential): """For input dense block, feature map size the same as input""" def __init__(self, num_layers, in_features, init_features, growth_rate, drop_rate, bn_size=4, bottleneck=False): super(_DenseBlockInput, self).__init__() self.num_layers = num_layers self.add_module('in_conv', nn.Conv2d(in_features, init_features - 1, kernel_size=3, stride=1, padding=1)) for i in range(num_layers - 1): layer = _DenseLayer(init_features + i * growth_rate, growth_rate, drop_rate=drop_rate, bn_size=bn_size, bottleneck=bottleneck) self.add_module(f'denselayer{i + 1}', layer) def forward(self, x): out = self.in_conv(x) out = torch.cat((x, out), 1) for i in range(self.num_layers - 1): out = self[i + 1](out) return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_layers': 1, 'in_features': 4, 'init_features': 4, 'growth_rate': 4, 'drop_rate': 0.5}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 448 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 16 % 7 x0 = xindex % 16 x2 = xindex // 112 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 7, tl.int64) tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 48 * x2), tmp6 & xmask, other=0.0) tmp10 = tl.load(in_ptr2 + (-4 + x1), tmp6 & xmask, eviction_policy= 'evict_last', other=0.0) tmp11 = tmp9 + tmp10 tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype) tmp13 = tl.where(tmp6, tmp11, tmp12) tmp14 = tl.where(tmp4, tmp5, tmp13) tl.store(out_ptr0 + x3, tmp14, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (3, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (3,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 3, 4, 4), (48, 16, 4, 1)) buf1 = empty_strided_cuda((4, 7, 4, 4), (112, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(448)](primals_3, buf0, primals_2, buf1, 448, XBLOCK=256, num_warps=4, num_stages=1) del buf0 del primals_2 return buf1, primals_1, primals_3 class _DenseLayer(nn.Sequential): """One dense layer within dense block, with bottleneck design. Args: in_features (int): growth_rate (int): # out feature maps of every dense layer drop_rate (float): bn_size (int): Specifies maximum # features is `bn_size` * `growth_rate` bottleneck (bool, False): If True, enable bottleneck design """ def __init__(self, in_features, growth_rate, drop_rate=0.0, bn_size=8, bottleneck=False): super(_DenseLayer, self).__init__() if bottleneck and in_features > bn_size * growth_rate: self.add_module('norm1', nn.BatchNorm2d(in_features)) self.add_module('relu1', nn.ReLU(inplace=True)) self.add_module('conv1', nn.Conv2d(in_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)) self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)) self.add_module('relu2', nn.ReLU(inplace=True)) self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)) else: self.add_module('norm1', nn.BatchNorm2d(in_features)) self.add_module('relu1', nn.ReLU(inplace=True)) self.add_module('conv1', nn.Conv2d(in_features, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)) if drop_rate > 0: self.add_module('dropout', nn.Dropout2d(p=drop_rate)) def forward(self, x): y = super(_DenseLayer, self).forward(x) return torch.cat([x, y], 1) class _DenseBlockInputNew(nn.Sequential): """For input dense block, feature map size the same as input""" def __init__(self, num_layers, in_features, init_features, growth_rate, drop_rate, bn_size=4, bottleneck=False): super(_DenseBlockInputNew, self).__init__() self.num_layers = num_layers self.add_module('in_conv', nn.Conv2d(in_features, init_features - 1, kernel_size=3, stride=1, padding=1)) for i in range(num_layers - 1): layer = _DenseLayer(init_features + i * growth_rate, growth_rate, drop_rate=drop_rate, bn_size=bn_size, bottleneck=bottleneck) self.add_module(f'denselayer{i + 1}', layer) def forward(self, input_0): primals_1 = self.in_conv.weight primals_2 = self.in_conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
KyleDavisSA/pde-surrogate
_DenseBlockInput
false
13,972
[ "MIT" ]
62
41ad2c9eb73c323e389174080f4b3df6cbd3c900
https://github.com/KyleDavisSA/pde-surrogate/tree/41ad2c9eb73c323e389174080f4b3df6cbd3c900