entry_point
stringlengths 1
65
| original_triton_python_code
stringlengths 208
619k
| optimised_triton_code
stringlengths 1.15k
275k
| repo_name
stringlengths 7
115
| module_name
stringlengths 1
65
| synthetic
bool 1
class | uuid
int64 0
18.5k
| licenses
listlengths 1
6
| stars
int64 0
19.8k
| sha
stringlengths 40
40
| repo_link
stringlengths 72
180
|
|---|---|---|---|---|---|---|---|---|---|---|
GLU
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.onnx
class GLU(nn.Module):
def __init__(self):
super(GLU, self).__init__()
def forward(self, x):
nc = x.size(1)
assert nc % 2 == 0, 'channels dont divide 2!'
nc = int(nc / 2)
return x[:, :nc] * torch.sigmoid(x[:, nc:])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.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_mul_sigmoid_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 % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(128)](arg0_1, buf0, 128, XBLOCK
=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class GLUNew(nn.Module):
def __init__(self):
super(GLUNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Nakachi-S/AttnGAN
|
GLU
| false
| 869
|
[
"MIT"
] | 0
|
2dfd1e38f78f2a58895d81131cd8c17e74dbacb2
|
https://github.com/Nakachi-S/AttnGAN/tree/2dfd1e38f78f2a58895d81131cd8c17e74dbacb2
|
LinearBlock
|
import torch
from torch import nn
from scipy.stats import truncnorm
def truncated_normal_(tensor, mean=0.0, std=1.0):
values = truncnorm.rvs(-2, 2, size=tensor.shape)
values = mean + std * values
tensor.copy_(torch.from_numpy(values))
return tensor
def fc_init_(module):
if hasattr(module, 'weight') and module.weight is not None:
truncated_normal_(module.weight.data, mean=0.0, std=0.01)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias.data, 0.0)
return module
class LinearBlock(nn.Module):
def __init__(self, input_size, output_size):
super(LinearBlock, self).__init__()
self.relu = nn.ReLU()
self.normalize = nn.BatchNorm1d(output_size, affine=True, momentum=
0.999, eps=0.001, track_running_stats=False)
self.linear = nn.Linear(input_size, output_size)
fc_init_(self.linear)
def forward(self, x):
x = self.linear(x)
x = self.normalize(x)
x = self.relu(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
from scipy.stats import truncnorm
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__native_batch_norm_legit_0(in_ptr0, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex % 4
r2 = rindex // 4
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 4 * x0 + 16 * r2), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 16.0
tmp18 = tmp16 / tmp17
tmp19 = 0.001
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tl.store(out_ptr2 + x0, tmp21, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
tl.store(out_ptr1 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused__native_batch_norm_legit_relu_threshold_backward_1(in_ptr0
, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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
x1 = xindex // 4 % 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')
tmp10 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = 16.0
tmp5 = tmp3 / tmp4
tmp6 = 0.001
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp2 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tmp14 = tl.full([1], 0, tl.int32)
tmp15 = triton_helpers.maximum(tmp14, tmp13)
tmp16 = 0.0
tmp17 = tmp15 <= tmp16
tl.store(out_ptr0 + x3, tmp15, xmask)
tl.store(out_ptr1 + x3, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((1, 4, 1), (4, 1, 4), torch.float32)
buf2 = empty_strided_cuda((1, 4, 1), (4, 1, 4), torch.float32)
buf4 = empty_strided_cuda((1, 4, 1), (4, 1, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_0[grid(4)](buf0, buf1,
buf2, buf4, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused__native_batch_norm_legit_relu_threshold_backward_1[
grid(64)](buf0, buf1, buf2, primals_4, primals_5, buf5, buf6,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf2
del primals_5
return buf5, primals_4, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf4, (4,), (1,), 0
), buf6, reinterpret_tensor(buf1, (1, 4, 1), (4, 1, 1), 0)
def truncated_normal_(tensor, mean=0.0, std=1.0):
values = truncnorm.rvs(-2, 2, size=tensor.shape)
values = mean + std * values
tensor.copy_(torch.from_numpy(values))
return tensor
def fc_init_(module):
if hasattr(module, 'weight') and module.weight is not None:
truncated_normal_(module.weight.data, mean=0.0, std=0.01)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias.data, 0.0)
return module
class LinearBlockNew(nn.Module):
def __init__(self, input_size, output_size):
super(LinearBlockNew, self).__init__()
self.relu = nn.ReLU()
self.normalize = nn.BatchNorm1d(output_size, affine=True, momentum=
0.999, eps=0.001, track_running_stats=False)
self.linear = nn.Linear(input_size, output_size)
fc_init_(self.linear)
def forward(self, input_0):
primals_2 = self.normalize.weight
primals_4 = self.normalize.bias
primals_1 = self.linear.weight
primals_5 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
JasonMa2016/learn2learn
|
LinearBlock
| false
| 870
|
[
"MIT"
] | 0
|
502e1ea6db64481d7464fdda4d4d0be9b0f1089a
|
https://github.com/JasonMa2016/learn2learn/tree/502e1ea6db64481d7464fdda4d4d0be9b0f1089a
|
ClipLoss
|
import torch
from torch import nn
from torch.nn import functional as F
from torch import distributed as dist
import torch.distributed.nn
def gather_features(image_features, text_features, local_loss=False,
gather_with_grad=False, rank=0, world_size=1, use_horovod=False):
if use_horovod:
assert hvd is not None, 'Please install horovod'
if gather_with_grad:
all_image_features = hvd.allgather(image_features)
all_text_features = hvd.allgather(text_features)
else:
with torch.no_grad():
all_image_features = hvd.allgather(image_features)
all_text_features = hvd.allgather(text_features)
if not local_loss:
gathered_image_features = list(all_image_features.chunk(
world_size, dim=0))
gathered_text_features = list(all_text_features.chunk(
world_size, dim=0))
gathered_image_features[rank] = image_features
gathered_text_features[rank] = text_features
all_image_features = torch.cat(gathered_image_features, dim=0)
all_text_features = torch.cat(gathered_text_features, dim=0)
elif gather_with_grad:
all_image_features = torch.cat(torch.distributed.nn.all_gather(
image_features), dim=0)
all_text_features = torch.cat(torch.distributed.nn.all_gather(
text_features), dim=0)
else:
gathered_image_features = [torch.zeros_like(image_features) for _ in
range(world_size)]
gathered_text_features = [torch.zeros_like(text_features) for _ in
range(world_size)]
dist.all_gather(gathered_image_features, image_features)
dist.all_gather(gathered_text_features, text_features)
if not local_loss:
gathered_image_features[rank] = image_features
gathered_text_features[rank] = text_features
all_image_features = torch.cat(gathered_image_features, dim=0)
all_text_features = torch.cat(gathered_text_features, dim=0)
return all_image_features, all_text_features
class ClipLoss(nn.Module):
def __init__(self, local_loss=False, gather_with_grad=False,
cache_labels=False, rank=0, world_size=1, use_horovod=False):
super().__init__()
self.local_loss = local_loss
self.gather_with_grad = gather_with_grad
self.cache_labels = cache_labels
self.rank = rank
self.world_size = world_size
self.use_horovod = use_horovod
self.prev_num_logits = 0
self.labels = {}
def forward(self, image_features, text_features, logit_scale):
device = image_features.device
if self.world_size > 1:
all_image_features, all_text_features = gather_features(
image_features, text_features, self.local_loss, self.
gather_with_grad, self.rank, self.world_size, self.use_horovod)
if self.local_loss:
logits_per_image = (logit_scale * image_features @
all_text_features.T)
logits_per_text = (logit_scale * text_features @
all_image_features.T)
else:
logits_per_image = (logit_scale * all_image_features @
all_text_features.T)
logits_per_text = logits_per_image.T
else:
logits_per_image = logit_scale * image_features @ text_features.T
logits_per_text = logit_scale * text_features @ image_features.T
num_logits = logits_per_image.shape[0]
if self.prev_num_logits != num_logits or device not in self.labels:
labels = torch.arange(num_logits, device=device, dtype=torch.long)
if self.world_size > 1 and self.local_loss:
labels = labels + num_logits * self.rank
if self.cache_labels:
self.labels[device] = labels
self.prev_num_logits = num_logits
else:
labels = self.labels[device]
total_loss = (F.cross_entropy(logits_per_image, labels) + F.
cross_entropy(logits_per_text, labels)) / 2
return total_loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
from torch import distributed as dist
import torch.distributed.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, in_ptr1, in_ptr2, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp3 = tl.load(in_ptr2 + x0, xmask)
tmp2 = tmp0 * tmp1
tmp4 = tmp0 * tmp3
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused_add_arange_div_nll_loss_forward_2(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp6 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp0 = r0
tmp1 = tl.full([1, 1], -100, tl.int64)
tmp2 = tmp0 != tmp1
tmp3 = tl.full([1, 1], 0, tl.int64)
tmp4 = tl.where(tmp2, tmp0, tmp3)
tmp5 = tl.load(in_ptr0 + (tmp4 + 4 * r0), None, eviction_policy=
'evict_last')
tmp7 = tl_math.exp(tmp6)
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp12 = tl_math.exp(tmp11)
tmp13 = tmp10 + tmp12
tmp15 = tl_math.exp(tmp14)
tmp16 = tmp13 + tmp15
tmp17 = tl_math.log(tmp16)
tmp18 = tmp5 - tmp17
tmp19 = -tmp18
tmp20 = 0.0
tmp21 = tl.where(tmp2, tmp19, tmp20)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK])
tmp24 = tl.sum(tmp22, 1)[:, None]
tmp25 = tl.load(in_ptr1 + (tmp4 + 4 * r0), None, eviction_policy=
'evict_last')
tmp27 = tl_math.exp(tmp26)
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp27 + tmp29
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp30 + tmp32
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp33 + tmp35
tmp37 = tl_math.log(tmp36)
tmp38 = tmp25 - tmp37
tmp39 = -tmp38
tmp40 = tl.where(tmp2, tmp39, tmp20)
tmp41 = tl.broadcast_to(tmp40, [XBLOCK, RBLOCK])
tmp43 = tl.sum(tmp41, 1)[:, None]
tmp44 = tmp2.to(tl.int64)
tmp45 = tl.broadcast_to(tmp44, [XBLOCK, RBLOCK])
tmp47 = tl.sum(tmp45, 1)[:, None]
tmp48 = tmp47.to(tl.float32)
tmp49 = tmp24 / tmp48
tmp50 = tmp43 / tmp48
tmp51 = tmp49 + tmp50
tmp52 = 0.5
tmp53 = tmp51 * tmp52
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp53, 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((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](arg1_1, arg0_1, arg2_1, buf0, buf5,
16, XBLOCK=16, num_warps=1, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(arg2_1, (4, 4), (1, 4),
0), out=buf1)
del arg2_1
buf2 = buf0
del buf0
triton_poi_fused__log_softmax_1[grid(16)](buf1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf6 = buf1
del buf1
extern_kernels.mm(buf5, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
0), out=buf6)
del arg0_1
buf7 = buf5
del buf5
triton_poi_fused__log_softmax_1[grid(16)](buf6, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf6
buf3 = empty_strided_cuda((), (), torch.float32)
buf10 = buf3
del buf3
triton_per_fused_add_arange_div_nll_loss_forward_2[grid(1)](buf10,
buf2, buf7, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf7
return buf10,
def gather_features(image_features, text_features, local_loss=False,
gather_with_grad=False, rank=0, world_size=1, use_horovod=False):
if use_horovod:
assert hvd is not None, 'Please install horovod'
if gather_with_grad:
all_image_features = hvd.allgather(image_features)
all_text_features = hvd.allgather(text_features)
else:
with torch.no_grad():
all_image_features = hvd.allgather(image_features)
all_text_features = hvd.allgather(text_features)
if not local_loss:
gathered_image_features = list(all_image_features.chunk(
world_size, dim=0))
gathered_text_features = list(all_text_features.chunk(
world_size, dim=0))
gathered_image_features[rank] = image_features
gathered_text_features[rank] = text_features
all_image_features = torch.cat(gathered_image_features, dim=0)
all_text_features = torch.cat(gathered_text_features, dim=0)
elif gather_with_grad:
all_image_features = torch.cat(torch.distributed.nn.all_gather(
image_features), dim=0)
all_text_features = torch.cat(torch.distributed.nn.all_gather(
text_features), dim=0)
else:
gathered_image_features = [torch.zeros_like(image_features) for _ in
range(world_size)]
gathered_text_features = [torch.zeros_like(text_features) for _ in
range(world_size)]
dist.all_gather(gathered_image_features, image_features)
dist.all_gather(gathered_text_features, text_features)
if not local_loss:
gathered_image_features[rank] = image_features
gathered_text_features[rank] = text_features
all_image_features = torch.cat(gathered_image_features, dim=0)
all_text_features = torch.cat(gathered_text_features, dim=0)
return all_image_features, all_text_features
class ClipLossNew(nn.Module):
def __init__(self, local_loss=False, gather_with_grad=False,
cache_labels=False, rank=0, world_size=1, use_horovod=False):
super().__init__()
self.local_loss = local_loss
self.gather_with_grad = gather_with_grad
self.cache_labels = cache_labels
self.rank = rank
self.world_size = world_size
self.use_horovod = use_horovod
self.prev_num_logits = 0
self.labels = {}
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]
|
NYU-DICE-Lab/open_clip
|
ClipLoss
| false
| 871
|
[
"MIT"
] | 0
|
fd71804b503135fb1c7cc8de3a0d6599741c8ed9
|
https://github.com/NYU-DICE-Lab/open_clip/tree/fd71804b503135fb1c7cc8de3a0d6599741c8ed9
|
DenseBlock
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalConv1d(nn.Module):
"""A 1D causal convolution layer.
Input: (B, D_in, T), where B is the minibatch size, D_in is the number of
dimensions per step, and T is the number of steps.
Output: (B, D_out, T), where B is the minibatch size, D_out is the number
of dimensions in the output, and T is the number of steps.
Arguments:
in_channels (int): number of input channels
out_channels (int): number of output channels
"""
def __init__(self, in_channels, out_channels, dilation=1):
super(CausalConv1d, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, 2, padding=
self.padding, dilation=dilation)
def forward(self, minibatch):
return self.causal_conv(minibatch)[:, :, :-self.padding]
class DenseBlock(nn.Module):
"""Two parallel 1D causal convolution layers w/tanh and sigmoid activations
Input: (B, D_in, T), where B is the minibatch size, D_in is the number of
dimensions of the input, and T is the number of steps.
Output: (B, D_in+F, T), where where `B` is the minibatch size, `D_in` is the
number of dimensions of the input, `F` is the number of filters, and `T`
is the length of the input sequence.
Arguments:
in_channels (int): number of input channels
filters (int): number of filters per channel
"""
def __init__(self, in_channels, filters, dilation=1):
super(DenseBlock, self).__init__()
self.causal_conv1 = CausalConv1d(in_channels, filters, dilation=
dilation)
self.causal_conv2 = CausalConv1d(in_channels, filters, dilation=
dilation)
def forward(self, minibatch):
tanh = F.tanh(self.causal_conv1(minibatch))
sig = F.sigmoid(self.causal_conv2(minibatch))
out = torch.cat([minibatch, tanh * sig], dim=1)
return out
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'filters': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 5 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 8
x0 = xindex % 4
x2 = xindex // 32
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
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 5 * (-4 + x1) + 20 * x2), tmp6 & xmask,
other=0.0)
tmp10 = libdevice.tanh(tmp9)
tmp11 = tl.load(in_ptr2 + (x0 + 5 * (-4 + x1) + 20 * x2), tmp6 & xmask,
other=0.0)
tmp12 = tl.sigmoid(tmp11)
tmp13 = tmp10 * tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp6, tmp13, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x3, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 2), (8, 2, 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, 2), (8, 2, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,),
padding=(1,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 5), (20, 5, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(80)](buf1, primals_2, 80,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,),
padding=(1,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 5), (20, 5, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(80)](buf3, primals_5, 80,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 8, 4), (32, 4, 1), torch.float32)
triton_poi_fused_cat_1[grid(128)](primals_3, buf1, buf3, buf4, 128,
XBLOCK=128, num_warps=4, num_stages=1)
return buf4, primals_1, primals_3, primals_4, buf1, buf3
class CausalConv1d(nn.Module):
"""A 1D causal convolution layer.
Input: (B, D_in, T), where B is the minibatch size, D_in is the number of
dimensions per step, and T is the number of steps.
Output: (B, D_out, T), where B is the minibatch size, D_out is the number
of dimensions in the output, and T is the number of steps.
Arguments:
in_channels (int): number of input channels
out_channels (int): number of output channels
"""
def __init__(self, in_channels, out_channels, dilation=1):
super(CausalConv1d, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, 2, padding=
self.padding, dilation=dilation)
def forward(self, minibatch):
return self.causal_conv(minibatch)[:, :, :-self.padding]
class DenseBlockNew(nn.Module):
"""Two parallel 1D causal convolution layers w/tanh and sigmoid activations
Input: (B, D_in, T), where B is the minibatch size, D_in is the number of
dimensions of the input, and T is the number of steps.
Output: (B, D_in+F, T), where where `B` is the minibatch size, `D_in` is the
number of dimensions of the input, `F` is the number of filters, and `T`
is the length of the input sequence.
Arguments:
in_channels (int): number of input channels
filters (int): number of filters per channel
"""
def __init__(self, in_channels, filters, dilation=1):
super(DenseBlockNew, self).__init__()
self.causal_conv1 = CausalConv1d(in_channels, filters, dilation=
dilation)
self.causal_conv2 = CausalConv1d(in_channels, filters, dilation=
dilation)
def forward(self, input_0):
primals_1 = self.causal_conv1.causal_conv.weight
primals_2 = self.causal_conv1.causal_conv.bias
primals_4 = self.causal_conv2.causal_conv.weight
primals_5 = self.causal_conv2.causal_conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
NagisaZj/oyster
|
DenseBlock
| false
| 872
|
[
"MIT"
] | 0
|
069a510fe63bb29ecd9871e0e189e58b03c8cad9
|
https://github.com/NagisaZj/oyster/tree/069a510fe63bb29ecd9871e0e189e58b03c8cad9
|
distLinear
|
import torch
import torch.nn as nn
import torch.utils.data
from torch.nn.utils.weight_norm import WeightNorm
import torch.nn.parallel
import torch.optim
class distLinear(nn.Module):
def __init__(self, indim, outdim):
super(distLinear, self).__init__()
self.L = nn.Linear(indim, outdim, bias=False)
self.class_wise_learnable_norm = True
if self.class_wise_learnable_norm:
WeightNorm.apply(self.L, 'weight', dim=0)
if outdim <= 200:
self.scale_factor = 2
else:
self.scale_factor = 10
def forward(self, x):
x_norm = torch.norm(x, p=2, dim=1).unsqueeze(1).expand_as(x)
x_normalized = x.div(x_norm + 1e-05)
if not self.class_wise_learnable_norm:
L_norm = torch.norm(self.L.weight.data, p=2, dim=1).unsqueeze(1
).expand_as(self.L.weight.data)
self.L.weight.data = self.L.weight.data.div(L_norm + 1e-05)
cos_dist = self.L(x_normalized)
scores = self.scale_factor * cos_dist
return scores
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'indim': 4, 'outdim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
from torch.nn.utils.weight_norm import WeightNorm
import torch.nn.parallel
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__weight_norm_interface_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = libdevice.sqrt(tmp10)
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused__weight_norm_interface_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_add_div_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x3, tmp15, xmask)
@triton.jit
def triton_poi_fused_mul_3(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 1), (1, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__weight_norm_interface_0[grid(4)](primals_3, buf0,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__weight_norm_interface_1[grid(16)](primals_3,
primals_2, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_2[grid(256)](primals_1, buf2, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_1
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (4, 4), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_mul_3[grid(256)](buf4, 256, XBLOCK=256, num_warps=
4, num_stages=1)
return buf4, buf1, primals_2, primals_3, buf0, reinterpret_tensor(buf2,
(64, 4), (4, 1), 0)
class distLinearNew(nn.Module):
def __init__(self, indim, outdim):
super(distLinearNew, self).__init__()
self.L = nn.Linear(indim, outdim, bias=False)
self.class_wise_learnable_norm = True
if self.class_wise_learnable_norm:
WeightNorm.apply(self.L, 'weight', dim=0)
if outdim <= 200:
self.scale_factor = 2
else:
self.scale_factor = 10
def forward(self, input_0):
primals_2 = self.L.weight_g
primals_3 = self.L.weight_v
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
MuawizChaudhary/STARTUP
|
distLinear
| false
| 873
|
[
"MIT"
] | 0
|
03f39b34a4ec232f132173b4a1e67ea04165e52b
|
https://github.com/MuawizChaudhary/STARTUP/tree/03f39b34a4ec232f132173b4a1e67ea04165e52b
|
BothContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class BothContextGate(nn.Module):
"""Apply the context gate to both contexts"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(BothContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh((1.0 - z) * target + z * source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_rsub_sigmoid_tanh_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp4 = tl.load(in_ptr1 + x0, xmask)
tmp6 = tl.load(in_ptr2 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp2 = 1.0
tmp3 = tmp2 - tmp1
tmp5 = tmp3 * tmp4
tmp7 = tmp1 * tmp6
tmp8 = tmp5 + tmp7
tmp9 = libdevice.tanh(tmp8)
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 8), (8, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del primals_6
del primals_7
buf3 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf3, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf4)
del primals_8
del primals_9
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_rsub_sigmoid_tanh_2[grid(16)](buf1, buf4,
buf2, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
return buf5, primals_3, buf0, buf1, buf2, buf3, buf4, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class BothContextGateNew(nn.Module):
"""Apply the context gate to both contexts"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(BothContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
NaomiatLibrary/OpenNMT-kpg-release
|
BothContextGate
| false
| 874
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
SourceContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class SourceContextGate(nn.Module):
"""Apply the context gate only to the source context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(SourceContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh(target + z * source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tl.sigmoid(tmp3)
tmp6 = tmp4 * tmp5
tmp7 = tmp2 + tmp6
tmp8 = libdevice.tanh(tmp7)
tl.store(in_out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 8), (8, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del primals_6
del primals_7
buf3 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf3, reinterpret_tensor(primals_8, (8, 4), (1, 8
), 0), out=buf4)
del primals_8
buf5 = buf4
del buf4
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf5, primals_9,
buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_9
return buf5, primals_3, buf0, buf1, buf2, buf3, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class SourceContextGateNew(nn.Module):
"""Apply the context gate only to the source context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(SourceContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
NaomiatLibrary/OpenNMT-kpg-release
|
SourceContextGate
| false
| 875
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
IIDTransform
|
import torch
import torch.nn.parallel
import torch.utils.data
from torchvision import transforms
import torch.nn as nn
import torch.cuda
class IIDTransform(nn.Module):
def __init__(self):
super(IIDTransform, self).__init__()
self.transform_op = transforms.Normalize((0.5,), (0.5,))
def mask_fill_nonzeros(self, input_tensor):
output_tensor = torch.clone(input_tensor)
masked_tensor = input_tensor <= 0.0
return output_tensor.masked_fill(masked_tensor, 1.0)
def revert_mask_fill_nonzeros(self, input_tensor):
output_tensor = torch.clone(input_tensor)
masked_tensor = input_tensor >= 1.0
return output_tensor.masked_fill_(masked_tensor, 0.0)
def forward(self, rgb_tensor, albedo_tensor):
min = 0.0
max = 1.0
shading_tensor = self.extract_shading(rgb_tensor, albedo_tensor, False)
shading_refined = self.mask_fill_nonzeros(shading_tensor)
albedo_refined = rgb_tensor / shading_refined
albedo_refined = torch.clip(albedo_refined, min, max)
albedo_refined = self.revert_mask_fill_nonzeros(albedo_refined)
rgb_recon = self.produce_rgb(albedo_refined, shading_refined, False)
rgb_recon = self.transform_op(rgb_recon)
albedo_refined = self.transform_op(albedo_refined)
shading_tensor = self.transform_op(shading_tensor)
return rgb_recon, albedo_refined, shading_tensor
def extract_shading(self, rgb_tensor, albedo_tensor, one_channel=False):
min = 0.0
max = 1.0
albedo_refined = self.mask_fill_nonzeros(albedo_tensor)
shading_tensor = rgb_tensor / albedo_refined
if one_channel is True:
shading_tensor = kornia.color.rgb_to_grayscale(shading_tensor)
shading_tensor = torch.clip(shading_tensor, min, max)
return shading_tensor
def produce_rgb(self, albedo_tensor, shading_tensor, tozeroone=True):
if tozeroone:
albedo_tensor = albedo_tensor * 0.5 + 0.5
shading_tensor = shading_tensor * 0.5 + 0.5
albedo_tensor = self.mask_fill_nonzeros(albedo_tensor)
shading_tensor = self.mask_fill_nonzeros(shading_tensor)
rgb_recon = albedo_tensor * shading_tensor
rgb_recon = torch.clip(rgb_recon, 0.0, 1.0)
return rgb_recon
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn.parallel
import torch.utils.data
from torchvision import transforms
import torch.nn as nn
import torch.cuda
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_ge_le_masked_fill_mul_0(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = 0.0
tmp3 = tmp1 <= tmp2
tmp4 = 1.0
tmp5 = tl.where(tmp3, tmp4, tmp1)
tmp6 = tmp0 / tmp5
tmp7 = triton_helpers.maximum(tmp6, tmp2)
tmp8 = triton_helpers.minimum(tmp7, tmp4)
tmp9 = tmp8 <= tmp2
tmp10 = tl.where(tmp9, tmp4, tmp8)
tmp11 = tmp0 / tmp10
tmp12 = triton_helpers.maximum(tmp11, tmp2)
tmp13 = triton_helpers.minimum(tmp12, tmp4)
tmp14 = tmp13 >= tmp4
tmp15 = tl.where(tmp14, tmp2, tmp13)
tmp16 = tmp15 <= tmp2
tmp17 = tl.where(tmp16, tmp4, tmp15)
tmp18 = tmp10 <= tmp2
tmp19 = tl.where(tmp18, tmp4, tmp10)
tmp20 = tmp17 * tmp19
tmp21 = triton_helpers.maximum(tmp20, tmp2)
tmp22 = triton_helpers.minimum(tmp21, tmp4)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp15, xmask)
tl.store(out_ptr2 + x0, tmp22, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_div_ge_le_masked_fill_mul_0[grid(256)](arg1_1,
arg0_1, buf0, buf1, buf2, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
return buf2, buf0, buf1
class IIDTransformNew(nn.Module):
def __init__(self):
super(IIDTransformNew, self).__init__()
self.transform_op = transforms.Normalize((0.5,), (0.5,))
def mask_fill_nonzeros(self, input_tensor):
output_tensor = torch.clone(input_tensor)
masked_tensor = input_tensor <= 0.0
return output_tensor.masked_fill(masked_tensor, 1.0)
def revert_mask_fill_nonzeros(self, input_tensor):
output_tensor = torch.clone(input_tensor)
masked_tensor = input_tensor >= 1.0
return output_tensor.masked_fill_(masked_tensor, 0.0)
def extract_shading(self, rgb_tensor, albedo_tensor, one_channel=False):
min = 0.0
max = 1.0
albedo_refined = self.mask_fill_nonzeros(albedo_tensor)
shading_tensor = rgb_tensor / albedo_refined
if one_channel is True:
shading_tensor = kornia.color.rgb_to_grayscale(shading_tensor)
shading_tensor = torch.clip(shading_tensor, min, max)
return shading_tensor
def produce_rgb(self, albedo_tensor, shading_tensor, tozeroone=True):
if tozeroone:
albedo_tensor = albedo_tensor * 0.5 + 0.5
shading_tensor = shading_tensor * 0.5 + 0.5
albedo_tensor = self.mask_fill_nonzeros(albedo_tensor)
shading_tensor = self.mask_fill_nonzeros(shading_tensor)
rgb_recon = albedo_tensor * shading_tensor
rgb_recon = torch.clip(rgb_recon, 0.0, 1.0)
return rgb_recon
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1], output[2]
|
NeilDG/NeuralNets-Experiment3
|
IIDTransform
| false
| 876
|
[
"MIT"
] | 0
|
f0d2f788eeca49f803f65810c155491ce687cf9e
|
https://github.com/NeilDG/NeuralNets-Experiment3/tree/f0d2f788eeca49f803f65810c155491ce687cf9e
|
TargetContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class TargetContextGate(nn.Module):
"""Apply the context gate only to the target context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(TargetContextGate, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, prev_emb, dec_state, attn_state):
z, source, target = self.context_gate(prev_emb, dec_state, attn_state)
return self.tanh(z * target + source)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_out_ptr0 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp6 = tmp4 + tmp5
tmp7 = tmp3 + tmp6
tmp8 = libdevice.tanh(tmp7)
tl.store(in_out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 8), (8, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 4), (1, 12), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_6, (4, 4),
(1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_1[grid(32)](primals_1, primals_2, buf3, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf3, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf4)
del primals_8
del primals_9
buf5 = buf2
del buf2
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf5, buf1, buf4,
primals_7, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_7
return buf5, primals_3, buf0, buf1, buf3, buf4, buf5
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
class TargetContextGateNew(nn.Module):
"""Apply the context gate only to the target context"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(TargetContextGateNew, self).__init__()
self.context_gate = ContextGate(embeddings_size, decoder_size,
attention_size, output_size)
self.tanh = nn.Tanh()
def forward(self, input_0, input_1, input_2):
primals_4 = self.context_gate.gate.weight
primals_5 = self.context_gate.gate.bias
primals_1 = self.context_gate.source_proj.weight
primals_7 = self.context_gate.source_proj.bias
primals_8 = self.context_gate.target_proj.weight
primals_9 = self.context_gate.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
NaomiatLibrary/OpenNMT-kpg-release
|
TargetContextGate
| false
| 877
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
UpSampler
|
import torch
from torch import nn
from torch.nn import functional as F
class UpSampler(nn.Module):
"""Up Sample module
Decrease the channels size and increase the spatial size of tensor
Extends:
nn.Module
"""
def __init__(self, inChannels, outChannels, spatial_size):
"""
Arguments:
inChannels {int} -- Number of in channels
outChannels {int} -- Number of out channels
spatial_size {tuple} -- Spatial size to get
"""
super(UpSampler, self).__init__()
self.spatial_size = spatial_size
self.conv = nn.Conv3d(inChannels, outChannels, 1)
def forward(self, x):
x = self.conv(x)
x = F.interpolate(x, self.spatial_size, mode='trilinear',
align_corners=False)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inChannels': 4, 'outChannels': 4, 'spatial_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 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__to_copy_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp6 = tmp5 - tmp2
tmp7 = 0.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tmp8.to(tl.int32)
tl.store(out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_clamp_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp6 = tmp5 - tmp2
tmp7 = 0.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tmp8.to(tl.int32)
tmp10 = tl.full([1], 1, tl.int64)
tmp11 = tmp9 + tmp10
tmp12 = tl.full([1], 3, tl.int64)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_2(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp6 = tmp5 - tmp2
tmp7 = 0.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tmp8.to(tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 - tmp10
tmp12 = triton_helpers.maximum(tmp11, tmp7)
tmp13 = triton_helpers.minimum(tmp12, tmp4)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_mul_sub_3(in_out_ptr1,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7,
in_ptr8, in_ptr9, in_ptr10, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x0 = xindex % 4
x6 = xindex // 64
x3 = xindex // 64 % 4
x8 = xindex
tmp0 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr4 + x3, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp38 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr9 + x2, xmask, eviction_policy='evict_last')
tmp63 = tl.load(in_ptr10 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, 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)
tmp10 = tmp9 + tmp1
tmp11 = tmp9 < 0
tmp12 = tl.where(tmp11, tmp10, tmp9)
tmp13 = tl.load(in_ptr3 + (tmp12 + 4 * tmp8 + 16 * tmp4 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp15 = tmp13 + tmp14
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr3 + (tmp12 + 4 * tmp19 + 16 * tmp4 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp21 = tmp20 + tmp14
tmp23 = tmp22 + tmp1
tmp24 = tmp22 < 0
tmp25 = tl.where(tmp24, tmp23, tmp22)
tmp26 = tl.load(in_ptr3 + (tmp25 + 4 * tmp19 + 16 * tmp4 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp27 = tmp26 + tmp14
tmp28 = tmp27 - tmp21
tmp30 = tmp28 * tmp29
tmp31 = tmp21 + tmp30
tmp32 = tl.load(in_ptr3 + (tmp25 + 4 * tmp8 + 16 * tmp4 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp33 = tmp32 + tmp14
tmp34 = tmp33 - tmp15
tmp35 = tmp34 * tmp29
tmp36 = tmp15 + tmp35
tmp37 = tmp36 - tmp31
tmp39 = tmp37 * tmp38
tmp41 = tmp40 + tmp1
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tmp44 = tl.load(in_ptr3 + (tmp12 + 4 * tmp8 + 16 * tmp43 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp45 = tmp44 + tmp14
tmp46 = tl.load(in_ptr3 + (tmp12 + 4 * tmp19 + 16 * tmp43 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp47 = tmp46 + tmp14
tmp48 = tl.load(in_ptr3 + (tmp25 + 4 * tmp19 + 16 * tmp43 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp49 = tmp48 + tmp14
tmp50 = tmp49 - tmp47
tmp51 = tmp50 * tmp29
tmp52 = tmp47 + tmp51
tmp53 = tl.load(in_ptr3 + (tmp25 + 4 * tmp8 + 16 * tmp43 + 64 * x6),
xmask, eviction_policy='evict_last')
tmp54 = tmp53 + tmp14
tmp55 = tmp54 - tmp45
tmp56 = tmp55 * tmp29
tmp57 = tmp45 + tmp56
tmp58 = tmp57 - tmp52
tmp59 = tmp58 * tmp38
tmp60 = tmp31 + tmp39
tmp61 = tmp52 + tmp59
tmp62 = tmp61 - tmp60
tmp64 = tmp62 * tmp63
tmp65 = tmp60 + tmp64
tl.store(in_out_ptr1 + x8, tmp65, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4, 4), (256, 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, 1), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused__to_copy_0[grid(4)](buf1, 4, XBLOCK=4, num_warps=1,
num_stages=1)
buf2 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.int64)
triton_poi_fused_add_clamp_1[grid(4)](buf2, 4, XBLOCK=4, num_warps=
1, num_stages=1)
buf3 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_0[grid(4)](buf3, 4, XBLOCK=4, num_warps=1,
num_stages=1)
buf4 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_1[grid(4)](buf4, 4, XBLOCK=4, num_warps=
1, num_stages=1)
buf5 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused__to_copy_0[grid(4)](buf5, 4, XBLOCK=4, num_warps=1,
num_stages=1)
buf6 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused_add_clamp_1[grid(4)](buf6, 4, XBLOCK=4, num_warps=
1, num_stages=1)
buf11 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_2[grid(4)](buf11,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf14 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_2[grid(4)](buf14,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_2[grid(4)](buf17,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
buf15 = buf8
del buf8
buf18 = buf15
del buf15
triton_poi_fused__unsafe_index_add_convolution_mul_sub_3[grid(1024)](
buf18, buf1, buf4, buf5, buf0, primals_2, buf3, buf6, buf11,
buf14, buf2, buf17, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_2
return (buf18, primals_1, primals_3, buf1, buf2, buf3, buf4, buf5, buf6,
buf11, buf14, buf17)
class UpSamplerNew(nn.Module):
"""Up Sample module
Decrease the channels size and increase the spatial size of tensor
Extends:
nn.Module
"""
def __init__(self, inChannels, outChannels, spatial_size):
"""
Arguments:
inChannels {int} -- Number of in channels
outChannels {int} -- Number of out channels
spatial_size {tuple} -- Spatial size to get
"""
super(UpSamplerNew, self).__init__()
self.spatial_size = spatial_size
self.conv = nn.Conv3d(inChannels, outChannels, 1)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Myyyr/segmentation
|
UpSampler
| false
| 878
|
[
"MIT"
] | 0
|
6b9423e327cff1eb23599404031b7fb8e9ecf75d
|
https://github.com/Myyyr/segmentation/tree/6b9423e327cff1eb23599404031b7fb8e9ecf75d
|
Conv
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class Conv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super().__init__()
conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
conv.weight.data.normal_()
conv.bias.data.zero_()
self.conv = equal_lr(conv)
def forward(self, input):
return self.conv(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.23570226039551584
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 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, 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 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(144)](primals_1, buf0, 144, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(primals_3, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(256)](buf2, primals_2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf2, buf0, primals_3, buf0
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class ConvNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super().__init__()
conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size, stride=stride, padding=padding)
conv.weight.data.normal_()
conv.bias.data.zero_()
self.conv = equal_lr(conv)
def forward(self, input_0):
primals_2 = self.conv.bias
primals_1 = self.conv.weight_orig
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio
|
Conv
| false
| 879
|
[
"MIT"
] | 0
|
231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
https://github.com/NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio/tree/231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
AverageAttention
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.dropout_1 = nn.Dropout(dropout)
self.relu = nn.ReLU()
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x):
"""Layer definition.
Args:
x: ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor): Output ``(batch_size, input_len, model_dim)``.
"""
inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))
output = self.dropout_2(self.w_2(inter))
return output + x
def update_dropout(self, dropout):
self.dropout_1.p = dropout
self.dropout_2.p = dropout
class AverageAttention(nn.Module):
"""
Average Attention module from
"Accelerating Neural Transformer via an Average Attention Network"
:cite:`DBLP:journals/corr/abs-1805-00631`.
Args:
model_dim (int): the dimension of keys/values/queries,
must be divisible by head_count
dropout (float): dropout parameter
"""
def __init__(self, model_dim, dropout=0.1, aan_useffn=False):
self.model_dim = model_dim
self.aan_useffn = aan_useffn
super(AverageAttention, self).__init__()
if aan_useffn:
self.average_layer = PositionwiseFeedForward(model_dim,
model_dim, dropout)
self.gating_layer = nn.Linear(model_dim * 2, model_dim * 2)
def cumulative_average_mask(self, batch_size, inputs_len, device):
"""
Builds the mask to compute the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Figure 3
Args:
batch_size (int): batch size
inputs_len (int): length of the inputs
Returns:
(FloatTensor):
* A Tensor of shape ``(batch_size, input_len, input_len)``
"""
triangle = torch.tril(torch.ones(inputs_len, inputs_len, dtype=
torch.float, device=device))
weights = torch.ones(1, inputs_len, dtype=torch.float, device=device
) / torch.arange(1, inputs_len + 1, dtype=torch.float, device=
device)
mask = triangle * weights.transpose(0, 1)
return mask.unsqueeze(0).expand(batch_size, inputs_len, inputs_len)
def cumulative_average(self, inputs, mask_or_step, layer_cache=None,
step=None):
"""
Computes the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Equations (1) (5) (6)
Args:
inputs (FloatTensor): sequence to average
``(batch_size, input_len, dimension)``
mask_or_step: if cache is set, this is assumed
to be the current step of the
dynamic decoding. Otherwise, it is the mask matrix
used to compute the cumulative average.
layer_cache: a dictionary containing the cumulative average
of the previous step.
Returns:
a tensor of the same shape and type as ``inputs``.
"""
if layer_cache is not None:
step = mask_or_step
average_attention = (inputs + step * layer_cache['prev_g']) / (step
+ 1)
layer_cache['prev_g'] = average_attention
return average_attention
else:
mask = mask_or_step
return torch.matmul(mask, inputs)
def forward(self, inputs, mask=None, layer_cache=None, step=None):
"""
Args:
inputs (FloatTensor): ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor, FloatTensor):
* gating_outputs ``(batch_size, input_len, model_dim)``
* average_outputs average attention
``(batch_size, input_len, model_dim)``
"""
batch_size = inputs.size(0)
inputs_len = inputs.size(1)
average_outputs = self.cumulative_average(inputs, self.
cumulative_average_mask(batch_size, inputs_len, inputs.device) if
layer_cache is None else step, layer_cache=layer_cache)
if self.aan_useffn:
average_outputs = self.average_layer(average_outputs)
gating_outputs = self.gating_layer(torch.cat((inputs,
average_outputs), -1))
input_gate, forget_gate = torch.chunk(gating_outputs, 2, dim=2)
gating_outputs = torch.sigmoid(input_gate) * inputs + torch.sigmoid(
forget_gate) * average_outputs
return gating_outputs, average_outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'model_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_ones_tril_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = x0 + -1 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 <= tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = 1 + x1
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp3 / tmp7
tmp9 = tmp5 * tmp8
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_sigmoid_backward_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 8 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x2, xmask)
tmp6 = tl.load(in_ptr0 + (4 + x0 + 8 * x1), xmask)
tmp7 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp5 = tmp3 * tmp4
tmp8 = tmp6 + tmp7
tmp9 = tl.sigmoid(tmp8)
tmp11 = tmp9 * tmp10
tmp12 = tmp5 + tmp11
tmp13 = 1.0
tmp14 = tmp13 - tmp9
tmp15 = tmp9 * tmp14
tmp16 = tmp13 - tmp3
tmp17 = tmp3 * tmp16
tl.store(out_ptr0 + x2, tmp12, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (8, 8), (8, 1))
assert_size_stride(primals_3, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_ones_tril_0[grid(16)](buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 4), (0, 4, 1), 0
), primals_1, out=buf1)
del buf0
buf2 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_1[grid(128)](primals_1, buf1, buf2, 128,
XBLOCK=128, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 8), (8, 1), 0),
reinterpret_tensor(primals_2, (8, 8), (1, 8), 0), out=buf3)
del primals_2
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_sigmoid_backward_2[grid(64)](buf3,
primals_3, primals_1, buf1, buf4, buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf3
del primals_3
return buf4, buf1, primals_1, buf1, reinterpret_tensor(buf2, (16, 8), (
8, 1), 0), buf5, buf6
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.dropout_1 = nn.Dropout(dropout)
self.relu = nn.ReLU()
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x):
"""Layer definition.
Args:
x: ``(batch_size, input_len, model_dim)``
Returns:
(FloatTensor): Output ``(batch_size, input_len, model_dim)``.
"""
inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))
output = self.dropout_2(self.w_2(inter))
return output + x
def update_dropout(self, dropout):
self.dropout_1.p = dropout
self.dropout_2.p = dropout
class AverageAttentionNew(nn.Module):
"""
Average Attention module from
"Accelerating Neural Transformer via an Average Attention Network"
:cite:`DBLP:journals/corr/abs-1805-00631`.
Args:
model_dim (int): the dimension of keys/values/queries,
must be divisible by head_count
dropout (float): dropout parameter
"""
def __init__(self, model_dim, dropout=0.1, aan_useffn=False):
self.model_dim = model_dim
self.aan_useffn = aan_useffn
super(AverageAttentionNew, self).__init__()
if aan_useffn:
self.average_layer = PositionwiseFeedForward(model_dim,
model_dim, dropout)
self.gating_layer = nn.Linear(model_dim * 2, model_dim * 2)
def cumulative_average_mask(self, batch_size, inputs_len, device):
"""
Builds the mask to compute the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Figure 3
Args:
batch_size (int): batch size
inputs_len (int): length of the inputs
Returns:
(FloatTensor):
* A Tensor of shape ``(batch_size, input_len, input_len)``
"""
triangle = torch.tril(torch.ones(inputs_len, inputs_len, dtype=
torch.float, device=device))
weights = torch.ones(1, inputs_len, dtype=torch.float, device=device
) / torch.arange(1, inputs_len + 1, dtype=torch.float, device=
device)
mask = triangle * weights.transpose(0, 1)
return mask.unsqueeze(0).expand(batch_size, inputs_len, inputs_len)
def cumulative_average(self, inputs, mask_or_step, layer_cache=None,
step=None):
"""
Computes the cumulative average as described in
:cite:`DBLP:journals/corr/abs-1805-00631` -- Equations (1) (5) (6)
Args:
inputs (FloatTensor): sequence to average
``(batch_size, input_len, dimension)``
mask_or_step: if cache is set, this is assumed
to be the current step of the
dynamic decoding. Otherwise, it is the mask matrix
used to compute the cumulative average.
layer_cache: a dictionary containing the cumulative average
of the previous step.
Returns:
a tensor of the same shape and type as ``inputs``.
"""
if layer_cache is not None:
step = mask_or_step
average_attention = (inputs + step * layer_cache['prev_g']) / (step
+ 1)
layer_cache['prev_g'] = average_attention
return average_attention
else:
mask = mask_or_step
return torch.matmul(mask, inputs)
def forward(self, input_0):
primals_2 = self.gating_layer.weight
primals_3 = self.gating_layer.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
NaomiatLibrary/OpenNMT-kpg-release
|
AverageAttention
| false
| 880
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
ContextGate
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class ContextGate(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGate, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, prev_emb, dec_state, attn_state):
input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1)
z = self.sig(self.gate(input_tensor))
proj_source = self.source_proj(attn_state)
proj_target = self.target_proj(torch.cat((prev_emb, dec_state), dim=1))
return z, proj_source, proj_target
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'embeddings_size': 4, 'decoder_size': 4, 'attention_size':
4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 12), (12, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 8), (8, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_4, (12, 4), (1,
12), 0), out=buf1)
del primals_4
buf2 = buf1
del buf1
triton_poi_fused_sigmoid_1[grid(16)](buf2, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_3, reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
del primals_6
del primals_7
buf4 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_2[grid(32)](primals_1, primals_2, buf4, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf4, reinterpret_tensor(primals_8,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf5)
del primals_8
del primals_9
return buf2, buf3, buf5, primals_3, buf0, buf2, buf4
class ContextGateNew(nn.Module):
"""
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and
produces a gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
def __init__(self, embeddings_size, decoder_size, attention_size,
output_size):
super(ContextGateNew, self).__init__()
input_size = embeddings_size + decoder_size + attention_size
self.gate = nn.Linear(input_size, output_size, bias=True)
self.sig = nn.Sigmoid()
self.source_proj = nn.Linear(attention_size, output_size)
self.target_proj = nn.Linear(embeddings_size + decoder_size,
output_size)
def forward(self, input_0, input_1, input_2):
primals_4 = self.gate.weight
primals_5 = self.gate.bias
primals_1 = self.source_proj.weight
primals_7 = self.source_proj.bias
primals_8 = self.target_proj.weight
primals_9 = self.target_proj.bias
primals_2 = input_0
primals_3 = input_1
primals_6 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0], output[1], output[2]
|
NaomiatLibrary/OpenNMT-kpg-release
|
ContextGate
| false
| 881
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
MultiHeadAttention
|
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, embedding_size, number_of_heads):
super(MultiHeadAttention, self).__init__()
self.embedding_size = embedding_size
self.number_of_heads = number_of_heads
self.head_dimension = embedding_size // number_of_heads
assert self.head_dimension * number_of_heads == embedding_size, 'Embedding size needs to be divisible by the number of heads'
self.value = nn.Linear(self.head_dimension, self.head_dimension,
bias=False)
self.key = nn.Linear(self.head_dimension, self.head_dimension, bias
=False)
self.query = nn.Linear(self.head_dimension, self.head_dimension,
bias=False)
self.full_connection = nn.Linear(number_of_heads * self.
head_dimension, embedding_size)
def forward(self, query, value, key, mask):
batch_size = query.shape[0]
value_len, key_len, query_len = value.shape[1], key.shape[1
], query.shape[1]
values = value.reshape(batch_size, value_len, self.number_of_heads,
self.head_dimension)
keys = key.reshape(batch_size, key_len, self.number_of_heads, self.
head_dimension)
queries = query.reshape(batch_size, query_len, self.number_of_heads,
self.head_dimension)
values = self.value(values)
keys = self.key(keys)
queries = self.query(queries)
attention = torch.einsum('bqhd,bkhd->bhqk', [queries, keys])
if mask is not None:
attention = attention.masked_fill(mask == 0, float('-1e20'))
attention /= self.embedding_size ** 0.5
attention = torch.softmax(attention, dim=3)
out = torch.einsum('bhql,blhd->bqhd', [attention, values]).reshape(
batch_size, query_len, self.number_of_heads * self.head_dimension)
out = self.full_connection(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 1]), torch.rand([4, 4, 4, 1]), torch.rand(
[4, 4, 4, 1]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'embedding_size': 4, 'number_of_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_eq_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 == tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_masked_fill_1(in_ptr0, in_ptr1, in_ptr2,
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
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last').to(tl.int1)
tmp1 = tl.load(in_ptr1 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + (y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last').to(tl.int1)
tmp9 = tl.load(in_ptr2 + (4 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (2 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last').to(tl.int1)
tmp15 = tl.load(in_ptr2 + (8 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr0 + (3 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr2 + (12 + y0 + 16 * y1), ymask, eviction_policy=
'evict_last')
tmp3 = tmp1 * tmp2
tmp4 = -1.0000000200408773e+20
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp6 = 1.0
tmp7 = tmp5 * tmp6
tmp10 = tmp1 * tmp9
tmp11 = tl.where(tmp8, tmp4, tmp10)
tmp12 = tmp11 * tmp6
tmp13 = triton_helpers.maximum(tmp7, tmp12)
tmp16 = tmp1 * tmp15
tmp17 = tl.where(tmp14, tmp4, tmp16)
tmp18 = tmp17 * tmp6
tmp19 = triton_helpers.maximum(tmp13, tmp18)
tmp22 = tmp1 * tmp21
tmp23 = tl.where(tmp20, tmp4, tmp22)
tmp24 = tmp23 * tmp6
tmp25 = triton_helpers.maximum(tmp19, tmp24)
tmp26 = tmp7 - tmp25
tmp27 = 0.5
tmp28 = tmp26 * tmp27
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp12 - tmp25
tmp31 = tmp30 * tmp27
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp29 + tmp32
tmp34 = tmp18 - tmp25
tmp35 = tmp34 * tmp27
tmp36 = tl_math.exp(tmp35)
tmp37 = tmp33 + tmp36
tmp38 = tmp24 - tmp25
tmp39 = tmp38 * tmp27
tmp40 = tl_math.exp(tmp39)
tmp41 = tmp37 + tmp40
tl.store(out_ptr0 + (x2 + 4 * y3), tmp25, xmask & ymask)
tl.store(out_ptr1 + (x2 + 4 * y3), tmp41, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_masked_fill_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x0 = xindex % 4
x5 = xindex // 4
tmp0 = tl.load(in_ptr0 + x4, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + (x2 + 4 * x1 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + (x2 + 4 * x0 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp8 = tl.load(in_ptr3 + x5, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr4 + x5, xmask, eviction_policy='evict_last')
tmp3 = tmp1 * tmp2
tmp4 = -1.0000000200408773e+20
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp6 = 1.0
tmp7 = tmp5 * tmp6
tmp9 = tmp7 - tmp8
tmp10 = 0.5
tmp11 = tmp9 * tmp10
tmp12 = tl_math.exp(tmp11)
tmp14 = tmp12 / tmp13
tl.store(out_ptr0 + x4, tmp14, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 1), (16, 4, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 1), (16, 4, 1, 1))
assert_size_stride(primals_3, (4, 4, 4, 1), (16, 4, 1, 1))
assert_size_stride(primals_4, (1, 1), (1, 1))
assert_size_stride(primals_5, (1, 1), (1, 1))
assert_size_stride(primals_6, (1, 1), (1, 1))
assert_size_stride(primals_7, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 1), (1, 1), 0),
primals_4, out=buf0)
del primals_4
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 1), (1, 1), 0),
primals_5, out=buf1)
del primals_5
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 1), (1, 1), 0),
primals_6, out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_0[grid(256)](primals_7, buf3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_7
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_masked_fill_1[grid(16, 4)](buf3, buf2,
buf1, buf4, buf5, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1,
num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_masked_fill_2[grid(256)](buf3, buf2, buf1,
buf4, buf5, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4, 4, 1, 1), (16, 4, 1, 1, 1), 0)
del buf5
triton_poi_fused_clone_3[grid(16, 4)](buf0, buf7, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf0, (16, 4, 1), (4, 1, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf7, (16, 4, 1), (4, 1, 0), 0), out=buf8)
buf9 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
triton_poi_fused_clone_3[grid(16, 4)](buf8, buf9, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf10 = reinterpret_tensor(buf8, (16, 4), (4, 1), 0)
del buf8
extern_kernels.mm(reinterpret_tensor(buf9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf10)
buf11 = reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0)
del buf10
triton_poi_fused_add_4[grid(64)](buf11, primals_9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_9
return buf11, reinterpret_tensor(primals_2, (64, 1), (1, 1), 0
), reinterpret_tensor(primals_3, (64, 1), (1, 1), 0
), buf1, reinterpret_tensor(primals_1, (64, 1), (1, 1), 0
), buf2, buf3, buf6, reinterpret_tensor(buf9, (16, 4), (4, 1), 0
), primals_8, reinterpret_tensor(buf7, (16, 1, 4), (4, 1, 1), 0)
class MultiHeadAttentionNew(nn.Module):
def __init__(self, embedding_size, number_of_heads):
super(MultiHeadAttentionNew, self).__init__()
self.embedding_size = embedding_size
self.number_of_heads = number_of_heads
self.head_dimension = embedding_size // number_of_heads
assert self.head_dimension * number_of_heads == embedding_size, 'Embedding size needs to be divisible by the number of heads'
self.value = nn.Linear(self.head_dimension, self.head_dimension,
bias=False)
self.key = nn.Linear(self.head_dimension, self.head_dimension, bias
=False)
self.query = nn.Linear(self.head_dimension, self.head_dimension,
bias=False)
self.full_connection = nn.Linear(number_of_heads * self.
head_dimension, embedding_size)
def forward(self, input_0, input_1, input_2, input_3):
primals_4 = self.value.weight
primals_5 = self.key.weight
primals_6 = self.query.weight
primals_8 = self.full_connection.weight
primals_9 = self.full_connection.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = 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]
|
NMT-hub/transformer
|
MultiHeadAttention
| false
| 882
|
[
"MIT"
] | 0
|
e5b332da6a322e8025c30ee7e31fe34a323e7388
|
https://github.com/NMT-hub/transformer/tree/e5b332da6a322e8025c30ee7e31fe34a323e7388
|
AdaIN
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class Linear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaIN(nn.Module):
def __init__(self, in_channels, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channels)
self.style = Linear(style_dim, in_channels * 2)
self.style.linear.bias.data[:in_channels] = 1
self.style.linear.bias.data[in_channels:] = 0
def forward(self, input, style):
style = self.style(style).unsqueeze(2).unsqueeze(3)
gamma, beta = style.chunk(2, 1)
out = self.norm(input)
out = gamma * out + beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_mul_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp22 = tl.load(in_ptr1 + (x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr1 + (4 + x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr2 + (4 + x2), xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 16.0
tmp18 = tmp16 / tmp17
tmp19 = 1e-05
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tmp24 = tmp22 + tmp23
tmp25 = tmp0 - tmp10
tmp26 = tmp25 * tmp21
tmp27 = tmp24 * tmp26
tmp30 = tmp28 + tmp29
tmp31 = tmp27 + tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(out_ptr1 + (r1 + 16 * x0), tmp31, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (8, 4), (4, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((8, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(32)](primals_1, buf0, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(buf0, (4, 8), (1, 4
), 0), out=buf1)
buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf3 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf5 = reinterpret_tensor(buf3, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused__native_batch_norm_legit_add_mul_1[grid(16)](buf5,
primals_4, buf1, primals_2, buf2, buf6, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del buf1
del primals_2
return buf6, buf0, primals_3, primals_4, buf2, buf5
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class Linear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaINNew(nn.Module):
def __init__(self, in_channels, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channels)
self.style = Linear(style_dim, in_channels * 2)
self.style.linear.bias.data[:in_channels] = 1
self.style.linear.bias.data[in_channels:] = 0
def forward(self, input_0, input_1):
primals_2 = self.style.linear.bias
primals_1 = self.style.linear.weight_orig
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio
|
AdaIN
| false
| 883
|
[
"MIT"
] | 0
|
231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
https://github.com/NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio/tree/231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
GlobalAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda
import torch.distributed
def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments
), 'Not all arguments have the same value: ' + str(args)
def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return torch.arange(0, max_len, device=lengths.device).type_as(lengths
).repeat(batch_size, 1).lt(lengths.unsqueeze(1))
class GlobalAttention(nn.Module):
"""
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
Constructs a unit mapping a query `q` of size `dim`
and a source matrix `H` of size `n x dim`, to an output
of size `dim`.
.. mermaid::
graph BT
A[Query]
subgraph RNN
C[H 1]
D[H 2]
E[H N]
end
F[Attn]
G[Output]
A --> F
C --> F
D --> F
E --> F
C -.-> G
D -.-> G
E -.-> G
F --> G
All models compute the output as
:math:`c = \\sum_{j=1}^{\\text{SeqLength}} a_j H_j` where
:math:`a_j` is the softmax of a score function.
Then then apply a projection layer to [q, c].
However they
differ on how they compute the attention score.
* Luong Attention (dot, general):
* dot: :math:`\\text{score}(H_j,q) = H_j^T q`
* general: :math:`\\text{score}(H_j, q) = H_j^T W_a q`
* Bahdanau Attention (mlp):
* :math:`\\text{score}(H_j, q) = v_a^T \\text{tanh}(W_a q + U_a h_j)`
Args:
dim (int): dimensionality of query and key
coverage (bool): use coverage term
attn_type (str): type of attention to use, options [dot,general,mlp]
attn_func (str): attention function to use, options [softmax,sparsemax]
"""
def __init__(self, dim, coverage=False, attn_type='dot', attn_func=
'softmax'):
super(GlobalAttention, self).__init__()
self.dim = dim
assert attn_type in ['dot', 'general', 'mlp'
], 'Please select a valid attention type (got {:s}).'.format(
attn_type)
self.attn_type = attn_type
assert attn_func in ['softmax', 'sparsemax'
], 'Please select a valid attention function.'
self.attn_func = attn_func
if self.attn_type == 'general':
self.linear_in = nn.Linear(dim, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = nn.Linear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=True)
self.v = nn.Linear(dim, 1, bias=False)
out_bias = self.attn_type == 'mlp'
self.linear_out = nn.Linear(dim * 2, dim, bias=out_bias)
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def score(self, h_t, h_s):
"""
Args:
h_t (FloatTensor): sequence of queries ``(batch, tgt_len, dim)``
h_s (FloatTensor): sequence of sources ``(batch, src_len, dim``
Returns:
FloatTensor: raw attention scores (unnormalized) for each src index
``(batch, tgt_len, src_len)``
"""
src_batch, src_len, src_dim = h_s.size()
tgt_batch, tgt_len, tgt_dim = h_t.size()
aeq(src_batch, tgt_batch)
aeq(src_dim, tgt_dim)
aeq(self.dim, src_dim)
if self.attn_type in ['general', 'dot']:
if self.attn_type == 'general':
h_t_ = h_t.view(tgt_batch * tgt_len, tgt_dim)
h_t_ = self.linear_in(h_t_)
h_t = h_t_.view(tgt_batch, tgt_len, tgt_dim)
h_s_ = h_s.transpose(1, 2)
return torch.bmm(h_t, h_s_)
else:
dim = self.dim
wq = self.linear_query(h_t.view(-1, dim))
wq = wq.view(tgt_batch, tgt_len, 1, dim)
wq = wq.expand(tgt_batch, tgt_len, src_len, dim)
uh = self.linear_context(h_s.contiguous().view(-1, dim))
uh = uh.view(src_batch, 1, src_len, dim)
uh = uh.expand(src_batch, tgt_len, src_len, dim)
wquh = torch.tanh(wq + uh)
return self.v(wquh.view(-1, dim)).view(tgt_batch, tgt_len, src_len)
def forward(self, source, memory_bank, memory_lengths=None, coverage=None):
"""
Args:
source (FloatTensor): query vectors ``(batch, tgt_len, dim)``
memory_bank (FloatTensor): source vectors ``(batch, src_len, dim)``
memory_lengths (LongTensor): the source context lengths ``(batch,)``
coverage (FloatTensor): None (not supported yet)
Returns:
(FloatTensor, FloatTensor):
* Computed vector ``(tgt_len, batch, dim)``
* Attention distribtutions for each query
``(tgt_len, batch, src_len)``
"""
if source.dim() == 2:
one_step = True
source = source.unsqueeze(1)
else:
one_step = False
batch, source_l, dim = memory_bank.size()
batch_, target_l, dim_ = source.size()
aeq(batch, batch_)
aeq(dim, dim_)
aeq(self.dim, dim)
if coverage is not None:
batch_, source_l_ = coverage.size()
aeq(batch, batch_)
aeq(source_l, source_l_)
if coverage is not None:
cover = coverage.view(-1).unsqueeze(1)
memory_bank += self.linear_cover(cover).view_as(memory_bank)
memory_bank = torch.tanh(memory_bank)
align = self.score(source, memory_bank)
if memory_lengths is not None:
mask = sequence_mask(memory_lengths, max_len=align.size(-1))
mask = mask.unsqueeze(1)
align.masked_fill_(~mask, -float('inf'))
if self.attn_func == 'softmax':
align_vectors = F.softmax(align.view(batch * target_l, source_l
), -1)
else:
align_vectors = sparsemax(align.view(batch * target_l, source_l
), -1)
align_vectors = align_vectors.view(batch, target_l, source_l)
c = torch.bmm(align_vectors, memory_bank)
concat_c = torch.cat([c, source], 2).view(batch * target_l, dim * 2)
attn_h = self.linear_out(concat_c).view(batch, target_l, dim)
if self.attn_type in ['general', 'dot']:
attn_h = torch.tanh(attn_h)
if one_step:
attn_h = attn_h.squeeze(1)
align_vectors = align_vectors.squeeze(1)
batch_, dim_ = attn_h.size()
aeq(batch, batch_)
aeq(dim, dim_)
batch_, source_l_ = align_vectors.size()
aeq(batch, batch_)
aeq(source_l, source_l_)
else:
attn_h = attn_h.transpose(0, 1).contiguous()
align_vectors = align_vectors.transpose(0, 1).contiguous()
target_l_, batch_, dim_ = attn_h.size()
aeq(target_l, target_l_)
aeq(batch, batch_)
aeq(dim, dim_)
target_l_, batch_, source_l_ = align_vectors.size()
aeq(target_l, target_l_)
aeq(batch, batch_)
aeq(source_l, source_l_)
return attn_h, align_vectors
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(out_ptr0 + x3, tmp1, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 8), (8, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(primals_2, (4, 4,
4), (16, 1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1),
0), primals_2, out=buf3)
del primals_2
buf4 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_2[grid(128)](buf3, primals_1, buf4, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf5 = reinterpret_tensor(buf3, (16, 4), (4, 1), 0)
del buf3
extern_kernels.mm(reinterpret_tensor(buf4, (16, 8), (8, 1), 0),
reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), out=buf5)
del primals_3
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(64)](buf2, buf7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf2
return buf6, buf7, reinterpret_tensor(buf4, (16, 8), (8, 1), 0), buf5
def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments
), 'Not all arguments have the same value: ' + str(args)
def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return torch.arange(0, max_len, device=lengths.device).type_as(lengths
).repeat(batch_size, 1).lt(lengths.unsqueeze(1))
class GlobalAttentionNew(nn.Module):
"""
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
Constructs a unit mapping a query `q` of size `dim`
and a source matrix `H` of size `n x dim`, to an output
of size `dim`.
.. mermaid::
graph BT
A[Query]
subgraph RNN
C[H 1]
D[H 2]
E[H N]
end
F[Attn]
G[Output]
A --> F
C --> F
D --> F
E --> F
C -.-> G
D -.-> G
E -.-> G
F --> G
All models compute the output as
:math:`c = \\sum_{j=1}^{\\text{SeqLength}} a_j H_j` where
:math:`a_j` is the softmax of a score function.
Then then apply a projection layer to [q, c].
However they
differ on how they compute the attention score.
* Luong Attention (dot, general):
* dot: :math:`\\text{score}(H_j,q) = H_j^T q`
* general: :math:`\\text{score}(H_j, q) = H_j^T W_a q`
* Bahdanau Attention (mlp):
* :math:`\\text{score}(H_j, q) = v_a^T \\text{tanh}(W_a q + U_a h_j)`
Args:
dim (int): dimensionality of query and key
coverage (bool): use coverage term
attn_type (str): type of attention to use, options [dot,general,mlp]
attn_func (str): attention function to use, options [softmax,sparsemax]
"""
def __init__(self, dim, coverage=False, attn_type='dot', attn_func=
'softmax'):
super(GlobalAttentionNew, self).__init__()
self.dim = dim
assert attn_type in ['dot', 'general', 'mlp'
], 'Please select a valid attention type (got {:s}).'.format(
attn_type)
self.attn_type = attn_type
assert attn_func in ['softmax', 'sparsemax'
], 'Please select a valid attention function.'
self.attn_func = attn_func
if self.attn_type == 'general':
self.linear_in = nn.Linear(dim, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = nn.Linear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=True)
self.v = nn.Linear(dim, 1, bias=False)
out_bias = self.attn_type == 'mlp'
self.linear_out = nn.Linear(dim * 2, dim, bias=out_bias)
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def score(self, h_t, h_s):
"""
Args:
h_t (FloatTensor): sequence of queries ``(batch, tgt_len, dim)``
h_s (FloatTensor): sequence of sources ``(batch, src_len, dim``
Returns:
FloatTensor: raw attention scores (unnormalized) for each src index
``(batch, tgt_len, src_len)``
"""
src_batch, src_len, src_dim = h_s.size()
tgt_batch, tgt_len, tgt_dim = h_t.size()
aeq(src_batch, tgt_batch)
aeq(src_dim, tgt_dim)
aeq(self.dim, src_dim)
if self.attn_type in ['general', 'dot']:
if self.attn_type == 'general':
h_t_ = h_t.view(tgt_batch * tgt_len, tgt_dim)
h_t_ = self.linear_in(h_t_)
h_t = h_t_.view(tgt_batch, tgt_len, tgt_dim)
h_s_ = h_s.transpose(1, 2)
return torch.bmm(h_t, h_s_)
else:
dim = self.dim
wq = self.linear_query(h_t.view(-1, dim))
wq = wq.view(tgt_batch, tgt_len, 1, dim)
wq = wq.expand(tgt_batch, tgt_len, src_len, dim)
uh = self.linear_context(h_s.contiguous().view(-1, dim))
uh = uh.view(src_batch, 1, src_len, dim)
uh = uh.expand(src_batch, tgt_len, src_len, dim)
wquh = torch.tanh(wq + uh)
return self.v(wquh.view(-1, dim)).view(tgt_batch, tgt_len, src_len)
def forward(self, input_0, input_1):
primals_3 = self.linear_out.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
NaomiatLibrary/OpenNMT-kpg-release
|
GlobalAttention
| false
| 884
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
PolicyNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PolicyNetwork(torch.nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.input_size = input_size
self.linear1 = nn.Linear(input_size, 32)
self.linear2 = nn.Linear(32, output_size)
def forward(self, x):
x = x.view((-1, self.input_size))
out = F.relu(self.linear1(x))
out = F.softmax(self.linear2(out), dim=1)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (32, 4), (4, 1))
assert_size_stride(primals_3, (32,), (1,))
assert_size_stride(primals_4, (4, 32), (32, 1))
assert_size_stride(primals_5, (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_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 32), (1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(2048)](buf1, primals_3, 2048, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(32, 4), (1, 32), 0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf3
return buf4, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1, buf4, primals_4
class PolicyNetworkNew(torch.nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.input_size = input_size
self.linear1 = nn.Linear(input_size, 32)
self.linear2 = nn.Linear(32, output_size)
def forward(self, input_0):
primals_2 = self.linear1.weight
primals_3 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
NiccoloSacchi/rlcard
|
PolicyNetwork
| false
| 885
|
[
"MIT"
] | 0
|
046129e8616b12e25652957869a94ab5fd838ae1
|
https://github.com/NiccoloSacchi/rlcard/tree/046129e8616b12e25652957869a94ab5fd838ae1
|
VdConv1D
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def calculate_kl(log_alpha):
return 0.5 * torch.sum(torch.log1p(torch.exp(-log_alpha)))
class VdConv1D(nn.Module):
"""
Conv1D Layer variational dropout
"""
def __init__(self, in_channels, out_channels, kernel_size, alpha_shape=
(1, 1), bias=True, stride=1, padding=0, dilation=1):
super(VdConv1D, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.alpha_shape = alpha_shape
self.groups = 1
self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels,
self.kernel_size))
self.log_alpha = nn.Parameter(torch.Tensor(*alpha_shape))
if bias:
self.bias = nn.Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.out_bias = lambda input, kernel: F.conv1d(input, kernel, self.
bias, self.stride, self.padding, self.dilation, self.groups)
self.out_nobias = lambda input, kernel: F.conv1d(input, kernel,
None, self.stride, self.padding, self.dilation, self.groups)
self.reset_parameters()
self.kl_value = calculate_kl
def reset_parameters(self):
n = self.in_channels
n *= self.kernel_size
stdv = 1.0 / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
self.log_alpha.data.fill_(-5.0)
def forward(self, x, sample=False):
mean = self.out_bias(x, self.weight)
sigma = torch.exp(self.log_alpha) * self.weight * self.weight
std = torch.sqrt(1e-16 + self.out_nobias(x * x, sigma))
if self.training or sample:
epsilon = std.data.new(std.size()).normal_()
else:
epsilon = 0.0
out = mean + std * epsilon
kl = self.kl_loss()
return out, kl
def kl_loss(self):
return self.weight.nelement() / self.log_alpha.nelement(
) * self.kl_value(self.log_alpha)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_exp_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tl_math.exp(tmp1)
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tl.store(out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_mul_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 = tmp0 * tmp0
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused_add_mul_sqrt_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp4 = 1e-16
tmp5 = tmp3 + tmp4
tmp6 = libdevice.sqrt(tmp5)
tmp7 = 0.0
tmp8 = tmp6 * tmp7
tmp9 = tmp2 + tmp8
tl.store(in_out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_poi_fused_exp_log1p_mul_neg_sum_3(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = -tmp1
tmp3 = tl_math.exp(tmp2)
tmp4 = libdevice.log1p(tmp3)
tmp5 = 0.5
tmp6 = tmp4 * tmp5
tmp7 = 64.0
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp8, None)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (1, 1), (1, 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=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 1), (4, 1, 1))
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_exp_mul_0[grid(64)](primals_4, primals_1, buf1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_1[grid(16)](primals_2, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf3 = extern_kernels.convolution(reinterpret_tensor(buf2, (1, 4, 4
), (0, 4, 1), 0), buf1, stride=(1,), padding=(0,), dilation=(1,
), transposed=False, output_padding=(0,), groups=1, bias=None)
assert_size_stride(buf3, (1, 4, 1), (4, 1, 1))
buf4 = reinterpret_tensor(buf0, (4, 1), (1, 1), 0)
del buf0
triton_poi_fused_add_mul_sqrt_2[grid(4)](buf4, primals_3, buf3, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_3
buf5 = empty_strided_cuda((), (), torch.float32)
triton_poi_fused_exp_log1p_mul_neg_sum_3[grid(1)](primals_4, buf5,
1, XBLOCK=1, num_warps=1, num_stages=1)
return buf4, buf5, primals_1, primals_4, reinterpret_tensor(primals_2,
(1, 4, 4), (16, 4, 1), 0), buf1, reinterpret_tensor(buf2, (1, 4, 4),
(16, 4, 1), 0), buf3
def calculate_kl(log_alpha):
return 0.5 * torch.sum(torch.log1p(torch.exp(-log_alpha)))
class VdConv1DNew(nn.Module):
"""
Conv1D Layer variational dropout
"""
def __init__(self, in_channels, out_channels, kernel_size, alpha_shape=
(1, 1), bias=True, stride=1, padding=0, dilation=1):
super(VdConv1DNew, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.alpha_shape = alpha_shape
self.groups = 1
self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels,
self.kernel_size))
self.log_alpha = nn.Parameter(torch.Tensor(*alpha_shape))
if bias:
self.bias = nn.Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.out_bias = lambda input, kernel: F.conv1d(input, kernel, self.
bias, self.stride, self.padding, self.dilation, self.groups)
self.out_nobias = lambda input, kernel: F.conv1d(input, kernel,
None, self.stride, self.padding, self.dilation, self.groups)
self.reset_parameters()
self.kl_value = calculate_kl
def reset_parameters(self):
n = self.in_channels
n *= self.kernel_size
stdv = 1.0 / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
self.log_alpha.data.fill_(-5.0)
def kl_loss(self):
return self.weight.nelement() / self.log_alpha.nelement(
) * self.kl_value(self.log_alpha)
def forward(self, input_0):
primals_1 = self.weight
primals_4 = self.log_alpha
primals_3 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
Neronjust2017/pytorch-classification-project
|
VdConv1D
| false
| 886
|
[
"MIT"
] | 0
|
fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
https://github.com/Neronjust2017/pytorch-classification-project/tree/fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
SpatialAttention
|
import torch
import torch.nn.parallel
import torch.utils.data
import torch.nn as nn
import torch.cuda
class SpatialAttention(nn.Module):
def __init__(self):
super(SpatialAttention, self).__init__()
self.conv = nn.Conv2d(2, 1, 7, padding=3, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
feat_avg = torch.mean(x, dim=1, keepdim=True)
feat_max = torch.max(x, dim=1, keepdim=True)[0]
feature = torch.cat((feat_avg, feat_max), dim=1)
return self.sigmoid(self.conv(feature))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn.parallel
import torch.utils.data
import torch.nn as nn
import torch.cuda
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 2
x0 = xindex % 16
x2 = xindex // 32
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp9 = tmp7 + tmp8
tmp10 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp9 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp4, tmp13, tmp14)
tmp16 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp19 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = triton_helpers.maximum(tmp19, tmp20)
tmp22 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = triton_helpers.maximum(tmp21, tmp22)
tmp24 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp25 = triton_helpers.maximum(tmp23, tmp24)
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp16, tmp25, tmp26)
tmp28 = tl.where(tmp4, tmp15, tmp27)
tl.store(out_ptr0 + x3, tmp28, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(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 = tl.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 2, 7, 7), (98, 49, 7, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](primals_1, buf0, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 1, 4, 4), (16, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_sigmoid_1[grid(64)](buf2, 64, XBLOCK=64, num_warps
=1, num_stages=1)
return buf2, primals_2, buf0, buf2
class SpatialAttentionNew(nn.Module):
def __init__(self):
super(SpatialAttentionNew, self).__init__()
self.conv = nn.Conv2d(2, 1, 7, padding=3, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.conv.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
NeilDG/NeuralNets-Experiment3
|
SpatialAttention
| false
| 887
|
[
"MIT"
] | 0
|
f0d2f788eeca49f803f65810c155491ce687cf9e
|
https://github.com/NeilDG/NeuralNets-Experiment3/tree/f0d2f788eeca49f803f65810c155491ce687cf9e
|
Loss
|
import math
import torch
import torch.nn as nn
class Loss(nn.Module):
def __init__(self, device, type_in='pred_intervals', alpha=0.1,
loss_type='qd_soft', censor_R=False, soften=100.0, lambda_in=10.0,
sigma_in=0.5):
super().__init__()
self.alpha = alpha
self.lambda_in = lambda_in
self.soften = soften
self.loss_type = loss_type
self.type_in = type_in
self.censor_R = censor_R
self.sigma_in = sigma_in
self.device = device
def forward(self, y_pred, y_true):
if self.type_in == 'pred_intervals':
metric = []
metric_name = []
y_U = y_pred[:, 0]
y_L = y_pred[:, 1]
y_T = y_true[:, 0]
N_ = y_T.shape[0]
alpha_ = self.alpha
lambda_ = self.lambda_in
torch.mean(y_pred, dim=1)
MPIW = torch.mean(y_U - y_L)
gamma_U = torch.sigmoid((y_U - y_T) * self.soften)
gamma_L = torch.sigmoid((y_T - y_L) * self.soften)
gamma_ = torch.mul(gamma_U, gamma_L)
torch.ones_like(gamma_)
zeros = torch.zeros_like(y_U)
gamma_U_hard = torch.max(zeros, torch.sign(y_U - y_T))
gamma_L_hard = torch.max(zeros, torch.sign(y_T - y_L))
gamma_hard = torch.mul(gamma_U_hard, gamma_L_hard)
qd_lhs_hard = torch.div(torch.mean(torch.abs(y_U - y_L) *
gamma_hard), torch.mean(gamma_hard) + 0.001)
torch.div(torch.mean(torch.abs(y_U - y_L) * gamma_), torch.mean
(gamma_) + 0.001)
PICP_soft = torch.mean(gamma_)
PICP_hard = torch.mean(gamma_hard)
zero = torch.tensor(0.0)
qd_rhs_soft = lambda_ * math.sqrt(N_) * torch.pow(torch.max(
zero, 1.0 - alpha_ - PICP_soft), 2)
qd_rhs_hard = lambda_ * math.sqrt(N_) * torch.pow(torch.max(
zero, 1.0 - alpha_ - PICP_hard), 2)
qd_loss_soft = qd_lhs_hard + qd_rhs_soft
qd_loss_hard = qd_lhs_hard + qd_rhs_hard
y_mean = y_U
y_var_limited = torch.min(y_L, torch.tensor(10.0))
y_var = torch.max(torch.log(1.0 + torch.exp(y_var_limited)),
torch.tensor(1e-05))
self.y_mean = y_mean
self.y_var = y_var
gauss_loss = torch.log(y_var) / 2.0 + torch.div(torch.pow(y_T -
y_mean, 2), 2.0 * y_var)
gauss_loss = torch.mean(gauss_loss)
if self.loss_type == 'qd_soft':
loss = qd_loss_soft
elif self.loss_type == 'qd_hard':
loss = qd_loss_hard
elif self.loss_type == 'gauss_like':
loss = gauss_loss
elif self.loss_type == 'picp':
loss = PICP_hard
elif self.loss_type == 'mse':
loss = torch.mean(torch.pow(y_U - y_T, 2))
torch.mean(gamma_U_hard)
torch.mean(gamma_L_hard)
PICP = torch.mean(gamma_hard)
metric.append(PICP)
metric_name.append('PICP')
metric.append(MPIW)
metric_name.append('MPIW')
return loss, PICP, MPIW
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'device': 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 math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_abs_add_div_exp_lift_fresh_log_maximum_mean_minimum_mul_pow_rsub_sigmoid_sign_sub_zeros_like_0(
in_out_ptr0, in_out_ptr1, in_out_ptr2, in_ptr0, in_ptr1, out_ptr2,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
r2 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp4 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp5 = tmp0 - tmp4
tmp6 = tl.full([1, 1], 0, tl.int32)
tmp7 = tmp6 < tmp5
tmp8 = tmp7.to(tl.int8)
tmp9 = tmp5 < tmp6
tmp10 = tmp9.to(tl.int8)
tmp11 = tmp8 - tmp10
tmp12 = tmp11.to(tmp5.dtype)
tmp13 = 0.0
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp15 = tmp4 - tmp1
tmp16 = tmp6 < tmp15
tmp17 = tmp16.to(tl.int8)
tmp18 = tmp15 < tmp6
tmp19 = tmp18.to(tl.int8)
tmp20 = tmp17 - tmp19
tmp21 = tmp20.to(tmp15.dtype)
tmp22 = triton_helpers.maximum(tmp13, tmp21)
tmp23 = tmp14 * tmp22
tmp24 = tmp3 * tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.sum(tmp25, 1)[:, None]
tmp28 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp30 = tl.sum(tmp28, 1)[:, None]
tmp31 = 100.0
tmp32 = tmp5 * tmp31
tmp33 = tl.sigmoid(tmp32)
tmp34 = tmp15 * tmp31
tmp35 = tl.sigmoid(tmp34)
tmp36 = tmp33 * tmp35
tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
tmp39 = tl.sum(tmp37, 1)[:, None]
tmp40 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp42 = tl.sum(tmp40, 1)[:, None]
tmp43 = 10.0
tmp44 = triton_helpers.minimum(tmp1, tmp43)
tmp45 = tl_math.exp(tmp44)
tmp46 = 1.0
tmp47 = tmp45 + tmp46
tmp48 = tl_math.log(tmp47)
tmp49 = 9.999999747378752e-06
tmp50 = triton_helpers.maximum(tmp48, tmp49)
tmp51 = 64.0
tmp52 = tmp27 / tmp51
tmp53 = tmp30 / tmp51
tmp54 = 0.001
tmp55 = tmp53 + tmp54
tmp56 = tmp52 / tmp55
tmp57 = tmp39 / tmp51
tmp58 = 0.9
tmp59 = tmp58 - tmp57
tmp60 = triton_helpers.maximum(tmp13, tmp59)
tmp61 = tmp60 * tmp60
tmp62 = 20.0
tmp63 = tmp61 * tmp62
tmp64 = tmp56 + tmp63
tmp65 = tmp42 / tmp51
tl.store(out_ptr2 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp50, None)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp64, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp53, None)
tl.debug_barrier()
tl.store(in_out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp65, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf6 = buf0
del buf0
buf7 = buf3
del buf3
buf8 = buf4
del buf4
get_raw_stream(0)
triton_per_fused_abs_add_div_exp_lift_fresh_log_maximum_mean_minimum_mul_pow_rsub_sigmoid_sign_sub_zeros_like_0[
grid(1)](buf6, buf7, buf8, arg0_1, arg1_1, buf5, 1, 64, XBLOCK=
1, num_warps=2, num_stages=1)
del arg1_1
return buf6, buf7, buf8, buf5, reinterpret_tensor(arg0_1, (4, 4, 4), (
64, 4, 1), 0)
class LossNew(nn.Module):
def __init__(self, device, type_in='pred_intervals', alpha=0.1,
loss_type='qd_soft', censor_R=False, soften=100.0, lambda_in=10.0,
sigma_in=0.5):
super().__init__()
self.alpha = alpha
self.lambda_in = lambda_in
self.soften = soften
self.loss_type = loss_type
self.type_in = type_in
self.censor_R = censor_R
self.sigma_in = sigma_in
self.device = device
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1], output[2]
|
Neronjust2017/pytorch-classification-project
|
Loss
| false
| 888
|
[
"MIT"
] | 0
|
fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
https://github.com/Neronjust2017/pytorch-classification-project/tree/fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
Linear
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class Linear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf0, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class LinearNew(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input_0):
primals_2 = self.linear.bias
primals_1 = self.linear.weight_orig
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio
|
Linear
| false
| 889
|
[
"MIT"
] | 0
|
231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
https://github.com/NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio/tree/231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
PixelNorm
|
import torch
import torch.nn as nn
class PixelNorm(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return input / torch.sqrt(torch.mean(input ** 2, dim=0, keepdim=
True) + 1e-08)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_pow_sqrt_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (192 + 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 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = 1e-08
tmp15 = tmp13 + tmp14
tmp16 = libdevice.sqrt(tmp15)
tmp17 = tmp0 / tmp16
tl.store(out_ptr0 + x2, tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_pow_sqrt_0[grid(256)](arg0_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class PixelNormNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio
|
PixelNorm
| false
| 890
|
[
"MIT"
] | 0
|
231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
https://github.com/NethraGunti/Woven-Artificial-Profile-WARP-Face-Video-Synthesis-from-Profile-and-Audio/tree/231d8daa8dddfd5eda8a092eb99c5d0e59d8b3f7
|
LayerNorm
|
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
"""Construct a layernorm module in the OpenAI style (epsilon inside the square root)."""
def __init__(self, n_state, e=1e-05):
super(LayerNorm, self).__init__()
self.g = nn.Parameter(torch.ones(n_state))
self.b = nn.Parameter(torch.zeros(n_state))
self.e = e
"""
Input:
x: n_state-dim
Output:
o: n_state-dim
"""
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.e)
return self.g * x + self.b
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_state': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mean_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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-05
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_sub_0[grid(256)](primals_1, buf0, 256, XBLOCK
=128, num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_1[grid(256)](primals_2,
buf0, primals_3, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
del primals_3
return buf1, primals_1
class LayerNormNew(nn.Module):
"""Construct a layernorm module in the OpenAI style (epsilon inside the square root)."""
def __init__(self, n_state, e=1e-05):
super(LayerNormNew, self).__init__()
self.g = nn.Parameter(torch.ones(n_state))
self.b = nn.Parameter(torch.zeros(n_state))
self.e = e
"""
Input:
x: n_state-dim
Output:
o: n_state-dim
"""
def forward(self, input_0):
primals_2 = self.g
primals_3 = self.b
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
NickSchoelkopf/SummerTime
|
LayerNorm
| false
| 891
|
[
"Apache-2.0"
] | 0
|
9a89aab8e1544e3c52c043b9c47ab325e665e11e
|
https://github.com/NickSchoelkopf/SummerTime/tree/9a89aab8e1544e3c52c043b9c47ab325e665e11e
|
VdLinear
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def calculate_kl(log_alpha):
return 0.5 * torch.sum(torch.log1p(torch.exp(-log_alpha)))
class VdLinear(nn.Module):
"""
Linear Layer variational dropout
"""
def __init__(self, n_in, n_out, alpha_shape=(1, 1), bias=True):
super(VdLinear, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.alpha_shape = alpha_shape
self.bias = bias
self.W = nn.Parameter(torch.Tensor(self.n_out, self.n_in))
self.log_alpha = nn.Parameter(torch.Tensor(*self.alpha_shape))
if bias:
self.bias = nn.Parameter(torch.Tensor(1, self.n_out))
else:
self.register_parameter('bias', None)
self.reset_parameters()
self.kl_value = calculate_kl
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.W.size(1))
self.W.data.uniform_(-stdv, stdv)
self.log_alpha.data.fill_(-5.0)
if self.bias is not None:
self.bias.data.zero_()
def forward(self, X, sample=False):
mean = F.linear(X, self.W)
if self.bias is not None:
mean = mean + self.bias
sigma = torch.exp(self.log_alpha) * self.W * self.W
std = torch.sqrt(1e-16 + F.linear(X * X, sigma))
if self.training or sample:
epsilon = std.data.new(std.size()).normal_()
else:
epsilon = 0.0
out = mean + std * epsilon
kl = self.kl_loss()
return out, kl
def kl_loss(self):
return self.W.nelement() * self.kl_value(self.log_alpha
) / self.log_alpha.nelement()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 4, 'n_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.triton_helpers import libdevice, math as tl_math
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 * tmp0
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused_exp_mul_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tl_math.exp(tmp1)
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tl.store(out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_mul_sqrt_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = 1e-16
tmp5 = tmp3 + tmp4
tmp6 = libdevice.sqrt(tmp5)
tmp7 = 0.0
tmp8 = tmp6 * tmp7
tmp9 = tmp2 + tmp8
tl.store(in_out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_div_exp_log1p_mul_neg_sum_3(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = -tmp1
tmp3 = tl_math.exp(tmp2)
tmp4 = libdevice.log1p(tmp3)
tmp5 = 0.5
tmp6 = tmp4 * tmp5
tmp7 = 16.0
tmp8 = tmp6 * tmp7
tmp9 = 1.0
tmp10 = tmp8 * tmp9
tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp10, None)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 4), (4, 1))
assert_size_stride(primals_4, (1, 1), (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_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_2, buf1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_exp_mul_1[grid(16)](primals_4, primals_1, buf2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(buf2, (4, 4), (1, 4), 0), out=buf3)
del buf2
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_add_mul_sqrt_2[grid(256)](buf4, primals_3, buf3,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf5 = empty_strided_cuda((), (), torch.float32)
triton_poi_fused_div_exp_log1p_mul_neg_sum_3[grid(1)](primals_4,
buf5, 1, XBLOCK=1, num_warps=1, num_stages=1)
return buf4, buf5, primals_1, primals_4, reinterpret_tensor(primals_2,
(64, 4), (4, 1), 0), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf3
def calculate_kl(log_alpha):
return 0.5 * torch.sum(torch.log1p(torch.exp(-log_alpha)))
class VdLinearNew(nn.Module):
"""
Linear Layer variational dropout
"""
def __init__(self, n_in, n_out, alpha_shape=(1, 1), bias=True):
super(VdLinearNew, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.alpha_shape = alpha_shape
self.bias = bias
self.W = nn.Parameter(torch.Tensor(self.n_out, self.n_in))
self.log_alpha = nn.Parameter(torch.Tensor(*self.alpha_shape))
if bias:
self.bias = nn.Parameter(torch.Tensor(1, self.n_out))
else:
self.register_parameter('bias', None)
self.reset_parameters()
self.kl_value = calculate_kl
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.W.size(1))
self.W.data.uniform_(-stdv, stdv)
self.log_alpha.data.fill_(-5.0)
if self.bias is not None:
self.bias.data.zero_()
def kl_loss(self):
return self.W.nelement() * self.kl_value(self.log_alpha
) / self.log_alpha.nelement()
def forward(self, input_0):
primals_1 = self.W
primals_4 = self.log_alpha
primals_3 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
Neronjust2017/pytorch-classification-project
|
VdLinear
| false
| 892
|
[
"MIT"
] | 0
|
fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
https://github.com/Neronjust2017/pytorch-classification-project/tree/fc5f4d7c46d071765f682ce20e6580646d4e5c76
|
C
|
import torch
import torch.nn as nn
class C(nn.Module):
def __init__(self, input_channel, output_channel, kernel_size, stride,
padding, activation=None):
"""
At the final layer, a 3x3 convolution is used to map each 64-component feature vector to the desired
number of classes.
:param input_channel: input channel size
:param output_channel: output channel size
"""
super(C, self).__init__()
if activation == 'sigmoid':
self.layer = nn.Sequential([nn.Conv2d(input_channel,
output_channel, kernel_size=kernel_size, stride=stride,
padding=padding), nn.Sigmoid()])
elif activation == 'tanh':
self.layer = nn.Sequential([nn.Conv2d(input_channel,
output_channel, kernel_size=kernel_size, stride=stride,
padding=padding), nn.Tanh()])
else:
self.layer = nn.Conv2d(input_channel, output_channel,
kernel_size=kernel_size, stride=stride, padding=padding)
def forward(self, x):
return self.layer(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_channel': 4, 'output_channel': 4, 'kernel_size': 4,
'stride': 1, 'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 9, 9), (324, 81, 9, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(1296)](buf1, primals_2, 1296,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class CNew(nn.Module):
def __init__(self, input_channel, output_channel, kernel_size, stride,
padding, activation=None):
"""
At the final layer, a 3x3 convolution is used to map each 64-component feature vector to the desired
number of classes.
:param input_channel: input channel size
:param output_channel: output channel size
"""
super(CNew, self).__init__()
if activation == 'sigmoid':
self.layer = nn.Sequential([nn.Conv2d(input_channel,
output_channel, kernel_size=kernel_size, stride=stride,
padding=padding), nn.Sigmoid()])
elif activation == 'tanh':
self.layer = nn.Sequential([nn.Conv2d(input_channel,
output_channel, kernel_size=kernel_size, stride=stride,
padding=padding), nn.Tanh()])
else:
self.layer = nn.Conv2d(input_channel, output_channel,
kernel_size=kernel_size, stride=stride, padding=padding)
def forward(self, input_0):
primals_1 = self.layer.weight
primals_2 = self.layer.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Nikronic/Deep-Halftoning
|
C
| false
| 893
|
[
"MIT"
] | 0
|
9564c592abf139ccab2791c1dbb354505edab5f9
|
https://github.com/Nikronic/Deep-Halftoning/tree/9564c592abf139ccab2791c1dbb354505edab5f9
|
ConcatReLU
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def concat_relu(x):
"""Concatenated ReLU (http://arxiv.org/abs/1603.05201)."""
return F.relu(torch.cat([x, -x], dim=1))
class ConcatReLU(nn.Module):
"""Concatenated ReLU (http://arxiv.org/abs/1603.05201)."""
def forward(self, input):
return concat_relu(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr0 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = -tmp9
tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
tmp12 = tl.where(tmp6, tmp10, tmp11)
tmp13 = tl.where(tmp4, tmp5, tmp12)
tmp14 = tl.full([1], 0, tl.int32)
tmp15 = triton_helpers.maximum(tmp14, tmp13)
tl.store(out_ptr0 + x3, tmp15, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_relu_0[grid(512)](arg0_1, buf0, 512, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def concat_relu(x):
"""Concatenated ReLU (http://arxiv.org/abs/1603.05201)."""
return F.relu(torch.cat([x, -x], dim=1))
class ConcatReLUNew(nn.Module):
"""Concatenated ReLU (http://arxiv.org/abs/1603.05201)."""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Nintorac/survae_experiments
|
ConcatReLU
| false
| 894
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
CrossEntropyLossOneHot
|
import torch
from torch import Tensor
from torch.nn.modules.loss import CrossEntropyLoss
class CrossEntropyLossOneHot(CrossEntropyLoss):
EPS: 'int' = 1e-07
def forward(self, input: 'Tensor', target: 'Tensor') ->Tensor:
assert self.weight is None or isinstance(self.weight, Tensor)
input = torch.clip(input, self.EPS, 1 - self.EPS)
crossentropy = target * torch.log(input)
crossentropy = -torch.sum(crossentropy, -1)
return torch.sum(crossentropy)
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
from torch.nn.modules.loss import CrossEntropyLoss
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_clamp_log_mul_neg_sum_0(in_ptr0, in_ptr1, out_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
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = 1e-07
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp4 = 0.9999999
tmp5 = triton_helpers.minimum(tmp3, tmp4)
tmp6 = tl_math.log(tmp5)
tmp7 = tmp0 * tmp6
tmp10 = triton_helpers.maximum(tmp9, tmp2)
tmp11 = triton_helpers.minimum(tmp10, tmp4)
tmp12 = tl_math.log(tmp11)
tmp13 = tmp8 * tmp12
tmp14 = tmp7 + tmp13
tmp17 = triton_helpers.maximum(tmp16, tmp2)
tmp18 = triton_helpers.minimum(tmp17, tmp4)
tmp19 = tl_math.log(tmp18)
tmp20 = tmp15 * tmp19
tmp21 = tmp14 + tmp20
tmp24 = triton_helpers.maximum(tmp23, tmp2)
tmp25 = triton_helpers.minimum(tmp24, tmp4)
tmp26 = tl_math.log(tmp25)
tmp27 = tmp22 * tmp26
tmp28 = tmp21 + tmp27
tmp29 = -tmp28
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_clamp_log_mul_neg_sum_0[grid(1)](arg1_1, arg0_1,
buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class CrossEntropyLossOneHotNew(CrossEntropyLoss):
EPS: 'int' = 1e-07
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
NikolayZakharevich/music-processing
|
CrossEntropyLossOneHot
| false
| 895
|
[
"MIT"
] | 0
|
516a3bca585f211d232cac7ede6cc417fb8878fe
|
https://github.com/NikolayZakharevich/music-processing/tree/516a3bca585f211d232cac7ede6cc417fb8878fe
|
Lookahead
|
import torch
import torch.utils.data.distributed
from torch import nn
import torch.nn.functional as F
class Lookahead(nn.Module):
def __init__(self, n_features, context):
super(Lookahead, self).__init__()
assert context > 0
self.context = context
self.n_features = n_features
self.pad = 0, self.context - 1
self.conv = nn.Conv1d(self.n_features, self.n_features, kernel_size
=self.context, stride=1, groups=self.n_features, padding=0,
bias=False)
def forward(self, x):
x = x.transpose(0, 1).transpose(1, 2)
x = F.pad(x, pad=self.pad, value=0)
x = self.conv(x)
x = x.transpose(1, 2).transpose(0, 1).contiguous()
return x
def __repr__(self):
return self.__class__.__name__ + '(' + 'n_features=' + str(self.
n_features) + ', context=' + str(self.context) + ')'
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_features': 4, 'context': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.utils.data.distributed
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_constant_pad_nd_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 7
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = x1
tmp1 = tl.full([1, 1], 4, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.load(in_ptr0 + (y0 + 16 * x1), tmp2 & xmask & ymask,
eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x1 + 7 * y0), tmp3, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 1, 4), (4, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 7), (28, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(16, 7)](primals_1, buf0, 16,
7, XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=4, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(4, 16)](buf1, buf2, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
del buf1
return buf2, primals_2, buf0
class LookaheadNew(nn.Module):
def __init__(self, n_features, context):
super(LookaheadNew, self).__init__()
assert context > 0
self.context = context
self.n_features = n_features
self.pad = 0, self.context - 1
self.conv = nn.Conv1d(self.n_features, self.n_features, kernel_size
=self.context, stride=1, groups=self.n_features, padding=0,
bias=False)
def __repr__(self):
return self.__class__.__name__ + '(' + 'n_features=' + str(self.
n_features) + ', context=' + str(self.context) + ')'
def forward(self, input_0):
primals_2 = self.conv.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
NikolaiBabkin/deepspeech.pytorch
|
Lookahead
| false
| 896
|
[
"MIT"
] | 0
|
2b120c6b735cc46200e10f81e169c8d7b75e8495
|
https://github.com/NikolaiBabkin/deepspeech.pytorch/tree/2b120c6b735cc46200e10f81e169c8d7b75e8495
|
ResidualAttentionBlock
|
import torch
from typing import Callable
from torch import nn
from torch.nn import functional as F
import torch.distributed.nn
from collections import OrderedDict
from typing import Optional
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: 'torch.Tensor'):
x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias,
self.eps)
return x
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', act_layer: 'Callable'
=nn.GELU):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', act_layer()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
def attention(self, x: 'torch.Tensor', attn_mask:
'Optional[torch.Tensor]'=None):
return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
def forward(self, x: 'torch.Tensor', attn_mask:
'Optional[torch.Tensor]'=None):
x = x + self.attention(self.ln_1(x), attn_mask=attn_mask)
x = x + self.mlp(self.ln_2(x))
return x
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'n_head': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from typing import Callable
from torch import nn
from torch.nn import functional as F
import torch.distributed.nn
from collections import OrderedDict
from typing import Optional
assert_size_stride = torch._C._dynamo.guards.assert_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 = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_mul_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__safe_softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__safe_softmax_5(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1e-05
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_gelu_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865476
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_out_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (16, 4), (4, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (4, 16), (16, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(4)](primals_3, buf0, buf1,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(16)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 16), out=buf4)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8),
buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha=
1, beta=1, out=buf5)
buf6 = reinterpret_tensor(buf3, (1, 4, 4, 1), (16, 1, 4, 16), 0)
del buf3
triton_poi_fused_mul_2[grid(16)](buf6, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf4, (1, 4, 1, 4), (16, 1, 16, 4), 0)
del buf4
triton_poi_fused_mul_3[grid(16)](buf7, primals_5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf6, (4, 4, 1), (1, 4, 0), 0
), reinterpret_tensor(buf7, (4, 1, 4), (1, 0, 4), 0), out=buf8)
buf9 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_4[grid(64)](buf8, buf9, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf10 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__safe_softmax_5[grid(64)](buf8, buf9, buf10, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf5, (4, 4, 1), (1, 4, 0), 0), out=buf11)
buf12 = empty_strided_cuda((4, 1, 4, 1), (4, 1, 1, 4), torch.float32)
triton_poi_fused_clone_6[grid(4, 4)](buf11, buf12, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf13 = reinterpret_tensor(buf11, (4, 4), (4, 1), 0)
del buf11
extern_kernels.addmm(primals_7, reinterpret_tensor(buf12, (4, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf13)
del primals_7
buf14 = buf1
del buf1
buf15 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_7[grid(4)](primals_3, buf13,
buf14, buf15, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf16 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_8[grid(16)](primals_3, buf13,
buf14, buf15, primals_8, primals_9, buf16, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf14
del buf15
del primals_9
buf17 = reinterpret_tensor(buf9, (4, 16), (16, 1), 0)
del buf9
extern_kernels.addmm(primals_11, buf16, reinterpret_tensor(
primals_10, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf17)
del primals_11
buf18 = reinterpret_tensor(buf8, (4, 16), (16, 1), 0)
del buf8
triton_poi_fused_gelu_9[grid(64)](buf17, buf18, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf18, reinterpret_tensor(primals_12, (16, 4), (1,
16), 0), out=buf19)
buf20 = buf19
del buf19
triton_poi_fused_add_10[grid(16)](buf20, primals_3, buf13,
primals_13, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_13
return (buf20, primals_3, primals_8, buf2, buf10, reinterpret_tensor(
buf12, (4, 4), (4, 1), 0), buf13, buf16, buf17, buf18, primals_12,
primals_10, primals_6, reinterpret_tensor(buf5, (4, 1, 4), (1, 1, 4
), 0), reinterpret_tensor(buf6, (4, 1, 4), (1, 4, 4), 0),
reinterpret_tensor(buf7, (4, 4, 1), (1, 4, 16), 0),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 0))
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: 'torch.Tensor'):
x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias,
self.eps)
return x
class ResidualAttentionBlockNew(nn.Module):
def __init__(self, d_model: 'int', n_head: 'int', act_layer: 'Callable'
=nn.GELU):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model,
d_model * 4)), ('gelu', act_layer()), ('c_proj', nn.Linear(
d_model * 4, d_model))]))
self.ln_2 = LayerNorm(d_model)
def attention(self, x: 'torch.Tensor', attn_mask:
'Optional[torch.Tensor]'=None):
return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
def forward(self, input_0):
primals_4 = self.attn.in_proj_weight
primals_5 = self.attn.in_proj_bias
primals_3 = self.attn.out_proj.weight
primals_1 = self.attn.out_proj.bias
primals_2 = self.ln_1.weight
primals_7 = self.ln_1.bias
primals_10 = self.mlp.c_fc.weight
primals_11 = self.mlp.c_fc.bias
primals_12 = self.mlp.c_proj.weight
primals_8 = self.mlp.c_proj.bias
primals_9 = self.ln_2.weight
primals_13 = self.ln_2.bias
primals_6 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
NYU-DICE-Lab/open_clip
|
ResidualAttentionBlock
| false
| 897
|
[
"MIT"
] | 0
|
fd71804b503135fb1c7cc8de3a0d6599741c8ed9
|
https://github.com/NYU-DICE-Lab/open_clip/tree/fd71804b503135fb1c7cc8de3a0d6599741c8ed9
|
SoftCrossEntropyLoss2d
|
import torch
import torch.utils.data.distributed
import torch
import torch.nn as nn
from numpy import int64 as int64
from torchvision.transforms import functional as F
import torch.nn.functional as F
import torch.utils
class SoftCrossEntropyLoss2d(nn.Module):
def __init__(self):
super(SoftCrossEntropyLoss2d, self).__init__()
def forward(self, inputs, targets):
loss = 0
inputs = -F.log_softmax(inputs, dim=1)
for index in range(inputs.size()[0]):
loss += F.conv2d(inputs[range(index, index + 1)], targets[range
(index, index + 1)]) / (targets.size()[2] * targets.size()[3])
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
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data.distributed
import torch
import torch.nn as nn
from numpy import int64 as int64
import torch.utils
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_neg_1(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp14 = -tmp13
tl.store(out_ptr0 + x3, tmp14, xmask)
@triton.jit
def triton_poi_fused_index_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (x1 + 16 * y0), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (y0 + 4 * x1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_index_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (64 + x1 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 4 * x1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_index_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (128 + x1 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 4 * x1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_index_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (192 + x1 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 4 * x1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_div_6(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp6 = tl.load(in_ptr1 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK])
tmp10 = tl.load(in_out_ptr0 + 0)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK])
tmp14 = tl.load(in_ptr2 + 0)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp2 = 0.0625
tmp3 = tmp1 * tmp2
tmp4 = 0.0
tmp5 = tmp3 + tmp4
tmp8 = tmp7 * tmp2
tmp9 = tmp5 + tmp8
tmp12 = tmp11 * tmp2
tmp13 = tmp9 + tmp12
tmp16 = tmp15 * tmp2
tmp17 = tmp13 + tmp16
tl.store(in_out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_neg_1[grid(256)](buf0, buf1, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf0
buf2 = empty_strided_cuda((1, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_index_2[grid(4, 16)](buf1, buf2, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((1, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_index_2[grid(4, 16)](arg1_1, buf3, 4, 16, XBLOCK=
16, YBLOCK=4, num_warps=1, num_stages=1)
buf4 = extern_kernels.convolution(buf2, buf3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (1, 1, 1, 1), (1, 1, 1, 1))
buf5 = buf3
del buf3
triton_poi_fused_index_3[grid(4, 16)](buf1, buf5, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf6 = buf2
del buf2
triton_poi_fused_index_3[grid(4, 16)](arg1_1, buf6, 4, 16, XBLOCK=
16, YBLOCK=4, num_warps=1, num_stages=1)
buf7 = extern_kernels.convolution(buf5, buf6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (1, 1, 1, 1), (1, 1, 1, 1))
buf8 = buf6
del buf6
triton_poi_fused_index_4[grid(4, 16)](buf1, buf8, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = buf5
del buf5
triton_poi_fused_index_4[grid(4, 16)](arg1_1, buf9, 4, 16, XBLOCK=
16, YBLOCK=4, num_warps=1, num_stages=1)
buf10 = extern_kernels.convolution(buf8, buf9, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (1, 1, 1, 1), (1, 1, 1, 1))
buf11 = buf9
del buf9
triton_poi_fused_index_5[grid(4, 16)](buf1, buf11, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
del buf1
buf12 = buf8
del buf8
triton_poi_fused_index_5[grid(4, 16)](arg1_1, buf12, 4, 16, XBLOCK=
16, YBLOCK=4, num_warps=1, num_stages=1)
del arg1_1
buf13 = extern_kernels.convolution(buf11, buf12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (1, 1, 1, 1), (1, 1, 1, 1))
del buf11
del buf12
buf14 = buf10
del buf10
triton_poi_fused_add_div_6[grid(1)](buf14, buf4, buf7, buf13, 1,
XBLOCK=1, num_warps=1, num_stages=1)
del buf13
del buf4
del buf7
return buf14,
class SoftCrossEntropyLoss2dNew(nn.Module):
def __init__(self):
super(SoftCrossEntropyLoss2dNew, 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]
|
HRTNet/HRTNet
|
SoftCrossEntropyLoss2d
| false
| 898
|
[
"MIT"
] | 0
|
6a51c9c34568988ea6125a1638794c63d8fadbea
|
https://github.com/HRTNet/HRTNet/tree/6a51c9c34568988ea6125a1638794c63d8fadbea
|
GatedTanhUnit
|
import torch
import torch.nn as nn
def gated_tanh(x, dim):
"""Gated Tanh activation."""
x_tanh, x_sigmoid = torch.chunk(x, 2, dim=dim)
return torch.tanh(x_tanh) * torch.sigmoid(x_sigmoid)
class GatedTanhUnit(nn.Module):
"""Gated Tanh activation."""
def __init__(self, dim=-1):
super(GatedTanhUnit, self).__init__()
self.dim = dim
def forward(self, x):
return gated_tanh(x, dim=self.dim)
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_mul_sigmoid_tanh_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
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1), xmask)
tmp2 = tl.load(in_ptr0 + (2 + x0 + 4 * x1), xmask)
tmp1 = libdevice.tanh(tmp0)
tmp3 = tl.sigmoid(tmp2)
tmp4 = tmp1 * tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_tanh_0[grid(128)](arg0_1, buf0, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def gated_tanh(x, dim):
"""Gated Tanh activation."""
x_tanh, x_sigmoid = torch.chunk(x, 2, dim=dim)
return torch.tanh(x_tanh) * torch.sigmoid(x_sigmoid)
class GatedTanhUnitNew(nn.Module):
"""Gated Tanh activation."""
def __init__(self, dim=-1):
super(GatedTanhUnitNew, self).__init__()
self.dim = dim
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Nintorac/survae_experiments
|
GatedTanhUnit
| false
| 899
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
ConcatELU
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def concat_elu(x):
"""Like concatenated ReLU (http://arxiv.org/abs/1603.05201), but with ELU instead."""
return F.elu(torch.cat([x, -x], dim=1))
class ConcatELU(nn.Module):
"""Like concatenated ReLU (http://arxiv.org/abs/1603.05201), but with ELU instead."""
def forward(self, input):
return concat_elu(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_elu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr0 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = -tmp9
tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
tmp12 = tl.where(tmp6, tmp10, tmp11)
tmp13 = tl.where(tmp4, tmp5, tmp12)
tmp14 = 0.0
tmp15 = tmp13 > tmp14
tmp16 = 1.0
tmp17 = tmp13 * tmp16
tmp18 = libdevice.expm1(tmp17)
tmp19 = tmp18 * tmp16
tmp20 = tl.where(tmp15, tmp17, tmp19)
tl.store(out_ptr0 + x3, tmp20, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_elu_0[grid(512)](arg0_1, buf0, 512, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
def concat_elu(x):
"""Like concatenated ReLU (http://arxiv.org/abs/1603.05201), but with ELU instead."""
return F.elu(torch.cat([x, -x], dim=1))
class ConcatELUNew(nn.Module):
"""Like concatenated ReLU (http://arxiv.org/abs/1603.05201), but with ELU instead."""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Nintorac/survae_experiments
|
ConcatELU
| false
| 900
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
PositionalEncoding1d
|
import math
import torch
import torch.nn as nn
class PositionalEncoding1d(nn.Module):
"""
Learning positional embeddings.
Args:
shape: Iterable, the shape of the input.
embedding_dim: int, the size of each embedding vector.
"""
def __init__(self, size, embedding_dim):
super(PositionalEncoding1d, self).__init__()
self.size = size
self.embedding_dim = embedding_dim
self.encode_l = nn.Parameter(torch.Tensor(size, 1, embedding_dim))
self.reset_parameters()
def reset_parameters(self):
nn.init.normal_(self.encode_l, std=0.125 / math.sqrt(self.
embedding_dim))
def forward(self, x):
return x + self.encode_l
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'size': 4, 'embedding_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 math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_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
x4 = xindex
x0 = xindex % 4
x2 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x4, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 4), (4, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_2, primals_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0,
class PositionalEncoding1dNew(nn.Module):
"""
Learning positional embeddings.
Args:
shape: Iterable, the shape of the input.
embedding_dim: int, the size of each embedding vector.
"""
def __init__(self, size, embedding_dim):
super(PositionalEncoding1dNew, self).__init__()
self.size = size
self.embedding_dim = embedding_dim
self.encode_l = nn.Parameter(torch.Tensor(size, 1, embedding_dim))
self.reset_parameters()
def reset_parameters(self):
nn.init.normal_(self.encode_l, std=0.125 / math.sqrt(self.
embedding_dim))
def forward(self, input_0):
primals_1 = self.encode_l
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Nintorac/survae_experiments
|
PositionalEncoding1d
| false
| 901
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
AutoregressiveShift
|
import torch
import torch.nn as nn
class AutoregressiveShift(nn.Module):
"""Shifts input right to make model autoregressive."""
def __init__(self, embed_dim):
super(AutoregressiveShift, self).__init__()
self.embed_dim = embed_dim
self.first_token = nn.Parameter(torch.Tensor(1, 1, embed_dim))
self._reset_parameters()
def _reset_parameters(self):
nn.init.xavier_uniform_(self.first_token)
def forward(self, x):
first_token = self.first_token.expand(1, x.shape[1], self.embed_dim)
return torch.cat([first_token, x[:-1]], dim=0)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embed_dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x0 = xindex % 4
x3 = xindex % 16
x4 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp9 = tl.load(in_ptr1 + (x3 + 16 * (-1 + x2)), tmp6 & xmask, other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x4, tmp10, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 4), (4, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(64)](primals_1, primals_2, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_1
del primals_2
return buf0,
class AutoregressiveShiftNew(nn.Module):
"""Shifts input right to make model autoregressive."""
def __init__(self, embed_dim):
super(AutoregressiveShiftNew, self).__init__()
self.embed_dim = embed_dim
self.first_token = nn.Parameter(torch.Tensor(1, 1, embed_dim))
self._reset_parameters()
def _reset_parameters(self):
nn.init.xavier_uniform_(self.first_token)
def forward(self, input_0):
primals_1 = self.first_token
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Nintorac/survae_experiments
|
AutoregressiveShift
| false
| 902
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
GatedConv2d
|
import torch
import torch.nn as nn
class GatedConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding):
super(GatedConv2d, self).__init__()
self.in_channels = in_channels
self.conv = nn.Conv2d(in_channels, out_channels * 3, kernel_size=
kernel_size, padding=padding)
def forward(self, x):
h = self.conv(x)
a, b, c = torch.chunk(h, chunks=3, dim=1)
return a + b * torch.sigmoid(c)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4,
'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 3888
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 81 % 12
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_1(in_ptr0, out_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1296
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 324
x1 = xindex // 324
x2 = xindex
tmp0 = tl.load(in_ptr0 + (648 + x0 + 972 * x1), xmask)
tmp2 = tl.load(in_ptr0 + (x0 + 972 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (324 + x0 + 972 * x1), xmask)
tmp1 = tl.sigmoid(tmp0)
tmp4 = tmp3 * tmp1
tmp5 = tmp2 + tmp4
tl.store(out_ptr0 + x2, tmp1, xmask)
tl.store(out_ptr1 + x2, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (12, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (12,), (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=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 12, 9, 9), (972, 81, 9, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(3888)](buf1, primals_2, 3888,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_1[grid(1296)](buf1, buf2, buf3,
1296, XBLOCK=128, num_warps=4, num_stages=1)
return buf3, primals_1, primals_3, reinterpret_tensor(buf1, (4, 4, 9, 9
), (972, 81, 9, 1), 324), buf2
class GatedConv2dNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding):
super(GatedConv2dNew, self).__init__()
self.in_channels = in_channels
self.conv = nn.Conv2d(in_channels, out_channels * 3, kernel_size=
kernel_size, padding=padding)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Nintorac/survae_experiments
|
GatedConv2d
| false
| 903
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
HeatmapLoss
|
import torch
import torch.utils.data
class HeatmapLoss(torch.nn.Module):
"""
loss for detection heatmap
"""
def __init__(self):
super(HeatmapLoss, self).__init__()
def forward(self, pred, gt):
l = (pred - gt) ** 2
l = l.mean(dim=3).mean(dim=2).mean(dim=1)
return l
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mean_pow_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 16 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr1 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr1 + (2 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr1 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (4 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp26 = tl.load(in_ptr1 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp31 = tl.load(in_ptr1 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp35 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp36 = tl.load(in_ptr1 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp42 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp43 = tl.load(in_ptr1 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp46 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp47 = tl.load(in_ptr1 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp51 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp52 = tl.load(in_ptr1 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp56 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp57 = tl.load(in_ptr1 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp63 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp64 = tl.load(in_ptr1 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp67 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp68 = tl.load(in_ptr1 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp72 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp73 = tl.load(in_ptr1 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp77 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp78 = tl.load(in_ptr1 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = 4.0
tmp20 = tmp18 / tmp19
tmp23 = tmp21 - tmp22
tmp24 = tmp23 * tmp23
tmp27 = tmp25 - tmp26
tmp28 = tmp27 * tmp27
tmp29 = tmp24 + tmp28
tmp32 = tmp30 - tmp31
tmp33 = tmp32 * tmp32
tmp34 = tmp29 + tmp33
tmp37 = tmp35 - tmp36
tmp38 = tmp37 * tmp37
tmp39 = tmp34 + tmp38
tmp40 = tmp39 / tmp19
tmp41 = tmp20 + tmp40
tmp44 = tmp42 - tmp43
tmp45 = tmp44 * tmp44
tmp48 = tmp46 - tmp47
tmp49 = tmp48 * tmp48
tmp50 = tmp45 + tmp49
tmp53 = tmp51 - tmp52
tmp54 = tmp53 * tmp53
tmp55 = tmp50 + tmp54
tmp58 = tmp56 - tmp57
tmp59 = tmp58 * tmp58
tmp60 = tmp55 + tmp59
tmp61 = tmp60 / tmp19
tmp62 = tmp41 + tmp61
tmp65 = tmp63 - tmp64
tmp66 = tmp65 * tmp65
tmp69 = tmp67 - tmp68
tmp70 = tmp69 * tmp69
tmp71 = tmp66 + tmp70
tmp74 = tmp72 - tmp73
tmp75 = tmp74 * tmp74
tmp76 = tmp71 + tmp75
tmp79 = tmp77 - tmp78
tmp80 = tmp79 * tmp79
tmp81 = tmp76 + tmp80
tmp82 = tmp81 / tmp19
tmp83 = tmp62 + tmp82
tmp84 = tmp83 / tmp19
tl.store(out_ptr0 + x0, tmp84, xmask)
@triton.jit
def triton_poi_fused_mean_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')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_pow_sub_0[grid(16)](arg0_1, arg1_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mean_1[grid(4)](buf0, buf1, 4, XBLOCK=4, num_warps
=1, num_stages=1)
del buf0
return buf1,
class HeatmapLossNew(torch.nn.Module):
"""
loss for detection heatmap
"""
def __init__(self):
super(HeatmapLossNew, 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]
|
NiranthS/pytorch_stacked_hourglass
|
HeatmapLoss
| false
| 904
|
[
"BSD-3-Clause"
] | 0
|
db9838eb13f6848ba3b9db844c1e023eb8688c3c
|
https://github.com/NiranthS/pytorch_stacked_hourglass/tree/db9838eb13f6848ba3b9db844c1e023eb8688c3c
|
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]
|
NiteshBharadwaj/structured_aleatoric_uncertainty_for_human_pose
|
AvgPoolHead
| false
| 905
|
[
"MIT"
] | 0
|
c74fb7384be562f0a0f1966b3fadf19e13a235f2
|
https://github.com/NiteshBharadwaj/structured_aleatoric_uncertainty_for_human_pose/tree/c74fb7384be562f0a0f1966b3fadf19e13a235f2
|
PositionalEncodingImage
|
import math
import torch
import torch.nn as nn
class PositionalEncodingImage(nn.Module):
"""
Learning positional embeddings for images.
Embeddings for channel, height and width are added to form the full positional embedding.
These encodings correspond to the ones from Sparse Transformers (https://arxiv.org/abs/1904.10509).
Args:
image_shape: Iterable, the shape of the image.
embedding_dim: int, the size of each embedding vector.
"""
def __init__(self, image_shape, embedding_dim):
super(PositionalEncodingImage, self).__init__()
assert len(image_shape
) == 3, 'image_shape should have length 3: (C,H,W)'
self.image_shape = image_shape
self.embedding_dim = embedding_dim
c, h, w = image_shape
self.encode_c = nn.Parameter(torch.Tensor(1, c, 1, 1, embedding_dim))
self.encode_h = nn.Parameter(torch.Tensor(1, 1, h, 1, embedding_dim))
self.encode_w = nn.Parameter(torch.Tensor(1, 1, 1, w, embedding_dim))
self.reset_parameters()
def reset_parameters(self):
nn.init.normal_(self.encode_c, std=0.125 / math.sqrt(3 * self.
embedding_dim))
nn.init.normal_(self.encode_h, std=0.125 / math.sqrt(3 * self.
embedding_dim))
nn.init.normal_(self.encode_w, std=0.125 / math.sqrt(3 * self.
embedding_dim))
def forward(self, x):
return x + self.encode_c + self.encode_h + self.encode_w
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'image_shape': [4, 4, 4], 'embedding_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 math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_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
x4 = xindex
x0 = xindex % 4
x3 = xindex // 64
x2 = xindex // 16 % 4
x7 = xindex % 16
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr3 + x7, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1, 4), (16, 4, 4, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 1, 4, 1, 4), (16, 16, 4, 4, 1))
assert_size_stride(primals_4, (1, 1, 1, 4, 4), (16, 16, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_2, primals_1, primals_3,
primals_4, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
del primals_3
del primals_4
return buf0,
class PositionalEncodingImageNew(nn.Module):
"""
Learning positional embeddings for images.
Embeddings for channel, height and width are added to form the full positional embedding.
These encodings correspond to the ones from Sparse Transformers (https://arxiv.org/abs/1904.10509).
Args:
image_shape: Iterable, the shape of the image.
embedding_dim: int, the size of each embedding vector.
"""
def __init__(self, image_shape, embedding_dim):
super(PositionalEncodingImageNew, self).__init__()
assert len(image_shape
) == 3, 'image_shape should have length 3: (C,H,W)'
self.image_shape = image_shape
self.embedding_dim = embedding_dim
c, h, w = image_shape
self.encode_c = nn.Parameter(torch.Tensor(1, c, 1, 1, embedding_dim))
self.encode_h = nn.Parameter(torch.Tensor(1, 1, h, 1, embedding_dim))
self.encode_w = nn.Parameter(torch.Tensor(1, 1, 1, w, embedding_dim))
self.reset_parameters()
def reset_parameters(self):
nn.init.normal_(self.encode_c, std=0.125 / math.sqrt(3 * self.
embedding_dim))
nn.init.normal_(self.encode_h, std=0.125 / math.sqrt(3 * self.
embedding_dim))
nn.init.normal_(self.encode_w, std=0.125 / math.sqrt(3 * self.
embedding_dim))
def forward(self, input_0):
primals_1 = self.encode_c
primals_3 = self.encode_h
primals_4 = self.encode_w
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Nintorac/survae_experiments
|
PositionalEncodingImage
| false
| 906
|
[
"MIT"
] | 0
|
d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
https://github.com/Nintorac/survae_experiments/tree/d68cc25e2604aab08b53617c1f3ffe4716f166c4
|
LinearZeros
|
import torch
import torch.nn as nn
class LinearZeros(nn.Linear):
def __init__(self, in_features, out_features, bias=True,
logscale_factor=3.0):
"""
Linear layer with zero initialization
:param in_features: size of each input sample
:type in_features: int
:param out_features: size of each output sample
:type out_features: int
:param bias: whether to learn an additive bias.
:type bias: bool
:param logscale_factor: factor of logscale
:type logscale_factor: float
"""
super().__init__(in_features, out_features, bias)
self.logscale_factor = logscale_factor
self.weight.data.zero_()
self.bias.data.zero_()
self.register_parameter('logs', nn.Parameter(torch.zeros(out_features))
)
def forward(self, x):
"""
Forward linear zero layer
:param x: input
:type x: torch.Tensor
:return: output
:rtype: torch.Tensor
"""
output = super().forward(x)
output *= torch.exp(self.logs * self.logscale_factor)
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.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_exp_mul_view_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = 3.0
tmp3 = tmp1 * tmp2
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp0 * tmp4
tl.store(in_out_ptr0 + x4, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4,), (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)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_exp_mul_view_0[grid(256)](buf2, buf0, primals_4,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf2, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0
class LinearZerosNew(nn.Linear):
def __init__(self, in_features, out_features, bias=True,
logscale_factor=3.0):
"""
Linear layer with zero initialization
:param in_features: size of each input sample
:type in_features: int
:param out_features: size of each output sample
:type out_features: int
:param bias: whether to learn an additive bias.
:type bias: bool
:param logscale_factor: factor of logscale
:type logscale_factor: float
"""
super().__init__(in_features, out_features, bias)
self.logscale_factor = logscale_factor
self.weight.data.zero_()
self.bias.data.zero_()
self.register_parameter('logs', nn.Parameter(torch.zeros(out_features))
)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_4 = self.logs
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
NirDiamant/pytorch-glow
|
LinearZeros
| false
| 907
|
[
"MIT"
] | 0
|
2ab11f3a8486b86a279fe4fa64f25aa91226ee8a
|
https://github.com/NirDiamant/pytorch-glow/tree/2ab11f3a8486b86a279fe4fa64f25aa91226ee8a
|
Conv2dZeros
|
import torch
import torch.nn as nn
class ActNorm(nn.Module):
def __init__(self, num_channels, scale=1.0, logscale_factor=3.0,
batch_variance=False):
"""
Activation normalization layer
:param num_channels: number of channels
:type num_channels: int
:param scale: scale
:type scale: float
:param logscale_factor: factor for logscale
:type logscale_factor: float
:param batch_variance: use batch variance
:type batch_variance: bool
"""
super().__init__()
self.num_channels = num_channels
self.scale = scale
self.logscale_factor = logscale_factor
self.batch_variance = batch_variance
self.bias_inited = False
self.logs_inited = False
self.register_parameter('bias', nn.Parameter(torch.zeros(1, self.
num_channels, 1, 1)))
self.register_parameter('logs', nn.Parameter(torch.zeros(1, self.
num_channels, 1, 1)))
def actnorm_center(self, x, reverse=False):
"""
center operation of activation normalization
:param x: input
:type x: torch.Tensor
:param reverse: whether to reverse bias
:type reverse: bool
:return: centered input
:rtype: torch.Tensor
"""
if not self.bias_inited:
self.initialize_bias(x)
if not reverse:
return x + self.bias
else:
return x - self.bias
def actnorm_scale(self, x, logdet, reverse=False):
"""
scale operation of activation normalization
:param x: input
:type x: torch.Tensor
:param logdet: log determinant
:type logdet:
:param reverse: whether to reverse bias
:type reverse: bool
:return: centered input and logdet
:rtype: tuple(torch.Tensor, torch.Tensor)
"""
if not self.logs_inited:
self.initialize_logs(x)
logs = self.logs * self.logscale_factor
if not reverse:
x *= torch.exp(logs)
else:
x *= torch.exp(-logs)
if logdet is not None:
logdet_factor = ops.count_pixels(x)
dlogdet = torch.sum(logs) * logdet_factor
if reverse:
dlogdet *= -1
logdet += dlogdet
return x, logdet
def initialize_bias(self, x):
"""
Initialize bias
:param x: input
:type x: torch.Tensor
"""
if not self.training:
return
with torch.no_grad():
x_mean = -1.0 * ops.reduce_mean(x, dim=[0, 2, 3], keepdim=True)
self.bias.data.copy_(x_mean.data)
self.bias_inited = True
def initialize_logs(self, x):
"""
Initialize logs
:param x: input
:type x: torch.Tensor
"""
if not self.training:
return
with torch.no_grad():
if self.batch_variance:
x_var = ops.reduce_mean(x ** 2, keepdim=True)
else:
x_var = ops.reduce_mean(x ** 2, dim=[0, 2, 3], keepdim=True)
logs = torch.log(self.scale / (torch.sqrt(x_var) + 1e-06)
) / self.logscale_factor
self.logs.data.copy_(logs.data)
self.logs_inited = True
def forward(self, x, logdet=None, reverse=False):
"""
Forward activation normalization layer
:param x: input
:type x: torch.Tensor
:param logdet: log determinant
:type logdet:
:param reverse: whether to reverse bias
:type reverse: bool
:return: normalized input and logdet
:rtype: tuple(torch.Tensor, torch.Tensor)
"""
assert len(x.shape) == 4
assert x.shape[1
] == self.num_channels, 'Input shape should be NxCxHxW, however channels are {} instead of {}'.format(
x.shape[1], self.num_channels)
assert x.device == self.bias.device and x.device == self.logs.device, 'Expect input device {} instead of {}'.format(
self.bias.device, x.device)
if not reverse:
x = self.actnorm_center(x, reverse=False)
x, logdet = self.actnorm_scale(x, logdet, reverse=False)
else:
x, logdet = self.actnorm_scale(x, logdet, reverse=True)
x = self.actnorm_center(x, reverse=True)
return x, logdet
class Conv2d(nn.Conv2d):
@staticmethod
def get_padding(padding_type, kernel_size, stride):
"""
Get padding size.
mentioned in https://github.com/pytorch/pytorch/issues/3867#issuecomment-361775080
behaves as 'SAME' padding in TensorFlow
independent on input size when stride is 1
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param kernel_size: kernel size
:type kernel_size: tuple(int) or int
:param stride: stride
:type stride: int
:return: padding size
:rtype: tuple(int)
"""
assert padding_type in ['SAME', 'VALID'
], 'Unsupported padding type: {}'.format(padding_type)
if isinstance(kernel_size, int):
kernel_size = [kernel_size, kernel_size]
if padding_type == 'SAME':
assert stride == 1, "'SAME' padding only supports stride=1"
return tuple((k - 1) // 2 for k in kernel_size)
return tuple(0 for _ in kernel_size)
def __init__(self, in_channels, out_channels, kernel_size=(3, 3),
stride=1, padding_type='SAME', do_weightnorm=False, do_actnorm=True,
dilation=1, groups=1):
"""
Wrapper of nn.Conv2d with weight normalization and activation normalization
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param do_weightnorm: whether to do weight normalization after convolution
:type do_weightnorm: bool
:param do_actnorm: whether to do activation normalization after convolution
:type do_actnorm: bool
"""
padding = self.get_padding(padding_type, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias=not do_actnorm)
self.do_weight_norm = do_weightnorm
self.do_actnorm = do_actnorm
self.weight.data.normal_(mean=0.0, std=0.05)
if self.do_actnorm:
self.actnorm = ActNorm(out_channels)
else:
self.bias.data.zero_()
def forward(self, x):
"""
Forward wrapped Conv2d layer
:param x: input
:type x: torch.Tensor
:return: output
:rtype: torch.Tensor
"""
x = super().forward(x)
if self.do_actnorm:
x, _ = self.actnorm(x)
return x
class Conv2dZeros(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size=(3, 3),
stride=1, padding_type='SAME', logscale_factor=3, dilation=1,
groups=1, bias=True):
"""
Wrapper of nn.Conv2d with zero initialization and logs
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param logscale_factor: factor for logscale
:type logscale_factor: float
"""
padding = Conv2d.get_padding(padding_type, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias)
self.logscale_factor = logscale_factor
self.bias.data.zero_()
self.weight.data.zero_()
self.register_parameter('logs', nn.Parameter(torch.zeros(
out_channels, 1, 1)))
def forward(self, x):
"""
Forward wrapped Conv2d layer
:param x: input
:type x: torch.Tensor
:return: output
:rtype: torch.Tensor
"""
x = super().forward(x)
x *= torch.exp(self.logs * self.logscale_factor)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_exp_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = 3.0
tmp5 = tmp3 * tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp2 * tmp6
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 1, 1), (1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_exp_mul_0[grid(256)](buf1, primals_2,
primals_4, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf2, primals_1, primals_3, primals_4, buf1
class ActNorm(nn.Module):
def __init__(self, num_channels, scale=1.0, logscale_factor=3.0,
batch_variance=False):
"""
Activation normalization layer
:param num_channels: number of channels
:type num_channels: int
:param scale: scale
:type scale: float
:param logscale_factor: factor for logscale
:type logscale_factor: float
:param batch_variance: use batch variance
:type batch_variance: bool
"""
super().__init__()
self.num_channels = num_channels
self.scale = scale
self.logscale_factor = logscale_factor
self.batch_variance = batch_variance
self.bias_inited = False
self.logs_inited = False
self.register_parameter('bias', nn.Parameter(torch.zeros(1, self.
num_channels, 1, 1)))
self.register_parameter('logs', nn.Parameter(torch.zeros(1, self.
num_channels, 1, 1)))
def actnorm_center(self, x, reverse=False):
"""
center operation of activation normalization
:param x: input
:type x: torch.Tensor
:param reverse: whether to reverse bias
:type reverse: bool
:return: centered input
:rtype: torch.Tensor
"""
if not self.bias_inited:
self.initialize_bias(x)
if not reverse:
return x + self.bias
else:
return x - self.bias
def actnorm_scale(self, x, logdet, reverse=False):
"""
scale operation of activation normalization
:param x: input
:type x: torch.Tensor
:param logdet: log determinant
:type logdet:
:param reverse: whether to reverse bias
:type reverse: bool
:return: centered input and logdet
:rtype: tuple(torch.Tensor, torch.Tensor)
"""
if not self.logs_inited:
self.initialize_logs(x)
logs = self.logs * self.logscale_factor
if not reverse:
x *= torch.exp(logs)
else:
x *= torch.exp(-logs)
if logdet is not None:
logdet_factor = ops.count_pixels(x)
dlogdet = torch.sum(logs) * logdet_factor
if reverse:
dlogdet *= -1
logdet += dlogdet
return x, logdet
def initialize_bias(self, x):
"""
Initialize bias
:param x: input
:type x: torch.Tensor
"""
if not self.training:
return
with torch.no_grad():
x_mean = -1.0 * ops.reduce_mean(x, dim=[0, 2, 3], keepdim=True)
self.bias.data.copy_(x_mean.data)
self.bias_inited = True
def initialize_logs(self, x):
"""
Initialize logs
:param x: input
:type x: torch.Tensor
"""
if not self.training:
return
with torch.no_grad():
if self.batch_variance:
x_var = ops.reduce_mean(x ** 2, keepdim=True)
else:
x_var = ops.reduce_mean(x ** 2, dim=[0, 2, 3], keepdim=True)
logs = torch.log(self.scale / (torch.sqrt(x_var) + 1e-06)
) / self.logscale_factor
self.logs.data.copy_(logs.data)
self.logs_inited = True
def forward(self, x, logdet=None, reverse=False):
"""
Forward activation normalization layer
:param x: input
:type x: torch.Tensor
:param logdet: log determinant
:type logdet:
:param reverse: whether to reverse bias
:type reverse: bool
:return: normalized input and logdet
:rtype: tuple(torch.Tensor, torch.Tensor)
"""
assert len(x.shape) == 4
assert x.shape[1
] == self.num_channels, 'Input shape should be NxCxHxW, however channels are {} instead of {}'.format(
x.shape[1], self.num_channels)
assert x.device == self.bias.device and x.device == self.logs.device, 'Expect input device {} instead of {}'.format(
self.bias.device, x.device)
if not reverse:
x = self.actnorm_center(x, reverse=False)
x, logdet = self.actnorm_scale(x, logdet, reverse=False)
else:
x, logdet = self.actnorm_scale(x, logdet, reverse=True)
x = self.actnorm_center(x, reverse=True)
return x, logdet
class Conv2d(nn.Conv2d):
@staticmethod
def get_padding(padding_type, kernel_size, stride):
"""
Get padding size.
mentioned in https://github.com/pytorch/pytorch/issues/3867#issuecomment-361775080
behaves as 'SAME' padding in TensorFlow
independent on input size when stride is 1
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param kernel_size: kernel size
:type kernel_size: tuple(int) or int
:param stride: stride
:type stride: int
:return: padding size
:rtype: tuple(int)
"""
assert padding_type in ['SAME', 'VALID'
], 'Unsupported padding type: {}'.format(padding_type)
if isinstance(kernel_size, int):
kernel_size = [kernel_size, kernel_size]
if padding_type == 'SAME':
assert stride == 1, "'SAME' padding only supports stride=1"
return tuple((k - 1) // 2 for k in kernel_size)
return tuple(0 for _ in kernel_size)
def __init__(self, in_channels, out_channels, kernel_size=(3, 3),
stride=1, padding_type='SAME', do_weightnorm=False, do_actnorm=True,
dilation=1, groups=1):
"""
Wrapper of nn.Conv2d with weight normalization and activation normalization
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param do_weightnorm: whether to do weight normalization after convolution
:type do_weightnorm: bool
:param do_actnorm: whether to do activation normalization after convolution
:type do_actnorm: bool
"""
padding = self.get_padding(padding_type, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias=not do_actnorm)
self.do_weight_norm = do_weightnorm
self.do_actnorm = do_actnorm
self.weight.data.normal_(mean=0.0, std=0.05)
if self.do_actnorm:
self.actnorm = ActNorm(out_channels)
else:
self.bias.data.zero_()
def forward(self, x):
"""
Forward wrapped Conv2d layer
:param x: input
:type x: torch.Tensor
:return: output
:rtype: torch.Tensor
"""
x = super().forward(x)
if self.do_actnorm:
x, _ = self.actnorm(x)
return x
class Conv2dZerosNew(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size=(3, 3),
stride=1, padding_type='SAME', logscale_factor=3, dilation=1,
groups=1, bias=True):
"""
Wrapper of nn.Conv2d with zero initialization and logs
:param padding_type: type of padding in ['SAME', 'VALID']
:type padding_type: str
:param logscale_factor: factor for logscale
:type logscale_factor: float
"""
padding = Conv2d.get_padding(padding_type, kernel_size, stride)
super().__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias)
self.logscale_factor = logscale_factor
self.bias.data.zero_()
self.weight.data.zero_()
self.register_parameter('logs', nn.Parameter(torch.zeros(
out_channels, 1, 1)))
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_4 = self.logs
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
NirDiamant/pytorch-glow
|
Conv2dZeros
| false
| 908
|
[
"MIT"
] | 0
|
2ab11f3a8486b86a279fe4fa64f25aa91226ee8a
|
https://github.com/NirDiamant/pytorch-glow/tree/2ab11f3a8486b86a279fe4fa64f25aa91226ee8a
|
GaussianKernel
|
import torch
from typing import Optional
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class GaussianKernel(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Parameters:
- sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
- track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
- alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernel, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, X: 'torch.Tensor') ->torch.Tensor:
l2_distance_square = ((X.unsqueeze(0) - X.unsqueeze(1)) ** 2).sum(2)
if self.track_running_stats:
self.sigma_square = self.alpha * torch.mean(l2_distance_square.
detach())
return torch.exp(-l2_distance_square / (2 * self.sigma_square))
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
from typing import Optional
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0(in_out_ptr0,
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 % 16
r1 = rindex // 16 % 4
r2 = rindex // 64
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.broadcast_to(tmp18, [RBLOCK])
tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0))
tmp22 = 256.0
tmp23 = tmp21 / tmp22
tmp24 = 1.0
tmp25 = tmp23 * tmp24
tmp26 = -tmp18
tmp27 = 2.0
tmp28 = tmp25 * tmp27
tmp29 = tmp26 / tmp28
tmp30 = tl_math.exp(tmp29)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp25, None)
tl.store(out_ptr1 + tl.broadcast_to(r3, [RBLOCK]), tmp30, 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((), (), torch.float32)
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0[grid(1)](buf2,
arg0_1, buf3, 1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf3, buf2
class GaussianKernelNew(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Parameters:
- sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
- track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
- alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernelNew, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
NiteshBharadwaj/ignoringhumanpose
|
GaussianKernel
| false
| 909
|
[
"MIT"
] | 0
|
1fb7a063fded9cff18f7de4e1d71845983077256
|
https://github.com/NiteshBharadwaj/ignoringhumanpose/tree/1fb7a063fded9cff18f7de4e1d71845983077256
|
Multihead_Attention_Layer
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def scaled_self_attention(q, k, v, key_size):
weight = torch.matmul(q, k)
weight = F.softmax(weight / math.sqrt(key_size), dim=-1)
attention = torch.matmul(weight, v)
return attention
class Multihead_Attention_Layer(nn.Module):
def __init__(self, embedding, heads):
super(Multihead_Attention_Layer, self).__init__()
self.embedding = embedding
self.heads = heads
assert self.embedding % self.heads == 0, 'The number of embedding channels must be divisible by the number of heads'
self.head_dim = self.embedding // self.heads
self.embedding_layer = nn.Conv1d(self.embedding, self.embedding * 3,
kernel_size=1, bias=False)
self.out = nn.Conv1d(self.embedding, self.embedding, kernel_size=1,
bias=False)
def forward(self, x):
batch_size, channels, num_points = x.size()
qkv = self.embedding_layer(x)
qkv = qkv.permute(0, 2, 1)
qkv = qkv.reshape(batch_size, num_points, self.heads, 3 * self.head_dim
)
qkv = qkv.permute(0, 2, 1, 3)
q, k, v = torch.chunk(qkv, 3, dim=-1)
k = k.permute(0, 1, 3, 2)
values = scaled_self_attention(q, k, v, self.embedding / self.heads)
values = values.permute(0, 2, 1, 3)
values = values.reshape(batch_size, num_points, channels)
x = values.permute(0, 2, 1)
x = self.out(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embedding': 4, 'heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 12 * x1), xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 + x0 + 12 * x1), xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_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 = tl.load(in_ptr0 + (8 + x0 + 12 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (12, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4, 4, 1), (4, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 12, 4), (48, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf2 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_1[grid(64)](buf0, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf2, (16, 1, 4), (4, 0, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_3[grid(256)](buf3, buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf3
del buf4
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_4[grid(64)](buf0, buf6, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf0
buf7 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 0), 0), out=buf7)
buf8 = extern_kernels.convolution(reinterpret_tensor(buf7, (4, 4, 4
), (16, 4, 1), 0), primals_3, 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))
return buf8, primals_1, primals_2, primals_3, buf5, reinterpret_tensor(buf6
, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf1, (16, 1, 4), (
4, 1, 1), 0), reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 4), 0
), reinterpret_tensor(buf7, (4, 4, 4), (16, 4, 1), 0)
def scaled_self_attention(q, k, v, key_size):
weight = torch.matmul(q, k)
weight = F.softmax(weight / math.sqrt(key_size), dim=-1)
attention = torch.matmul(weight, v)
return attention
class Multihead_Attention_LayerNew(nn.Module):
def __init__(self, embedding, heads):
super(Multihead_Attention_LayerNew, self).__init__()
self.embedding = embedding
self.heads = heads
assert self.embedding % self.heads == 0, 'The number of embedding channels must be divisible by the number of heads'
self.head_dim = self.embedding // self.heads
self.embedding_layer = nn.Conv1d(self.embedding, self.embedding * 3,
kernel_size=1, bias=False)
self.out = nn.Conv1d(self.embedding, self.embedding, kernel_size=1,
bias=False)
def forward(self, input_0):
primals_2 = self.embedding_layer.weight
primals_3 = self.out.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
NilsLusch/Point-Cloud-Transformer
|
Multihead_Attention_Layer
| false
| 910
|
[
"MIT"
] | 0
|
84a16b45b8949bbf8e7730b10bd5835e2ab4e642
|
https://github.com/NilsLusch/Point-Cloud-Transformer/tree/84a16b45b8949bbf8e7730b10bd5835e2ab4e642
|
Conv
|
import torch
import torch.nn as nn
class Conv(nn.Module):
"""
Convolution Module
"""
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=0, dilation=1, bias=True, w_init='linear'):
"""
:param in_channels: dimension of input
:param out_channels: dimension of output
:param kernel_size: size of kernel
:param stride: size of stride
:param padding: size of padding
:param dilation: dilation rate
:param bias: boolean. if True, bias is included.
:param w_init: str. weight inits with xavier initialization.
"""
super(Conv, self).__init__()
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
bias=bias)
def forward(self, x):
x = x.contiguous().transpose(1, 2)
x = self.conv(x)
x = x.contiguous().transpose(1, 2)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
del buf0
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0
), primals_2, reinterpret_tensor(primals_1, (4, 4, 4), (16, 1, 4), 0)
class ConvNew(nn.Module):
"""
Convolution Module
"""
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=0, dilation=1, bias=True, w_init='linear'):
"""
:param in_channels: dimension of input
:param out_channels: dimension of output
:param kernel_size: size of kernel
:param stride: size of stride
:param padding: size of padding
:param dilation: dilation rate
:param bias: boolean. if True, bias is included.
:param w_init: str. weight inits with xavier initialization.
"""
super(ConvNew, self).__init__()
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
bias=bias)
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]
|
Numb523/FastSpeech2_emotion
|
Conv
| false
| 911
|
[
"MIT"
] | 0
|
a541ce89ddf66625ee57c0a294d0bec1ae701f0c
|
https://github.com/Numb523/FastSpeech2_emotion/tree/a541ce89ddf66625ee57c0a294d0bec1ae701f0c
|
Theta
|
from torch.autograd import Function
import torch
from typing import Optional
from typing import Tuple
import torch.nn as nn
from typing import Any
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class GradientReverseFunction(Function):
@staticmethod
def forward(ctx: 'Any', input: 'torch.Tensor', coeff: 'Optional[float]'=1.0
) ->torch.Tensor:
ctx.coeff = coeff
output = input * 1.0
return output
@staticmethod
def backward(ctx: 'Any', grad_output: 'torch.Tensor') ->Tuple[torch.
Tensor, Any]:
return grad_output.neg() * ctx.coeff, None
class GradientReverseLayer(nn.Module):
def __init__(self):
super(GradientReverseLayer, self).__init__()
def forward(self, *input):
return GradientReverseFunction.apply(*input)
class Theta(nn.Module):
"""
maximize loss respect to :math:` heta`
minimize loss respect to features
"""
def __init__(self, dim: 'int'):
super(Theta, self).__init__()
self.grl1 = GradientReverseLayer()
self.grl2 = GradientReverseLayer()
self.layer1 = nn.Linear(dim, dim)
nn.init.eye_(self.layer1.weight)
nn.init.zeros_(self.layer1.bias)
def forward(self, features: 'torch.Tensor') ->torch.Tensor:
features = self.grl1(features)
return self.grl2(self.layer1(features))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
from typing import Optional
from typing import Tuple
import torch.nn as nn
from typing import Any
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@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 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, buf0, 256, XBLOCK=256,
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 = 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=128,
num_warps=4, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class GradientReverseFunction(Function):
@staticmethod
def forward(ctx: 'Any', input: 'torch.Tensor', coeff: 'Optional[float]'=1.0
) ->torch.Tensor:
ctx.coeff = coeff
output = input * 1.0
return output
@staticmethod
def backward(ctx: 'Any', grad_output: 'torch.Tensor') ->Tuple[torch.
Tensor, Any]:
return grad_output.neg() * ctx.coeff, None
class GradientReverseLayer(nn.Module):
def __init__(self):
super(GradientReverseLayer, self).__init__()
def forward(self, *input):
return GradientReverseFunction.apply(*input)
class ThetaNew(nn.Module):
"""
maximize loss respect to :math:` heta`
minimize loss respect to features
"""
def __init__(self, dim: 'int'):
super(ThetaNew, self).__init__()
self.grl1 = GradientReverseLayer()
self.grl2 = GradientReverseLayer()
self.layer1 = nn.Linear(dim, dim)
nn.init.eye_(self.layer1.weight)
nn.init.zeros_(self.layer1.bias)
def forward(self, input_0):
primals_2 = self.layer1.weight
primals_3 = self.layer1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
NiteshBharadwaj/ignoringhumanpose
|
Theta
| false
| 912
|
[
"MIT"
] | 0
|
1fb7a063fded9cff18f7de4e1d71845983077256
|
https://github.com/NiteshBharadwaj/ignoringhumanpose/tree/1fb7a063fded9cff18f7de4e1d71845983077256
|
LastTimeStep
|
import torch
from torch import nn
import torch.utils.data
from typing import Tuple
class LastTimeStep(nn.Module):
"""
A class for extracting the hidden activations of the last time step following
the output of a PyTorch RNN module.
"""
def __init__(self, bidirectional=False):
super(LastTimeStep, self).__init__()
if bidirectional:
self.num_driections = 2
else:
self.num_driections = 1
def forward(self, x: 'Tuple'):
last_step = x[0]
batch_size = last_step.shape[1]
seq_len = last_step.shape[0]
last_step = last_step.view(seq_len, batch_size, self.num_driections, -1
)
last_step = torch.mean(last_step, 2)
last_step = last_step[0]
return last_step.reshape(batch_size, -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 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_mean_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 / tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4), (4, 1), 0),
class LastTimeStepNew(nn.Module):
"""
A class for extracting the hidden activations of the last time step following
the output of a PyTorch RNN module.
"""
def __init__(self, bidirectional=False):
super(LastTimeStepNew, self).__init__()
if bidirectional:
self.num_driections = 2
else:
self.num_driections = 1
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Onion-Team-VN/skilledlab
|
LastTimeStep
| false
| 913
|
[
"Apache-2.0"
] | 0
|
ac5cd7b5aee52da98aee8a32e5d161fd8b7dddab
|
https://github.com/Onion-Team-VN/skilledlab/tree/ac5cd7b5aee52da98aee8a32e5d161fd8b7dddab
|
myLoss2
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class myLoss2(nn.Module):
def __init__(self, alpha=1.0):
super(myLoss2, self).__init__()
self.alpha = alpha
def forward(self, sent_probs, doc_probs, sent_targets, doc_targets):
loss_1 = F.mse_loss(sent_probs, sent_targets)
loss_2 = F.mse_loss(doc_probs, doc_targets)
norm = 1.0 + self.alpha
loss = (loss_1 + self.alpha * loss_2) / norm
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mse_loss_mul_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)
tmp7 = tl.load(in_ptr2 + r0, None)
tmp8 = tl.load(in_ptr3 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
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 = tmp6 / tmp14
tmp16 = tmp13 / tmp14
tmp17 = 1.0
tmp18 = tmp16 * tmp17
tmp19 = tmp15 + tmp18
tmp20 = 0.5
tmp21 = tmp19 * tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, 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)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mse_loss_mul_0[grid(1)](buf2, arg1_1,
arg0_1, arg3_1, arg2_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
return buf2,
class myLoss2New(nn.Module):
def __init__(self, alpha=1.0):
super(myLoss2New, self).__init__()
self.alpha = alpha
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]
|
PKULiuHui/LiveBlogSum
|
myLoss2
| false
| 914
|
[
"MIT"
] | 0
|
b6a22521ee454e649981d70ddca6c89a1bac5a4c
|
https://github.com/PKULiuHui/LiveBlogSum/tree/b6a22521ee454e649981d70ddca6c89a1bac5a4c
|
relu_constant_fraction
|
import torch
import numpy as np
from torch import nn
from torch.nn.functional import relu
def regula_falsi(func, a, b, iterations):
f_a = func(a, -1)
f_b = func(b, -1)
if torch.any(f_a * f_b >= 0):
None
raise Exception(
'You have not assumed right initial values in regula falsi')
c = a
break_indices = torch.zeros_like(a).bool()
for i in range(iterations):
c = (a * f_b - b * f_a) / (f_b - f_a)
f_c = func(c, i)
break_indices[f_c == 0] = True
b_eq_c_indices = (f_c * f_a < 0) & ~break_indices
b[b_eq_c_indices] = c[b_eq_c_indices]
a_eq_c_indices = ~(b_eq_c_indices | break_indices)
a[a_eq_c_indices] = c[a_eq_c_indices]
return c
class relu_constant_fraction(nn.Module):
def __init__(self, nb_channels):
super(relu_constant_fraction, self).__init__()
self.biases = nn.Parameter(torch.zeros(nb_channels))
self.biases.requires_grad = False
self.bias_buffer = None
def forward(self, x):
return relu(x - self.biases.view(1, -1, 1, 1))
def adjust_bias(self, desired_fraction, prev_layer_outputs):
if desired_fraction > 1 - 0.001:
self.biases.data = -10 * torch.ones_like(self.biases)
return
def get_fraction_deviation(biases, j):
activations = relu(prev_layer_outputs - biases.view(1, -1, 1, 1))
ratios = (activations > 0.001).float().mean(dim=(0, 2, 3))
return ratios - desired_fraction
with torch.no_grad():
solutions = regula_falsi(get_fraction_deviation, -3 * torch.
ones_like(self.biases), 3 * torch.ones_like(self.biases), 20)
momentum = 0.75
dampening = 0.0
lr = 0.5
delta = solutions - self.biases
buf = self.bias_buffer
if buf is None:
buf = torch.clone(delta).detach()
self.bias_buffer = buf
else:
buf.mul_(momentum).add_(delta, alpha=1 - dampening)
delta = buf
self.biases.add_(delta, alpha=lr)
def get_activation_fractions(self, prev_layer_outputs):
activations = relu(prev_layer_outputs - self.biases.view(1, -1, 1, 1))
ratios = (activations > 0.001).float().mean(dim=(0, 2, 3))
return ratios
def show_trajectory(self, prev_layer_outputs):
import matplotlib.pyplot as plt
bias_values = np.linspace(-10, 10, 1000)
fractions = np.zeros((1000, self.biases.shape[0]))
for j, bias in enumerate(bias_values):
cumulative_ratios = torch.zeros_like(self.biases)
batch_size = 1000
for i in range(0, len(prev_layer_outputs), batch_size):
data = prev_layer_outputs[i:i + batch_size]
activations = relu(data - bias)
cumulative_ratios += (activations > 0.001).float().mean(dim
=(0, 2, 3)) * len(data)
fractions[j] = (cumulative_ratios / len(prev_layer_outputs)
).detach().cpu().numpy()
plt.plot(bias_values, fractions)
plt.show()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nb_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 numpy as np
from torch import nn
from torch.nn.functional import relu
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + x3, tmp4, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (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_relu_sub_0[grid(256)](arg1_1, arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
def regula_falsi(func, a, b, iterations):
f_a = func(a, -1)
f_b = func(b, -1)
if torch.any(f_a * f_b >= 0):
None
raise Exception(
'You have not assumed right initial values in regula falsi')
c = a
break_indices = torch.zeros_like(a).bool()
for i in range(iterations):
c = (a * f_b - b * f_a) / (f_b - f_a)
f_c = func(c, i)
break_indices[f_c == 0] = True
b_eq_c_indices = (f_c * f_a < 0) & ~break_indices
b[b_eq_c_indices] = c[b_eq_c_indices]
a_eq_c_indices = ~(b_eq_c_indices | break_indices)
a[a_eq_c_indices] = c[a_eq_c_indices]
return c
class relu_constant_fractionNew(nn.Module):
def __init__(self, nb_channels):
super(relu_constant_fractionNew, self).__init__()
self.biases = nn.Parameter(torch.zeros(nb_channels))
self.biases.requires_grad = False
self.bias_buffer = None
def adjust_bias(self, desired_fraction, prev_layer_outputs):
if desired_fraction > 1 - 0.001:
self.biases.data = -10 * torch.ones_like(self.biases)
return
def get_fraction_deviation(biases, j):
activations = relu(prev_layer_outputs - biases.view(1, -1, 1, 1))
ratios = (activations > 0.001).float().mean(dim=(0, 2, 3))
return ratios - desired_fraction
with torch.no_grad():
solutions = regula_falsi(get_fraction_deviation, -3 * torch.
ones_like(self.biases), 3 * torch.ones_like(self.biases), 20)
momentum = 0.75
dampening = 0.0
lr = 0.5
delta = solutions - self.biases
buf = self.bias_buffer
if buf is None:
buf = torch.clone(delta).detach()
self.bias_buffer = buf
else:
buf.mul_(momentum).add_(delta, alpha=1 - dampening)
delta = buf
self.biases.add_(delta, alpha=lr)
def get_activation_fractions(self, prev_layer_outputs):
activations = relu(prev_layer_outputs - self.biases.view(1, -1, 1, 1))
ratios = (activations > 0.001).float().mean(dim=(0, 2, 3))
return ratios
def show_trajectory(self, prev_layer_outputs):
import matplotlib.pyplot as plt
bias_values = np.linspace(-10, 10, 1000)
fractions = np.zeros((1000, self.biases.shape[0]))
for j, bias in enumerate(bias_values):
cumulative_ratios = torch.zeros_like(self.biases)
batch_size = 1000
for i in range(0, len(prev_layer_outputs), batch_size):
data = prev_layer_outputs[i:i + batch_size]
activations = relu(data - bias)
cumulative_ratios += (activations > 0.001).float().mean(dim
=(0, 2, 3)) * len(data)
fractions[j] = (cumulative_ratios / len(prev_layer_outputs)
).detach().cpu().numpy()
plt.plot(bias_values, fractions)
plt.show()
def forward(self, input_0):
arg0_1 = self.biases
arg1_1 = input_0
output = call([arg0_1, arg1_1])
return output[0]
|
Noppornying00/constant-fraction-activation
|
relu_constant_fraction
| false
| 915
|
[
"Apache-2.0"
] | 0
|
b25745e7339df13e3db34d8c8372d5cbaa3c13bb
|
https://github.com/Noppornying00/constant-fraction-activation/tree/b25745e7339df13e3db34d8c8372d5cbaa3c13bb
|
MarginDisparityDiscrepancy
|
import torch
from typing import Optional
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
def shift_log(x: 'torch.Tensor', offset: 'Optional[float]'=1e-06
) ->torch.Tensor:
"""
First shift, then calculate log, which can be described as:
.. math::
y = \\max(\\log(x+\\text{offset}), 0)
Used to avoid the gradient explosion problem in log(x) function when x=0.
Parameters:
- **x**: input tensor
- **offset**: offset size. Default: 1e-6
.. note::
Input tensor falls in [0., 1.] and the output tensor falls in [-log(offset), 0]
"""
return torch.log(torch.clamp(x + offset, max=1.0))
class MarginDisparityDiscrepancy(nn.Module):
"""The margin disparity discrepancy (MDD) is proposed to measure the distribution discrepancy in domain adaptation.
The :math:`y^s` and :math:`y^t` are logits output by the main classifier on the source and target domain respectively.
The :math:`y_{adv}^s` and :math:`y_{adv}^t` are logits output by the adversarial classifier.
They are expected to contain raw, unnormalized scores for each class.
The definition can be described as:
.. math::
\\mathcal{D}_{\\gamma}(\\hat{\\mathcal{S}}, \\hat{\\mathcal{T}}) =
\\gamma \\mathbb{E}_{y^s, y_{adv}^s \\sim\\hat{\\mathcal{S}}} \\log\\left(\\frac{\\exp(y_{adv}^s[h_{y^s}])}{\\sum_j \\exp(y_{adv}^s[j])}\\right) +
\\mathbb{E}_{y^t, y_{adv}^t \\sim\\hat{\\mathcal{T}}} \\log\\left(1-\\frac{\\exp(y_{adv}^t[h_{y^t}])}{\\sum_j \\exp(y_{adv}^t[j])}\\right),
where :math:`\\gamma` is a margin hyper-parameter and :math:`h_y` refers to the predicted label when the logits output is :math:`y`.
You can see more details in `Bridging Theory and Algorithm for Domain Adaptation <https://arxiv.org/abs/1904.05801>`_.
Parameters:
- **margin** (float): margin :math:`\\gamma`. Default: 4
- **reduction** (string, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs: y_s, y_s_adv, y_t, y_t_adv
- **y_s**: logits output :math:`y^s` by the main classifier on the source domain
- **y_s_adv**: logits output :math:`y^s` by the adversarial classifier on the source domain
- **y_t**: logits output :math:`y^t` by the main classifier on the target domain
- **y_t_adv**: logits output :math:`y_{adv}^t` by the adversarial classifier on the target domain
Shape:
- Inputs: :math:`(minibatch, C)` where C = number of classes, or :math:`(minibatch, C, d_1, d_2, ..., d_K)`
with :math:`K \\geq 1` in the case of `K`-dimensional loss.
- Output: scalar. If :attr:`reduction` is ``'none'``, then the same size as the target: :math:`(minibatch)`, or
:math:`(minibatch, d_1, d_2, ..., d_K)` with :math:`K \\geq 1` in the case of K-dimensional loss.
Examples::
>>> num_classes = 2
>>> batch_size = 10
>>> loss = MarginDisparityDiscrepancy(margin=4.)
>>> # logits output from source domain and target domain
>>> y_s, y_t = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
>>> # adversarial logits output from source domain and target domain
>>> y_s_adv, y_t_adv = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
>>> output = loss(y_s, y_s_adv, y_t, y_t_adv)
"""
def __init__(self, margin: 'Optional[int]'=4, reduction:
'Optional[str]'='mean'):
super(MarginDisparityDiscrepancy, self).__init__()
self.margin = margin
self.reduction = reduction
def forward(self, y_s: 'torch.Tensor', y_s_adv: 'torch.Tensor', y_t:
'torch.Tensor', y_t_adv: 'torch.Tensor') ->torch.Tensor:
_, prediction_s = y_s.max(dim=1)
_, prediction_t = y_t.max(dim=1)
return self.margin * F.cross_entropy(y_s_adv, prediction_s,
reduction=self.reduction) + F.nll_loss(shift_log(1.0 - F.
softmax(y_t_adv, dim=1)), prediction_t, reduction=self.reduction)
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
from typing import Optional
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@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__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_per_fused_add_max_mul_nll_loss2d_forward_2(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, 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)
tmp79 = tl.load(in_ptr2 + (r0 + 64 * r1), None)
tmp80 = tl.load(in_ptr2 + (16 + r0 + 64 * r1), None)
tmp93 = tl.load(in_ptr2 + (32 + r0 + 64 * r1), None)
tmp107 = tl.load(in_ptr2 + (48 + r0 + 64 * r1), None)
tmp128 = tl.load(in_ptr3 + (r0 + 64 * r1), None)
tmp129 = tl.load(in_ptr3 + (16 + r0 + 64 * r1), None)
tmp131 = tl.load(in_ptr3 + (32 + r0 + 64 * r1), None)
tmp133 = tl.load(in_ptr3 + (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 = tmp48.to(tl.int64)
tmp76 = tl.broadcast_to(tmp75, [XBLOCK, RBLOCK])
tmp78 = tl.sum(tmp76, 1)[:, None]
tmp81 = tmp79 > tmp80
tmp82 = tmp79 == tmp80
tmp83 = tmp79 != tmp79
tmp84 = tmp80 != tmp80
tmp85 = tmp83 > tmp84
tmp86 = tmp81 | tmp85
tmp87 = tmp83 & tmp84
tmp88 = tmp82 | tmp87
tmp89 = tmp88 & tmp12
tmp90 = tmp86 | tmp89
tmp91 = tl.where(tmp90, tmp79, tmp80)
tmp92 = tl.where(tmp90, tmp10, tmp11)
tmp94 = tmp91 > tmp93
tmp95 = tmp91 == tmp93
tmp96 = tmp91 != tmp91
tmp97 = tmp93 != tmp93
tmp98 = tmp96 > tmp97
tmp99 = tmp94 | tmp98
tmp100 = tmp96 & tmp97
tmp101 = tmp95 | tmp100
tmp102 = tmp92 < tmp26
tmp103 = tmp101 & tmp102
tmp104 = tmp99 | tmp103
tmp105 = tl.where(tmp104, tmp91, tmp93)
tmp106 = tl.where(tmp104, tmp92, tmp26)
tmp108 = tmp105 > tmp107
tmp109 = tmp105 == tmp107
tmp110 = tmp105 != tmp105
tmp111 = tmp107 != tmp107
tmp112 = tmp110 > tmp111
tmp113 = tmp108 | tmp112
tmp114 = tmp110 & tmp111
tmp115 = tmp109 | tmp114
tmp116 = tmp106 < tmp41
tmp117 = tmp115 & tmp116
tmp118 = tmp113 | tmp117
tl.where(tmp118, tmp105, tmp107)
tmp120 = tl.where(tmp118, tmp106, tmp41)
tmp121 = tmp120 != tmp47
tmp122 = tl.where(tmp121, tmp120, tmp10)
tmp123 = tmp122 + tmp50
tmp124 = tmp122 < 0
tmp125 = tl.where(tmp124, tmp123, tmp122)
tl.device_assert((0 <= tmp125) & (tmp125 < 4),
'index out of bounds: 0 <= tmp125 < 4')
tmp127 = tl.load(in_ptr3 + (r0 + 16 * tmp125 + 64 * r1), None)
tmp130 = tmp128 + tmp129
tmp132 = tmp130 + tmp131
tmp134 = tmp132 + tmp133
tmp135 = tmp127 / tmp134
tmp136 = 1.0
tmp137 = tmp136 - tmp135
tmp138 = 1e-06
tmp139 = tmp137 + tmp138
tmp140 = triton_helpers.minimum(tmp139, tmp136)
tmp141 = tl_math.log(tmp140)
tmp142 = -tmp141
tmp143 = tl.where(tmp121, tmp142, tmp70)
tmp144 = tl.broadcast_to(tmp143, [XBLOCK, RBLOCK])
tmp146 = tl.sum(tmp144, 1)[:, None]
tmp147 = tmp121.to(tl.int64)
tmp148 = tl.broadcast_to(tmp147, [XBLOCK, RBLOCK])
tmp150 = tl.sum(tmp148, 1)[:, None]
tmp151 = tmp78.to(tl.float32)
tmp152 = tmp74 / tmp151
tmp153 = 4.0
tmp154 = tmp152 * tmp153
tmp155 = tmp150.to(tl.float32)
tmp156 = tmp146 / tmp155
tmp157 = tmp154 + tmp156
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp157, 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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg2_1, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg2_1
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](arg3_1, buf5, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg3_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf8 = buf3
del buf3
triton_per_fused_add_max_mul_nll_loss2d_forward_2[grid(1)](buf8,
arg0_1, buf2, arg1_1, buf5, 1, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del arg0_1
del arg1_1
del buf2
del buf5
return buf8,
def shift_log(x: 'torch.Tensor', offset: 'Optional[float]'=1e-06
) ->torch.Tensor:
"""
First shift, then calculate log, which can be described as:
.. math::
y = \\max(\\log(x+\\text{offset}), 0)
Used to avoid the gradient explosion problem in log(x) function when x=0.
Parameters:
- **x**: input tensor
- **offset**: offset size. Default: 1e-6
.. note::
Input tensor falls in [0., 1.] and the output tensor falls in [-log(offset), 0]
"""
return torch.log(torch.clamp(x + offset, max=1.0))
class MarginDisparityDiscrepancyNew(nn.Module):
"""The margin disparity discrepancy (MDD) is proposed to measure the distribution discrepancy in domain adaptation.
The :math:`y^s` and :math:`y^t` are logits output by the main classifier on the source and target domain respectively.
The :math:`y_{adv}^s` and :math:`y_{adv}^t` are logits output by the adversarial classifier.
They are expected to contain raw, unnormalized scores for each class.
The definition can be described as:
.. math::
\\mathcal{D}_{\\gamma}(\\hat{\\mathcal{S}}, \\hat{\\mathcal{T}}) =
\\gamma \\mathbb{E}_{y^s, y_{adv}^s \\sim\\hat{\\mathcal{S}}} \\log\\left(\\frac{\\exp(y_{adv}^s[h_{y^s}])}{\\sum_j \\exp(y_{adv}^s[j])}\\right) +
\\mathbb{E}_{y^t, y_{adv}^t \\sim\\hat{\\mathcal{T}}} \\log\\left(1-\\frac{\\exp(y_{adv}^t[h_{y^t}])}{\\sum_j \\exp(y_{adv}^t[j])}\\right),
where :math:`\\gamma` is a margin hyper-parameter and :math:`h_y` refers to the predicted label when the logits output is :math:`y`.
You can see more details in `Bridging Theory and Algorithm for Domain Adaptation <https://arxiv.org/abs/1904.05801>`_.
Parameters:
- **margin** (float): margin :math:`\\gamma`. Default: 4
- **reduction** (string, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs: y_s, y_s_adv, y_t, y_t_adv
- **y_s**: logits output :math:`y^s` by the main classifier on the source domain
- **y_s_adv**: logits output :math:`y^s` by the adversarial classifier on the source domain
- **y_t**: logits output :math:`y^t` by the main classifier on the target domain
- **y_t_adv**: logits output :math:`y_{adv}^t` by the adversarial classifier on the target domain
Shape:
- Inputs: :math:`(minibatch, C)` where C = number of classes, or :math:`(minibatch, C, d_1, d_2, ..., d_K)`
with :math:`K \\geq 1` in the case of `K`-dimensional loss.
- Output: scalar. If :attr:`reduction` is ``'none'``, then the same size as the target: :math:`(minibatch)`, or
:math:`(minibatch, d_1, d_2, ..., d_K)` with :math:`K \\geq 1` in the case of K-dimensional loss.
Examples::
>>> num_classes = 2
>>> batch_size = 10
>>> loss = MarginDisparityDiscrepancy(margin=4.)
>>> # logits output from source domain and target domain
>>> y_s, y_t = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
>>> # adversarial logits output from source domain and target domain
>>> y_s_adv, y_t_adv = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
>>> output = loss(y_s, y_s_adv, y_t, y_t_adv)
"""
def __init__(self, margin: 'Optional[int]'=4, reduction:
'Optional[str]'='mean'):
super(MarginDisparityDiscrepancyNew, self).__init__()
self.margin = margin
self.reduction = reduction
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0]
|
NiteshBharadwaj/ignoringhumanpose
|
MarginDisparityDiscrepancy
| false
| 916
|
[
"MIT"
] | 0
|
1fb7a063fded9cff18f7de4e1d71845983077256
|
https://github.com/NiteshBharadwaj/ignoringhumanpose/tree/1fb7a063fded9cff18f7de4e1d71845983077256
|
DivisiveNormalization2d
|
from torch.nn import Module
import torch
from torch import Tensor
from typing import Union
from typing import Tuple
import torch.nn.functional as F
class DivisiveNormalization2d(Module):
"""Applies a 2D divisive normalization over an input signal composed of several input
planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`
and output :math:`(N, C, H, W)`.
Args:
b_type: Type of suppressin field, must be one of (`linf`, `l1`, `l2`).
b_size: The size of the suppression field, must be > 0.
sigma: Constant added to suppression field, must be > 0.
Shape:
- Input: :math:`(N, C, H, W)`
- Output: :math:`(N, C, H, W)`
Examples::
>>> # suppression of size=3, sigma=1
>>> d = DivisiveNormalization2d(b_size=3, sigma=1)
>>> input = torch.randn(20, 16, 50, 50)
>>> output = d(input)
"""
def __init__(self, b_type: 'str'='linf', b_size:
'Union[int, Tuple[int, int]]'=(5, 5), sigma: 'float'=1.0) ->None:
super(DivisiveNormalization2d, self).__init__()
self.sigma = sigma
if isinstance(b_size, int):
self.b_size = b_size, b_size
else:
self.b_size = b_size
self.padding = self.b_size[0] // 2, self.b_size[1] // 2
self.b_type = b_type
def forward(self, input: 'Tensor') ->Tensor:
if self.b_type == 'linf':
suppression_field = F.max_pool2d(torch.abs(input), self.b_size,
1, self.padding, 1)
elif self.b_type == 'l1':
weight = torch.ones((input.shape[1], 1, self.b_size[0], self.
b_size[1]))
suppression_field = F.conv2d(torch.abs(input), weight=weight,
padding=self.padding, groups=input.shape[1])
elif self.b_type == 'l2':
weight = torch.ones((input.shape[1], 1, self.b_size[0], self.
b_size[1]))
suppression_field = torch.sqrt(F.conv2d(input ** 2, weight=
weight, padding=self.padding, groups=input.shape[1]))
else:
raise NotImplementedError
return input / (self.sigma + suppression_field)
def __repr__(self) ->str:
s = 'DivisiveNormalization2d('
s += f'b_type={self.b_type}, b_size={self.b_size}, sigma={self.sigma}'
s += ')'
return s.format(**self.__dict__)
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
from torch.nn import Module
from typing import Union
from typing import Tuple
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_abs_add_div_max_pool2d_with_indices_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
x1 = xindex // 4 % 4
x0 = xindex % 4
x3 = xindex
tmp191 = tl.load(in_ptr0 + x3, xmask)
tmp0 = -2 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -2 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-10 + x3), tmp10 & xmask, other=0.0)
tmp12 = tl_math.abs(tmp11)
tmp13 = tl.full(tmp12.shape, float('-inf'), tmp12.dtype)
tmp14 = tl.where(tmp10, tmp12, tmp13)
tmp15 = -1 + x0
tmp16 = tmp15 >= tmp1
tmp17 = tmp15 < tmp3
tmp18 = tmp16 & tmp17
tmp19 = tmp5 & tmp18
tmp20 = tl.load(in_ptr0 + (-9 + x3), tmp19 & xmask, other=0.0)
tmp21 = tl_math.abs(tmp20)
tmp22 = tl.full(tmp21.shape, float('-inf'), tmp21.dtype)
tmp23 = tl.where(tmp19, tmp21, tmp22)
tmp24 = triton_helpers.maximum(tmp23, tmp14)
tmp25 = x0
tmp26 = tmp25 >= tmp1
tmp27 = tmp25 < tmp3
tmp28 = tmp26 & tmp27
tmp29 = tmp5 & tmp28
tmp30 = tl.load(in_ptr0 + (-8 + x3), tmp29 & xmask, other=0.0)
tmp31 = tl_math.abs(tmp30)
tmp32 = tl.full(tmp31.shape, float('-inf'), tmp31.dtype)
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = triton_helpers.maximum(tmp33, tmp24)
tmp35 = 1 + x0
tmp36 = tmp35 >= tmp1
tmp37 = tmp35 < tmp3
tmp38 = tmp36 & tmp37
tmp39 = tmp5 & tmp38
tmp40 = tl.load(in_ptr0 + (-7 + x3), tmp39 & xmask, other=0.0)
tmp41 = tl_math.abs(tmp40)
tmp42 = tl.full(tmp41.shape, float('-inf'), tmp41.dtype)
tmp43 = tl.where(tmp39, tmp41, tmp42)
tmp44 = triton_helpers.maximum(tmp43, tmp34)
tmp45 = 2 + x0
tmp46 = tmp45 >= tmp1
tmp47 = tmp45 < tmp3
tmp48 = tmp46 & tmp47
tmp49 = tmp5 & tmp48
tmp50 = tl.load(in_ptr0 + (-6 + x3), tmp49 & xmask, other=0.0)
tmp51 = tl_math.abs(tmp50)
tmp52 = tl.full(tmp51.shape, float('-inf'), tmp51.dtype)
tmp53 = tl.where(tmp49, tmp51, tmp52)
tmp54 = triton_helpers.maximum(tmp53, tmp44)
tmp55 = -1 + x1
tmp56 = tmp55 >= tmp1
tmp57 = tmp55 < tmp3
tmp58 = tmp56 & tmp57
tmp59 = tmp58 & tmp9
tmp60 = tl.load(in_ptr0 + (-6 + x3), tmp59 & xmask, other=0.0)
tmp61 = tl_math.abs(tmp60)
tmp62 = tl.full(tmp61.shape, float('-inf'), tmp61.dtype)
tmp63 = tl.where(tmp59, tmp61, tmp62)
tmp64 = triton_helpers.maximum(tmp63, tmp54)
tmp65 = tmp58 & tmp18
tmp66 = tl.load(in_ptr0 + (-5 + x3), tmp65 & xmask, other=0.0)
tmp67 = tl_math.abs(tmp66)
tmp68 = tl.full(tmp67.shape, float('-inf'), tmp67.dtype)
tmp69 = tl.where(tmp65, tmp67, tmp68)
tmp70 = triton_helpers.maximum(tmp69, tmp64)
tmp71 = tmp58 & tmp28
tmp72 = tl.load(in_ptr0 + (-4 + x3), tmp71 & xmask, other=0.0)
tmp73 = tl_math.abs(tmp72)
tmp74 = tl.full(tmp73.shape, float('-inf'), tmp73.dtype)
tmp75 = tl.where(tmp71, tmp73, tmp74)
tmp76 = triton_helpers.maximum(tmp75, tmp70)
tmp77 = tmp58 & tmp38
tmp78 = tl.load(in_ptr0 + (-3 + x3), tmp77 & xmask, other=0.0)
tmp79 = tl_math.abs(tmp78)
tmp80 = tl.full(tmp79.shape, float('-inf'), tmp79.dtype)
tmp81 = tl.where(tmp77, tmp79, tmp80)
tmp82 = triton_helpers.maximum(tmp81, tmp76)
tmp83 = tmp58 & tmp48
tmp84 = tl.load(in_ptr0 + (-2 + x3), tmp83 & xmask, other=0.0)
tmp85 = tl_math.abs(tmp84)
tmp86 = tl.full(tmp85.shape, float('-inf'), tmp85.dtype)
tmp87 = tl.where(tmp83, tmp85, tmp86)
tmp88 = triton_helpers.maximum(tmp87, tmp82)
tmp89 = x1
tmp90 = tmp89 >= tmp1
tmp91 = tmp89 < tmp3
tmp92 = tmp90 & tmp91
tmp93 = tmp92 & tmp9
tmp94 = tl.load(in_ptr0 + (-2 + x3), tmp93 & xmask, other=0.0)
tmp95 = tl_math.abs(tmp94)
tmp96 = tl.full(tmp95.shape, float('-inf'), tmp95.dtype)
tmp97 = tl.where(tmp93, tmp95, tmp96)
tmp98 = triton_helpers.maximum(tmp97, tmp88)
tmp99 = tmp92 & tmp18
tmp100 = tl.load(in_ptr0 + (-1 + x3), tmp99 & xmask, other=0.0)
tmp101 = tl_math.abs(tmp100)
tmp102 = tl.full(tmp101.shape, float('-inf'), tmp101.dtype)
tmp103 = tl.where(tmp99, tmp101, tmp102)
tmp104 = triton_helpers.maximum(tmp103, tmp98)
tmp105 = tmp92 & tmp28
tmp106 = tl.load(in_ptr0 + x3, tmp105 & xmask, other=0.0)
tmp107 = tl_math.abs(tmp106)
tmp108 = tl.full(tmp107.shape, float('-inf'), tmp107.dtype)
tmp109 = tl.where(tmp105, tmp107, tmp108)
tmp110 = triton_helpers.maximum(tmp109, tmp104)
tmp111 = tmp92 & tmp38
tmp112 = tl.load(in_ptr0 + (1 + x3), tmp111 & xmask, other=0.0)
tmp113 = tl_math.abs(tmp112)
tmp114 = tl.full(tmp113.shape, float('-inf'), tmp113.dtype)
tmp115 = tl.where(tmp111, tmp113, tmp114)
tmp116 = triton_helpers.maximum(tmp115, tmp110)
tmp117 = tmp92 & tmp48
tmp118 = tl.load(in_ptr0 + (2 + x3), tmp117 & xmask, other=0.0)
tmp119 = tl_math.abs(tmp118)
tmp120 = tl.full(tmp119.shape, float('-inf'), tmp119.dtype)
tmp121 = tl.where(tmp117, tmp119, tmp120)
tmp122 = triton_helpers.maximum(tmp121, tmp116)
tmp123 = 1 + x1
tmp124 = tmp123 >= tmp1
tmp125 = tmp123 < tmp3
tmp126 = tmp124 & tmp125
tmp127 = tmp126 & tmp9
tmp128 = tl.load(in_ptr0 + (2 + x3), tmp127 & xmask, other=0.0)
tmp129 = tl_math.abs(tmp128)
tmp130 = tl.full(tmp129.shape, float('-inf'), tmp129.dtype)
tmp131 = tl.where(tmp127, tmp129, tmp130)
tmp132 = triton_helpers.maximum(tmp131, tmp122)
tmp133 = tmp126 & tmp18
tmp134 = tl.load(in_ptr0 + (3 + x3), tmp133 & xmask, other=0.0)
tmp135 = tl_math.abs(tmp134)
tmp136 = tl.full(tmp135.shape, float('-inf'), tmp135.dtype)
tmp137 = tl.where(tmp133, tmp135, tmp136)
tmp138 = triton_helpers.maximum(tmp137, tmp132)
tmp139 = tmp126 & tmp28
tmp140 = tl.load(in_ptr0 + (4 + x3), tmp139 & xmask, other=0.0)
tmp141 = tl_math.abs(tmp140)
tmp142 = tl.full(tmp141.shape, float('-inf'), tmp141.dtype)
tmp143 = tl.where(tmp139, tmp141, tmp142)
tmp144 = triton_helpers.maximum(tmp143, tmp138)
tmp145 = tmp126 & tmp38
tmp146 = tl.load(in_ptr0 + (5 + x3), tmp145 & xmask, other=0.0)
tmp147 = tl_math.abs(tmp146)
tmp148 = tl.full(tmp147.shape, float('-inf'), tmp147.dtype)
tmp149 = tl.where(tmp145, tmp147, tmp148)
tmp150 = triton_helpers.maximum(tmp149, tmp144)
tmp151 = tmp126 & tmp48
tmp152 = tl.load(in_ptr0 + (6 + x3), tmp151 & xmask, other=0.0)
tmp153 = tl_math.abs(tmp152)
tmp154 = tl.full(tmp153.shape, float('-inf'), tmp153.dtype)
tmp155 = tl.where(tmp151, tmp153, tmp154)
tmp156 = triton_helpers.maximum(tmp155, tmp150)
tmp157 = 2 + x1
tmp158 = tmp157 >= tmp1
tmp159 = tmp157 < tmp3
tmp160 = tmp158 & tmp159
tmp161 = tmp160 & tmp9
tmp162 = tl.load(in_ptr0 + (6 + x3), tmp161 & xmask, other=0.0)
tmp163 = tl_math.abs(tmp162)
tmp164 = tl.full(tmp163.shape, float('-inf'), tmp163.dtype)
tmp165 = tl.where(tmp161, tmp163, tmp164)
tmp166 = triton_helpers.maximum(tmp165, tmp156)
tmp167 = tmp160 & tmp18
tmp168 = tl.load(in_ptr0 + (7 + x3), tmp167 & xmask, other=0.0)
tmp169 = tl_math.abs(tmp168)
tmp170 = tl.full(tmp169.shape, float('-inf'), tmp169.dtype)
tmp171 = tl.where(tmp167, tmp169, tmp170)
tmp172 = triton_helpers.maximum(tmp171, tmp166)
tmp173 = tmp160 & tmp28
tmp174 = tl.load(in_ptr0 + (8 + x3), tmp173 & xmask, other=0.0)
tmp175 = tl_math.abs(tmp174)
tmp176 = tl.full(tmp175.shape, float('-inf'), tmp175.dtype)
tmp177 = tl.where(tmp173, tmp175, tmp176)
tmp178 = triton_helpers.maximum(tmp177, tmp172)
tmp179 = tmp160 & tmp38
tmp180 = tl.load(in_ptr0 + (9 + x3), tmp179 & xmask, other=0.0)
tmp181 = tl_math.abs(tmp180)
tmp182 = tl.full(tmp181.shape, float('-inf'), tmp181.dtype)
tmp183 = tl.where(tmp179, tmp181, tmp182)
tmp184 = triton_helpers.maximum(tmp183, tmp178)
tmp185 = tmp160 & tmp48
tmp186 = tl.load(in_ptr0 + (10 + x3), tmp185 & xmask, other=0.0)
tmp187 = tl_math.abs(tmp186)
tmp188 = tl.full(tmp187.shape, float('-inf'), tmp187.dtype)
tmp189 = tl.where(tmp185, tmp187, tmp188)
tmp190 = triton_helpers.maximum(tmp189, tmp184)
tmp192 = 1.0
tmp193 = tmp190 + tmp192
tmp194 = tmp191 / tmp193
tl.store(in_out_ptr0 + x3, tmp194, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_abs_add_div_max_pool2d_with_indices_0[grid(256)](buf1,
arg0_1, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf1,
class DivisiveNormalization2dNew(Module):
"""Applies a 2D divisive normalization over an input signal composed of several input
planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`
and output :math:`(N, C, H, W)`.
Args:
b_type: Type of suppressin field, must be one of (`linf`, `l1`, `l2`).
b_size: The size of the suppression field, must be > 0.
sigma: Constant added to suppression field, must be > 0.
Shape:
- Input: :math:`(N, C, H, W)`
- Output: :math:`(N, C, H, W)`
Examples::
>>> # suppression of size=3, sigma=1
>>> d = DivisiveNormalization2d(b_size=3, sigma=1)
>>> input = torch.randn(20, 16, 50, 50)
>>> output = d(input)
"""
def __init__(self, b_type: 'str'='linf', b_size:
'Union[int, Tuple[int, int]]'=(5, 5), sigma: 'float'=1.0) ->None:
super(DivisiveNormalization2dNew, self).__init__()
self.sigma = sigma
if isinstance(b_size, int):
self.b_size = b_size, b_size
else:
self.b_size = b_size
self.padding = self.b_size[0] // 2, self.b_size[1] // 2
self.b_type = b_type
def __repr__(self) ->str:
s = 'DivisiveNormalization2d('
s += f'b_type={self.b_type}, b_size={self.b_size}, sigma={self.sigma}'
s += ')'
return s.format(**self.__dict__)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Noppornying00/constant-fraction-activation
|
DivisiveNormalization2d
| false
| 917
|
[
"Apache-2.0"
] | 0
|
b25745e7339df13e3db34d8c8372d5cbaa3c13bb
|
https://github.com/Noppornying00/constant-fraction-activation/tree/b25745e7339df13e3db34d8c8372d5cbaa3c13bb
|
UPChannelRPN
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def xcorr_fast(x, kernel):
"""group conv2d to calculate cross correlation, fast version
"""
batch = kernel.size()[0]
pk = kernel.view(-1, x.size()[1], kernel.size()[2], kernel.size()[3])
px = x.view(1, -1, x.size()[2], x.size()[3])
po = F.conv2d(px, pk, groups=batch)
po = po.view(batch, -1, po.size()[2], po.size()[3])
return po
class RPN(nn.Module):
def __init__(self):
super(RPN, self).__init__()
def forward(self, z_f, x_f):
raise NotImplementedError
class UPChannelRPN(RPN):
def __init__(self, anchor_num=5, feature_in=256):
super(UPChannelRPN, self).__init__()
cls_output = 2 * anchor_num
loc_output = 4 * anchor_num
self.template_cls_conv = nn.Conv2d(feature_in, feature_in *
cls_output, kernel_size=3)
self.template_loc_conv = nn.Conv2d(feature_in, feature_in *
loc_output, kernel_size=3)
self.search_cls_conv = nn.Conv2d(feature_in, feature_in, kernel_size=3)
self.search_loc_conv = nn.Conv2d(feature_in, feature_in, kernel_size=3)
self.loc_adjust = nn.Conv2d(loc_output, loc_output, kernel_size=1)
def forward(self, z_f, x_f):
cls_kernel = self.template_cls_conv(z_f)
loc_kernel = self.template_loc_conv(z_f)
cls_feature = self.search_cls_conv(x_f)
loc_feature = self.search_loc_conv(x_f)
cls = xcorr_fast(cls_feature, cls_kernel)
loc = self.loc_adjust(xcorr_fast(loc_feature, loc_kernel))
return cls, loc
def get_inputs():
return [torch.rand([4, 256, 64, 64]), torch.rand([4, 256, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_view_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)
x4 = xindex
x1 = xindex // 3844 % 2560
tmp0 = tl.load(in_out_ptr0 + x4, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x4, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_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 // 3844 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_view_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)
x4 = xindex
x1 = xindex // 3844 % 5120
tmp0 = tl.load(in_out_ptr0 + x4, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x4, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 20
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (2560, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_2, (2560,), (1,))
assert_size_stride(primals_3, (4, 256, 64, 64), (1048576, 4096, 64, 1))
assert_size_stride(primals_4, (5120, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_5, (5120,), (1,))
assert_size_stride(primals_6, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (4, 256, 64, 64), (1048576, 4096, 64, 1))
assert_size_stride(primals_9, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_10, (256,), (1,))
assert_size_stride(primals_11, (20, 20, 1, 1), (20, 1, 1, 1))
assert_size_stride(primals_12, (20,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 2560, 62, 62), (9840640, 3844, 62, 1))
buf1 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 5120, 62, 62), (19681280, 3844, 62, 1))
buf2 = extern_kernels.convolution(primals_8, primals_6, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 256, 62, 62), (984064, 3844, 62, 1))
buf3 = extern_kernels.convolution(primals_8, primals_9, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 256, 62, 62), (984064, 3844, 62, 1))
buf4 = buf0
del buf0
buf5 = reinterpret_tensor(buf4, (40, 256, 62, 62), (984064, 3844,
62, 1), 0)
del buf4
get_raw_stream(0)
triton_poi_fused_convolution_view_0[grid(39362560)](buf5, primals_2,
39362560, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf6 = buf2
del buf2
triton_poi_fused_convolution_1[grid(3936256)](buf6, primals_7,
3936256, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf7 = extern_kernels.convolution(reinterpret_tensor(buf6, (1, 1024,
62, 62), (0, 3844, 62, 1), 0), buf5, stride=(1, 1), padding=(0,
0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf7, (1, 40, 1, 1), (40, 1, 1, 1))
buf8 = buf1
del buf1
buf9 = reinterpret_tensor(buf8, (80, 256, 62, 62), (984064, 3844,
62, 1), 0)
del buf8
triton_poi_fused_convolution_view_2[grid(78725120)](buf9, primals_5,
78725120, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf10 = buf3
del buf3
triton_poi_fused_convolution_1[grid(3936256)](buf10, primals_10,
3936256, XBLOCK=512, num_warps=8, num_stages=1)
del primals_10
buf11 = extern_kernels.convolution(reinterpret_tensor(buf10, (1,
1024, 62, 62), (0, 3844, 62, 1), 0), buf9, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf11, (1, 80, 1, 1), (80, 1, 1, 1))
buf12 = extern_kernels.convolution(reinterpret_tensor(buf11, (4, 20,
1, 1), (20, 1, 1, 1), 0), primals_11, stride=(1, 1), padding=(0,
0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf12, (4, 20, 1, 1), (20, 1, 1, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_3[grid(80)](buf13, primals_12, 80,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_12
return (reinterpret_tensor(buf7, (4, 10, 1, 1), (10, 1, 1, 1), 0),
buf13, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_9, primals_11, buf5, reinterpret_tensor(buf6, (1, 1024, 62,
62), (3936256, 3844, 62, 1), 0), buf9, reinterpret_tensor(buf10, (1,
1024, 62, 62), (3936256, 3844, 62, 1), 0), reinterpret_tensor(buf11,
(4, 20, 1, 1), (20, 1, 1, 1), 0))
def xcorr_fast(x, kernel):
"""group conv2d to calculate cross correlation, fast version
"""
batch = kernel.size()[0]
pk = kernel.view(-1, x.size()[1], kernel.size()[2], kernel.size()[3])
px = x.view(1, -1, x.size()[2], x.size()[3])
po = F.conv2d(px, pk, groups=batch)
po = po.view(batch, -1, po.size()[2], po.size()[3])
return po
class RPN(nn.Module):
def __init__(self):
super(RPN, self).__init__()
def forward(self, z_f, x_f):
raise NotImplementedError
class UPChannelRPNNew(RPN):
def __init__(self, anchor_num=5, feature_in=256):
super(UPChannelRPNNew, self).__init__()
cls_output = 2 * anchor_num
loc_output = 4 * anchor_num
self.template_cls_conv = nn.Conv2d(feature_in, feature_in *
cls_output, kernel_size=3)
self.template_loc_conv = nn.Conv2d(feature_in, feature_in *
loc_output, kernel_size=3)
self.search_cls_conv = nn.Conv2d(feature_in, feature_in, kernel_size=3)
self.search_loc_conv = nn.Conv2d(feature_in, feature_in, kernel_size=3)
self.loc_adjust = nn.Conv2d(loc_output, loc_output, kernel_size=1)
def forward(self, input_0, input_1):
primals_1 = self.template_cls_conv.weight
primals_2 = self.template_cls_conv.bias
primals_4 = self.template_loc_conv.weight
primals_5 = self.template_loc_conv.bias
primals_6 = self.search_cls_conv.weight
primals_7 = self.search_cls_conv.bias
primals_9 = self.search_loc_conv.weight
primals_10 = self.search_loc_conv.bias
primals_11 = self.loc_adjust.weight
primals_12 = self.loc_adjust.bias
primals_3 = input_0
primals_8 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0], output[1]
|
LSH9832/MyPythonModules
|
UPChannelRPN
| false
| 918
|
[
"MIT"
] | 0
|
442566a0fbd6ebe2bc20b6914686a1e2663d10c0
|
https://github.com/LSH9832/MyPythonModules/tree/442566a0fbd6ebe2bc20b6914686a1e2663d10c0
|
MatrixTree
|
import torch
import torch.nn as nn
import torch.cuda
import torch.distributed
class MatrixTree(nn.Module):
"""Implementation of the matrix-tree theorem for computing marginals
of non-projective dependency parsing. This attention layer is used
in the paper "Learning Structured Text Representations"
:cite:`DBLP:journals/corr/LiuL17d`.
"""
def __init__(self, eps=1e-05):
self.eps = eps
super(MatrixTree, self).__init__()
def forward(self, input):
laplacian = input.exp() + self.eps
output = input.clone()
for b in range(input.size(0)):
lap = laplacian[b].masked_fill(torch.eye(input.size(1), device=
input.device).ne(0), 0)
lap = -lap + torch.diag(lap.sum(0))
lap[0] = input[b].diag().exp()
inv_laplacian = lap.inverse()
factor = inv_laplacian.diag().unsqueeze(1).expand_as(input[b]
).transpose(0, 1)
term1 = input[b].exp().mul(factor).clone()
term2 = input[b].exp().mul(inv_laplacian.transpose(0, 1)).clone()
term1[:, 0] = 0
term2[0] = 0
output[b] = term1 - term2
roots_output = input[b].diag().exp().mul(inv_laplacian.
transpose(0, 1)[0])
output[b] = output[b] + torch.diag(roots_output)
return output
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.cuda
import torch.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp7 = tl.load(in_ptr0 + x0, xmask)
tmp16 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (12 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_1(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + x2, xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_2(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp7 = tl.load(in_ptr0 + (16 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (20 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (24 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (28 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_3(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (16 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_4(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp6 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + x2, xmask)
tmp18 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 0, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tmp2 == tmp0
tmp5 = tl_math.exp(tmp4)
tmp7 = tmp5 * tmp6
tmp8 = 0.0
tmp9 = tl.where(tmp3, tmp8, tmp7)
tmp10 = x1
tmp11 = tmp10 == tmp0
tmp13 = tmp5 * tmp12
tmp14 = tl.where(tmp11, tmp8, tmp13)
tmp15 = tmp9 - tmp14
tmp16 = tl.where(tmp1, tmp15, tmp4)
tmp17 = tmp2 == tmp10
tmp19 = tl_math.exp(tmp18)
tmp21 = tmp19 * tmp20
tmp22 = tl.where(tmp17, tmp21, tmp8)
tmp23 = tmp16 + tmp22
tl.store(out_ptr0 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_5(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr1 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tmp4 == tmp1
tmp7 = tl_math.exp(tmp6)
tmp9 = tmp7 * tmp8
tmp10 = 0.0
tmp11 = tl.where(tmp5, tmp10, tmp9)
tmp12 = x1
tmp13 = tmp12 == tmp1
tmp15 = tmp7 * tmp14
tmp16 = tl.where(tmp13, tmp10, tmp15)
tmp17 = tmp11 - tmp16
tmp19 = tl.where(tmp2, tmp17, tmp18)
tmp20 = tl.where(tmp2, tmp3, tmp19)
tl.store(out_ptr0 + x5, tmp20, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_6(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp7 = tl.load(in_ptr0 + (32 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (36 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (40 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (44 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_7(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (32 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_8(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp5 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (16 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (16 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 1, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_9(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (16 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
@triton.jit
def triton_poi_fused_eye_masked_fill_ne_sum_10(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp7 = tl.load(in_ptr0 + (48 + x0), xmask)
tmp16 = tl.load(in_ptr0 + (52 + x0), xmask)
tmp25 = tl.load(in_ptr0 + (56 + x0), xmask)
tmp34 = tl.load(in_ptr0 + (60 + x0), xmask)
tmp0 = tl.full([1], 0, tl.int64)
tmp1 = x0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp5 != tmp4
tmp8 = tl_math.exp(tmp7)
tmp9 = 1e-05
tmp10 = tmp8 + tmp9
tmp11 = tl.where(tmp6, tmp4, tmp10)
tmp12 = tl.full([1], 1, tl.int64)
tmp13 = tmp12 == tmp1
tmp14 = tl.where(tmp13, tmp3, tmp4)
tmp15 = tmp14 != tmp4
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp17 + tmp9
tmp19 = tl.where(tmp15, tmp4, tmp18)
tmp20 = tmp11 + tmp19
tmp21 = tl.full([1], 2, tl.int64)
tmp22 = tmp21 == tmp1
tmp23 = tl.where(tmp22, tmp3, tmp4)
tmp24 = tmp23 != tmp4
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp26 + tmp9
tmp28 = tl.where(tmp24, tmp4, tmp27)
tmp29 = tmp20 + tmp28
tmp30 = tl.full([1], 3, tl.int64)
tmp31 = tmp30 == tmp1
tmp32 = tl.where(tmp31, tmp3, tmp4)
tmp33 = tmp32 != tmp4
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp35 + tmp9
tmp37 = tl.where(tmp33, tmp4, tmp36)
tmp38 = tmp29 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_11(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (48 + 5 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp18 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl_math.exp(tmp3)
tmp5 = x0
tmp6 = tmp0 == tmp5
tmp7 = 1.0
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = tmp9 != tmp8
tmp12 = tl_math.exp(tmp11)
tmp13 = 1e-05
tmp14 = tmp12 + tmp13
tmp15 = tl.where(tmp10, tmp8, tmp14)
tmp16 = -tmp15
tmp17 = tmp5 == tmp0
tmp19 = tl.where(tmp17, tmp18, tmp8)
tmp20 = tmp16 + tmp19
tmp21 = tl.where(tmp2, tmp4, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_12(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp5 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (32 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (32 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 2, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_13(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (32 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_14(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp5 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp7 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x2, xmask)
tmp17 = tl.load(in_ptr2 + (48 + x2), xmask)
tmp20 = tl.load(in_ptr0 + (48 + 5 * x0), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp0 = tl.full([1], 3, tl.int32)
tmp1 = tmp0 == tmp0
tmp2 = x0
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp2 == tmp3
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = x1
tmp12 = tmp11 == tmp3
tmp14 = tmp6 * tmp13
tmp15 = tl.where(tmp12, tmp9, tmp14)
tmp16 = tmp10 - tmp15
tmp18 = tl.where(tmp1, tmp16, tmp17)
tmp19 = tmp2 == tmp11
tmp21 = tl_math.exp(tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tl.where(tmp19, tmp23, tmp9)
tmp25 = tmp18 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_15(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (48 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + 5 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_out_ptr0 + x5, xmask)
tmp0 = x2
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x0
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp4 == tmp5
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = 0.0
tmp12 = tl.where(tmp6, tmp11, tmp10)
tmp13 = x1
tmp14 = tmp13 == tmp5
tmp16 = tmp8 * tmp15
tmp17 = tl.where(tmp14, tmp11, tmp16)
tmp18 = tmp12 - tmp17
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(in_out_ptr0 + x5, tmp21, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_eye_masked_fill_ne_sum_0[grid(4)](arg0_1, buf0, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_1[
grid(16)](arg0_1, buf0, buf1, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf2 = torch.ops.aten.linalg_inv_ex.default(buf1)
buf3 = buf2[0]
del buf2
buf5 = buf0
del buf0
triton_poi_fused_eye_masked_fill_ne_sum_2[grid(4)](arg0_1, buf5, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf6 = buf1
del buf1
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_3[
grid(16)](arg0_1, buf5, buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = torch.ops.aten.linalg_inv_ex.default(buf6)
buf8 = buf7[0]
del buf7
buf10 = buf6
del buf6
triton_poi_fused_add_diag_embed_4[grid(16)](arg0_1, buf3, buf10, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_5[grid(64)
](buf10, arg0_1, buf3, buf11, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf10
buf12 = buf5
del buf5
triton_poi_fused_eye_masked_fill_ne_sum_6[grid(4)](arg0_1, buf12, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf13 = reinterpret_tensor(buf3, (4, 4), (4, 1), 0)
del buf3
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_7[
grid(16)](arg0_1, buf12, buf13, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf14 = torch.ops.aten.linalg_inv_ex.default(buf13)
buf15 = buf14[0]
del buf14
buf17 = buf13
del buf13
triton_poi_fused_add_diag_embed_8[grid(16)](arg0_1, buf8, buf11,
buf17, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf18 = buf11
del buf11
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_9[grid(64)
](buf18, buf17, arg0_1, buf8, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf17
buf19 = buf12
del buf12
triton_poi_fused_eye_masked_fill_ne_sum_10[grid(4)](arg0_1, buf19,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf20 = reinterpret_tensor(buf8, (4, 4), (4, 1), 0)
del buf8
triton_poi_fused_add_diag_embed_diagonal_copy_exp_eye_masked_fill_ne_neg_11[
grid(16)](arg0_1, buf19, buf20, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf19
buf21 = torch.ops.aten.linalg_inv_ex.default(buf20)
buf22 = buf21[0]
del buf21
buf24 = buf20
del buf20
triton_poi_fused_add_diag_embed_12[grid(16)](arg0_1, buf15, buf18,
buf24, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf25 = buf18
del buf18
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_13[grid(64)
](buf25, buf24, arg0_1, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf15
buf26 = buf24
del buf24
triton_poi_fused_add_diag_embed_14[grid(16)](arg0_1, buf22, buf25,
buf26, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf27 = buf25
del buf25
triton_poi_fused_add_diag_embed_exp_fill_lift_fresh_mul_sub_15[grid(64)
](buf27, buf26, arg0_1, buf22, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del arg0_1
del buf22
del buf26
return buf27,
class MatrixTreeNew(nn.Module):
"""Implementation of the matrix-tree theorem for computing marginals
of non-projective dependency parsing. This attention layer is used
in the paper "Learning Structured Text Representations"
:cite:`DBLP:journals/corr/LiuL17d`.
"""
def __init__(self, eps=1e-05):
self.eps = eps
super(MatrixTreeNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
NaomiatLibrary/OpenNMT-kpg-release
|
MatrixTree
| false
| 919
|
[
"MIT"
] | 0
|
1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
https://github.com/NaomiatLibrary/OpenNMT-kpg-release/tree/1da3468d7dad22529a77f3526abf9b373bd3dc4c
|
JointsMSELossNoReduction
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class JointsMSELossNoReduction(nn.Module):
def __init__(self, use_target_weight, logger):
super(JointsMSELossNoReduction, self).__init__()
self.criterion = lambda x, y: ((x - y) ** 2).sum(1).unsqueeze(1)
self.use_target_weight = use_target_weight
self.logger = logger
def forward(self, output, target, target_weight):
batch_size = output.size(0)
num_joints = output.size(1)
heatmaps_pred = output.reshape((batch_size, num_joints, -1)).split(1, 1
)
heatmaps_gt = target.reshape((batch_size, num_joints, -1)).split(1, 1)
loss = []
for idx in range(num_joints):
heatmap_pred = heatmaps_pred[idx].squeeze()
heatmap_gt = heatmaps_gt[idx].squeeze()
if self.use_target_weight:
heatmap_pred = heatmap_pred.mul(target_weight[:, idx])
loss_val = self.criterion(heatmap_pred, heatmap_gt.mul(
target_weight[:, idx]))
loss.append(0.5 * loss_val)
else:
loss.append(0.5 * self.criterion(heatmap_pred, heatmap_gt))
loss = torch.cat(loss, dim=1)
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'use_target_weight': 4, 'logger': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_pow_sub_sum_0(in_ptr0, in_ptr1, in_ptr2, 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 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + 16 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp9 = tl.load(in_ptr0 + 4)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp11 = tl.load(in_ptr1 + (1 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + 4)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp19 = tl.load(in_ptr0 + 8)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp21 = tl.load(in_ptr1 + (2 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + 8)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK])
tmp29 = tl.load(in_ptr0 + 12)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp31 = tl.load(in_ptr1 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr2 + 12)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp5 * tmp2
tmp7 = tmp3 - tmp6
tmp8 = tmp7 * tmp7
tmp12 = tmp10 * tmp11
tmp15 = tmp14 * tmp11
tmp16 = tmp12 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp8 + tmp17
tmp22 = tmp20 * tmp21
tmp25 = tmp24 * tmp21
tmp26 = tmp22 - tmp25
tmp27 = tmp26 * tmp26
tmp28 = tmp18 + tmp27
tmp32 = tmp30 * tmp31
tmp35 = tmp34 * tmp31
tmp36 = tmp32 - tmp35
tmp37 = tmp36 * tmp36
tmp38 = tmp28 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_mul_pow_sub_sum_1(in_ptr0, in_ptr1, in_ptr2, 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 + 1)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr2 + 1)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp9 = tl.load(in_ptr0 + 5)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp11 = tl.load(in_ptr1 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + 5)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp19 = tl.load(in_ptr0 + 9)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp21 = tl.load(in_ptr1 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + 9)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK])
tmp29 = tl.load(in_ptr0 + 13)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp31 = tl.load(in_ptr1 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr2 + 13)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp5 * tmp2
tmp7 = tmp3 - tmp6
tmp8 = tmp7 * tmp7
tmp12 = tmp10 * tmp11
tmp15 = tmp14 * tmp11
tmp16 = tmp12 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp8 + tmp17
tmp22 = tmp20 * tmp21
tmp25 = tmp24 * tmp21
tmp26 = tmp22 - tmp25
tmp27 = tmp26 * tmp26
tmp28 = tmp18 + tmp27
tmp32 = tmp30 * tmp31
tmp35 = tmp34 * tmp31
tmp36 = tmp32 - tmp35
tmp37 = tmp36 * tmp36
tmp38 = tmp28 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_mul_pow_sub_sum_2(in_ptr0, in_ptr1, in_ptr2, 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 + 2)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + (8 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr2 + 2)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp9 = tl.load(in_ptr0 + 6)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp11 = tl.load(in_ptr1 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + 6)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp19 = tl.load(in_ptr0 + 10)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp21 = tl.load(in_ptr1 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + 10)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK])
tmp29 = tl.load(in_ptr0 + 14)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp31 = tl.load(in_ptr1 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr2 + 14)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp5 * tmp2
tmp7 = tmp3 - tmp6
tmp8 = tmp7 * tmp7
tmp12 = tmp10 * tmp11
tmp15 = tmp14 * tmp11
tmp16 = tmp12 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp8 + tmp17
tmp22 = tmp20 * tmp21
tmp25 = tmp24 * tmp21
tmp26 = tmp22 - tmp25
tmp27 = tmp26 * tmp26
tmp28 = tmp18 + tmp27
tmp32 = tmp30 * tmp31
tmp35 = tmp34 * tmp31
tmp36 = tmp32 - tmp35
tmp37 = tmp36 * tmp36
tmp38 = tmp28 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_mul_pow_sub_sum_3(in_ptr0, in_ptr1, in_ptr2, 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 + 3)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr2 + 3)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp9 = tl.load(in_ptr0 + 7)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp11 = tl.load(in_ptr1 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + 7)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp19 = tl.load(in_ptr0 + 11)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp21 = tl.load(in_ptr1 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + 11)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK])
tmp29 = tl.load(in_ptr0 + 15)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp31 = tl.load(in_ptr1 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr2 + 15)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp5 * tmp2
tmp7 = tmp3 - tmp6
tmp8 = tmp7 * tmp7
tmp12 = tmp10 * tmp11
tmp15 = tmp14 * tmp11
tmp16 = tmp12 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp8 + tmp17
tmp22 = tmp20 * tmp21
tmp25 = tmp24 * tmp21
tmp26 = tmp22 - tmp25
tmp27 = tmp26 * tmp26
tmp28 = tmp18 + tmp27
tmp32 = tmp30 * tmp31
tmp35 = tmp34 * tmp31
tmp36 = tmp32 - tmp35
tmp37 = tmp36 * tmp36
tmp38 = tmp28 + tmp37
tl.store(out_ptr0 + x0, tmp38, xmask)
@triton.jit
def triton_poi_fused_cat_4(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
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 = 0.5
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], 2, tl.int64)
tmp12 = tmp0 < tmp11
tmp13 = tmp10 & tmp12
tmp14 = tl.load(in_ptr1 + x1, tmp13 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tmp14 * tmp6
tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
tmp17 = tl.where(tmp13, tmp15, tmp16)
tmp18 = tmp0 >= tmp11
tmp19 = tl.full([1], 3, tl.int64)
tmp20 = tmp0 < tmp19
tmp21 = tmp18 & tmp20
tmp22 = tl.load(in_ptr2 + x1, tmp21 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp23 = tmp22 * tmp6
tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype)
tmp25 = tl.where(tmp21, tmp23, tmp24)
tmp26 = tmp0 >= tmp19
tl.full([1], 4, tl.int64)
tmp29 = tl.load(in_ptr3 + x1, tmp26 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp30 = tmp29 * tmp6
tmp31 = tl.full(tmp30.shape, 0.0, tmp30.dtype)
tmp32 = tl.where(tmp26, tmp30, tmp31)
tmp33 = tl.where(tmp21, tmp25, tmp32)
tmp34 = tl.where(tmp13, tmp17, tmp33)
tmp35 = tl.where(tmp4, tmp9, tmp34)
tl.store(out_ptr0 + x2, tmp35, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_pow_sub_sum_0[grid(4)](arg0_1, arg2_1, arg1_1,
buf0, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_pow_sub_sum_1[grid(4)](arg0_1, arg2_1, arg1_1,
buf1, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_pow_sub_sum_2[grid(4)](arg0_1, arg2_1, arg1_1,
buf2, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_pow_sub_sum_3[grid(4)](arg0_1, arg2_1, arg1_1,
buf3, 4, XBLOCK=4, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_cat_4[grid(16)](buf0, buf1, buf2, buf3, buf4, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf0
del buf1
del buf2
del buf3
return buf4,
class JointsMSELossNoReductionNew(nn.Module):
def __init__(self, use_target_weight, logger):
super(JointsMSELossNoReductionNew, self).__init__()
self.criterion = lambda x, y: ((x - y) ** 2).sum(1).unsqueeze(1)
self.use_target_weight = use_target_weight
self.logger = logger
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]
|
NiteshBharadwaj/ignoringhumanpose
|
JointsMSELossNoReduction
| false
| 920
|
[
"MIT"
] | 0
|
1fb7a063fded9cff18f7de4e1d71845983077256
|
https://github.com/NiteshBharadwaj/ignoringhumanpose/tree/1fb7a063fded9cff18f7de4e1d71845983077256
|
Attention
|
import math
import torch
import torch.nn
import torch.optim
from torch.nn import functional as F
from torch import nn
class Attention(nn.Module):
def __init__(self, hidden_size):
super(Attention, self).__init__()
self.hidden_size = hidden_size
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.rand(hidden_size))
stdv = 1.0 / math.sqrt(self.v.size(0))
self.v.data.uniform_(-stdv, stdv)
def forward(self, hidden, encoder_outputs):
timestep = encoder_outputs.size(0)
h = hidden.repeat(timestep, 1, 1).transpose(0, 1)
encoder_outputs = encoder_outputs.transpose(0, 1)
attn_energies = self.score(h, encoder_outputs)
return F.relu(attn_energies).unsqueeze(1)
def score(self, hidden, encoder_outputs):
energy = F.softmax(self.attn(torch.cat([hidden, encoder_outputs], 2
)), dim=2)
energy = energy.transpose(1, 2)
v = self.v.repeat(encoder_outputs.size(0), 1).unsqueeze(1)
energy = torch.bmm(v, energy)
return energy.squeeze(1)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn
import torch.optim
from torch.nn import functional as F
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(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
x2 = xindex // 32
x1 = xindex // 8 % 4
x3 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x2 + 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 * x2 + 16 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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_repeat_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 % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_4(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.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, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 8), (8, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](primals_2, primals_1, buf0, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(buf0, (16, 8), (
8, 1), 0), reinterpret_tensor(primals_3, (8, 4), (1, 8), 0),
alpha=1, beta=1, out=buf1)
del primals_3
del primals_4
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused__softmax_2[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_repeat_3[grid(16)](primals_5, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (4, 1, 4), (4, 0, 1), 0
), reinterpret_tensor(buf3, (4, 4, 4), (16, 1, 4), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4), (4, 1), 0)
del buf5
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_4[grid(16)](buf6, buf7, 16,
XBLOCK=16, num_warps=1, num_stages=1)
return reinterpret_tensor(buf6, (4, 1, 4), (4, 4, 1), 0
), reinterpret_tensor(buf0, (16, 8), (8, 1), 0
), buf3, buf7, reinterpret_tensor(buf4, (4, 4, 1), (4, 1, 4), 0)
class AttentionNew(nn.Module):
def __init__(self, hidden_size):
super(AttentionNew, self).__init__()
self.hidden_size = hidden_size
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.rand(hidden_size))
stdv = 1.0 / math.sqrt(self.v.size(0))
self.v.data.uniform_(-stdv, stdv)
def score(self, hidden, encoder_outputs):
energy = F.softmax(self.attn(torch.cat([hidden, encoder_outputs], 2
)), dim=2)
energy = energy.transpose(1, 2)
v = self.v.repeat(encoder_outputs.size(0), 1).unsqueeze(1)
energy = torch.bmm(v, energy)
return energy.squeeze(1)
def forward(self, input_0, input_1):
primals_4 = self.v
primals_3 = self.attn.weight
primals_5 = self.attn.bias
primals_2 = input_0
primals_1 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
OneAdder/hseling-repo-chukchi-type
|
Attention
| false
| 921
|
[
"MIT"
] | 0
|
5f5e651510bca7cfb89dc2e98b07bcc63b6330a4
|
https://github.com/OneAdder/hseling-repo-chukchi-type/tree/5f5e651510bca7cfb89dc2e98b07bcc63b6330a4
|
myLoss3
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class myLoss3(nn.Module):
def __init__(self, alpha=1.0, beta=1.0):
super(myLoss3, self).__init__()
self.alpha = alpha
self.beta = beta
def forward(self, sent_probs, doc_probs, event_probs, sent_targets,
doc_targets, event_targets):
loss_1 = F.mse_loss(sent_probs, sent_targets)
loss_2 = F.mse_loss(doc_probs, doc_targets)
loss_3 = F.mse_loss(event_probs, event_targets)
norm = 1.0 + self.alpha + self.beta
loss = (loss_1 + self.alpha * loss_2 + self.beta * loss_3) / norm
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]),
torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mse_loss_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp7 = tl.load(in_ptr2 + r0, None)
tmp8 = tl.load(in_ptr3 + r0, None)
tmp14 = tl.load(in_ptr4 + r0, None)
tmp15 = tl.load(in_ptr5 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp9 = tmp7 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tl.broadcast_to(tmp10, [RBLOCK])
tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0))
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tl.broadcast_to(tmp17, [RBLOCK])
tmp20 = triton_helpers.promote_to_tensor(tl.sum(tmp18, 0))
tmp21 = 256.0
tmp22 = tmp6 / tmp21
tmp23 = tmp13 / tmp21
tmp24 = 1.0
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = tmp20 / tmp21
tmp28 = tmp27 * tmp24
tmp29 = tmp26 + tmp28
tmp30 = 0.3333333333333333
tmp31 = tmp29 * tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp31, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg4_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg5_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mse_loss_mul_0[grid(1)](buf3, arg1_1,
arg0_1, arg3_1, arg2_1, arg5_1, arg4_1, 1, 256, num_warps=2,
num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
del arg4_1
del arg5_1
return buf3,
class myLoss3New(nn.Module):
def __init__(self, alpha=1.0, beta=1.0):
super(myLoss3New, self).__init__()
self.alpha = alpha
self.beta = beta
def forward(self, input_0, input_1, input_2, input_3, input_4, input_5):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
arg4_1 = input_4
arg5_1 = input_5
output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1])
return output[0]
|
PKULiuHui/LiveBlogSum
|
myLoss3
| false
| 924
|
[
"MIT"
] | 0
|
b6a22521ee454e649981d70ddca6c89a1bac5a4c
|
https://github.com/PKULiuHui/LiveBlogSum/tree/b6a22521ee454e649981d70ddca6c89a1bac5a4c
|
GraphLearner
|
from torch.nn import Module
import torch
from torch.nn.modules.module import Module
import torch.nn as nn
import torch.nn.functional as F
class GraphLearner(Module):
def __init__(self, in_feature_dim, combined_feature_dim, n_obj, dropout=0.0
):
"""
eq(1): A=EE^T, build adj matrix
## Variables:
- in_feature_dim: dimensionality of input features
- combined_feature_dim: dimensionality of the joint hidden embedding
- k: number of graph nodes/objects on the image
"""
super(GraphLearner, self).__init__()
self.in_dim = in_feature_dim
self.combined_dim = combined_feature_dim
self.n_obj = n_obj
self.edge_layer_1 = nn.Linear(in_feature_dim, combined_feature_dim)
self.edge_layer_2 = nn.Linear(combined_feature_dim,
combined_feature_dim)
self.dropout = nn.Dropout(p=dropout)
self.edge_layer_1 = nn.utils.weight_norm(self.edge_layer_1)
self.edge_layer_2 = nn.utils.weight_norm(self.edge_layer_2)
def forward(self, graph_nodes):
"""
## Inputs:
- graph_nodes (batch_size, K, in_feat_dim): input features
## Returns:
- adjacency matrix (batch_size, K, K)
"""
h = self.edge_layer_1(graph_nodes)
h = F.relu(h)
h = self.edge_layer_2(h)
h = F.relu(h)
h = h.view(-1, self.n_obj, self.combined_dim)
adjacency_matrix = torch.matmul(h, h.transpose(1, 2))
return adjacency_matrix
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_feature_dim': 4, 'combined_feature_dim': 4, 'n_obj': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch.nn import Module
from torch.nn.modules.module import Module
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__weight_norm_interface_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = libdevice.sqrt(tmp10)
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused__weight_norm_interface_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.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, 1), (1, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (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, 1), (1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__weight_norm_interface_0[grid(4)](primals_2, buf0,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__weight_norm_interface_1[grid(16)](primals_2,
primals_1, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_4, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (4, 4), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
triton_poi_fused__weight_norm_interface_0[grid(4)](primals_6, buf3,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__weight_norm_interface_1[grid(16)](primals_6,
primals_5, buf3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf5 = 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_2[grid(256)](buf5,
primals_3, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (64, 4), (4, 1), 0),
reinterpret_tensor(buf4, (4, 4), (1, 4), 0), out=buf6)
buf7 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf6
triton_poi_fused_relu_3[grid(256)](buf7, primals_7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf8 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf7, (16, 4, 4), (16, 1, 4), 0), out=buf8)
return (buf8, buf1, buf4, primals_1, primals_2, primals_5, primals_6,
buf0, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0), buf3,
reinterpret_tensor(buf5, (64, 4), (4, 1), 0), buf7, buf4, buf9)
class GraphLearnerNew(Module):
def __init__(self, in_feature_dim, combined_feature_dim, n_obj, dropout=0.0
):
"""
eq(1): A=EE^T, build adj matrix
## Variables:
- in_feature_dim: dimensionality of input features
- combined_feature_dim: dimensionality of the joint hidden embedding
- k: number of graph nodes/objects on the image
"""
super(GraphLearnerNew, self).__init__()
self.in_dim = in_feature_dim
self.combined_dim = combined_feature_dim
self.n_obj = n_obj
self.edge_layer_1 = nn.Linear(in_feature_dim, combined_feature_dim)
self.edge_layer_2 = nn.Linear(combined_feature_dim,
combined_feature_dim)
self.dropout = nn.Dropout(p=dropout)
self.edge_layer_1 = nn.utils.weight_norm(self.edge_layer_1)
self.edge_layer_2 = nn.utils.weight_norm(self.edge_layer_2)
def forward(self, input_0):
primals_3 = self.edge_layer_1.bias
primals_1 = self.edge_layer_1.weight_g
primals_2 = self.edge_layer_1.weight_v
primals_7 = self.edge_layer_2.bias
primals_5 = self.edge_layer_2.weight_g
primals_6 = self.edge_layer_2.weight_v
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Originofamonia/vqa-project
|
GraphLearner
| false
| 925
|
[
"Apache-2.0"
] | 0
|
cf67b62ddf5732881dfb4278478accfd15c4df6d
|
https://github.com/Originofamonia/vqa-project/tree/cf67b62ddf5732881dfb4278478accfd15c4df6d
|
AE_Net
|
import torch
from torch.optim import *
from torch import nn
class AE_Net(nn.Module):
"""docstring for AE_Net."""
def __init__(self, input_shape):
super(AE_Net, self).__init__()
self.encoder_hidden_layer = nn.Linear(in_features=input_shape,
out_features=128)
self.encoder_output_layer = nn.Linear(in_features=128, out_features=64)
self.decoder_hidden_layer = nn.Linear(in_features=64, out_features=128)
self.decoder_output_layer = nn.Linear(in_features=128, out_features
=input_shape)
def forward(self, features):
activation = self.encoder_hidden_layer(features)
activation = torch.relu(activation)
state_logit = self.encoder_output_layer(activation)
code = torch.relu(state_logit)
activation = self.decoder_hidden_layer(code)
activation = torch.relu(activation)
activation = self.decoder_output_layer(activation)
reconstructed = activation
return reconstructed, state_logit
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': 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.optim import *
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_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 + x0, None)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(out_ptr0 + x0, tmp2, None)
tl.store(out_ptr1 + x0, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (128, 4), (4, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 128), (128, 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, (4, 128), (128, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 128), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
buf9 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1,
primals_2, buf9, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_4, (128, 64), (1, 128),
0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.
float32)
buf8 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_1[grid(4096)](buf2, buf3,
buf8, 4096, XBLOCK=128, num_warps=4, num_stages=1)
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
buf7 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf5,
primals_7, buf7, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_8, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf6)
del primals_9
return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 128), (128, 1), 0
), reinterpret_tensor(buf3, (64, 64), (64, 1), 0), reinterpret_tensor(
buf5, (64, 128), (128, 1), 0
), primals_8, buf7, primals_6, buf8, primals_4, buf9
class AE_NetNew(nn.Module):
"""docstring for AE_Net."""
def __init__(self, input_shape):
super(AE_NetNew, self).__init__()
self.encoder_hidden_layer = nn.Linear(in_features=input_shape,
out_features=128)
self.encoder_output_layer = nn.Linear(in_features=128, out_features=64)
self.decoder_hidden_layer = nn.Linear(in_features=64, out_features=128)
self.decoder_output_layer = nn.Linear(in_features=128, out_features
=input_shape)
def forward(self, input_0):
primals_1 = self.encoder_hidden_layer.weight
primals_2 = self.encoder_hidden_layer.bias
primals_4 = self.encoder_output_layer.weight
primals_5 = self.encoder_output_layer.bias
primals_6 = self.decoder_hidden_layer.weight
primals_7 = self.decoder_hidden_layer.bias
primals_8 = self.decoder_output_layer.weight
primals_9 = self.decoder_output_layer.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0], output[1]
|
Paratra/IoTAnalytics_pub
|
AE_Net
| false
| 926
|
[
"MIT"
] | 0
|
8c1d02b60ef609c3cba654ce4a5568c39fc63edf
|
https://github.com/Paratra/IoTAnalytics_pub/tree/8c1d02b60ef609c3cba654ce4a5568c39fc63edf
|
NormedLinear
|
import torch
import torch.nn.functional as F
from torch import nn
class NormedLinear(nn.Linear):
"""Normalized Linear Layer.
Args:
tempeature (float, optional): Tempeature term. Default to 20.
power (int, optional): Power term. Default to 1.0.
eps (float, optional): The minimal value of divisor to
keep numerical stability. Default to 1e-6.
"""
def __init__(self, *args, tempearture=20, power=1.0, eps=1e-06, **kwargs):
super(NormedLinear, self).__init__(*args, **kwargs)
self.tempearture = tempearture
self.power = power
self.eps = eps
self.init_weights()
def init_weights(self):
nn.init.normal_(self.weight, mean=0, std=0.01)
if self.bias is not None:
nn.init.constant_(self.bias, 0)
def forward(self, x):
weight_ = self.weight / (self.weight.norm(dim=1, keepdim=True).pow(
self.power) + self.eps)
x_ = x / (x.norm(dim=1, keepdim=True).pow(self.power) + self.eps)
x_ = x_ * self.tempearture
return F.linear(x_, weight_, 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.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_linalg_vector_norm_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
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 = 1e-06
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tmp16 = 20.0
tmp17 = tmp15 * tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
@triton.jit
def triton_poi_fused_add_div_linalg_vector_norm_pow_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')
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-06
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, 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)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_linalg_vector_norm_mul_pow_0[grid(256)](
primals_2, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_div_linalg_vector_norm_pow_1[grid(16)](primals_1,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(buf1, (4, 4), (1, 4), 0), alpha=1,
beta=1, out=buf2)
del buf1
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class NormedLinearNew(nn.Linear):
"""Normalized Linear Layer.
Args:
tempeature (float, optional): Tempeature term. Default to 20.
power (int, optional): Power term. Default to 1.0.
eps (float, optional): The minimal value of divisor to
keep numerical stability. Default to 1e-6.
"""
def __init__(self, *args, tempearture=20, power=1.0, eps=1e-06, **kwargs):
super(NormedLinearNew, self).__init__(*args, **kwargs)
self.tempearture = tempearture
self.power = power
self.eps = eps
self.init_weights()
def init_weights(self):
nn.init.normal_(self.weight, mean=0, std=0.01)
if self.bias is not None:
nn.init.constant_(self.bias, 0)
def forward(self, input_0):
primals_1 = self.weight
primals_3 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Parskatt/mmdetection
|
NormedLinear
| false
| 927
|
[
"Apache-2.0"
] | 0
|
ee4cfa29e7f479b2454b1f1355f8c05be62d8466
|
https://github.com/Parskatt/mmdetection/tree/ee4cfa29e7f479b2454b1f1355f8c05be62d8466
|
NormedConv2d
|
import torch
from torch import nn
class NormedConv2d(nn.Conv2d):
"""Normalized Conv2d Layer.
Args:
tempeature (float, optional): Tempeature term. Default to 20.
power (int, optional): Power term. Default to 1.0.
eps (float, optional): The minimal value of divisor to
keep numerical stability. Default to 1e-6.
norm_over_kernel (bool, optional): Normalize over kernel.
Default to False.
"""
def __init__(self, *args, tempearture=20, power=1.0, eps=1e-06,
norm_over_kernel=False, **kwargs):
super(NormedConv2d, self).__init__(*args, **kwargs)
self.tempearture = tempearture
self.power = power
self.norm_over_kernel = norm_over_kernel
self.eps = eps
def forward(self, x):
if not self.norm_over_kernel:
weight_ = self.weight / (self.weight.norm(dim=1, keepdim=True).
pow(self.power) + self.eps)
else:
weight_ = self.weight / (self.weight.view(self.weight.size(0),
-1).norm(dim=1, keepdim=True).pow(self.power)[..., None,
None] + self.eps)
x_ = x / (x.norm(dim=1, keepdim=True).pow(self.power) + self.eps)
x_ = x_ * self.tempearture
if hasattr(self, 'conv2d_forward'):
x_ = self.conv2d_forward(x_, weight_)
elif torch.__version__ >= '1.8':
x_ = self._conv_forward(x_, weight_, self.bias)
else:
x_ = self._conv_forward(x_, weight_)
return x_
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_linalg_vector_norm_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
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 = 1e-06
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x3, tmp15, xmask)
@triton.jit
def triton_poi_fused_add_div_linalg_vector_norm_mul_pow_1(in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = 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-06
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tmp16 = 20.0
tmp17 = tmp15 * tmp16
tl.store(out_ptr0 + x3, tmp17, 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)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_linalg_vector_norm_pow_0[grid(256)](primals_1,
buf0, 256, XBLOCK=256, 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_linalg_vector_norm_mul_pow_1[grid(256)](
primals_2, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, buf0, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1, 1), (4, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_2[grid(16)](buf3, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return buf3, primals_1, buf0, buf1
class NormedConv2dNew(nn.Conv2d):
"""Normalized Conv2d Layer.
Args:
tempeature (float, optional): Tempeature term. Default to 20.
power (int, optional): Power term. Default to 1.0.
eps (float, optional): The minimal value of divisor to
keep numerical stability. Default to 1e-6.
norm_over_kernel (bool, optional): Normalize over kernel.
Default to False.
"""
def __init__(self, *args, tempearture=20, power=1.0, eps=1e-06,
norm_over_kernel=False, **kwargs):
super(NormedConv2dNew, self).__init__(*args, **kwargs)
self.tempearture = tempearture
self.power = power
self.norm_over_kernel = norm_over_kernel
self.eps = eps
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]
|
Parskatt/mmdetection
|
NormedConv2d
| false
| 928
|
[
"Apache-2.0"
] | 0
|
ee4cfa29e7f479b2454b1f1355f8c05be62d8466
|
https://github.com/Parskatt/mmdetection/tree/ee4cfa29e7f479b2454b1f1355f8c05be62d8466
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
class Net(nn.Module):
def __init__(self, num_rej=0):
super(Net, self).__init__()
self.num_rej = num_rej + 1
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10 + self.num_rej)
self.loss = lambda g: -F.logsigmoid(-g)
def forward(self, x):
h = self.pool(F.relu(self.conv1(x)))
h = self.pool(F.relu(self.conv2(h)))
h = h.view(-1, 16 * 5 * 5)
h = F.relu(self.fc1(h))
h = F.relu(self.fc2(h))
h = self.fc3(h)
h1 = h[:, :-self.num_rej]
h2 = h[:, -self.num_rej:]
return h, h1, h2
def pconf(self, hidden, t, loss, rate_all=1.0, rate_inv=0.8):
for i in range(self.num_rej):
if i == 0:
h = hidden[:, i]
loss += torch.mean(self.loss(h) + (1 - rate_all) / rate_all *
self.loss(-h))
else:
h = hidden[:, i]
temp = (t == i).type(torch.FloatTensor)
if type(rate_inv) == float:
temp *= rate_inv
else:
temp *= rate_inv[i]
loss += torch.mean((self.loss(h) + (1 - rate_inv) /
rate_inv * self.loss(-h)) * temp)
return loss
def get_inputs():
return [torch.rand([4, 3, 32, 32])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 18816
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 784 % 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_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4704
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 14
x3 = xindex // 14
x2 = xindex // 1176
x4 = xindex % 1176
tmp0 = tl.load(in_ptr0 + (2 * x0 + 56 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 56 * x3), xmask, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (28 + 2 * x0 + 56 * x3), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (29 + 2 * x0 + 56 * x3), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (x4 + 1184 * x2), tmp6, xmask)
tl.store(out_ptr1 + (x4 + 1280 * x2), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 100 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 20 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 20 * x1), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (10 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (11 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 480
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 120
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 336
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 84
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (6, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (6,), (1,))
assert_size_stride(primals_3, (4, 3, 32, 32), (3072, 1024, 32, 1))
assert_size_stride(primals_4, (16, 6, 5, 5), (150, 25, 5, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (120, 400), (400, 1))
assert_size_stride(primals_7, (120,), (1,))
assert_size_stride(primals_8, (84, 120), (120, 1))
assert_size_stride(primals_9, (84,), (1,))
assert_size_stride(primals_10, (11, 84), (84, 1))
assert_size_stride(primals_11, (11,), (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, 6, 28, 28), (4704, 784, 28, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(18816)](buf1, primals_2,
18816, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 6, 14, 14), (1184, 196, 14, 1), torch
.float32)
buf3 = empty_strided_cuda((4, 6, 14, 14), (1280, 196, 14, 1), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(4704)](buf1, buf2,
buf3, 4704, XBLOCK=128, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 16, 10, 10), (1600, 100, 10, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(6400)](buf5, primals_5,
6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.int8)
buf7 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.float32
)
triton_poi_fused_max_pool2d_with_indices_3[grid(1600)](buf5, buf6,
buf7, 1600, XBLOCK=256, num_warps=4, num_stages=1)
buf8 = empty_strided_cuda((4, 120), (120, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 400), (400, 1), 0),
reinterpret_tensor(primals_6, (400, 120), (1, 400), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(480)](buf9, primals_7, 480, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 84), (84, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_8, (120, 84), (1,
120), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(336)](buf11, primals_9, 336, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 11), (11, 1), torch.float32)
extern_kernels.addmm(primals_11, buf11, reinterpret_tensor(
primals_10, (84, 11), (1, 84), 0), alpha=1, beta=1, out=buf12)
del primals_11
return (buf12, reinterpret_tensor(buf12, (4, 10), (11, 1), 0),
reinterpret_tensor(buf12, (4, 1), (11, 1), 10), primals_1,
primals_3, primals_4, buf1, buf2, buf3, buf5, buf6,
reinterpret_tensor(buf7, (4, 400), (400, 1), 0), buf9, buf11,
primals_10, primals_8, primals_6)
class NetNew(nn.Module):
def __init__(self, num_rej=0):
super(NetNew, self).__init__()
self.num_rej = num_rej + 1
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10 + self.num_rej)
self.loss = lambda g: -F.logsigmoid(-g)
def pconf(self, hidden, t, loss, rate_all=1.0, rate_inv=0.8):
for i in range(self.num_rej):
if i == 0:
h = hidden[:, i]
loss += torch.mean(self.loss(h) + (1 - rate_all) / rate_all *
self.loss(-h))
else:
h = hidden[:, i]
temp = (t == i).type(torch.FloatTensor)
if type(rate_inv) == float:
temp *= rate_inv
else:
temp *= rate_inv[i]
loss += torch.mean((self.loss(h) + (1 - rate_inv) /
rate_inv * self.loss(-h)) * temp)
return loss
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_10 = self.fc3.weight
primals_11 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1], output[2]
|
NlGG/Rejection
|
Net
| false
| 929
|
[
"MIT"
] | 0
|
5f7cc64b71dacc2eb794b3f7c48390457e363cc5
|
https://github.com/NlGG/Rejection/tree/5f7cc64b71dacc2eb794b3f7c48390457e363cc5
|
BPMLLLoss
|
import torch
from torch import Tensor
class BPMLLLoss(torch.nn.Module):
def __init__(self, bias=(1, 1)):
super(BPMLLLoss, self).__init__()
self.bias = bias
assert len(self.bias) == 2 and all(map(lambda x: isinstance(x, int) and
x > 0, bias)), 'bias must be positive integers'
def forward(self, c: 'Tensor', y: 'Tensor') ->Tensor:
"""
compute the loss, which has the form:
L = \\sum_{i=1}^{m} \\frac{1}{|Y_i| \\cdot |\\bar{Y}_i|} \\sum_{(k, l) \\in Y_i \\times \\bar{Y}_i} \\exp{-c^i_k+c^i_l}
:param c: prediction tensor, size: batch_size * n_labels
:param y: target tensor, size: batch_size * n_labels
:return: size: scalar tensor
"""
c = torch.sigmoid(c)
y = y.float()
y_bar = -y + 1
y_norm = torch.pow(y.sum(dim=(1,)), self.bias[0])
y_bar_norm = torch.pow(y_bar.sum(dim=(1,)), self.bias[1])
assert torch.all(y_norm != 0) or torch.all(y_bar_norm != 0
), 'an instance cannot have none or all the labels'
return torch.mean(1 / torch.mul(y_norm, y_bar_norm) * self.
pairwise_sub_exp(y, y_bar, c))
def pairwise_sub_exp(self, y: 'Tensor', y_bar: 'Tensor', c: 'Tensor'
) ->Tensor:
"""
compute \\sum_{(k, l) \\in Y_i \\times \\bar{Y}_i} \\exp{-c^i_k+c^i_l}
"""
truth_matrix = y.unsqueeze(2).float() @ y_bar.unsqueeze(1).float()
exp_matrix = torch.exp(c.unsqueeze(1) - c.unsqueeze(2))
return torch.mul(truth_matrix, exp_matrix).sum(dim=(1, 2))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import Tensor
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_neg_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = -tmp0
tmp2 = 1.0
tmp3 = tmp1 + tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_sum_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_sigmoid_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_per_fused_all_ne_sum_3(in_out_ptr0, in_ptr0, out_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
r2 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp3 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.0
tmp8 = tmp6 != tmp7
tmp9 = tmp8 == 0
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = triton_helpers.any(tmp10, 1)[:, None]
tmp13 = tmp12 == 0
tl.store(out_ptr0 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp6, None)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 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_add_neg_0[grid(256)](arg1_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sum_1[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_2[grid(256)](arg0_1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((), (), torch.bool)
buf5 = buf4
del buf4
triton_per_fused_all_ne_sum_3[grid(1)](buf5, arg1_1, buf3, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
return buf1, buf3, buf0, arg1_1, buf2, buf5
class BPMLLLossNew(torch.nn.Module):
def __init__(self, bias=(1, 1)):
super(BPMLLLossNew, self).__init__()
self.bias = bias
assert len(self.bias) == 2 and all(map(lambda x: isinstance(x, int) and
x > 0, bias)), 'bias must be positive integers'
def pairwise_sub_exp(self, y: 'Tensor', y_bar: 'Tensor', c: 'Tensor'
) ->Tensor:
"""
compute \\sum_{(k, l) \\in Y_i \\times \\bar{Y}_i} \\exp{-c^i_k+c^i_l}
"""
truth_matrix = y.unsqueeze(2).float() @ y_bar.unsqueeze(1).float()
exp_matrix = torch.exp(c.unsqueeze(1) - c.unsqueeze(2))
return torch.mul(truth_matrix, exp_matrix).sum(dim=(1, 2))
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
PaulStryck/nih-chest-x-ray
|
BPMLLLoss
| false
| 931
|
[
"MIT"
] | 0
|
92bfef80f49e7e38ad8a0156be43f10879b3f737
|
https://github.com/PaulStryck/nih-chest-x-ray/tree/92bfef80f49e7e38ad8a0156be43f10879b3f737
|
FirstNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class FirstNet(nn.Module):
def __init__(self):
super(FirstNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=
3, padding=1, stride=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
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 % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (y0 + 64 * x2 + 262144 * y1), tmp4, ymask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 64
x1 = xindex // 64 % 32
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 8192 * x2), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 8192 * x2), None)
tmp3 = tl.load(in_ptr0 + (4096 + x0 + 128 * x1 + 8192 * x2), None)
tmp5 = tl.load(in_ptr0 + (4160 + x0 + 128 * x1 + 8192 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_4(in_ptr0, out_ptr0, out_ptr1,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 128
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x3 = xindex
y0 = yindex % 16
y4 = yindex // 16
y2 = yindex // 256
y5 = yindex % 256
y6 = yindex
tmp0 = tl.load(in_ptr0 + (x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (128 + x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (4096 + x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (4224 + x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1, 1], 1, tl.int8)
tmp9 = tl.full([1, 1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1, 1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1, 1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (y5 + 256 * x3 + 32768 * y2), tmp6, xmask)
tl.store(out_ptr1 + (x3 + 128 * y6), tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (64, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(8192, 9)](primals_4, buf0, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf1 = 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(buf1, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf2 = empty_strided_cuda((4, 64, 64, 64), (262144, 1, 4096, 64),
torch.float32)
triton_poi_fused_convolution_relu_1[grid(256, 4096)](buf1,
primals_2, buf2, 256, 4096, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf1
del primals_2
buf3 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.float32)
buf4 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_2[grid(262144)](buf2, buf3,
buf4, 262144, XBLOCK=512, num_warps=8, num_stages=1)
buf5 = extern_kernels.convolution(buf3, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 128, 32, 32), (131072, 1, 4096, 128))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_3[grid(524288)](buf6, primals_5,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf7 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
buf8 = empty_strided_cuda((4, 128, 16, 16), (32768, 1, 2048, 128),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_4[grid(1024, 128)](buf6,
buf7, buf8, 1024, 128, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
return buf7, primals_1, primals_3, buf0, buf2, buf3, buf4, buf6, buf8
class FirstNetNew(nn.Module):
def __init__(self):
super(FirstNetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=
3, padding=1, stride=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
PacktPublishing/Designing-Models-for-Responsible-AI
|
FirstNet
| false
| 932
|
[
"MIT"
] | 0
|
36b60f1e3e9db8b3d2db3ace873dbdee1b076b74
|
https://github.com/PacktPublishing/Designing-Models-for-Responsible-AI/tree/36b60f1e3e9db8b3d2db3ace873dbdee1b076b74
|
AsymmetricLoss
|
import torch
import torch.nn as nn
class AsymmetricLoss(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-08,
disable_torch_grad_focal_loss=False):
super(AsymmetricLoss, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
self.clip = clip
self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
self.eps = eps
def forward(self, x, y):
""""
Parameters
----------
x: input logits
y: targets (multi-label binarized vector)
"""
x_sigmoid = torch.sigmoid(x)
xs_pos = x_sigmoid
xs_neg = 1 - x_sigmoid
if self.clip is not None and self.clip > 0:
xs_neg = (xs_neg + self.clip).clamp(max=1)
los_pos = y * torch.log(xs_pos.clamp(min=self.eps))
los_neg = (1 - y) * torch.log(xs_neg.clamp(min=self.eps))
loss = los_pos + los_neg
if self.gamma_neg > 0 or self.gamma_pos > 0:
pt0 = xs_pos * y
pt1 = xs_neg * (1 - y)
pt = pt0 + pt1
one_sided_gamma = self.gamma_pos * y + self.gamma_neg * (1 - y)
one_sided_w = torch.pow(1 - pt, one_sided_gamma)
loss *= one_sided_w
return -loss.sum()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_log_mul_neg_pow_rsub_sigmoid_sum_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.sigmoid(tmp1)
tmp3 = 1e-08
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = tl_math.log(tmp4)
tmp6 = tmp0 * tmp5
tmp7 = 1.0
tmp8 = tmp7 - tmp0
tmp9 = tmp7 - tmp2
tmp10 = 0.05
tmp11 = tmp9 + tmp10
tmp12 = triton_helpers.minimum(tmp11, tmp7)
tmp13 = triton_helpers.maximum(tmp12, tmp3)
tmp14 = tl_math.log(tmp13)
tmp15 = tmp8 * tmp14
tmp16 = tmp6 + tmp15
tmp17 = tmp2 * tmp0
tmp18 = tmp12 * tmp8
tmp19 = tmp17 + tmp18
tmp20 = tmp7 - tmp19
tmp21 = tmp0 * tmp7
tmp22 = 4.0
tmp23 = tmp8 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = libdevice.pow(tmp20, tmp24)
tmp26 = tmp16 * tmp25
tmp27 = tl.broadcast_to(tmp26, [RBLOCK])
tmp29 = triton_helpers.promote_to_tensor(tl.sum(tmp27, 0))
tmp30 = -tmp29
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp30, 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_mul_neg_pow_rsub_sigmoid_sum_0[grid(1)](
buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class AsymmetricLossNew(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-08,
disable_torch_grad_focal_loss=False):
super(AsymmetricLossNew, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
self.clip = clip
self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
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]
|
Pepijnnn/MasterThesis
|
AsymmetricLoss
| false
| 933
|
[
"MIT"
] | 0
|
7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
https://github.com/Pepijnnn/MasterThesis/tree/7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
ConvBlockFixup
|
import torch
from torch import nn
class ConvBlockFixup(nn.Module):
def __init__(self, filter_width, input_filters, nb_filters, dilation):
super(ConvBlockFixup, self).__init__()
self.filter_width = filter_width
self.input_filters = input_filters
self.nb_filters = nb_filters
self.dilation = dilation
self.bias1a = nn.Parameter(torch.zeros(1))
self.conv1 = nn.Conv2d(self.input_filters, self.nb_filters, (self.
filter_width, 1), dilation=(self.dilation, 1), bias=False,
padding='same')
self.bias1b = nn.Parameter(torch.zeros(1))
self.relu = nn.ReLU(inplace=True)
self.bias2a = nn.Parameter(torch.zeros(1))
self.conv2 = nn.Conv2d(self.nb_filters, self.nb_filters, (self.
filter_width, 1), dilation=(self.dilation, 1), bias=False,
padding='same')
self.scale = nn.Parameter(torch.ones(1))
self.bias2b = nn.Parameter(torch.zeros(1))
def forward(self, x):
identity = x
out = self.conv1(x + self.bias1a)
out = self.relu(out + self.bias1b)
out = self.conv2(out + self.bias2a)
out = out * self.scale + self.bias2b
out += identity
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'filter_width': 4, 'input_filters': 4, 'nb_filters': 4,
'dilation': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_constant_pad_nd_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 5
x2 = xindex // 20
x3 = xindex % 20
x4 = xindex
tmp4 = tl.load(in_ptr1 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp0 = x1
tmp1 = tl.full([1], 4, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.load(in_ptr0 + (x3 + 16 * x2), tmp2 & xmask, other=0.0)
tmp6 = tmp3 + tmp5
tmp7 = tl.full(tmp6.shape, 0.0, tmp6.dtype)
tmp8 = tl.where(tmp2, tmp6, tmp7)
tl.store(out_ptr0 + x4, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_constant_pad_nd_relu_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 5
x2 = xindex // 20
x3 = xindex % 20
x4 = xindex
tmp4 = tl.load(in_ptr1 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp9 = tl.load(in_ptr2 + 0)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp0 = x1
tmp1 = tl.full([1], 4, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.load(in_ptr0 + (x3 + 16 * x2), tmp2 & xmask, other=0.0)
tmp6 = tmp3 + tmp5
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp11 = tmp8 + tmp10
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp2, tmp11, tmp12)
tl.store(out_ptr0 + x4, tmp13, xmask)
@triton.jit
def triton_poi_fused_add_mul_relu_threshold_backward_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr3 + x0, xmask)
tmp3 = tmp0 * tmp2
tmp6 = tmp3 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp11 = 0.0
tmp12 = tmp10 <= tmp11
tl.store(out_ptr0 + x0, tmp10, xmask)
tl.store(out_ptr1 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 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(out_ptr0 + x0, tmp7, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 1), (16, 4, 1, 1))
assert_size_stride(primals_4, (1,), (1,))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 1), (16, 4, 1, 1))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5, 4), (80, 20, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_constant_pad_nd_0[grid(320)](primals_1,
primals_2, buf0, 320, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf1 = extern_kernels.convolution(buf0, primals_3, stride=(1, 1),
padding=(1, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 5, 4), (80, 20, 4, 1), torch.float32)
triton_poi_fused_add_constant_pad_nd_relu_1[grid(320)](buf1,
primals_4, primals_5, buf2, 320, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_5
buf3 = extern_kernels.convolution(buf2, primals_6, stride=(1, 1),
padding=(1, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_mul_relu_threshold_backward_2[grid(256)](buf3,
primals_7, primals_8, primals_1, buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_1
del primals_8
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_3[grid(256)](buf1,
primals_4, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_4
return buf4, primals_3, primals_6, primals_7, buf0, buf2, buf3, buf5, buf6
class ConvBlockFixupNew(nn.Module):
def __init__(self, filter_width, input_filters, nb_filters, dilation):
super(ConvBlockFixupNew, self).__init__()
self.filter_width = filter_width
self.input_filters = input_filters
self.nb_filters = nb_filters
self.dilation = dilation
self.bias1a = nn.Parameter(torch.zeros(1))
self.conv1 = nn.Conv2d(self.input_filters, self.nb_filters, (self.
filter_width, 1), dilation=(self.dilation, 1), bias=False,
padding='same')
self.bias1b = nn.Parameter(torch.zeros(1))
self.relu = nn.ReLU(inplace=True)
self.bias2a = nn.Parameter(torch.zeros(1))
self.conv2 = nn.Conv2d(self.nb_filters, self.nb_filters, (self.
filter_width, 1), dilation=(self.dilation, 1), bias=False,
padding='same')
self.scale = nn.Parameter(torch.ones(1))
self.bias2b = nn.Parameter(torch.zeros(1))
def forward(self, input_0):
primals_2 = self.bias1a
primals_4 = self.bias1b
primals_5 = self.bias2a
primals_7 = self.scale
primals_8 = self.bias2b
primals_3 = self.conv1.weight
primals_6 = self.conv2.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
OmarNajdi/dl-for-har
|
ConvBlockFixup
| false
| 934
|
[
"MIT"
] | 0
|
5e1b7c29caf2b41fcba106cd901c45d8f2d18429
|
https://github.com/OmarNajdi/dl-for-har/tree/5e1b7c29caf2b41fcba106cd901c45d8f2d18429
|
MarginRankingLoss_learning_loss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class MarginRankingLoss_learning_loss(nn.Module):
"""
Ranking loss as described in LPM paper
inputs/targets are randomly permutated
final target is a list of -1 and 1's
-1 means the item in the i list is higher 1 means the item in the j list is higher
This creates a pairwise ranking loss
"""
def __init__(self, margin=0.5):
super(MarginRankingLoss_learning_loss, self).__init__()
self.margin = margin
def forward(self, inputs, targets):
random = torch.randperm(inputs.size(0))
mid = int(inputs.size(0) // 2)
pred_lossi = inputs[:mid]
pred_lossj = inputs[mid:]
target_loss = targets.reshape(inputs.size(0), 1)
target_loss = target_loss[random]
target_lossi = target_loss[:mid]
target_lossj = target_loss[mid:]
final_target = torch.sign(target_lossi - target_lossj)
return F.margin_ranking_loss(pred_lossi, pred_lossj, final_target,
margin=self.margin, reduction='mean')
def get_inputs():
return [torch.rand([4, 1]), torch.rand([4, 1])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch import device
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_min_mean_mul_neg_sign_sub_0(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 2
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)
tmp7 = tl.load(in_ptr0 + (2 + r0), None)
tmp22 = tl.load(in_ptr2 + r0, None)
tmp23 = tl.load(in_ptr2 + (2 + r0), None)
tmp1 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4),
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + tmp4, None, eviction_policy='evict_last')
tmp8 = tmp7 + tmp1
tmp9 = tmp7 < 0
tmp10 = tl.where(tmp9, tmp8, tmp7)
tl.device_assert((0 <= tmp10) & (tmp10 < 4),
'index out of bounds: 0 <= tmp10 < 4')
tmp12 = tl.load(in_ptr1 + tmp10, None, eviction_policy='evict_last')
tmp13 = tmp6 - tmp12
tmp14 = tl.full([1, 1], 0, tl.int32)
tmp15 = tmp14 < tmp13
tmp16 = tmp15.to(tl.int8)
tmp17 = tmp13 < tmp14
tmp18 = tmp17.to(tl.int8)
tmp19 = tmp16 - tmp18
tmp20 = tmp19.to(tmp13.dtype)
tmp21 = -tmp20
tmp24 = tmp22 - tmp23
tmp25 = tmp21 * tmp24
tmp26 = 0.5
tmp27 = tmp25 + tmp26
tmp28 = 0.0
tmp29 = triton_helpers.maximum(tmp27, tmp28)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tmp33 = 2.0
tmp34 = tmp32 / tmp33
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp34, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 1), (1, 1))
assert_size_stride(arg1_1, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten.randperm.default(4, device=device(type='cuda',
index=0), pin_memory=False)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
get_raw_stream(0)
triton_per_fused_add_clamp_min_mean_mul_neg_sign_sub_0[grid(1)](buf3,
buf1, arg1_1, arg0_1, 1, 2, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del buf1
return buf3,
class MarginRankingLoss_learning_lossNew(nn.Module):
"""
Ranking loss as described in LPM paper
inputs/targets are randomly permutated
final target is a list of -1 and 1's
-1 means the item in the i list is higher 1 means the item in the j list is higher
This creates a pairwise ranking loss
"""
def __init__(self, margin=0.5):
super(MarginRankingLoss_learning_lossNew, self).__init__()
self.margin = margin
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Pepijnnn/MasterThesis
|
MarginRankingLoss_learning_loss
| false
| 936
|
[
"MIT"
] | 0
|
7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
https://github.com/Pepijnnn/MasterThesis/tree/7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
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]
|
PengJingchao/DFNet
|
LRN
| false
| 937
|
[
"MIT"
] | 0
|
49e83501f81515aebca211351e315896da7afc54
|
https://github.com/PengJingchao/DFNet/tree/49e83501f81515aebca211351e315896da7afc54
|
ListNetLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ListNetLoss(nn.Module):
def __init__(self):
super(ListNetLoss, self).__init__()
return
def forward(self, y_pred, y_true, eps=0.0005, padded_value_indicator=-1):
"""
ListNet loss introduced in "Learning to Rank: From Pairwise Approach to Listwise Approach".
:param y_pred: predictions from the model, shape [batch_size, slate_length]
:param y_true: ground truth labels, shape [batch_size, slate_length]
:param eps: epsilon value, used for numerical stability
:param padded_value_indicator: an indicator of the y_true index containing a padded item, e.g. -1
:return: loss value, a torch.Tensor
"""
y_pred = y_pred.clone()
y_true = y_true.clone()
preds_smax = F.softmax(y_pred, dim=1)
true_smax = F.softmax(y_true, dim=1)
preds_smax = preds_smax + eps
preds_log = torch.log(preds_smax)
return torch.mean(-torch.sum(true_smax * preds_log, dim=1))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_add_log_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
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr1 + x3, xmask)
tmp10 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp12 = tmp10 + tmp11
tmp14 = tmp12 + tmp13
tmp16 = tmp14 + tmp15
tmp17 = tmp9 / tmp16
tmp18 = 0.0005
tmp19 = tmp17 + tmp18
tmp20 = tl_math.log(tmp19)
tmp21 = tmp8 * tmp20
tl.store(out_ptr0 + x3, tmp21, xmask)
@triton.jit
def triton_per_fused_mean_neg_sum_2(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)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp3 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = -tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.sum(tmp8, 1)[:, None]
tmp11 = 64.0
tmp12 = tmp10 / tmp11
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp12, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf1, 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__softmax_add_log_mul_1[grid(256)](buf0, buf1, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del buf1
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused_mean_neg_sum_2[grid(1)](buf4, buf2, 1, 64, XBLOCK=
1, num_warps=2, num_stages=1)
del buf2
return buf4,
class ListNetLossNew(nn.Module):
def __init__(self):
super(ListNetLossNew, self).__init__()
return
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Pepijnnn/MasterThesis
|
ListNetLoss
| false
| 938
|
[
"MIT"
] | 0
|
7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
https://github.com/Pepijnnn/MasterThesis/tree/7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
AsymmetricLossOptimized
|
import torch
import torch.nn as nn
class AsymmetricLossOptimized(nn.Module):
""" Notice - optimized version, minimizes memory allocation and gpu uploading,
favors inplace operations"""
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-08,
disable_torch_grad_focal_loss=False):
super(AsymmetricLossOptimized, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
self.clip = clip
self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
self.eps = eps
(self.targets) = (self.anti_targets) = (self.xs_pos) = (self.xs_neg
) = (self.asymmetric_w) = (self.loss) = None
def forward(self, x, y):
""""
Parameters
----------
x: input logits
y: targets (multi-label binarized vector)
"""
self.targets = y
self.anti_targets = 1 - y
self.xs_pos = torch.sigmoid(x)
self.xs_neg = 1.0 - self.xs_pos
if self.clip is not None and self.clip > 0:
self.xs_neg.add_(self.clip).clamp_(max=1)
self.loss = self.targets * torch.log(self.xs_pos.clamp(min=self.eps))
self.loss.add_(self.anti_targets * torch.log(self.xs_neg.clamp(min=
self.eps)))
if self.gamma_neg > 0 or self.gamma_pos > 0:
self.xs_pos = self.xs_pos * self.targets
self.xs_neg = self.xs_neg * self.anti_targets
self.asymmetric_w = torch.pow(1 - self.xs_pos - self.xs_neg,
self.gamma_pos * self.targets + self.gamma_neg * self.
anti_targets)
self.loss *= self.asymmetric_w
return -self.loss.sum()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_log_mul_neg_pow_rsub_sigmoid_sub_sum_0(
in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, out_ptr3,
out_ptr4, 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 = tl.sigmoid(tmp3)
tmp5 = tmp4 * tmp0
tmp6 = tmp1 - tmp4
tmp7 = 0.05
tmp8 = tmp6 + tmp7
tmp9 = triton_helpers.minimum(tmp8, tmp1)
tmp10 = tmp9 * tmp2
tmp11 = tmp1 - tmp5
tmp12 = tmp11 - tmp10
tmp13 = tmp0 * tmp1
tmp14 = 4.0
tmp15 = tmp2 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = libdevice.pow(tmp12, tmp16)
tmp18 = 1e-08
tmp19 = triton_helpers.maximum(tmp4, tmp18)
tmp20 = tl_math.log(tmp19)
tmp21 = tmp0 * tmp20
tmp22 = triton_helpers.maximum(tmp9, tmp18)
tmp23 = tl_math.log(tmp22)
tmp24 = tmp2 * tmp23
tmp25 = tmp21 + tmp24
tmp26 = tmp25 * tmp17
tmp27 = tl.broadcast_to(tmp26, [RBLOCK])
tmp29 = triton_helpers.promote_to_tensor(tl.sum(tmp27, 0))
tmp30 = -tmp29
tl.store(out_ptr0 + tl.broadcast_to(r0, [RBLOCK]), tmp2, None)
tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp5, None)
tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), tmp10, None)
tl.store(out_ptr3 + tl.broadcast_to(r0, [RBLOCK]), tmp17, None)
tl.store(out_ptr4 + tl.broadcast_to(r0, [RBLOCK]), tmp26, None)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp30, 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)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((), (), torch.float32)
buf6 = buf5
del buf5
get_raw_stream(0)
triton_per_fused_add_clamp_log_mul_neg_pow_rsub_sigmoid_sub_sum_0[grid
(1)](buf6, arg0_1, arg1_1, buf0, buf1, buf2, buf3, buf4, 1, 256,
num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf6, buf3, buf4, buf2, buf1, buf0
class AsymmetricLossOptimizedNew(nn.Module):
""" Notice - optimized version, minimizes memory allocation and gpu uploading,
favors inplace operations"""
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-08,
disable_torch_grad_focal_loss=False):
super(AsymmetricLossOptimizedNew, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
self.clip = clip
self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
self.eps = eps
(self.targets) = (self.anti_targets) = (self.xs_pos) = (self.xs_neg
) = (self.asymmetric_w) = (self.loss) = None
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Pepijnnn/MasterThesis
|
AsymmetricLossOptimized
| false
| 939
|
[
"MIT"
] | 0
|
7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
https://github.com/Pepijnnn/MasterThesis/tree/7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
HorizontalMaxPool2d
|
import torch
import torch.nn as nn
class HorizontalMaxPool2d(nn.Module):
def __init__(self):
super(HorizontalMaxPool2d, self).__init__()
def forward(self, x):
inp_size = x.size()
return nn.functional.max_pool2d(input=x, kernel_size=(1, inp_size[3]))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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 = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(64)](arg0_1, buf0,
64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
return buf0,
class HorizontalMaxPool2dNew(nn.Module):
def __init__(self):
super(HorizontalMaxPool2dNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Qidian213/NAIC2019
|
HorizontalMaxPool2d
| false
| 940
|
[
"MIT"
] | 0
|
23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
https://github.com/Qidian213/NAIC2019/tree/23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
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, dim=1)[:, 1]
neg_loss = -F.log_softmax(neg_score, dim=1)[:, 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=256, 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=256, 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]
|
PengJingchao/DFNet
|
BinaryLoss
| false
| 941
|
[
"MIT"
] | 0
|
49e83501f81515aebca211351e315896da7afc54
|
https://github.com/PengJingchao/DFNet/tree/49e83501f81515aebca211351e315896da7afc54
|
HSigmoid
|
import torch
import torch.utils.data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.functional
import torch.optim
import torch.nn.parallel
import torch.utils.data.distributed
class HSigmoid(nn.Module):
""" Applies the Hard-Sigmoid function element-wise.
`"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_
Examples:
>>> m = Mish()
>>> x = torch.randn(2)
>>> output = m(x)
"""
@staticmethod
def forward(x: 'torch.Tensor') ->torch.Tensor:
return F.relu6(x + 3, inplace=True) / 6.0
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch
import torch.nn as nn
import torch.nn.functional
import torch.optim
import torch.nn.parallel
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_hardtanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 3.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = 6.0
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp7 = 0.16666666666666666
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_hardtanh_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HSigmoidNew(nn.Module):
""" Applies the Hard-Sigmoid function element-wise.
`"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_
Examples:
>>> m = Mish()
>>> x = torch.randn(2)
>>> output = m(x)
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
PhelaPoscam/SRGAN-PyTorch
|
HSigmoid
| false
| 942
|
[
"Apache-2.0"
] | 0
|
c1c68707dbddd1130b2ea71023df748080bcbd52
|
https://github.com/PhelaPoscam/SRGAN-PyTorch/tree/c1c68707dbddd1130b2ea71023df748080bcbd52
|
Module_CharbonnierLoss
|
import torch
import torch.nn as nn
class Module_CharbonnierLoss(nn.Module):
def __init__(self, epsilon=0.001):
super(Module_CharbonnierLoss, self).__init__()
self.epsilon = epsilon
def forward(self, output, gt):
return torch.mean(torch.sqrt((output - gt) ** 2 + self.epsilon ** 2))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mean_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-06
tmp5 = tmp3 + tmp4
tmp6 = libdevice.sqrt(tmp5)
tmp7 = tl.broadcast_to(tmp6, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = 256.0
tmp11 = tmp9 / tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mean_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,
class Module_CharbonnierLossNew(nn.Module):
def __init__(self, epsilon=0.001):
super(Module_CharbonnierLossNew, self).__init__()
self.epsilon = epsilon
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Pumpkin123709/LBEC
|
Module_CharbonnierLoss
| false
| 944
|
[
"MIT"
] | 0
|
18661faa35769f731847e0226ff601754e134668
|
https://github.com/Pumpkin123709/LBEC/tree/18661faa35769f731847e0226ff601754e134668
|
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=2, 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]
|
PattynR/PyTorch-NLP
|
Attention
| false
| 945
|
[
"BSD-3-Clause"
] | 0
|
8995774abf3734db6da174425843d883face5218
|
https://github.com/PattynR/PyTorch-NLP/tree/8995774abf3734db6da174425843d883face5218
|
Reg_layer
|
import torch
from torch import nn
class Reg_layer(nn.Module):
"""
modified by Zylo117
"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3,
padding=1, bias=True)
self.header = nn.Conv2d(in_channels, out_channels, kernel_size=1,
stride=1, padding=0, bias=True)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
x = self.header(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(256)](buf3, primals_5, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class Reg_layerNew(nn.Module):
"""
modified by Zylo117
"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3,
padding=1, bias=True)
self.header = nn.Conv2d(in_channels, out_channels, kernel_size=1,
stride=1, padding=0, bias=True)
self.relu = nn.ReLU(inplace=True)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_4 = self.header.weight
primals_5 = self.header.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Peiiii/detro
|
Reg_layer
| false
| 946
|
[
"MIT"
] | 0
|
26d74468d7554dc20b2a2daf7ec5009302c820f2
|
https://github.com/Peiiii/detro/tree/26d74468d7554dc20b2a2daf7ec5009302c820f2
|
Classifier
|
import torch
import torch.nn as nn
class Classifier(nn.Module):
def __init__(self, num_inputs1, num_inputs2):
super().__init__()
self.network = nn.Bilinear(num_inputs1, num_inputs2, 1)
def forward(self, x1, x2):
return self.network(x1, x2)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs1': 4, 'num_inputs2': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 4), (16, 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, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten._trilinear.default(reinterpret_tensor(
primals_4, (64, 4), (4, 1), 0), primals_1, reinterpret_tensor(
primals_3, (64, 4), (4, 1), 0), [1, 3], [0], [1, 2], [2, 3])
del primals_1
buf1 = buf0
del buf0
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
get_raw_stream(0)
triton_poi_fused_add_0[grid(64)](buf2, primals_2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
return buf2, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
class ClassifierNew(nn.Module):
def __init__(self, num_inputs1, num_inputs2):
super().__init__()
self.network = nn.Bilinear(num_inputs1, num_inputs2, 1)
def forward(self, input_0, input_1):
primals_1 = self.network.weight
primals_2 = self.network.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Project-Agni/Detection
|
Classifier
| false
| 947
|
[
"MIT"
] | 0
|
6b2c8ec25f8bd2bd15995d67f2808352cec9e2af
|
https://github.com/Project-Agni/Detection/tree/6b2c8ec25f8bd2bd15995d67f2808352cec9e2af
|
DQNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class Prediction(nn.Module):
"""Defines the prediction module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(Prediction, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(state_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, action_size)
def forward(self, state):
"""Prediction unit forward pass. Input state, s_t. Output, action, a_t"""
x = self.fc1(state)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
class Environment(nn.Module):
"""Defines the Environment module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(Environment, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(action_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, state_size)
def forward(self, action):
"""Environment unit forward pass. Input action, a_t. Output, s_t+1."""
x = self.fc1(action)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
class DQNetwork(nn.Module):
"""Main DQN network utilizing `Prediction` and `Environment` modules"""
def __init__(self, state_size: 'int', action_size: 'int'):
super(DQNetwork, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.prediction = Prediction(state_size, action_size)
self.env = Environment(state_size, action_size)
def forward(self, state):
"""Returns a_t and s_t+1"""
action = self.prediction(state)
predicted_next_state = self.env(action)
return action, predicted_next_state
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_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.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1536
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 24
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (24, 4), (4, 1))
assert_size_stride(primals_2, (24,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (24, 24), (24, 1))
assert_size_stride(primals_5, (24,), (1,))
assert_size_stride(primals_6, (4, 24), (24, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (24, 4), (4, 1))
assert_size_stride(primals_9, (24,), (1,))
assert_size_stride(primals_10, (24, 24), (24, 1))
assert_size_stride(primals_11, (24,), (1,))
assert_size_stride(primals_12, (4, 24), (24, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 24), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf0
buf13 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf1,
primals_2, buf13, 1536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 24), (24, 1), 0),
reinterpret_tensor(primals_4, (24, 24), (1, 24), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf2
buf12 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf3,
primals_5, buf12, 1536, 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, 24),
(24, 1), 0), reinterpret_tensor(primals_6, (24, 4), (1, 24), 0),
alpha=1, beta=1, out=buf4)
del primals_7
buf5 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_8, (4, 24), (1,
4), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf5
buf11 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf6,
primals_9, buf11, 1536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf7 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 24), (24, 1), 0),
reinterpret_tensor(primals_10, (24, 24), (1, 24), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf7
buf10 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf8,
primals_11, buf10, 1536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf9 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf8, (64, 24),
(24, 1), 0), reinterpret_tensor(primals_12, (24, 4), (1, 24), 0
), alpha=1, beta=1, out=buf9)
del primals_13
return (reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0),
reinterpret_tensor(buf9, (4, 4, 4, 4), (64, 16, 4, 1), 0),
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (64, 24), (24, 1), 0), reinterpret_tensor(
buf3, (64, 24), (24, 1), 0), buf4, reinterpret_tensor(buf6, (64, 24
), (24, 1), 0), reinterpret_tensor(buf8, (64, 24), (24, 1), 0),
primals_12, buf10, primals_10, buf11, primals_8, primals_6, buf12,
primals_4, buf13)
class Prediction(nn.Module):
"""Defines the prediction module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(Prediction, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(state_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, action_size)
def forward(self, state):
"""Prediction unit forward pass. Input state, s_t. Output, action, a_t"""
x = self.fc1(state)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
class Environment(nn.Module):
"""Defines the Environment module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(Environment, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(action_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, state_size)
def forward(self, action):
"""Environment unit forward pass. Input action, a_t. Output, s_t+1."""
x = self.fc1(action)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
class DQNetworkNew(nn.Module):
"""Main DQN network utilizing `Prediction` and `Environment` modules"""
def __init__(self, state_size: 'int', action_size: 'int'):
super(DQNetworkNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.prediction = Prediction(state_size, action_size)
self.env = Environment(state_size, action_size)
def forward(self, input_0):
primals_1 = self.prediction.fc1.weight
primals_2 = self.prediction.fc1.bias
primals_4 = self.prediction.fc2.weight
primals_5 = self.prediction.fc2.bias
primals_6 = self.prediction.fc3.weight
primals_7 = self.prediction.fc3.bias
primals_8 = self.env.fc1.weight
primals_9 = self.env.fc1.bias
primals_10 = self.env.fc2.weight
primals_11 = self.env.fc2.bias
primals_12 = self.env.fc3.weight
primals_13 = self.env.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0], output[1]
|
QasimWani/EARL
|
DQNetwork
| false
| 948
|
[
"MIT"
] | 0
|
05c303335e67903380771c4954a5317bd46fc0e7
|
https://github.com/QasimWani/EARL/tree/05c303335e67903380771c4954a5317bd46fc0e7
|
hsigmoid
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class hsigmoid(nn.Module):
def forward(self, x):
out = F.relu6(x + 3, inplace=True) / 6
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_hardtanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 3.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = 6.0
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp7 = 0.16666666666666666
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_hardtanh_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class hsigmoidNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Qidian213/NAIC2019
|
hsigmoid
| false
| 949
|
[
"MIT"
] | 0
|
23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
https://github.com/Qidian213/NAIC2019/tree/23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
SeparableConv2d
|
import torch
class SeparableConv2d(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=0, dilation=1, bias=False):
super(SeparableConv2d, self).__init__()
self.conv1 = torch.nn.Conv2d(in_channels, in_channels, kernel_size,
stride, padding, dilation, groups=in_channels)
self.pointwise = torch.nn.Conv2d(in_channels, out_channels, 1, 1, 0,
1, 1, bias=bias)
def forward(self, x):
x = self.conv1(x)
x = self.pointwise(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf0, (4, 4, 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=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
return buf2, primals_1, primals_3, primals_4, buf1
class SeparableConv2dNew(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=0, dilation=1, bias=False):
super(SeparableConv2dNew, self).__init__()
self.conv1 = torch.nn.Conv2d(in_channels, in_channels, kernel_size,
stride, padding, dilation, groups=in_channels)
self.pointwise = torch.nn.Conv2d(in_channels, out_channels, 1, 1, 0,
1, 1, bias=bias)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.pointwise.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Pumpkin123709/LBEC
|
SeparableConv2d
| false
| 950
|
[
"MIT"
] | 0
|
18661faa35769f731847e0226ff601754e134668
|
https://github.com/Pumpkin123709/LBEC/tree/18661faa35769f731847e0226ff601754e134668
|
InputProjectionA
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
class InputProjectionA(nn.Module):
"""
This class projects the input image to the same spatial dimensions as the feature map.
For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then
this class will generate an output of 56x56x3
"""
def __init__(self, samplingTimes):
"""
:param samplingTimes: The rate at which you want to down-sample the image
"""
super().__init__()
self.pool = nn.ModuleList()
for i in range(0, samplingTimes):
self.pool.append(nn.AvgPool2d(2, stride=2, padding=0))
def forward(self, input):
"""
:param input: Input RGB Image
:return: down-sampled image (pyramid-based approach)
"""
for pool in self.pool:
input = pool(input)
return input
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'samplingTimes': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (32 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (33 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_avg_pool2d_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 32 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 32 * x1), xmask, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (16 + 2 * x0 + 32 * x1), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (17 + 2 * x0 + 32 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 16 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 16 * x1), xmask, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (8 + 2 * x0 + 16 * x1), xmask, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (9 + 2 * x0 + 16 * 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, 64, 64), (16384, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_0[grid(16384)](arg0_1, buf0, 16384,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch
.float32)
triton_poi_fused_avg_pool2d_1[grid(4096)](buf0, buf1, 4096, XBLOCK=
128, num_warps=4, num_stages=1)
del buf0
buf2 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32)
triton_poi_fused_avg_pool2d_2[grid(1024)](buf1, buf2, 1024, XBLOCK=
128, num_warps=4, num_stages=1)
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_avg_pool2d_3[grid(256)](buf2, buf3, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf2
return buf3,
class InputProjectionANew(nn.Module):
"""
This class projects the input image to the same spatial dimensions as the feature map.
For example, if the input image is 512 x512 x3 and spatial dimensions of feature map size are 56x56xF, then
this class will generate an output of 56x56x3
"""
def __init__(self, samplingTimes):
"""
:param samplingTimes: The rate at which you want to down-sample the image
"""
super().__init__()
self.pool = nn.ModuleList()
for i in range(0, samplingTimes):
self.pool.append(nn.AvgPool2d(2, stride=2, padding=0))
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
PhillipHuang2017/ext_portrait_segmentation
|
InputProjectionA
| false
| 951
|
[
"MIT"
] | 0
|
6d0cec0a953dacbc94a01ea8b719feb687b7c029
|
https://github.com/PhillipHuang2017/ext_portrait_segmentation/tree/6d0cec0a953dacbc94a01ea8b719feb687b7c029
|
SelfAttention
|
import torch
from torch import nn
class SelfAttention(nn.Module):
""" Self attention Layer"""
def __init__(self, in_dim, activation):
super(SelfAttention, self).__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim //
2, kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim //
2, kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X W X H)
returns :
out : self attention value + input feature
attention: B X N X N (N is Width*Height)
"""
m_batchsize, C, width, height = x.size()
proj_query = self.query_conv(x).view(m_batchsize, -1, width * height
).permute(0, 2, 1)
proj_key = self.key_conv(x).view(m_batchsize, -1, width * height)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.value_conv(x).view(m_batchsize, -1, width * height)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, C, width, height)
out = self.gamma * out * x
return out, attention
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'activation': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 2
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tmp6 / tmp10
tl.store(out_ptr2 + (r1 + 16 * x0), tmp11, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tmp1 * tmp2
tmp5 = tmp3 * tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (2,), (1,))
assert_size_stride(primals_6, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 2, 4, 4), (32, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(128)](buf1, primals_3, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(primals_1, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 4, 4), (32, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(128)](buf3, primals_5, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 16, 16), (256, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 16, 2), (32, 1, 16),
0), reinterpret_tensor(buf3, (4, 2, 16), (32, 16, 1), 0), out=buf4)
buf7 = empty_strided_cuda((4, 16, 16), (256, 16, 1), torch.float32)
triton_per_fused__softmax_1[grid(64)](buf4, buf7, 64, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del buf4
buf8 = extern_kernels.convolution(primals_1, primals_6, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_2[grid(256)](buf9, primals_7, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf9, (4, 4, 16), (64, 16, 1),
0), reinterpret_tensor(buf7, (4, 16, 16), (256, 1, 16), 0), out
=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_3[grid(256)](primals_8, buf10, primals_1,
buf11, 256, XBLOCK=256, num_warps=4, num_stages=1)
return (buf11, buf7, primals_1, primals_2, primals_4, primals_6,
primals_8, buf7, buf10, reinterpret_tensor(buf9, (4, 16, 4), (64, 1,
16), 0), reinterpret_tensor(buf1, (4, 2, 16), (32, 16, 1), 0),
reinterpret_tensor(buf3, (4, 16, 2), (32, 1, 16), 0))
class SelfAttentionNew(nn.Module):
""" Self attention Layer"""
def __init__(self, in_dim, activation):
super(SelfAttentionNew, self).__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim //
2, kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim //
2, kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, input_0):
primals_8 = self.gamma
primals_2 = self.query_conv.weight
primals_3 = self.query_conv.bias
primals_4 = self.key_conv.weight
primals_5 = self.key_conv.bias
primals_6 = self.value_conv.weight
primals_7 = self.value_conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
PauPerezT/EmoSSpeech
|
SelfAttention
| false
| 952
|
[
"Apache-2.0"
] | 0
|
168a951a838d0bfb838e7d0e3f6895bff68164a4
|
https://github.com/PauPerezT/EmoSSpeech/tree/168a951a838d0bfb838e7d0e3f6895bff68164a4
|
Environment
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class Environment(nn.Module):
"""Defines the Environment module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(Environment, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(action_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, state_size)
def forward(self, action):
"""Environment unit forward pass. Input action, a_t. Output, s_t+1."""
x = self.fc1(action)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1536
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 24
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) = args
args.clear()
assert_size_stride(primals_1, (24, 4), (4, 1))
assert_size_stride(primals_2, (24,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (24, 24), (24, 1))
assert_size_stride(primals_5, (24,), (1,))
assert_size_stride(primals_6, (4, 24), (24, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 24), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf1,
primals_2, buf6, 1536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 24), (24, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 24), (24, 1), 0),
reinterpret_tensor(primals_4, (24, 24), (1, 24), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 24), (384, 96, 24, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 24), (384, 96, 24, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(1536)](buf3,
primals_5, buf5, 1536, 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, 24),
(24, 1), 0), reinterpret_tensor(primals_6, (24, 4), (1, 24), 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, 24), (24, 1), 0), reinterpret_tensor(
buf3, (64, 24), (24, 1), 0), primals_6, buf5, primals_4, buf6
class EnvironmentNew(nn.Module):
"""Defines the Environment module as an ANN"""
def __init__(self, state_size: 'int', action_size: 'int', fc1: 'int'=24,
fc2: 'int'=24):
super(EnvironmentNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.fc1 = nn.Linear(action_size, fc1)
self.fc2 = nn.Linear(fc1, fc2)
self.fc3 = nn.Linear(fc2, state_size)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
QasimWani/EARL
|
Environment
| false
| 953
|
[
"MIT"
] | 0
|
05c303335e67903380771c4954a5317bd46fc0e7
|
https://github.com/QasimWani/EARL/tree/05c303335e67903380771c4954a5317bd46fc0e7
|
attention2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class attention2d(nn.Module):
def __init__(self, in_planes, ratios, K, temperature, init_weight=True):
super(attention2d, self).__init__()
assert temperature % 3 == 1
self.avgpool = nn.AdaptiveAvgPool2d(1)
if in_planes != 3:
hidden_planes = int(in_planes * ratios)
else:
hidden_planes = K
self.fc1 = nn.Conv2d(in_planes, hidden_planes, 1, bias=False)
self.fc2 = nn.Conv2d(hidden_planes, K, 1, bias=False)
self.temperature = temperature
if init_weight:
self._initialize_weights()
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out',
nonlinearity='leaky_relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
if isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def updata_temperature(self):
if self.temperature != 1:
self.temperature -= 1
def forward(self, x):
x = self.avgpool(x)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x).view(x.size(0), -1)
return F.softmax(x / self.temperature, 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'ratios': 4, 'K': 4, 'temperature': 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_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, 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)
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (16, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (4, 16, 1, 1), (16, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 16, 1, 1), (16, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_relu_1[grid(64)](buf3, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf4 = extern_kernels.convolution(buf3, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 1, 1), (4, 1, 1, 1))
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(16)](buf4, buf5, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4), (4, 1), 0)
del buf4
triton_poi_fused__softmax_3[grid(16)](buf5, buf6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf5
return buf6, primals_2, primals_3, buf1, buf3, buf6
class attention2dNew(nn.Module):
def __init__(self, in_planes, ratios, K, temperature, init_weight=True):
super(attention2dNew, self).__init__()
assert temperature % 3 == 1
self.avgpool = nn.AdaptiveAvgPool2d(1)
if in_planes != 3:
hidden_planes = int(in_planes * ratios)
else:
hidden_planes = K
self.fc1 = nn.Conv2d(in_planes, hidden_planes, 1, bias=False)
self.fc2 = nn.Conv2d(hidden_planes, K, 1, bias=False)
self.temperature = temperature
if init_weight:
self._initialize_weights()
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out',
nonlinearity='leaky_relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
if isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def updata_temperature(self):
if self.temperature != 1:
self.temperature -= 1
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc2.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
PengJingchao/DFNet
|
attention2d
| false
| 954
|
[
"MIT"
] | 0
|
49e83501f81515aebca211351e315896da7afc54
|
https://github.com/PengJingchao/DFNet/tree/49e83501f81515aebca211351e315896da7afc54
|
ShearY
|
import torch
import torch.nn as nn
from torchvision import transforms as ttf
class ShearY(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M - 180
def forward(self, img):
return ttf.functional.affine(img, 0, [0, 0], 1, [0, self.angle])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'M': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x2 = xindex // 12
x1 = xindex // 3 % 4
x4 = xindex
tmp0 = x0
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp0 == tmp3
tmp5 = x2
tmp6 = tmp5.to(tl.float32)
tmp7 = 2.0
tmp8 = tmp6 < tmp7
tmp9 = 1.0
tmp10 = tmp6 * tmp9
tmp11 = -1.5
tmp12 = tmp10 + tmp11
tmp13 = 3 + -1 * x2
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 * tmp9
tmp16 = 1.5
tmp17 = tmp16 - tmp15
tmp18 = tl.where(tmp8, tmp12, tmp17)
tmp19 = tl.full([1], 0, tl.int32)
tmp20 = tmp0 == tmp19
tmp21 = x1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp22 < tmp7
tmp24 = tmp22 * tmp9
tmp25 = tmp24 + tmp11
tmp26 = 3 + -1 * x1
tmp27 = tmp26.to(tl.float32)
tmp28 = tmp27 * tmp9
tmp29 = tmp16 - tmp28
tmp30 = tl.where(tmp23, tmp25, tmp29)
tmp31 = float('nan')
tmp32 = tl.where(tmp20, tmp30, tmp31)
tmp33 = tl.where(tmp4, tmp18, tmp32)
tmp34 = tl.where(tmp2, tmp9, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_div_lift_fresh_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x1 + 3 * x0
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = 0.0
tmp8 = tl.where(tmp6, tmp7, tmp7)
tmp9 = 1.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = tl.full([1], 4, tl.int64)
tmp12 = tmp0 < tmp11
tmp13 = tl.full([1], 5, tl.int64)
tmp14 = tmp0 < tmp13
tmp15 = tl.where(tmp14, tmp9, tmp7)
tmp16 = -0.737263560295105
tmp17 = tl.where(tmp12, tmp16, tmp15)
tmp18 = tl.where(tmp2, tmp10, tmp17)
tmp19 = x0
tmp20 = tmp19 < tmp3
tmp21 = 2.0
tmp22 = tl.where(tmp20, tmp21, tmp21)
tmp23 = tmp18 / tmp22
tl.store(out_ptr0 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_grid_sampler_2d_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
x0 = xindex % 16
x3 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.5
tmp4 = tmp2 + tmp3
tmp5 = libdevice.nearbyint(tmp4)
tmp6 = 0.0
tmp7 = tmp5 >= tmp6
tmp8 = 4.0
tmp9 = tmp5 < tmp8
tmp11 = tmp10 * tmp1
tmp12 = tmp11 + tmp3
tmp13 = libdevice.nearbyint(tmp12)
tmp14 = tmp13 >= tmp6
tmp15 = tmp13 < tmp8
tmp16 = tmp14 & tmp15
tmp17 = tmp9 & tmp16
tmp18 = tmp7 & tmp17
tmp19 = tmp13.to(tl.int64)
tmp20 = tl.full([1], 0, tl.int64)
tmp21 = tl.where(tmp18, tmp19, tmp20)
tmp22 = tl.full([XBLOCK], 4, tl.int32)
tmp23 = tmp21 + tmp22
tmp24 = tmp21 < 0
tmp25 = tl.where(tmp24, tmp23, tmp21)
tl.device_assert((0 <= tmp25) & (tmp25 < 4) | ~xmask,
'index out of bounds: 0 <= tmp25 < 4')
tmp27 = tmp5.to(tl.int64)
tmp28 = tl.where(tmp18, tmp27, tmp20)
tmp29 = tmp28 + tmp22
tmp30 = tmp28 < 0
tmp31 = tl.where(tmp30, tmp29, tmp28)
tl.device_assert((0 <= tmp31) & (tmp31 < 4) | ~xmask,
'index out of bounds: 0 <= tmp31 < 4')
tmp33 = tl.load(in_ptr1 + (tmp31 + 4 * tmp25 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp34 = tl.full([1], 1, tl.int64)
tmp35 = tl.where(tmp18, tmp34, tmp20)
tmp36 = tmp35.to(tl.float32)
tmp37 = tmp33 * tmp36
tl.store(out_ptr0 + x4, tmp37, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((1, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_0[grid(48)](buf2, 48, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((1, 3, 2), (6, 2, 1), torch.float32)
triton_poi_fused_div_lift_fresh_1[grid(6)](buf3, 6, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 16, 2), (32, 2, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (1, 16, 3), (48, 3, 1),
0), buf3, out=buf4)
del buf2
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_grid_sampler_2d_2[grid(256)](buf4, arg0_1, buf5,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf4
return buf5,
class ShearYNew(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M - 180
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Hayoung93/UDA
|
ShearY
| false
| 955
|
[
"Apache-2.0"
] | 0
|
a587b01c76141d64e7cead55b62e0f3ed75890bf
|
https://github.com/Hayoung93/UDA/tree/a587b01c76141d64e7cead55b62e0f3ed75890bf
|
fully_conv_layer
|
import torch
import torch.nn as nn
class fully_conv_layer(nn.Module):
def __init__(self, c):
super(fully_conv_layer, self).__init__()
self.conv = nn.Conv2d(c, 1, 1)
def forward(self, x):
return self.conv(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c': 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 = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (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 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 4, 4), (16, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(64)](buf1, primals_2, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class fully_conv_layerNew(nn.Module):
def __init__(self, c):
super(fully_conv_layerNew, self).__init__()
self.conv = nn.Conv2d(c, 1, 1)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
QiweiMa-LL/STAGCN
|
fully_conv_layer
| false
| 956
|
[
"MIT"
] | 0
|
c6889c845ac7fcba4419b2727022a599981f2a54
|
https://github.com/QiweiMa-LL/STAGCN/tree/c6889c845ac7fcba4419b2727022a599981f2a54
|
HSwish
|
import torch
import torch.utils.data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.functional
import torch.optim
import torch.nn.parallel
import torch.utils.data.distributed
class HSwish(nn.Module):
""" Applies the Hard-Swish function element-wise.
`"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_
Examples:
>>> m = Mish()
>>> x = torch.randn(2)
>>> output = m(x)
"""
@staticmethod
def forward(x: 'torch.Tensor') ->torch.Tensor:
return x * F.relu6(x + 3, inplace=True) / 6.0
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch
import torch.nn as nn
import torch.nn.functional
import torch.optim
import torch.nn.parallel
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 3.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = 6.0
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = 0.16666666666666666
tmp9 = tmp7 * tmp8
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_hardtanh_mul_0[grid(256)](arg0_1, buf0,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HSwishNew(nn.Module):
""" Applies the Hard-Swish function element-wise.
`"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_
Examples:
>>> m = Mish()
>>> x = torch.randn(2)
>>> output = m(x)
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
PhelaPoscam/SRGAN-PyTorch
|
HSwish
| false
| 957
|
[
"Apache-2.0"
] | 0
|
c1c68707dbddd1130b2ea71023df748080bcbd52
|
https://github.com/PhelaPoscam/SRGAN-PyTorch/tree/c1c68707dbddd1130b2ea71023df748080bcbd52
|
TranslateX
|
import torch
import torch.nn as nn
from torchvision import transforms as ttf
class TranslateX(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
def forward(self, img):
try:
max_size = img.size()[0]
except TypeError:
max_size = img.size()[0]
return ttf.functional.affine(img, 0, [(max_size - 1) / 10 * self.M,
0], 1, [0, 0])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'M': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x2 = xindex // 12
x1 = xindex // 3 % 4
x4 = xindex
tmp0 = x0
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp0 == tmp3
tmp5 = x2
tmp6 = tmp5.to(tl.float32)
tmp7 = 2.0
tmp8 = tmp6 < tmp7
tmp9 = 1.0
tmp10 = tmp6 * tmp9
tmp11 = -1.5
tmp12 = tmp10 + tmp11
tmp13 = 3 + -1 * x2
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 * tmp9
tmp16 = 1.5
tmp17 = tmp16 - tmp15
tmp18 = tl.where(tmp8, tmp12, tmp17)
tmp19 = tl.full([1], 0, tl.int32)
tmp20 = tmp0 == tmp19
tmp21 = x1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp22 < tmp7
tmp24 = tmp22 * tmp9
tmp25 = tmp24 + tmp11
tmp26 = 3 + -1 * x1
tmp27 = tmp26.to(tl.float32)
tmp28 = tmp27 * tmp9
tmp29 = tmp16 - tmp28
tmp30 = tl.where(tmp23, tmp25, tmp29)
tmp31 = float('nan')
tmp32 = tl.where(tmp20, tmp30, tmp31)
tmp33 = tl.where(tmp4, tmp18, tmp32)
tmp34 = tl.where(tmp2, tmp9, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_div_lift_fresh_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x1 + 3 * x0
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = 0.0
tmp8 = -1.2000000476837158
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = 1.0
tmp11 = tl.where(tmp4, tmp10, tmp9)
tmp12 = tl.full([1], 4, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tl.full([1], 5, tl.int64)
tmp15 = tmp0 < tmp14
tmp16 = tl.where(tmp15, tmp10, tmp7)
tmp17 = -0.0
tmp18 = tl.where(tmp13, tmp17, tmp16)
tmp19 = tl.where(tmp2, tmp11, tmp18)
tmp20 = x0
tmp21 = tmp20 < tmp3
tmp22 = 2.0
tmp23 = tl.where(tmp21, tmp22, tmp22)
tmp24 = tmp19 / tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_grid_sampler_2d_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
x0 = xindex % 16
x3 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.5
tmp4 = tmp2 + tmp3
tmp5 = libdevice.nearbyint(tmp4)
tmp6 = 0.0
tmp7 = tmp5 >= tmp6
tmp8 = 4.0
tmp9 = tmp5 < tmp8
tmp11 = tmp10 * tmp1
tmp12 = tmp11 + tmp3
tmp13 = libdevice.nearbyint(tmp12)
tmp14 = tmp13 >= tmp6
tmp15 = tmp13 < tmp8
tmp16 = tmp14 & tmp15
tmp17 = tmp9 & tmp16
tmp18 = tmp7 & tmp17
tmp19 = tmp13.to(tl.int64)
tmp20 = tl.full([1], 0, tl.int64)
tmp21 = tl.where(tmp18, tmp19, tmp20)
tmp22 = tl.full([XBLOCK], 4, tl.int32)
tmp23 = tmp21 + tmp22
tmp24 = tmp21 < 0
tmp25 = tl.where(tmp24, tmp23, tmp21)
tl.device_assert((0 <= tmp25) & (tmp25 < 4) | ~xmask,
'index out of bounds: 0 <= tmp25 < 4')
tmp27 = tmp5.to(tl.int64)
tmp28 = tl.where(tmp18, tmp27, tmp20)
tmp29 = tmp28 + tmp22
tmp30 = tmp28 < 0
tmp31 = tl.where(tmp30, tmp29, tmp28)
tl.device_assert((0 <= tmp31) & (tmp31 < 4) | ~xmask,
'index out of bounds: 0 <= tmp31 < 4')
tmp33 = tl.load(in_ptr1 + (tmp31 + 4 * tmp25 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp34 = tl.full([1], 1, tl.int64)
tmp35 = tl.where(tmp18, tmp34, tmp20)
tmp36 = tmp35.to(tl.float32)
tmp37 = tmp33 * tmp36
tl.store(out_ptr0 + x4, tmp37, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((1, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_0[grid(48)](buf2, 48, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((1, 3, 2), (6, 2, 1), torch.float32)
triton_poi_fused_div_lift_fresh_1[grid(6)](buf3, 6, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 16, 2), (32, 2, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (1, 16, 3), (48, 3, 1),
0), buf3, out=buf4)
del buf2
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_grid_sampler_2d_2[grid(256)](buf4, arg0_1, buf5,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf4
return buf5,
class TranslateXNew(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Hayoung93/UDA
|
TranslateX
| false
| 958
|
[
"Apache-2.0"
] | 0
|
a587b01c76141d64e7cead55b62e0f3ed75890bf
|
https://github.com/Hayoung93/UDA/tree/a587b01c76141d64e7cead55b62e0f3ed75890bf
|
Rotate
|
import torch
import torch.nn as nn
from torchvision import transforms as ttf
class Rotate(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M
def forward(self, img):
return ttf.functional.rotate(img, self.angle)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'M': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x2 = xindex // 12
x1 = xindex // 3 % 4
x4 = xindex
tmp0 = x0
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp0 == tmp3
tmp5 = x2
tmp6 = tmp5.to(tl.float32)
tmp7 = 2.0
tmp8 = tmp6 < tmp7
tmp9 = 1.0
tmp10 = tmp6 * tmp9
tmp11 = -1.5
tmp12 = tmp10 + tmp11
tmp13 = 3 + -1 * x2
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 * tmp9
tmp16 = 1.5
tmp17 = tmp16 - tmp15
tmp18 = tl.where(tmp8, tmp12, tmp17)
tmp19 = tl.full([1], 0, tl.int32)
tmp20 = tmp0 == tmp19
tmp21 = x1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp22 < tmp7
tmp24 = tmp22 * tmp9
tmp25 = tmp24 + tmp11
tmp26 = 3 + -1 * x1
tmp27 = tmp26.to(tl.float32)
tmp28 = tmp27 * tmp9
tmp29 = tmp16 - tmp28
tmp30 = tl.where(tmp23, tmp25, tmp29)
tmp31 = float('nan')
tmp32 = tl.where(tmp20, tmp30, tmp31)
tmp33 = tl.where(tmp4, tmp18, tmp32)
tmp34 = tl.where(tmp2, tmp9, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_div_lift_fresh_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x1 + 3 * x0
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = -0.5934188961982727
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = -0.8048937916755676
tmp11 = tl.where(tmp4, tmp10, tmp9)
tmp12 = tl.full([1], 4, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tl.full([1], 5, tl.int64)
tmp15 = tmp0 < tmp14
tmp16 = tl.where(tmp15, tmp10, tmp8)
tmp17 = 0.5934188961982727
tmp18 = tl.where(tmp13, tmp17, tmp16)
tmp19 = tl.where(tmp2, tmp11, tmp18)
tmp20 = x0
tmp21 = tmp20 < tmp3
tmp22 = 2.0
tmp23 = tl.where(tmp21, tmp22, tmp22)
tmp24 = tmp19 / tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_grid_sampler_2d_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
x0 = xindex % 16
x3 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.5
tmp4 = tmp2 + tmp3
tmp5 = libdevice.nearbyint(tmp4)
tmp6 = 0.0
tmp7 = tmp5 >= tmp6
tmp8 = 4.0
tmp9 = tmp5 < tmp8
tmp11 = tmp10 * tmp1
tmp12 = tmp11 + tmp3
tmp13 = libdevice.nearbyint(tmp12)
tmp14 = tmp13 >= tmp6
tmp15 = tmp13 < tmp8
tmp16 = tmp14 & tmp15
tmp17 = tmp9 & tmp16
tmp18 = tmp7 & tmp17
tmp19 = tmp13.to(tl.int64)
tmp20 = tl.full([1], 0, tl.int64)
tmp21 = tl.where(tmp18, tmp19, tmp20)
tmp22 = tl.full([XBLOCK], 4, tl.int32)
tmp23 = tmp21 + tmp22
tmp24 = tmp21 < 0
tmp25 = tl.where(tmp24, tmp23, tmp21)
tl.device_assert((0 <= tmp25) & (tmp25 < 4) | ~xmask,
'index out of bounds: 0 <= tmp25 < 4')
tmp27 = tmp5.to(tl.int64)
tmp28 = tl.where(tmp18, tmp27, tmp20)
tmp29 = tmp28 + tmp22
tmp30 = tmp28 < 0
tmp31 = tl.where(tmp30, tmp29, tmp28)
tl.device_assert((0 <= tmp31) & (tmp31 < 4) | ~xmask,
'index out of bounds: 0 <= tmp31 < 4')
tmp33 = tl.load(in_ptr1 + (tmp31 + 4 * tmp25 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp34 = tl.full([1], 1, tl.int64)
tmp35 = tl.where(tmp18, tmp34, tmp20)
tmp36 = tmp35.to(tl.float32)
tmp37 = tmp33 * tmp36
tl.store(out_ptr0 + x4, tmp37, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((1, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_0[grid(48)](buf2, 48, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((1, 3, 2), (6, 2, 1), torch.float32)
triton_poi_fused_div_lift_fresh_1[grid(6)](buf3, 6, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 16, 2), (32, 2, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (1, 16, 3), (48, 3, 1),
0), buf3, out=buf4)
del buf2
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_grid_sampler_2d_2[grid(256)](buf4, arg0_1, buf5,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf4
return buf5,
class RotateNew(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Hayoung93/UDA
|
Rotate
| false
| 959
|
[
"Apache-2.0"
] | 0
|
a587b01c76141d64e7cead55b62e0f3ed75890bf
|
https://github.com/Hayoung93/UDA/tree/a587b01c76141d64e7cead55b62e0f3ed75890bf
|
hswish
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class hswish(nn.Module):
def forward(self, x):
out = x * F.relu6(x + 3, inplace=True) / 6
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 3.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = 6.0
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = 0.16666666666666666
tmp9 = tmp7 * tmp8
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_hardtanh_mul_0[grid(256)](arg0_1, buf0,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class hswishNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Qidian213/NAIC2019
|
hswish
| false
| 960
|
[
"MIT"
] | 0
|
23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
https://github.com/Qidian213/NAIC2019/tree/23e05a8a096168ccfa4d1743467fdf78ffcaabba
|
TranslateY
|
import torch
import torch.nn as nn
from torchvision import transforms as ttf
class TranslateY(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
def forward(self, img):
try:
max_size = img.size()[1]
except TypeError:
max_size = img.size()[1]
return ttf.functional.affine(img, 0, [0, (max_size - 1) / 10 * self
.M], 1, [0, 0])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'M': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x2 = xindex // 12
x1 = xindex // 3 % 4
x4 = xindex
tmp0 = x0
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp0 == tmp3
tmp5 = x2
tmp6 = tmp5.to(tl.float32)
tmp7 = 2.0
tmp8 = tmp6 < tmp7
tmp9 = 1.0
tmp10 = tmp6 * tmp9
tmp11 = -1.5
tmp12 = tmp10 + tmp11
tmp13 = 3 + -1 * x2
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 * tmp9
tmp16 = 1.5
tmp17 = tmp16 - tmp15
tmp18 = tl.where(tmp8, tmp12, tmp17)
tmp19 = tl.full([1], 0, tl.int32)
tmp20 = tmp0 == tmp19
tmp21 = x1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp22 < tmp7
tmp24 = tmp22 * tmp9
tmp25 = tmp24 + tmp11
tmp26 = 3 + -1 * x1
tmp27 = tmp26.to(tl.float32)
tmp28 = tmp27 * tmp9
tmp29 = tmp16 - tmp28
tmp30 = tl.where(tmp23, tmp25, tmp29)
tmp31 = float('nan')
tmp32 = tl.where(tmp20, tmp30, tmp31)
tmp33 = tl.where(tmp4, tmp18, tmp32)
tmp34 = tl.where(tmp2, tmp9, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_div_lift_fresh_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x1 + 3 * x0
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = 0.0
tmp8 = tl.where(tmp6, tmp7, tmp7)
tmp9 = 1.0
tmp10 = tl.where(tmp4, tmp9, tmp8)
tmp11 = tl.full([1], 4, tl.int64)
tmp12 = tmp0 < tmp11
tmp13 = tl.full([1], 5, tl.int64)
tmp14 = tmp0 < tmp13
tmp15 = -1.2000000476837158
tmp16 = tl.where(tmp14, tmp9, tmp15)
tmp17 = -0.0
tmp18 = tl.where(tmp12, tmp17, tmp16)
tmp19 = tl.where(tmp2, tmp10, tmp18)
tmp20 = x0
tmp21 = tmp20 < tmp3
tmp22 = 2.0
tmp23 = tl.where(tmp21, tmp22, tmp22)
tmp24 = tmp19 / tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_grid_sampler_2d_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
x0 = xindex % 16
x3 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.5
tmp4 = tmp2 + tmp3
tmp5 = libdevice.nearbyint(tmp4)
tmp6 = 0.0
tmp7 = tmp5 >= tmp6
tmp8 = 4.0
tmp9 = tmp5 < tmp8
tmp11 = tmp10 * tmp1
tmp12 = tmp11 + tmp3
tmp13 = libdevice.nearbyint(tmp12)
tmp14 = tmp13 >= tmp6
tmp15 = tmp13 < tmp8
tmp16 = tmp14 & tmp15
tmp17 = tmp9 & tmp16
tmp18 = tmp7 & tmp17
tmp19 = tmp13.to(tl.int64)
tmp20 = tl.full([1], 0, tl.int64)
tmp21 = tl.where(tmp18, tmp19, tmp20)
tmp22 = tl.full([XBLOCK], 4, tl.int32)
tmp23 = tmp21 + tmp22
tmp24 = tmp21 < 0
tmp25 = tl.where(tmp24, tmp23, tmp21)
tl.device_assert((0 <= tmp25) & (tmp25 < 4) | ~xmask,
'index out of bounds: 0 <= tmp25 < 4')
tmp27 = tmp5.to(tl.int64)
tmp28 = tl.where(tmp18, tmp27, tmp20)
tmp29 = tmp28 + tmp22
tmp30 = tmp28 < 0
tmp31 = tl.where(tmp30, tmp29, tmp28)
tl.device_assert((0 <= tmp31) & (tmp31 < 4) | ~xmask,
'index out of bounds: 0 <= tmp31 < 4')
tmp33 = tl.load(in_ptr1 + (tmp31 + 4 * tmp25 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp34 = tl.full([1], 1, tl.int64)
tmp35 = tl.where(tmp18, tmp34, tmp20)
tmp36 = tmp35.to(tl.float32)
tmp37 = tmp33 * tmp36
tl.store(out_ptr0 + x4, tmp37, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((1, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_0[grid(48)](buf2, 48, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((1, 3, 2), (6, 2, 1), torch.float32)
triton_poi_fused_div_lift_fresh_1[grid(6)](buf3, 6, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 16, 2), (32, 2, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (1, 16, 3), (48, 3, 1),
0), buf3, out=buf4)
del buf2
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_grid_sampler_2d_2[grid(256)](buf4, arg0_1, buf5,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf4
return buf5,
class TranslateYNew(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Hayoung93/UDA
|
TranslateY
| false
| 961
|
[
"Apache-2.0"
] | 0
|
a587b01c76141d64e7cead55b62e0f3ed75890bf
|
https://github.com/Hayoung93/UDA/tree/a587b01c76141d64e7cead55b62e0f3ed75890bf
|
ListMLELoss
|
import torch
import torch.nn as nn
class ListMLELoss(nn.Module):
def __init__(self):
super(ListMLELoss, self).__init__()
return
def forward(self, y_pred, y_true, eps=1e-05, padded_value_indicator=-1):
"""
ListMLE loss introduced in "Listwise Approach to Learning to Rank - Theory and Algorithm".
:param y_pred: predictions from the model, shape [batch_size, slate_length]
:param y_true: ground truth labels, shape [batch_size, slate_length]
:param eps: epsilon value, used for numerical stability
:param padded_value_indicator: an indicator of the y_true index containing a padded item, e.g. -1
:return: loss value, a torch.Tensor
"""
random_indices = torch.randperm(y_pred.shape[-1])
y_pred_shuffled = y_pred[:, random_indices]
y_true_shuffled = y_true[:, random_indices]
_y_true_sorted, indices = y_true_shuffled.sort(descending=True, dim=-1)
preds_sorted_by_true = torch.gather(y_pred_shuffled, dim=1, index=
indices)
max_pred_values, _ = preds_sorted_by_true.max(dim=1, keepdim=True)
preds_sorted_by_true_minus_max = preds_sorted_by_true - max_pred_values
cumsums = torch.cumsum(preds_sorted_by_true_minus_max.exp().flip(
dims=[1]), dim=1).flip(dims=[1])
observation_loss = torch.log(cumsums + eps
) - preds_sorted_by_true_minus_max
return torch.mean(torch.sum(observation_loss, dim=1))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch import device
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn 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_index_sort_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x1 = xindex // 4 % 4
r3 = rindex
x0 = xindex % 4
x2 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (r3 + 4 * x0 + 16 * tmp4 + 64 * x2), xmask,
other=0.0)
tmp7 = r3
tmp8 = tmp7.to(tl.int16)
tmp9 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp10 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
_tmp11, tmp12 = triton_helpers.sort_with_index(tmp9, tmp10, None, 1,
stable=False, descending=True)
tl.store(out_ptr0 + (r3 + 4 * x4), tmp12, xmask)
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_cumsum_exp_flip_gather_index_max_sort_sub_1(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr
):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x3 = xindex
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp26 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp39 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp52 = tl.load(in_ptr0 + (48 + x0 + -16 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = tmp0.to(tl.int64)
tmp2 = tl.full([XBLOCK, 1], 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_ptr1 + tmp5, xmask, eviction_policy='evict_last')
tmp8 = tmp7 + tmp2
tmp9 = tmp7 < 0
tmp10 = tl.where(tmp9, tmp8, tmp7)
tl.device_assert((0 <= tmp10) & (tmp10 < 4) | ~xmask,
'index out of bounds: 0 <= tmp10 < 4')
tmp12 = tl.load(in_ptr2 + (x0 + 16 * tmp10 + 64 * x1), xmask)
tmp14 = tmp13.to(tl.int64)
tmp15 = tmp14 + tmp2
tmp16 = tmp14 < 0
tmp17 = tl.where(tmp16, tmp15, tmp14)
tl.device_assert((0 <= tmp17) & (tmp17 < 4) | ~xmask,
'index out of bounds: 0 <= tmp17 < 4')
tmp19 = tl.load(in_ptr1 + tmp17, xmask, eviction_policy='evict_last')
tmp20 = tmp19 + tmp2
tmp21 = tmp19 < 0
tmp22 = tl.where(tmp21, tmp20, tmp19)
tl.device_assert((0 <= tmp22) & (tmp22 < 4) | ~xmask,
'index out of bounds: 0 <= tmp22 < 4')
tmp24 = tl.load(in_ptr2 + (x0 + 16 * tmp22 + 64 * x1), xmask)
tmp25 = triton_helpers.maximum(tmp12, tmp24)
tmp27 = tmp26.to(tl.int64)
tmp28 = tmp27 + tmp2
tmp29 = tmp27 < 0
tmp30 = tl.where(tmp29, tmp28, tmp27)
tl.device_assert((0 <= tmp30) & (tmp30 < 4) | ~xmask,
'index out of bounds: 0 <= tmp30 < 4')
tmp32 = tl.load(in_ptr1 + tmp30, xmask, eviction_policy='evict_last')
tmp33 = tmp32 + tmp2
tmp34 = tmp32 < 0
tmp35 = tl.where(tmp34, tmp33, tmp32)
tl.device_assert((0 <= tmp35) & (tmp35 < 4) | ~xmask,
'index out of bounds: 0 <= tmp35 < 4')
tmp37 = tl.load(in_ptr2 + (x0 + 16 * tmp35 + 64 * x1), xmask)
tmp38 = triton_helpers.maximum(tmp25, tmp37)
tmp40 = tmp39.to(tl.int64)
tmp41 = tmp40 + tmp2
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tl.device_assert((0 <= tmp43) & (tmp43 < 4) | ~xmask,
'index out of bounds: 0 <= tmp43 < 4')
tmp45 = tl.load(in_ptr1 + tmp43, xmask, eviction_policy='evict_last')
tmp46 = tmp45 + tmp2
tmp47 = tmp45 < 0
tmp48 = tl.where(tmp47, tmp46, tmp45)
tl.device_assert((0 <= tmp48) & (tmp48 < 4) | ~xmask,
'index out of bounds: 0 <= tmp48 < 4')
tmp50 = tl.load(in_ptr2 + (x0 + 16 * tmp48 + 64 * x1), xmask)
tmp51 = triton_helpers.maximum(tmp38, tmp50)
tmp53 = tmp52.to(tl.int64)
tmp54 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp55 = tmp53 + tmp54
tmp56 = tmp53 < 0
tmp57 = tl.where(tmp56, tmp55, tmp53)
tl.device_assert((0 <= tmp57) & (tmp57 < 4) | ~xmask,
'index out of bounds: 0 <= tmp57 < 4')
tmp59 = tl.load(in_ptr1 + tmp57, xmask, eviction_policy='evict_last')
tmp60 = tmp59 + tmp54
tmp61 = tmp59 < 0
tmp62 = tl.where(tmp61, tmp60, tmp59)
tl.device_assert((0 <= tmp62) & (tmp62 < 4) | ~xmask,
'index out of bounds: 0 <= tmp62 < 4')
tmp64 = tl.load(in_ptr2 + (x0 + 16 * tmp62 + 64 * x1), xmask)
tmp65 = tmp64 - tmp51
tmp66 = tl_math.exp(tmp65)
tmp67 = tmp66.to(tl.float32)
tmp68 = tl.broadcast_to(tmp67, [XBLOCK, RBLOCK])
tmp69, = tl.associative_scan((tmp68,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + x3, tmp51, xmask)
tl.store(out_ptr1 + (x0 + 16 * r2 + 64 * x1), tmp69, xmask)
@triton.jit
def triton_per_fused_add_flip_gather_index_log_mean_sort_sub_sum_2(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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 + (48 + r0 + 64 * r1), None)
tmp4 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp17 = tl.load(in_out_ptr0 + r2, None)
tmp20 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp23 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp38 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp41 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp56 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp59 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp1 = 1e-05
tmp2 = tmp0 + tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp4.to(tl.int64)
tmp6 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp7 = tmp5 + tmp6
tmp8 = tmp5 < 0
tmp9 = tl.where(tmp8, tmp7, tmp5)
tl.device_assert((0 <= tmp9) & (tmp9 < 4),
'index out of bounds: 0 <= tmp9 < 4')
tmp11 = tl.load(in_ptr2 + tmp9, None, eviction_policy='evict_last')
tmp12 = tmp11 + tmp6
tmp13 = tmp11 < 0
tmp14 = tl.where(tmp13, tmp12, tmp11)
tl.device_assert((0 <= tmp14) & (tmp14 < 4),
'index out of bounds: 0 <= tmp14 < 4')
tmp16 = tl.load(in_ptr3 + (r0 + 16 * tmp14 + 64 * r1), None)
tmp18 = tmp16 - tmp17
tmp19 = tmp3 - tmp18
tmp21 = tmp20 + tmp1
tmp22 = tl_math.log(tmp21)
tmp24 = tmp23.to(tl.int64)
tmp25 = tmp24 + tmp6
tmp26 = tmp24 < 0
tmp27 = tl.where(tmp26, tmp25, tmp24)
tl.device_assert((0 <= tmp27) & (tmp27 < 4),
'index out of bounds: 0 <= tmp27 < 4')
tmp29 = tl.load(in_ptr2 + tmp27, None, eviction_policy='evict_last')
tmp30 = tmp29 + tmp6
tmp31 = tmp29 < 0
tmp32 = tl.where(tmp31, tmp30, tmp29)
tl.device_assert((0 <= tmp32) & (tmp32 < 4),
'index out of bounds: 0 <= tmp32 < 4')
tmp34 = tl.load(in_ptr3 + (r0 + 16 * tmp32 + 64 * r1), None)
tmp35 = tmp34 - tmp17
tmp36 = tmp22 - tmp35
tmp37 = tmp19 + tmp36
tmp39 = tmp38 + tmp1
tmp40 = tl_math.log(tmp39)
tmp42 = tmp41.to(tl.int64)
tmp43 = tmp42 + tmp6
tmp44 = tmp42 < 0
tmp45 = tl.where(tmp44, tmp43, tmp42)
tl.device_assert((0 <= tmp45) & (tmp45 < 4),
'index out of bounds: 0 <= tmp45 < 4')
tmp47 = tl.load(in_ptr2 + tmp45, None, eviction_policy='evict_last')
tmp48 = tmp47 + tmp6
tmp49 = tmp47 < 0
tmp50 = tl.where(tmp49, tmp48, tmp47)
tl.device_assert((0 <= tmp50) & (tmp50 < 4),
'index out of bounds: 0 <= tmp50 < 4')
tmp52 = tl.load(in_ptr3 + (r0 + 16 * tmp50 + 64 * r1), None)
tmp53 = tmp52 - tmp17
tmp54 = tmp40 - tmp53
tmp55 = tmp37 + tmp54
tmp57 = tmp56 + tmp1
tmp58 = tl_math.log(tmp57)
tmp60 = tmp59.to(tl.int64)
tmp61 = tmp60 + tmp6
tmp62 = tmp60 < 0
tmp63 = tl.where(tmp62, tmp61, tmp60)
tl.device_assert((0 <= tmp63) & (tmp63 < 4),
'index out of bounds: 0 <= tmp63 < 4')
tmp65 = tl.load(in_ptr2 + tmp63, None, eviction_policy='evict_last')
tmp66 = tmp65 + tmp6
tmp67 = tmp65 < 0
tmp68 = tl.where(tmp67, tmp66, tmp65)
tl.device_assert((0 <= tmp68) & (tmp68 < 4),
'index out of bounds: 0 <= tmp68 < 4')
tmp70 = tl.load(in_ptr3 + (r0 + 16 * tmp68 + 64 * r1), None)
tmp71 = tmp70 - tmp17
tmp72 = tmp58 - tmp71
tmp73 = tmp55 + tmp72
tmp74 = tl.broadcast_to(tmp73, [XBLOCK, RBLOCK])
tmp76 = tl.sum(tmp74, 1)[:, None]
tmp77 = 64.0
tmp78 = tmp76 / tmp77
tl.debug_barrier()
tl.store(in_out_ptr1 + 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)
buf0 = torch.ops.aten.randperm.default(4, device=device(type='cuda',
index=0), pin_memory=False)
buf1 = buf0
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int16)
get_raw_stream(0)
triton_per_fused_index_sort_0[grid(64)](buf1, arg1_1, buf3, 64, 4,
XBLOCK=8, num_warps=2, num_stages=1)
del arg1_1
buf4 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_cumsum_exp_flip_gather_index_max_sort_sub_1[grid(64)](
buf3, buf1, arg0_1, buf4, buf5, 64, 4, XBLOCK=8, num_warps=2,
num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = buf7
del buf7
triton_per_fused_add_flip_gather_index_log_mean_sort_sub_sum_2[grid(1)
](buf6, buf8, buf5, buf3, buf1, arg0_1, 1, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del arg0_1
del buf1
del buf3
del buf5
del buf6
return buf8,
class ListMLELossNew(nn.Module):
def __init__(self):
super(ListMLELossNew, self).__init__()
return
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Pepijnnn/MasterThesis
|
ListMLELoss
| false
| 962
|
[
"MIT"
] | 0
|
7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
https://github.com/Pepijnnn/MasterThesis/tree/7ec831f5e55f5f181e0196fa78284e2846ce2e26
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self):
super(DiceLoss, self).__init__()
def forward(self, input, target):
N = target.size(0)
smooth = 1
input_flat = input.view(N, -1)
target_flat = target.view(N, -1)
intersection = input_flat * target_flat
loss = 2 * (intersection.sum(1) + smooth) / (input_flat.sum(1) +
target_flat.sum(1) + smooth)
loss = 1 - loss.sum() / N
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.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_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp13 = tl.where(xmask, tmp11, 0)
tmp14 = tl.sum(tmp13, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp10, xmask)
tl.store(out_ptr2 + x0, tmp14, xmask)
@triton.jit
def triton_per_fused_add_div_mul_rsub_sum_1(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp6 = tl.load(in_ptr2 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tmp7 = tmp5 + tmp6
tmp8 = tmp7 + tmp1
tmp9 = tmp4 / tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tmp13 = 0.25
tmp14 = tmp12 * tmp13
tmp15 = tmp1 - tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(4)](arg1_1, arg0_1, buf0, buf1,
buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused_add_div_mul_rsub_sum_1[grid(1)](buf4, buf0, buf1,
buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf4,
class DiceLossNew(nn.Module):
def __init__(self):
super(DiceLossNew, self).__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Qsingle/MedicalImage
|
DiceLoss
| false
| 963
|
[
"MIT"
] | 0
|
a5020d7d2266669a4d6ffec224430e8b25cc1dfc
|
https://github.com/Qsingle/MedicalImage/tree/a5020d7d2266669a4d6ffec224430e8b25cc1dfc
|
DummyLayer
|
import torch
class DummyLayer(torch.nn.Module):
def __init__(self):
super().__init__()
self.dummy = torch.nn.Parameter(torch.ones(1, dtype=torch.float32))
def forward(self, x):
return x + self.dummy - self.dummy
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tmp3 - tmp2
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_sub_0[grid(256)](primals_2, primals_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0,
class DummyLayerNew(torch.nn.Module):
def __init__(self):
super().__init__()
self.dummy = torch.nn.Parameter(torch.ones(1, dtype=torch.float32))
def forward(self, input_0):
primals_1 = self.dummy
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
RICE-EIC/Early-Bird-GCN
|
DummyLayer
| false
| 964
|
[
"Apache-2.0"
] | 0
|
25a80b23f2ecfc46ffe00b1cf0e06052b32aad0f
|
https://github.com/RICE-EIC/Early-Bird-GCN/tree/25a80b23f2ecfc46ffe00b1cf0e06052b32aad0f
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
"""
Criterion that computes Sørensen-Dice Coefficient loss.
https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
"""
def __init__(self):
super().__init__()
self.smooth = 1.0
def forward(self, input, target):
input = input.view(-1)
target = target.view(-1)
intersection = (input * target).sum()
dice = (2.0 * intersection + self.smooth) / (input.sum() + target.
sum() + self.smooth)
return 1 - dice
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mul_rsub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = tl.broadcast_to(tmp0, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.broadcast_to(tmp1, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tmp12 = 2.0
tmp13 = tmp5 * tmp12
tmp14 = 1.0
tmp15 = tmp13 + tmp14
tmp16 = tmp8 + tmp11
tmp17 = tmp16 + tmp14
tmp18 = tmp15 / tmp17
tmp19 = tmp14 - tmp18
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp19, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mul_rsub_sum_0[grid(1)](buf3, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf3,
class DiceLossNew(nn.Module):
"""
Criterion that computes Sørensen-Dice Coefficient loss.
https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
"""
def __init__(self):
super().__init__()
self.smooth = 1.0
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Quentin18/road-segmentation
|
DiceLoss
| false
| 965
|
[
"MIT"
] | 0
|
9d212c80fa3f6926c431847337d2ca38ec96b614
|
https://github.com/Quentin18/road-segmentation/tree/9d212c80fa3f6926c431847337d2ca38ec96b614
|
ShearX
|
import torch
import torch.nn as nn
from torchvision import transforms as ttf
class ShearX(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M - 180
def forward(self, img):
return ttf.functional.affine(img, 0, [0, 0], 1, [self.angle, 0])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'M': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_fill_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x2 = xindex // 12
x1 = xindex // 3 % 4
x4 = xindex
tmp0 = x0
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp0 == tmp3
tmp5 = x2
tmp6 = tmp5.to(tl.float32)
tmp7 = 2.0
tmp8 = tmp6 < tmp7
tmp9 = 1.0
tmp10 = tmp6 * tmp9
tmp11 = -1.5
tmp12 = tmp10 + tmp11
tmp13 = 3 + -1 * x2
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 * tmp9
tmp16 = 1.5
tmp17 = tmp16 - tmp15
tmp18 = tl.where(tmp8, tmp12, tmp17)
tmp19 = tl.full([1], 0, tl.int32)
tmp20 = tmp0 == tmp19
tmp21 = x1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp22 < tmp7
tmp24 = tmp22 * tmp9
tmp25 = tmp24 + tmp11
tmp26 = 3 + -1 * x1
tmp27 = tmp26.to(tl.float32)
tmp28 = tmp27 * tmp9
tmp29 = tmp16 - tmp28
tmp30 = tl.where(tmp23, tmp25, tmp29)
tmp31 = float('nan')
tmp32 = tl.where(tmp20, tmp30, tmp31)
tmp33 = tl.where(tmp4, tmp18, tmp32)
tmp34 = tl.where(tmp2, tmp9, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_div_lift_fresh_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x1 + 3 * x0
tmp1 = tl.full([1], 3, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 2, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = -0.737263560295105
tmp8 = 0.0
tmp9 = tl.where(tmp6, tmp7, tmp8)
tmp10 = 1.0
tmp11 = tl.where(tmp4, tmp10, tmp9)
tmp12 = tl.full([1], 4, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tl.full([1], 5, tl.int64)
tmp15 = tmp0 < tmp14
tmp16 = tl.where(tmp15, tmp10, tmp8)
tmp17 = -0.0
tmp18 = tl.where(tmp13, tmp17, tmp16)
tmp19 = tl.where(tmp2, tmp11, tmp18)
tmp20 = x0
tmp21 = tmp20 < tmp3
tmp22 = 2.0
tmp23 = tl.where(tmp21, tmp22, tmp22)
tmp24 = tmp19 / tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_grid_sampler_2d_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
x0 = xindex % 16
x3 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.5
tmp4 = tmp2 + tmp3
tmp5 = libdevice.nearbyint(tmp4)
tmp6 = 0.0
tmp7 = tmp5 >= tmp6
tmp8 = 4.0
tmp9 = tmp5 < tmp8
tmp11 = tmp10 * tmp1
tmp12 = tmp11 + tmp3
tmp13 = libdevice.nearbyint(tmp12)
tmp14 = tmp13 >= tmp6
tmp15 = tmp13 < tmp8
tmp16 = tmp14 & tmp15
tmp17 = tmp9 & tmp16
tmp18 = tmp7 & tmp17
tmp19 = tmp13.to(tl.int64)
tmp20 = tl.full([1], 0, tl.int64)
tmp21 = tl.where(tmp18, tmp19, tmp20)
tmp22 = tl.full([XBLOCK], 4, tl.int32)
tmp23 = tmp21 + tmp22
tmp24 = tmp21 < 0
tmp25 = tl.where(tmp24, tmp23, tmp21)
tl.device_assert((0 <= tmp25) & (tmp25 < 4) | ~xmask,
'index out of bounds: 0 <= tmp25 < 4')
tmp27 = tmp5.to(tl.int64)
tmp28 = tl.where(tmp18, tmp27, tmp20)
tmp29 = tmp28 + tmp22
tmp30 = tmp28 < 0
tmp31 = tl.where(tmp30, tmp29, tmp28)
tl.device_assert((0 <= tmp31) & (tmp31 < 4) | ~xmask,
'index out of bounds: 0 <= tmp31 < 4')
tmp33 = tl.load(in_ptr1 + (tmp31 + 4 * tmp25 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp34 = tl.full([1], 1, tl.int64)
tmp35 = tl.where(tmp18, tmp34, tmp20)
tmp36 = tmp35.to(tl.float32)
tmp37 = tmp33 * tmp36
tl.store(out_ptr0 + x4, tmp37, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((1, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_0[grid(48)](buf2, 48, XBLOCK=64, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((1, 3, 2), (6, 2, 1), torch.float32)
triton_poi_fused_div_lift_fresh_1[grid(6)](buf3, 6, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 16, 2), (32, 2, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (1, 16, 3), (48, 3, 1),
0), buf3, out=buf4)
del buf2
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_grid_sampler_2d_2[grid(256)](buf4, arg0_1, buf5,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf4
return buf5,
class ShearXNew(nn.Module):
def __init__(self, M):
super().__init__()
self.M = M
self.angle = 359 / 10 * self.M - 180
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Hayoung93/UDA
|
ShearX
| false
| 966
|
[
"Apache-2.0"
] | 0
|
a587b01c76141d64e7cead55b62e0f3ed75890bf
|
https://github.com/Hayoung93/UDA/tree/a587b01c76141d64e7cead55b62e0f3ed75890bf
|
Convolution
|
import torch
import torch.nn as nn
import torch.nn.functional as fn
from torch.nn.parameter import Parameter
import torch.nn
def to_pair(data):
"""Converts a single or a tuple of data into a pair. If the data is a tuple with more than two elements, it selects
the first two of them. In case of single data, it duplicates that data into a pair.
Args:
data (object or tuple): The input data.
Returns:
Tuple: A pair of data.
"""
if isinstance(data, tuple):
return data[0:2]
return data, data
class Convolution(nn.Module):
"""Performs a 2D convolution over an input spike-wave composed of several input
planes. Current version only supports stride of 1 with no padding.
The input is a 4D tensor with the size :math:`(T, C_{{in}}, H_{{in}}, W_{{in}})` and the crresponsing output
is of size :math:`(T, C_{{out}}, H_{{out}}, W_{{out}})`,
where :math:`T` is the number of time steps, :math:`C` is the number of feature maps (channels), and
:math:`H`, and :math:`W` are the hight and width of the input/output planes.
* :attr:`in_channels` controls the number of input planes (channels/feature maps).
* :attr:`out_channels` controls the number of feature maps in the current layer.
* :attr:`kernel_size` controls the size of the convolution kernel. It can be a single integer or a tuple of two integers.
* :attr:`weight_mean` controls the mean of the normal distribution used for initial random weights.
* :attr:`weight_std` controls the standard deviation of the normal distribution used for initial random weights.
.. note::
Since this version of convolution does not support padding, it is the user responsibility to add proper padding
on the input before applying convolution.
Args:
in_channels (int): Number of channels in the input.
out_channels (int): Number of channels produced by the convolution.
kernel_size (int or tuple): Size of the convolving kernel.
weight_mean (float, optional): Mean of the initial random weights. Default: 0.8
weight_std (float, optional): Standard deviation of the initial random weights. Default: 0.02
"""
def __init__(self, in_channels, out_channels, kernel_size, weight_mean=
0.8, weight_std=0.02):
super(Convolution, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = to_pair(kernel_size)
self.stride = 1
self.bias = None
self.dilation = 1
self.groups = 1
self.padding = 0
self.weight = Parameter(torch.Tensor(self.out_channels, self.
in_channels, *self.kernel_size))
self.weight.requires_grad_(False)
self.reset_weight(weight_mean, weight_std)
def reset_weight(self, weight_mean=0.8, weight_std=0.02):
"""Resets weights to random values based on a normal distribution.
Args:
weight_mean (float, optional): Mean of the random weights. Default: 0.8
weight_std (float, optional): Standard deviation of the random weights. Default: 0.02
"""
self.weight.normal_(weight_mean, weight_std)
def load_weight(self, target):
"""Loads weights with the target tensor.
Args:
target (Tensor=): The target tensor.
"""
self.weight.copy_(target)
def forward(self, input):
return fn.conv2d(input, self.weight, self.bias, self.stride, self.
padding, self.dilation, self.groups)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from torch.nn.parameter import Parameter
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
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, 1, 16, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 16)](arg1_1, buf0, 16, 16,
XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_convolution_0[grid(16, 16)](arg0_1, buf1, 16, 16,
XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del arg0_1
buf2 = extern_kernels.convolution(buf0, buf1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1, 1), (4, 1, 4, 4))
del buf0
del buf1
return buf2,
def to_pair(data):
"""Converts a single or a tuple of data into a pair. If the data is a tuple with more than two elements, it selects
the first two of them. In case of single data, it duplicates that data into a pair.
Args:
data (object or tuple): The input data.
Returns:
Tuple: A pair of data.
"""
if isinstance(data, tuple):
return data[0:2]
return data, data
class ConvolutionNew(nn.Module):
"""Performs a 2D convolution over an input spike-wave composed of several input
planes. Current version only supports stride of 1 with no padding.
The input is a 4D tensor with the size :math:`(T, C_{{in}}, H_{{in}}, W_{{in}})` and the crresponsing output
is of size :math:`(T, C_{{out}}, H_{{out}}, W_{{out}})`,
where :math:`T` is the number of time steps, :math:`C` is the number of feature maps (channels), and
:math:`H`, and :math:`W` are the hight and width of the input/output planes.
* :attr:`in_channels` controls the number of input planes (channels/feature maps).
* :attr:`out_channels` controls the number of feature maps in the current layer.
* :attr:`kernel_size` controls the size of the convolution kernel. It can be a single integer or a tuple of two integers.
* :attr:`weight_mean` controls the mean of the normal distribution used for initial random weights.
* :attr:`weight_std` controls the standard deviation of the normal distribution used for initial random weights.
.. note::
Since this version of convolution does not support padding, it is the user responsibility to add proper padding
on the input before applying convolution.
Args:
in_channels (int): Number of channels in the input.
out_channels (int): Number of channels produced by the convolution.
kernel_size (int or tuple): Size of the convolving kernel.
weight_mean (float, optional): Mean of the initial random weights. Default: 0.8
weight_std (float, optional): Standard deviation of the initial random weights. Default: 0.02
"""
def __init__(self, in_channels, out_channels, kernel_size, weight_mean=
0.8, weight_std=0.02):
super(ConvolutionNew, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = to_pair(kernel_size)
self.stride = 1
self.bias = None
self.dilation = 1
self.groups = 1
self.padding = 0
self.weight = Parameter(torch.Tensor(self.out_channels, self.
in_channels, *self.kernel_size))
self.weight.requires_grad_(False)
self.reset_weight(weight_mean, weight_std)
def reset_weight(self, weight_mean=0.8, weight_std=0.02):
"""Resets weights to random values based on a normal distribution.
Args:
weight_mean (float, optional): Mean of the random weights. Default: 0.8
weight_std (float, optional): Standard deviation of the random weights. Default: 0.02
"""
self.weight.normal_(weight_mean, weight_std)
def load_weight(self, target):
"""Loads weights with the target tensor.
Args:
target (Tensor=): The target tensor.
"""
self.weight.copy_(target)
def forward(self, input_0):
arg0_1 = self.weight
arg1_1 = input_0
output = call([arg0_1, arg1_1])
return output[0]
|
R1704/SpeechRecognitionSNN
|
Convolution
| false
| 967
|
[
"MIT"
] | 0
|
4b788d1bd20d8ce201da6da8b200b3ca722c7efa
|
https://github.com/R1704/SpeechRecognitionSNN/tree/4b788d1bd20d8ce201da6da8b200b3ca722c7efa
|
HighwayLayer
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
class HighwayLayer(nn.Module):
def __init__(self, input_dim, transform_activation=F.relu,
gate_activation=F.softmax, gate_bias=-2):
super().__init__()
self.highway_transform_activation = transform_activation
self.highway_gate_activation = gate_activation
self.highway_transform = nn.Linear(input_dim, input_dim)
self.highway_gate = nn.Linear(input_dim, input_dim)
self.highway_gate.bias.data.fill_(gate_bias)
def forward(self, x):
transform_output = self.highway_transform_activation(self.
highway_transform(x))
gate_output = self.highway_gate_activation(self.highway_gate(x))
transformation_part = torch.mul(transform_output, gate_output)
carry_part = torch.mul(torch.FloatTensor([1.0]).type_as(gate_output
) - gate_output, x)
return torch.add(transformation_part, carry_part)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn.functional as F
import torch.nn as nn
import torch.jit
import torch.jit.quantized
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax__to_copy_add_mul_relu_sub_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr1 + x3, xmask)
tmp15 = tl.load(in_ptr2 + x3, xmask)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = triton_helpers.maximum(tmp10, tmp9)
tmp12 = tmp11 * tmp8
tmp13 = 1.0
tmp14 = tmp13 - tmp8
tmp16 = tmp14 * tmp15
tmp17 = tmp12 + tmp16
tl.store(in_out_ptr0 + x3, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf1, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = buf3
del buf3
triton_poi_fused__softmax__to_copy_add_mul_relu_sub_1[grid(256)](buf4,
buf2, buf0, primals_3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
return buf4, primals_3, buf0, buf1
class HighwayLayerNew(nn.Module):
def __init__(self, input_dim, transform_activation=F.relu,
gate_activation=F.softmax, gate_bias=-2):
super().__init__()
self.highway_transform_activation = transform_activation
self.highway_gate_activation = gate_activation
self.highway_transform = nn.Linear(input_dim, input_dim)
self.highway_gate = nn.Linear(input_dim, input_dim)
self.highway_gate.bias.data.fill_(gate_bias)
def forward(self, input_0):
primals_1 = self.highway_transform.weight
primals_2 = self.highway_transform.bias
primals_4 = self.highway_gate.weight
primals_5 = self.highway_gate.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
ROCmSoftwarePlatform/translate
|
HighwayLayer
| false
| 968
|
[
"BSD-3-Clause"
] | 0
|
32a6380d914ebe1a6c38c4992aac9600ed3d9810
|
https://github.com/ROCmSoftwarePlatform/translate/tree/32a6380d914ebe1a6c38c4992aac9600ed3d9810
|
Attention
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.checkpoint
class Attention(nn.Module):
def __init__(self, in_size, hidden_size):
super(Attention, self).__init__()
self.hidden = nn.Linear(in_size, hidden_size)
nn.init.orthogonal_(self.hidden.weight.data)
self.out = nn.Linear(hidden_size, in_size)
nn.init.orthogonal_(self.hidden.weight.data)
self.softmax = nn.Softmax(dim=1)
def forward(self, input):
self.alpha = self.softmax(self.out(torch.tanh(self.hidden(input))))
x = torch.sum(self.alpha * input, 1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime 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.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp4 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x2, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = 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
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf3
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_mul_sum_3[grid(64)](buf4, primals_3, buf5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
return buf5, buf4, primals_3, buf1, buf4, primals_4
class AttentionNew(nn.Module):
def __init__(self, in_size, hidden_size):
super(AttentionNew, self).__init__()
self.hidden = nn.Linear(in_size, hidden_size)
nn.init.orthogonal_(self.hidden.weight.data)
self.out = nn.Linear(hidden_size, in_size)
nn.init.orthogonal_(self.hidden.weight.data)
self.softmax = nn.Softmax(dim=1)
def forward(self, input_0):
primals_1 = self.hidden.weight
primals_2 = self.hidden.bias
primals_4 = self.out.weight
primals_5 = self.out.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
MarvinLvn/platalea
|
Attention
| false
| 969
|
[
"Apache-2.0"
] | 0
|
31def0813c90a3259f86f7d86cb576cd66dca3fe
|
https://github.com/MarvinLvn/platalea/tree/31def0813c90a3259f86f7d86cb576cd66dca3fe
|
Generator
|
import torch
import torch.nn as nn
class Generator(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, size, vocab):
super(Generator, self).__init__()
self.size = size
self.proj = nn.Linear(self.size, vocab)
def forward(self, x):
sliced_x = x[:, 0, :]
out = self.proj(sliced_x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'size': 4, 'vocab': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
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, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_add_1[grid(64)](buf2, primals_3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
class GeneratorNew(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, size, vocab):
super(GeneratorNew, self).__init__()
self.size = size
self.proj = nn.Linear(self.size, vocab)
def forward(self, input_0):
primals_2 = self.proj.weight
primals_3 = self.proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
QuLog1/QuLog
|
Generator
| false
| 970
|
[
"Apache-2.0"
] | 0
|
121f3a8c6f5ee60cde771c36b9eef823a1b2597a
|
https://github.com/QuLog1/QuLog/tree/121f3a8c6f5ee60cde771c36b9eef823a1b2597a
|
CosLoss
|
import torch
from torch import nn
import torch.utils.data
class CosLoss(nn.Module):
def __init__(self, factor=6e-07, havesum=True, havemax=True):
super(CosLoss, self).__init__()
self.factor = factor
self.havesum = havesum
self.havemax = havemax
def forward(self, w):
mask = torch.ones_like(w)
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
mask[i, j, j] = -1
nw = mask * w
tmp, _ = torch.max(nw, dim=1)
tmp, _ = torch.max(tmp, dim=1)
if self.havesum and self.havemax:
tmp_all = tmp + self.factor * torch.sum(torch.sum(nw, dim=1), dim=1
)
elif self.havesum:
tmp_all = self.factor * torch.sum(torch.sum(nw, dim=1), dim=1)
else:
tmp_all = tmp
loss = torch.mean(tmp_all)
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 import nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_fill_lift_fresh_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex
tmp0 = x2
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp5 == tmp5
tmp7 = tl.full([1], 1, tl.int32)
tmp8 = tmp1 == tmp7
tmp9 = tmp3 == tmp7
tmp10 = tmp7 == tmp5
tmp11 = tmp3 == tmp5
tmp12 = -1.0
tmp13 = 1.0
tmp14 = tl.where(tmp11, tmp12, tmp13)
tmp15 = tl.where(tmp10, tmp14, tmp13)
tmp16 = tl.where(tmp6, tmp15, tmp13)
tmp17 = tl.where(tmp9, tmp12, tmp16)
tmp18 = tmp1 == tmp5
tmp19 = tl.where(tmp18, tmp14, tmp13)
tmp20 = tl.where(tmp6, tmp19, tmp13)
tmp21 = tl.where(tmp8, tmp17, tmp20)
tmp22 = tl.where(tmp6, tmp21, tmp20)
tmp23 = tl.where(tmp4, tmp12, tmp22)
tmp24 = tmp0 == tmp7
tmp25 = tmp0 == tmp5
tmp26 = tl.where(tmp25, tmp14, tmp13)
tmp27 = tl.where(tmp6, tmp26, tmp13)
tmp28 = tl.where(tmp24, tmp17, tmp27)
tmp29 = tl.where(tmp6, tmp28, tmp27)
tmp30 = tl.where(tmp2, tmp23, tmp29)
tl.store(out_ptr0 + x3, tmp30, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_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 // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp7 = tl.load(in_ptr0 + (48 + x3), xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + x4, xmask)
tmp0 = x2
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp5 == tmp5
tmp8 = tl.full([1], 1, tl.int32)
tmp9 = tmp1 == tmp8
tmp10 = tmp3 == tmp8
tmp11 = tmp8 == tmp5
tmp12 = tmp3 == tmp5
tmp13 = -1.0
tmp14 = 1.0
tmp15 = tl.where(tmp12, tmp13, tmp14)
tmp16 = tl.where(tmp11, tmp15, tmp14)
tmp17 = tl.where(tmp6, tmp16, tmp14)
tmp18 = tl.where(tmp10, tmp13, tmp17)
tmp19 = tmp1 == tmp5
tmp20 = tl.where(tmp19, tmp15, tmp14)
tmp21 = tl.where(tmp6, tmp20, tmp14)
tmp22 = tl.where(tmp9, tmp18, tmp21)
tmp23 = tl.where(tmp6, tmp22, tmp21)
tmp24 = tl.where(tmp6, tmp7, tmp23)
tmp25 = tl.where(tmp4, tmp13, tmp24)
tmp27 = tmp0 == tmp8
tmp28 = tmp0 == tmp5
tmp29 = tl.where(tmp28, tmp15, tmp14)
tmp30 = tl.where(tmp6, tmp29, tmp14)
tmp31 = tl.where(tmp27, tmp18, tmp30)
tmp32 = tl.where(tmp6, tmp31, tmp30)
tmp33 = tl.where(tmp6, tmp26, tmp32)
tmp34 = tl.where(tmp2, tmp25, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp7 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + x4, xmask)
tmp27 = tl.load(in_ptr1 + x4, xmask)
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 1, tl.int32)
tmp6 = tmp5 == tmp1
tmp9 = tmp1 == tmp5
tmp10 = tmp3 == tmp5
tmp11 = tmp1 == tmp1
tmp12 = -1.0
tmp13 = 1.0
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tl.where(tmp6, tmp14, tmp13)
tmp16 = tl.where(tmp11, tmp15, tmp13)
tmp17 = tl.where(tmp10, tmp12, tmp16)
tmp18 = tl.where(tmp11, tmp14, tmp13)
tmp19 = tl.where(tmp11, tmp18, tmp13)
tmp20 = tl.where(tmp9, tmp17, tmp19)
tmp21 = tl.where(tmp6, tmp18, tmp13)
tmp22 = tl.where(tmp6, tmp20, tmp21)
tmp23 = tl.where(tmp6, tmp8, tmp22)
tmp24 = tl.where(tmp6, tmp7, tmp23)
tmp25 = tl.where(tmp4, tmp12, tmp24)
tmp28 = tmp0 == tmp5
tmp29 = tl.where(tmp2, tmp14, tmp13)
tmp30 = tl.where(tmp11, tmp29, tmp13)
tmp31 = tl.where(tmp28, tmp17, tmp30)
tmp32 = tl.where(tmp6, tmp29, tmp13)
tmp33 = tl.where(tmp6, tmp31, tmp32)
tmp34 = tl.where(tmp6, tmp27, tmp33)
tmp35 = tl.where(tmp6, tmp26, tmp34)
tmp36 = tl.where(tmp2, tmp25, tmp35)
tl.store(out_ptr0 + x4, tmp36, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp6 = tl.load(in_ptr0 + (16 + x3), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (16 + x3), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr2 + (16 + x3), xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + x4, xmask)
tmp27 = tl.load(in_ptr1 + x4, xmask)
tmp28 = tl.load(in_ptr2 + x4, xmask)
tmp0 = x2
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tmp1 == tmp1
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = tmp1 == tmp7
tmp11 = tmp7 == tmp7
tmp12 = tmp3 == tmp7
tmp13 = -1.0
tmp14 = 1.0
tmp15 = tl.where(tmp12, tmp13, tmp14)
tmp16 = tl.where(tmp8, tmp15, tmp14)
tmp17 = tl.where(tmp11, tmp16, tmp14)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tmp19 = tl.where(tmp5, tmp18, tmp17)
tmp20 = tl.where(tmp8, tmp16, tmp14)
tmp21 = tl.where(tmp8, tmp19, tmp20)
tmp22 = tl.where(tmp8, tmp10, tmp21)
tmp23 = tl.where(tmp8, tmp9, tmp22)
tmp24 = tl.where(tmp5, tmp6, tmp23)
tmp25 = tl.where(tmp4, tmp13, tmp24)
tmp29 = tmp0 == tmp7
tmp30 = tl.where(tmp29, tmp15, tmp14)
tmp31 = tl.where(tmp11, tmp30, tmp14)
tmp32 = tl.where(tmp2, tmp18, tmp31)
tmp33 = tl.where(tmp8, tmp30, tmp14)
tmp34 = tl.where(tmp8, tmp32, tmp33)
tmp35 = tl.where(tmp8, tmp28, tmp34)
tmp36 = tl.where(tmp8, tmp27, tmp35)
tmp37 = tl.where(tmp5, tmp26, tmp36)
tmp38 = tl.where(tmp2, tmp25, tmp37)
tl.store(out_ptr0 + x4, tmp38, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_ones_like_4(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
x3 = xindex // 64
x4 = xindex % 64
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
tmp0 = x3
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp0 == tmp5
tmp9 = x2
tmp10 = tmp9 == tmp1
tmp11 = x1
tmp12 = tmp11 == tmp1
tmp13 = tmp5 == tmp5
tmp14 = tmp1 == tmp5
tmp15 = tmp11 == tmp5
tmp16 = -1.0
tmp17 = 1.0
tmp18 = tl.where(tmp15, tmp16, tmp17)
tmp19 = tl.where(tmp14, tmp18, tmp17)
tmp20 = tl.where(tmp13, tmp19, tmp17)
tmp21 = tl.where(tmp12, tmp16, tmp20)
tmp22 = tmp9 == tmp5
tmp23 = tl.where(tmp22, tmp18, tmp17)
tmp24 = tl.where(tmp13, tmp23, tmp17)
tmp25 = tl.where(tmp10, tmp21, tmp24)
tmp26 = tl.where(tmp6, tmp23, tmp17)
tmp27 = tl.where(tmp6, tmp25, tmp26)
tmp28 = tl.where(tmp6, tmp8, tmp27)
tmp29 = tl.where(tmp6, tmp7, tmp28)
tmp30 = tl.where(tmp2, tmp4, tmp29)
tmp31 = tl.where(tmp2, tmp3, tmp30)
tl.store(out_ptr0 + x5, tmp31, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_5(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp14 = tl.load(in_ptr0 + (96 + x3), xmask, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr0 + (112 + x3), xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr0 + (64 + x3), xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + (128 + x3), xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr0 + (64 + x4), xmask)
tmp36 = tl.load(in_ptr0 + (128 + x4), xmask)
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 2, tl.int32)
tmp6 = tl.full([1], 1, tl.int32)
tmp7 = tmp5 == tmp6
tmp8 = tl.full([1], 3, tl.int32)
tmp9 = tmp1 == tmp8
tmp10 = tmp3 == tmp8
tmp11 = tmp6 == tmp6
tmp12 = tmp8 == tmp5
tmp13 = tmp3 == tmp5
tmp15 = -1.0
tmp16 = tl.where(tmp13, tmp15, tmp14)
tmp18 = tl.where(tmp12, tmp16, tmp17)
tmp19 = tl.where(tmp11, tmp18, tmp17)
tmp20 = tl.where(tmp10, tmp15, tmp19)
tmp21 = tmp1 == tmp5
tmp23 = tl.where(tmp21, tmp16, tmp22)
tmp24 = tl.where(tmp11, tmp23, tmp22)
tmp25 = tl.where(tmp9, tmp20, tmp24)
tmp27 = tl.where(tmp7, tmp23, tmp26)
tmp28 = tl.where(tmp7, tmp25, tmp27)
tmp29 = tl.where(tmp4, tmp15, tmp28)
tmp30 = tmp0 == tmp8
tmp31 = tmp0 == tmp5
tmp33 = tl.where(tmp31, tmp16, tmp32)
tmp34 = tl.where(tmp11, tmp33, tmp32)
tmp35 = tl.where(tmp30, tmp20, tmp34)
tmp37 = tl.where(tmp7, tmp33, tmp36)
tmp38 = tl.where(tmp7, tmp35, tmp37)
tmp39 = tl.where(tmp2, tmp29, tmp38)
tl.store(out_ptr0 + x4, tmp39, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_6(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
x4 = xindex % 64
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x6 = xindex % 16
x7 = xindex
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr1 + (96 + x6), xmask, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr1 + (112 + x6), xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr1 + (64 + x4), xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr1 + x7, xmask)
tmp0 = x3
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl.full([1], 1, tl.int32)
tmp5 = tmp0 == tmp4
tmp6 = x2
tmp7 = tl.full([1], 3, tl.int32)
tmp8 = tmp6 == tmp7
tmp9 = x1
tmp10 = tmp9 == tmp7
tmp11 = tmp4 == tmp4
tmp12 = tmp7 == tmp1
tmp13 = tmp9 == tmp1
tmp15 = -1.0
tmp16 = tl.where(tmp13, tmp15, tmp14)
tmp18 = tl.where(tmp12, tmp16, tmp17)
tmp19 = tl.where(tmp11, tmp18, tmp17)
tmp20 = tl.where(tmp10, tmp15, tmp19)
tmp21 = tmp6 == tmp1
tmp23 = tl.where(tmp21, tmp16, tmp22)
tmp24 = tl.where(tmp11, tmp23, tmp22)
tmp25 = tl.where(tmp8, tmp20, tmp24)
tmp27 = tl.where(tmp5, tmp23, tmp26)
tmp28 = tl.where(tmp5, tmp25, tmp27)
tmp29 = tl.where(tmp2, tmp3, tmp28)
tl.store(out_ptr0 + x7, tmp29, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_7(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp12 = tl.load(in_ptr0 + (144 + x3), xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (160 + x3), xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr0 + (176 + x3), xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr0 + (128 + x4), xmask)
tmp0 = x2
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 2, tl.int32)
tmp6 = tmp5 == tmp5
tmp7 = tmp1 == tmp5
tmp8 = tmp3 == tmp5
tmp9 = tl.full([1], 1, tl.int32)
tmp10 = tmp5 == tmp9
tmp11 = tmp3 == tmp9
tmp13 = -1.0
tmp14 = tl.where(tmp11, tmp13, tmp12)
tmp16 = tl.where(tmp10, tmp14, tmp15)
tmp17 = tl.where(tmp6, tmp16, tmp15)
tmp18 = tl.where(tmp8, tmp13, tmp17)
tmp19 = tmp1 == tmp9
tmp21 = tl.where(tmp19, tmp14, tmp20)
tmp22 = tl.where(tmp6, tmp21, tmp20)
tmp23 = tl.where(tmp7, tmp18, tmp22)
tmp24 = tl.where(tmp6, tmp23, tmp22)
tmp25 = tl.where(tmp4, tmp13, tmp24)
tmp26 = tmp0 == tmp5
tmp27 = tmp0 == tmp9
tmp29 = tl.where(tmp27, tmp14, tmp28)
tmp30 = tl.where(tmp6, tmp29, tmp28)
tmp31 = tl.where(tmp26, tmp18, tmp30)
tmp32 = tl.where(tmp6, tmp31, tmp30)
tmp33 = tl.where(tmp2, tmp25, tmp32)
tl.store(out_ptr0 + x4, tmp33, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_8(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
x4 = xindex % 64
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x6 = xindex % 16
x7 = xindex
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + (144 + x6), xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + (160 + x6), xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr1 + (128 + x4), xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr1 + x7, xmask)
tmp0 = x3
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x2
tmp5 = tmp4 == tmp1
tmp6 = x1
tmp7 = tmp6 == tmp1
tmp8 = tmp1 == tmp1
tmp9 = tl.full([1], 1, tl.int32)
tmp10 = tmp1 == tmp9
tmp11 = tmp6 == tmp9
tmp13 = -1.0
tmp14 = tl.where(tmp11, tmp13, tmp12)
tmp16 = tl.where(tmp10, tmp14, tmp15)
tmp17 = tl.where(tmp8, tmp16, tmp15)
tmp18 = tl.where(tmp7, tmp13, tmp17)
tmp19 = tmp4 == tmp9
tmp21 = tl.where(tmp19, tmp14, tmp20)
tmp22 = tl.where(tmp8, tmp21, tmp20)
tmp23 = tl.where(tmp5, tmp18, tmp22)
tmp25 = tl.where(tmp2, tmp21, tmp24)
tmp26 = tl.where(tmp2, tmp23, tmp25)
tmp27 = tl.where(tmp2, tmp3, tmp26)
tl.store(out_ptr0 + x7, tmp27, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_9(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp13 = tl.load(in_ptr0 + (192 + x3), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (208 + x3), xmask, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr0 + (224 + x3), xmask, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr0 + (192 + x4), xmask)
tmp0 = x2
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = x1
tmp4 = tmp3 == tmp1
tmp5 = tl.full([1], 3, tl.int32)
tmp6 = tmp5 == tmp5
tmp7 = tl.full([1], 1, tl.int32)
tmp8 = tmp1 == tmp7
tmp9 = tmp3 == tmp7
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = tmp7 == tmp10
tmp12 = tmp3 == tmp10
tmp14 = -1.0
tmp15 = tl.where(tmp12, tmp14, tmp13)
tmp17 = tl.where(tmp11, tmp15, tmp16)
tmp18 = tl.where(tmp6, tmp17, tmp16)
tmp19 = tl.where(tmp9, tmp14, tmp18)
tmp20 = tmp1 == tmp10
tmp22 = tl.where(tmp20, tmp15, tmp21)
tmp23 = tl.where(tmp6, tmp22, tmp21)
tmp24 = tl.where(tmp8, tmp19, tmp23)
tmp25 = tl.where(tmp6, tmp24, tmp23)
tmp26 = tl.where(tmp4, tmp14, tmp25)
tmp27 = tmp0 == tmp7
tmp28 = tmp0 == tmp10
tmp30 = tl.where(tmp28, tmp15, tmp29)
tmp31 = tl.where(tmp6, tmp30, tmp29)
tmp32 = tl.where(tmp27, tmp19, tmp31)
tmp33 = tl.where(tmp6, tmp32, tmp31)
tmp34 = tl.where(tmp2, tmp26, tmp33)
tl.store(out_ptr0 + x4, tmp34, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_10(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
x4 = xindex % 64
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x6 = xindex % 16
x7 = xindex
tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + (192 + x6), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (208 + x6), xmask, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr1 + (192 + x4), xmask, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr1 + x7, xmask)
tmp0 = x3
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = x2
tmp5 = tl.full([1], 1, tl.int32)
tmp6 = tmp4 == tmp5
tmp7 = x1
tmp8 = tmp7 == tmp5
tmp9 = tmp1 == tmp1
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = tmp5 == tmp10
tmp12 = tmp7 == tmp10
tmp14 = -1.0
tmp15 = tl.where(tmp12, tmp14, tmp13)
tmp17 = tl.where(tmp11, tmp15, tmp16)
tmp18 = tl.where(tmp9, tmp17, tmp16)
tmp19 = tl.where(tmp8, tmp14, tmp18)
tmp20 = tmp4 == tmp10
tmp22 = tl.where(tmp20, tmp15, tmp21)
tmp23 = tl.where(tmp9, tmp22, tmp21)
tmp24 = tl.where(tmp6, tmp19, tmp23)
tmp26 = tl.where(tmp2, tmp22, tmp25)
tmp27 = tl.where(tmp2, tmp24, tmp26)
tmp28 = tl.where(tmp2, tmp3, tmp27)
tl.store(out_ptr0 + x7, tmp28, xmask)
@triton.jit
def triton_poi_fused_fill_lift_fresh_max_mul_sum_11(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp7 = tl.load(in_ptr0 + (240 + x3), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (192 + x3), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask)
tmp14 = tl.load(in_ptr1 + (x3 + 64 * x2), xmask)
tmp18 = tl.load(in_ptr0 + (208 + x3), xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask)
tmp22 = tl.load(in_ptr1 + (16 + x3 + 64 * x2), xmask)
tmp27 = tl.load(in_ptr0 + (224 + x3), xmask, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask)
tmp31 = tl.load(in_ptr1 + (32 + x3 + 64 * x2), xmask)
tmp36 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask)
tmp38 = tl.load(in_ptr1 + (48 + x3 + 64 * x2), xmask)
tmp0 = x2
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = tmp3 == tmp1
tmp5 = x1
tmp6 = tmp5 == tmp1
tmp8 = -1.0
tmp9 = tl.where(tmp6, tmp8, tmp7)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp13 = tl.where(tmp2, tmp11, tmp12)
tmp15 = tmp13 * tmp14
tmp16 = tl.full([1], 1, tl.int32)
tmp17 = tmp16 == tmp1
tmp19 = tl.where(tmp17, tmp9, tmp18)
tmp21 = tl.where(tmp2, tmp19, tmp20)
tmp23 = tmp21 * tmp22
tmp24 = triton_helpers.maximum(tmp15, tmp23)
tmp25 = tl.full([1], 2, tl.int32)
tmp26 = tmp25 == tmp1
tmp28 = tl.where(tmp26, tmp9, tmp27)
tmp30 = tl.where(tmp2, tmp28, tmp29)
tmp32 = tmp30 * tmp31
tmp33 = triton_helpers.maximum(tmp24, tmp32)
tmp34 = tmp1 == tmp1
tmp35 = tl.where(tmp34, tmp9, tmp7)
tmp37 = tl.where(tmp2, tmp35, tmp36)
tmp39 = tmp37 * tmp38
tmp40 = triton_helpers.maximum(tmp33, tmp39)
tmp41 = tmp15 + tmp23
tmp42 = tmp41 + tmp32
tmp43 = tmp42 + tmp39
tl.store(out_ptr0 + x4, tmp40, xmask)
tl.store(out_ptr1 + x4, tmp43, xmask)
@triton.jit
def triton_per_fused_add_max_mean_mul_sum_12(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 4
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + (r0 + 16 * r1), None)
tmp1 = tl.load(in_ptr0 + (4 + r0 + 16 * r1), None)
tmp3 = tl.load(in_ptr0 + (8 + r0 + 16 * r1), None)
tmp5 = tl.load(in_ptr0 + (12 + r0 + 16 * r1), None)
tmp7 = tl.load(in_ptr1 + (r0 + 16 * r1), None)
tmp8 = tl.load(in_ptr1 + (4 + r0 + 16 * r1), None)
tmp10 = tl.load(in_ptr1 + (8 + r0 + 16 * r1), None)
tmp12 = tl.load(in_ptr1 + (12 + r0 + 16 * r1), None)
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp9 = tmp7 + tmp8
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp14 = 6e-07
tmp15 = tmp13 * tmp14
tmp16 = tmp6 + tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = tl.sum(tmp17, 1)[:, None]
tmp20 = 16.0
tmp21 = tmp19 / tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp21, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_lift_fresh_0[grid(64)](buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_fill_lift_fresh_1[grid(64)](buf0, buf1, 64, XBLOCK
=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_fill_lift_fresh_2[grid(64)](buf1, buf0, buf2, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_fill_lift_fresh_3[grid(64)](buf2, buf1, buf0, buf3,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_fill_lift_fresh_ones_like_4[grid(256)](buf3, buf2,
buf1, buf0, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del buf1
buf5 = buf3
del buf3
triton_poi_fused_fill_lift_fresh_5[grid(64)](buf4, buf5, 64, XBLOCK
=64, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_fill_lift_fresh_6[grid(256)](buf5, buf4, buf6, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused_fill_lift_fresh_7[grid(64)](buf6, buf7, 64, XBLOCK
=64, num_warps=1, num_stages=1)
buf8 = buf4
del buf4
triton_poi_fused_fill_lift_fresh_8[grid(256)](buf7, buf6, buf8, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused_fill_lift_fresh_9[grid(64)](buf8, buf9, 64, XBLOCK
=64, num_warps=1, num_stages=1)
buf10 = buf6
del buf6
triton_poi_fused_fill_lift_fresh_10[grid(256)](buf9, buf8, buf10,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf8
buf11 = buf9
del buf9
buf12 = buf2
del buf2
triton_poi_fused_fill_lift_fresh_max_mul_sum_11[grid(64)](buf10,
arg0_1, buf11, buf12, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del buf10
buf13 = empty_strided_cuda((), (), torch.float32)
buf14 = buf13
del buf13
triton_per_fused_add_max_mean_mul_sum_12[grid(1)](buf14, buf11,
buf12, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf11
del buf12
return buf14,
class CosLossNew(nn.Module):
def __init__(self, factor=6e-07, havesum=True, havemax=True):
super(CosLossNew, self).__init__()
self.factor = factor
self.havesum = havesum
self.havemax = havemax
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
PatrickGui/Face_Pytorch
|
CosLoss
| false
| 971
|
[
"Apache-2.0"
] | 0
|
ff5b820ca3978883f7cf95f0209fba3ee958c939
|
https://github.com/PatrickGui/Face_Pytorch/tree/ff5b820ca3978883f7cf95f0209fba3ee958c939
|
CumulativeLinkLoss
|
import torch
import numpy as np
from torch import nn
from typing import Optional
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
def _reduction(loss: 'torch.Tensor', reduction: 'str') ->torch.Tensor:
"""
Reduce loss
Parameters
----------
loss : torch.Tensor, [batch_size, num_classes]
Batch losses.
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
Returns
-------
loss : torch.Tensor
Reduced loss.
"""
if reduction == 'elementwise_mean':
return loss.mean()
elif reduction == 'none':
return loss
elif reduction == 'sum':
return loss.sum()
else:
raise ValueError(f'{reduction} is not a valid reduction')
def cumulative_link_loss(y_pred: 'torch.Tensor', y_true: 'torch.Tensor',
reduction: 'str'='elementwise_mean', class_weights:
'Optional[np.ndarray]'=None) ->torch.Tensor:
"""
Calculates the negative log likelihood using the logistic cumulative link
function.
See "On the consistency of ordinal regression methods", Pedregosa et. al.
for more details. While this paper is not the first to introduce this, it
is the only one that I could find that was easily readable outside of
paywalls.
Parameters
----------
y_pred : torch.Tensor, [batch_size, num_classes]
Predicted target class probabilities. float dtype.
y_true : torch.Tensor, [batch_size, 1]
True target classes. long dtype.
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
class_weights : np.ndarray, [num_classes] optional (default=None)
An array of weights for each class. If included, then for each sample,
look up the true class and multiply that sample's loss by the weight in
this array.
Returns
-------
loss: torch.Tensor
"""
eps = 1e-15
likelihoods = torch.clamp(torch.gather(y_pred, 1, y_true.unsqueeze(1)),
eps, 1 - eps)
neg_log_likelihood = -torch.log(likelihoods)
if class_weights is not None:
class_weights = torch.as_tensor(class_weights, dtype=
neg_log_likelihood.dtype, device=neg_log_likelihood.device)
neg_log_likelihood *= class_weights[y_true]
loss = _reduction(neg_log_likelihood, reduction)
return loss
class CumulativeLinkLoss(nn.Module):
"""
Module form of cumulative_link_loss() loss function
Parameters
----------
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
class_weights : np.ndarray, [num_classes] optional (default=None)
An array of weights for each class. If included, then for each sample,
look up the true class and multiply that sample's loss by the weight in
this array.
"""
def __init__(self, reduction: 'str'='elementwise_mean', class_weights:
'Optional[torch.Tensor]'=None) ->None:
super().__init__()
self.class_weights = class_weights
self.reduction = reduction
def forward(self, y_pred: 'torch.Tensor', y_true: 'torch.Tensor'
) ->torch.Tensor:
return cumulative_link_loss(y_pred, y_true, reduction=self.
reduction, class_weights=self.class_weights)
def get_inputs():
return [torch.ones([4, 4], dtype=torch.int64), torch.ones([4], dtype=
torch.int64)]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import numpy as np
from torch import nn
from typing import Optional
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_clamp_gather_log_mean_neg_0(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4),
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (tmp4 + 4 * r0), None, eviction_policy=
'evict_last')
tmp7 = tmp6.to(tl.float32)
tmp8 = 1e-15
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = 0.999999999999999
tmp11 = triton_helpers.minimum(tmp9, tmp10)
tmp12 = tmp11.to(tl.int64)
tmp13 = tmp12.to(tl.float32)
tmp14 = tl_math.log(tmp13)
tmp15 = -tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp19 = 4.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, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (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_clamp_gather_log_mean_neg_0[grid(1)](buf1, arg1_1,
arg0_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def _reduction(loss: 'torch.Tensor', reduction: 'str') ->torch.Tensor:
"""
Reduce loss
Parameters
----------
loss : torch.Tensor, [batch_size, num_classes]
Batch losses.
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
Returns
-------
loss : torch.Tensor
Reduced loss.
"""
if reduction == 'elementwise_mean':
return loss.mean()
elif reduction == 'none':
return loss
elif reduction == 'sum':
return loss.sum()
else:
raise ValueError(f'{reduction} is not a valid reduction')
def cumulative_link_loss(y_pred: 'torch.Tensor', y_true: 'torch.Tensor',
reduction: 'str'='elementwise_mean', class_weights:
'Optional[np.ndarray]'=None) ->torch.Tensor:
"""
Calculates the negative log likelihood using the logistic cumulative link
function.
See "On the consistency of ordinal regression methods", Pedregosa et. al.
for more details. While this paper is not the first to introduce this, it
is the only one that I could find that was easily readable outside of
paywalls.
Parameters
----------
y_pred : torch.Tensor, [batch_size, num_classes]
Predicted target class probabilities. float dtype.
y_true : torch.Tensor, [batch_size, 1]
True target classes. long dtype.
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
class_weights : np.ndarray, [num_classes] optional (default=None)
An array of weights for each class. If included, then for each sample,
look up the true class and multiply that sample's loss by the weight in
this array.
Returns
-------
loss: torch.Tensor
"""
eps = 1e-15
likelihoods = torch.clamp(torch.gather(y_pred, 1, y_true.unsqueeze(1)),
eps, 1 - eps)
neg_log_likelihood = -torch.log(likelihoods)
if class_weights is not None:
class_weights = torch.as_tensor(class_weights, dtype=
neg_log_likelihood.dtype, device=neg_log_likelihood.device)
neg_log_likelihood *= class_weights[y_true]
loss = _reduction(neg_log_likelihood, reduction)
return loss
class CumulativeLinkLossNew(nn.Module):
"""
Module form of cumulative_link_loss() loss function
Parameters
----------
reduction : str
Method for reducing the loss. Options include 'elementwise_mean',
'none', and 'sum'.
class_weights : np.ndarray, [num_classes] optional (default=None)
An array of weights for each class. If included, then for each sample,
look up the true class and multiply that sample's loss by the weight in
this array.
"""
def __init__(self, reduction: 'str'='elementwise_mean', class_weights:
'Optional[torch.Tensor]'=None) ->None:
super().__init__()
self.class_weights = class_weights
self.reduction = reduction
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Ramstein/Retinopathy2
|
CumulativeLinkLoss
| false
| 972
|
[
"MIT"
] | 0
|
669e74206c466e6351d4e3df6087c6aa39b5c6c2
|
https://github.com/Ramstein/Retinopathy2/tree/669e74206c466e6351d4e3df6087c6aa39b5c6c2
|
CustomBatchNormAutograd
|
import torch
import torch.nn as nn
class CustomBatchNormAutograd(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
The operations called in self.forward track the history if the input tensors have the
flag requires_grad set to True.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormAutograd object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
"""
super(CustomBatchNormAutograd, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.beta = nn.Parameter(torch.zeros(self.n_neurons))
self.gamma = nn.Parameter(torch.ones(self.n_neurons))
def forward(self, input):
"""
Compute the batch normalization
Args:
input: input tensor of shape (n_batch, n_neurons)
Returns:
out: batch-normalized tensor
"""
batch_size = input.shape[0]
assert input.shape[1
] == self.n_neurons, 'Input not in the correct shape'
mean = 1 / batch_size * torch.sum(input, dim=0)
var = input.var(dim=0, unbiased=False)
norm = (input - mean) / torch.sqrt(var + self.eps)
out = self.gamma * norm + self.beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_neurons': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mul_sqrt_sub_sum_var_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x4 = xindex
x5 = xindex % 64
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x4, xmask)
tmp2 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (64 + x5), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (128 + x5), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (192 + x5), xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 0.25
tmp10 = tmp8 * tmp9
tmp11 = tmp1 - tmp10
tmp12 = 4.0
tmp13 = tmp8 / tmp12
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tmp3 - tmp13
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp19 = tmp5 - tmp13
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp7 - tmp13
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp24 / tmp12
tmp26 = 1e-05
tmp27 = tmp25 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = tmp11 / tmp28
tmp30 = tmp0 * tmp29
tmp32 = tmp30 + tmp31
tl.store(in_out_ptr0 + x4, 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,), (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)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_div_mul_sqrt_sub_sum_var_0[grid(256)](buf1,
primals_2, primals_1, primals_3, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_2
del primals_3
return buf1, primals_1
class CustomBatchNormAutogradNew(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
The operations called in self.forward track the history if the input tensors have the
flag requires_grad set to True.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormAutograd object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
"""
super(CustomBatchNormAutogradNew, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.beta = nn.Parameter(torch.zeros(self.n_neurons))
self.gamma = nn.Parameter(torch.ones(self.n_neurons))
def forward(self, input_0):
primals_2 = self.beta
primals_3 = self.gamma
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
RaymondKoopmanschap/DL_assignment_code
|
CustomBatchNormAutograd
| false
| 973
|
[
"MIT"
] | 0
|
68b3290be9fbd6c55433a7585e2cfa18e0f35f5c
|
https://github.com/RaymondKoopmanschap/DL_assignment_code/tree/68b3290be9fbd6c55433a7585e2cfa18e0f35f5c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.