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
|
|---|---|---|---|---|---|---|---|---|---|---|
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. The backward pass does not need to be implemented, it
is dealt with by the automatic differentiation provided by PyTorch.
"""
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
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormAutograd, self).__init__()
self.gamma = nn.Parameter(torch.ones(n_neurons))
self.beta = nn.Parameter(torch.zeros(n_neurons))
self.eps = eps
def forward(self, input):
"""
Compute the batch normalization
Args:
input: input tensor of shape (n_batch, n_neurons)
Returns:
out: batch-normalized tensor
TODO:
Check for the correctness of the shape of the input tensor.
Implement batch normalization forward pass as given in the assignment.
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
shape = input.shape
if len(shape) == 1:
input = input.unsqueeze(0)
shape = input.shape
elif len(shape) > 2:
raise ValueError(
f'Expected 2D input. Instead, got {len(shape)}D input with shape of {shape}.'
)
elif shape[1] != self.gamma.shape[0]:
raise ValueError(
f'Expected input of shape batch_size x {self.gamma.shape[0]}. Instead, got input withshape of {shape}.'
)
mean = input.mean(0)
var = input.var(0)
x_hat = (input - mean) / torch.sqrt(var + self.eps)
out = self.gamma * x_hat + self.beta
return out
def get_inputs():
return [torch.rand([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_mean_mul_sqrt_sub_var_0(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
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp2 - tmp10
tmp13 = tmp12 * tmp12
tmp14 = tmp3 - tmp10
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp10
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp7 - tmp10
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = 3.0
tmp24 = tmp22 / tmp23
tmp25 = 1e-05
tmp26 = tmp24 + tmp25
tmp27 = libdevice.sqrt(tmp26)
tmp28 = tmp11 / tmp27
tmp29 = tmp0 * tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, 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,), (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_add_div_mean_mul_sqrt_sub_var_0[grid(16)](primals_2,
primals_1, primals_3, buf0, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_3
return buf0, 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. The backward pass does not need to be implemented, it
is dealt with by the automatic differentiation provided by PyTorch.
"""
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
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormAutogradNew, self).__init__()
self.gamma = nn.Parameter(torch.ones(n_neurons))
self.beta = nn.Parameter(torch.zeros(n_neurons))
self.eps = eps
def forward(self, input_0):
primals_2 = self.gamma
primals_3 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
askliar/deep_learning
|
CustomBatchNormAutograd
| false
| 1,488
|
[
"MIT"
] | 0
|
e61b2391a3258d18719bf12d9ed1404620ce6c02
|
https://github.com/askliar/deep_learning/tree/e61b2391a3258d18719bf12d9ed1404620ce6c02
|
CustomBatchNormManualModule
|
import torch
import torch.nn as nn
class CustomBatchNormManualFunction(torch.autograd.Function):
"""
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs.
Using torch.autograd.Function allows you to write a custom backward function.
The function will be called from the nn.Module CustomBatchNormManualModule
Inside forward the tensors are (automatically) not recorded for automatic differentiation since the backward
pass is done via the backward method.
The forward pass is not called directly but via the apply() method. This makes sure that the context objects
are dealt with correctly. Example:
my_bn_fct = CustomBatchNormManualFunction()
normalized = fct.apply(input, gamma, beta, eps)
"""
@staticmethod
def forward(ctx, input, gamma, beta, eps=1e-05):
"""
Compute the batch normalization
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
input: input tensor of shape (n_batch, n_neurons)
gamma: variance scaling tensor, applied per neuron, shpae (n_neurons)
beta: mean bias tensor, applied per neuron, shpae (n_neurons)
eps: small float added to the variance for stability
Returns:
out: batch-normalized tensor
TODO:
Implement the forward pass of batch normalization
Store constant non-tensor objects via ctx.constant=myconstant
Store tensors which you need in the backward pass via ctx.save_for_backward(tensor1, tensor2, ...)
Intermediate results can be decided to be either recomputed in the backward pass or to be stored
for the backward pass. Do not store tensors which are unnecessary for the backward pass to save memory!
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
shape = input.shape
if len(shape) == 1:
input = input.unsqueeze(0)
shape = input.shape
elif len(shape) > 2:
raise ValueError(
f'Expected 2D input. Instead, got {len(shape)}D input with shape of {shape}.'
)
elif shape[1] != gamma.shape[0]:
raise ValueError(
f'Expected input of shape batch_size x {gamma.shape[0]}. Instead, got input withshape of {shape}.'
)
mean = input.mean(0)
var = input.var(0, unbiased=False)
inv_var = 1 / torch.sqrt(var + eps)
x_hat = (input - mean) * inv_var
out = gamma * x_hat + beta
ctx.save_for_backward(input, gamma, beta, mean, inv_var)
ctx.eps = eps
return out
@staticmethod
def backward(ctx, grad_output):
"""
Compute backward pass of the batch normalization.
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
Returns:
out: tuple containing gradients for all input arguments
TODO:
Retrieve saved tensors and constants via ctx.saved_tensors and ctx.constant
Compute gradients for inputs where ctx.needs_input_grad[idx] is True. Set gradients for other
inputs to None. This should be decided dynamically.
"""
input, gamma, _beta, mean, inv_var = ctx.saved_tensors
input_needs_grad, gamma_needs_grad, beta_needs_grad = (ctx.
needs_input_grad)
batch_dim = input.shape[0]
x_hat = (input - mean) * inv_var
dx_hat = grad_output * gamma
grad_gamma = (grad_output * x_hat).sum(0) if gamma_needs_grad else None
grad_beta = grad_output.sum(0) if beta_needs_grad else None
grad_input = 1.0 / batch_dim * inv_var * (batch_dim * dx_hat -
dx_hat.sum(0) - x_hat * (dx_hat * x_hat).sum(0)
) if input_needs_grad else None
return grad_input, grad_gamma, grad_beta, None
class CustomBatchNormManualModule(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
In self.forward the functional version CustomBatchNormManualFunction.forward is called.
The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormManualModule object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormManualModule, self).__init__()
self.gamma = nn.Parameter(torch.ones(n_neurons))
self.beta = nn.Parameter(torch.zeros(n_neurons))
self.eps = eps
def forward(self, input):
"""
Compute the batch normalization via CustomBatchNormManualFunction
Args:
input: input tensor of shape (n_batch, n_neurons)
Returns:
out: batch-normalized tensor
TODO:
Check for the correctness of the shape of the input tensor.
Instantiate a CustomBatchNormManualFunction.
Call it via its .apply() method.
"""
shape = input.shape
if len(shape) == 1:
input = input.unsqueeze(0)
shape = input.shape
elif len(shape) > 2:
raise ValueError(
f'Expected 2D input. Instead, got {len(shape)}D input with shape of {shape}.'
)
elif shape[1] != self.gamma.shape[0]:
raise ValueError(
f'Expected input of shape batch_size x {self.gamma.shape[0]}. Instead, got input withshape of {shape}.'
)
batchNormFunc = CustomBatchNormManualFunction()
out = batchNormFunc.apply(input, self.gamma, self.beta, self.eps)
return out
def get_inputs():
return [torch.rand([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_mean_mul_reciprocal_sqrt_var_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 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
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.sqrt(tmp22)
tmp24 = tl.full([1], 1, tl.int32)
tmp25 = tmp24 / tmp23
tmp26 = 1.0
tmp27 = tmp25 * tmp26
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp27, xmask)
@triton.jit
def triton_poi_fused_add_mul_sub_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
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 - tmp2
tmp5 = tmp3 * tmp4
tmp6 = tmp0 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, 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,), (1,))
assert_size_stride(arg2_1, (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)
get_raw_stream(0)
triton_poi_fused_add_mean_mul_reciprocal_sqrt_var_0[grid(4)](arg0_1,
buf0, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_sub_1[grid(16)](arg1_1, arg0_1, buf0, buf1,
arg2_1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0, buf1, buf2
class CustomBatchNormManualFunction(torch.autograd.Function):
"""
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs.
Using torch.autograd.Function allows you to write a custom backward function.
The function will be called from the nn.Module CustomBatchNormManualModule
Inside forward the tensors are (automatically) not recorded for automatic differentiation since the backward
pass is done via the backward method.
The forward pass is not called directly but via the apply() method. This makes sure that the context objects
are dealt with correctly. Example:
my_bn_fct = CustomBatchNormManualFunction()
normalized = fct.apply(input, gamma, beta, eps)
"""
@staticmethod
def forward(ctx, input, gamma, beta, eps=1e-05):
"""
Compute the batch normalization
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
input: input tensor of shape (n_batch, n_neurons)
gamma: variance scaling tensor, applied per neuron, shpae (n_neurons)
beta: mean bias tensor, applied per neuron, shpae (n_neurons)
eps: small float added to the variance for stability
Returns:
out: batch-normalized tensor
TODO:
Implement the forward pass of batch normalization
Store constant non-tensor objects via ctx.constant=myconstant
Store tensors which you need in the backward pass via ctx.save_for_backward(tensor1, tensor2, ...)
Intermediate results can be decided to be either recomputed in the backward pass or to be stored
for the backward pass. Do not store tensors which are unnecessary for the backward pass to save memory!
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
shape = input.shape
if len(shape) == 1:
input = input.unsqueeze(0)
shape = input.shape
elif len(shape) > 2:
raise ValueError(
f'Expected 2D input. Instead, got {len(shape)}D input with shape of {shape}.'
)
elif shape[1] != gamma.shape[0]:
raise ValueError(
f'Expected input of shape batch_size x {gamma.shape[0]}. Instead, got input withshape of {shape}.'
)
mean = input.mean(0)
var = input.var(0, unbiased=False)
inv_var = 1 / torch.sqrt(var + eps)
x_hat = (input - mean) * inv_var
out = gamma * x_hat + beta
ctx.save_for_backward(input, gamma, beta, mean, inv_var)
ctx.eps = eps
return out
@staticmethod
def backward(ctx, grad_output):
"""
Compute backward pass of the batch normalization.
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
Returns:
out: tuple containing gradients for all input arguments
TODO:
Retrieve saved tensors and constants via ctx.saved_tensors and ctx.constant
Compute gradients for inputs where ctx.needs_input_grad[idx] is True. Set gradients for other
inputs to None. This should be decided dynamically.
"""
input, gamma, _beta, mean, inv_var = ctx.saved_tensors
input_needs_grad, gamma_needs_grad, beta_needs_grad = (ctx.
needs_input_grad)
batch_dim = input.shape[0]
x_hat = (input - mean) * inv_var
dx_hat = grad_output * gamma
grad_gamma = (grad_output * x_hat).sum(0) if gamma_needs_grad else None
grad_beta = grad_output.sum(0) if beta_needs_grad else None
grad_input = 1.0 / batch_dim * inv_var * (batch_dim * dx_hat -
dx_hat.sum(0) - x_hat * (dx_hat * x_hat).sum(0)
) if input_needs_grad else None
return grad_input, grad_gamma, grad_beta, None
class CustomBatchNormManualModuleNew(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
In self.forward the functional version CustomBatchNormManualFunction.forward is called.
The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormManualModule object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormManualModuleNew, self).__init__()
self.gamma = nn.Parameter(torch.ones(n_neurons))
self.beta = nn.Parameter(torch.zeros(n_neurons))
self.eps = eps
def forward(self, input_0):
arg1_1 = self.gamma
arg2_1 = self.beta
arg0_1 = input_0
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
askliar/deep_learning
|
CustomBatchNormManualModule
| false
| 1,489
|
[
"MIT"
] | 0
|
e61b2391a3258d18719bf12d9ed1404620ce6c02
|
https://github.com/askliar/deep_learning/tree/e61b2391a3258d18719bf12d9ed1404620ce6c02
|
ScalarMix
|
import torch
import torch.nn as nn
class ScalarMix(nn.Module):
"""
Computes a parameterized scalar mixture of :math:`N` tensors, :math:`mixture = \\gamma * \\sum_{k}(s_k * tensor_k)`
where :math:`s = \\mathrm{softmax}(w)`, with :math:`w` and :math:`\\gamma` scalar parameters.
Args:
n_layers (int):
The number of layers to be mixed, i.e., :math:`N`.
dropout (float):
The dropout ratio of the layer weights.
If dropout > 0, then for each scalar weight, adjusts its softmax weight mass to 0
with the dropout probability (i.e., setting the unnormalized weight to -inf).
This effectively redistributes the dropped probability mass to all other weights.
Default: 0.
"""
def __init__(self, n_layers, dropout=0):
super().__init__()
self.n_layers = n_layers
self.weights = nn.Parameter(torch.zeros(n_layers))
self.gamma = nn.Parameter(torch.tensor([1.0]))
self.dropout = nn.Dropout(dropout)
def __repr__(self):
s = f'n_layers={self.n_layers}'
if self.dropout.p > 0:
s += f', dropout={self.dropout.p}'
return f'{self.__class__.__name__}({s})'
def forward(self, tensors):
"""
Args:
tensors (list[~torch.Tensor]):
:math:`N` tensors to be mixed.
Returns:
The mixture of :math:`N` tensors.
"""
normed_weights = self.dropout(self.weights.softmax(-1))
weighted_sum = sum(w * h for w, h in zip(normed_weights, tensors))
return self.gamma * weighted_sum
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_layers': 1}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp7 = tl.load(in_ptr2 + x0, xmask)
tmp4 = tmp3 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp5 / tmp5
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = tmp8 + tmp9
tmp11 = tmp1 * tmp10
tl.store(out_ptr0 + x0, tmp11, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(64)](primals_3, primals_1,
primals_2, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
return buf0, primals_1, primals_3, reinterpret_tensor(primals_2, (4, 4,
4), (16, 4, 1), 0)
class ScalarMixNew(nn.Module):
"""
Computes a parameterized scalar mixture of :math:`N` tensors, :math:`mixture = \\gamma * \\sum_{k}(s_k * tensor_k)`
where :math:`s = \\mathrm{softmax}(w)`, with :math:`w` and :math:`\\gamma` scalar parameters.
Args:
n_layers (int):
The number of layers to be mixed, i.e., :math:`N`.
dropout (float):
The dropout ratio of the layer weights.
If dropout > 0, then for each scalar weight, adjusts its softmax weight mass to 0
with the dropout probability (i.e., setting the unnormalized weight to -inf).
This effectively redistributes the dropped probability mass to all other weights.
Default: 0.
"""
def __init__(self, n_layers, dropout=0):
super().__init__()
self.n_layers = n_layers
self.weights = nn.Parameter(torch.zeros(n_layers))
self.gamma = nn.Parameter(torch.tensor([1.0]))
self.dropout = nn.Dropout(dropout)
def __repr__(self):
s = f'n_layers={self.n_layers}'
if self.dropout.p > 0:
s += f', dropout={self.dropout.p}'
return f'{self.__class__.__name__}({s})'
def forward(self, input_0):
primals_1 = self.weights
primals_3 = self.gamma
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
attardi/parser
|
ScalarMix
| false
| 1,490
|
[
"MIT"
] | 0
|
1978ba94ba649ad0a723d71bb2ca225c7e705702
|
https://github.com/attardi/parser/tree/1978ba94ba649ad0a723d71bb2ca225c7e705702
|
TorchGloVeLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class TorchGloVeLoss(nn.Module):
def __init__(self):
super().__init__()
self.reduction = 'sum'
def forward(self, diffs, weights):
return torch.sum(0.5 * torch.mul(weights, diffs ** 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
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mul_pow_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp1 * tmp1
tmp3 = tmp0 * tmp2
tmp4 = 0.5
tmp5 = tmp3 * tmp4
tmp6 = tl.broadcast_to(tmp5, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp8, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_pow_sum_0[grid(1)](arg1_1, arg0_1, buf0, 1,
256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class TorchGloVeLossNew(nn.Module):
def __init__(self):
super().__init__()
self.reduction = 'sum'
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
atticusg/cs224u
|
TorchGloVeLoss
| false
| 1,491
|
[
"Apache-2.0"
] | 0
|
66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
https://github.com/atticusg/cs224u/tree/66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
TorchGloVeModel
|
import torch
import torch.nn as nn
import torch.utils.data
from torch.nn.init import xavier_uniform_
class TorchGloVeModel(nn.Module):
def __init__(self, n_words, embed_dim):
super().__init__()
self.n_words = n_words
self.embed_dim = embed_dim
self.W = self._init_weights(self.n_words, self.embed_dim)
self.C = self._init_weights(self.n_words, self.embed_dim)
self.bw = self._init_weights(self.n_words, 1)
self.bc = self._init_weights(self.n_words, 1)
def _init_weights(self, m, n):
return nn.Parameter(xavier_uniform_(torch.empty(m, n)))
def forward(self, X_log, idx):
"""
Parameters
----------
X_log : torch.FloatTensor, shape `(batch_size, n_vocab)`.
idx : torch.LongTensor, shape `(batch_size, )`
Indices of the vocab items in the current batch.
Returns
-------
torch.FloatTensor, shape `(n_vocab, n_vocab)`.
"""
preds = self.W[idx].matmul(self.C.T) + self.bw[idx] + self.bc.T
diffs = preds - X_log
return diffs
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4], dtype=torch.int64)]
def get_init_inputs():
return [[], {'n_words': 4, 'embed_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.utils.data
from torch.nn.init import xavier_uniform_
assert_size_stride = torch._C._dynamo.guards.assert_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_index_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_index_sub_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 16
x1 = xindex // 4 % 4
x0 = xindex % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x4, xmask)
tmp2 = tl.full([XBLOCK], 4, tl.int32)
tmp3 = tmp1 + tmp2
tmp4 = tmp1 < 0
tmp5 = tl.where(tmp4, tmp3, tmp1)
tl.device_assert((0 <= tmp5) & (tmp5 < 4) | ~xmask,
'index out of bounds: 0 <= tmp5 < 4')
tmp7 = tl.load(in_ptr2 + tmp5, xmask, eviction_policy='evict_last')
tmp8 = tmp0 + tmp7
tmp10 = tmp8 + tmp9
tmp12 = tmp10 - tmp11
tl.store(out_ptr0 + x4, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 1), (1, 1))
assert_size_stride(primals_5, (4, 1), (1, 1))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_index_0[grid(16)](primals_2, 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.mm(buf0, reinterpret_tensor(primals_3, (4, 4), (1, 4
), 0), out=buf1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_index_sub_1[grid(256)](buf1, primals_2,
primals_4, primals_5, primals_6, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
del primals_4
del primals_5
del primals_6
return buf2, primals_2, buf0, primals_3
class TorchGloVeModelNew(nn.Module):
def __init__(self, n_words, embed_dim):
super().__init__()
self.n_words = n_words
self.embed_dim = embed_dim
self.W = self._init_weights(self.n_words, self.embed_dim)
self.C = self._init_weights(self.n_words, self.embed_dim)
self.bw = self._init_weights(self.n_words, 1)
self.bc = self._init_weights(self.n_words, 1)
def _init_weights(self, m, n):
return nn.Parameter(xavier_uniform_(torch.empty(m, n)))
def forward(self, input_0, input_1):
primals_1 = self.W
primals_3 = self.C
primals_4 = self.bw
primals_5 = self.bc
primals_6 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
atticusg/cs224u
|
TorchGloVeModel
| false
| 1,492
|
[
"Apache-2.0"
] | 0
|
66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
https://github.com/atticusg/cs224u/tree/66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
CrossEntropyLossIIT
|
import torch
import torch.nn as nn
import torch.utils.data
class CrossEntropyLossIIT(nn.Module):
def __init__(self):
super().__init__()
self.loss = nn.CrossEntropyLoss(reduction='mean')
def forward(self, preds, labels):
return self.loss(preds[0], labels[:, 0]) + self.loss(preds[1],
labels[:, 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
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + (64 + x3), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (68 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (72 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (76 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_add_div_mul_neg_sum_2(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
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)
r3 = rindex
r0 = rindex % 4
r2 = rindex // 16
r4 = rindex % 16
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 16 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (4 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (8 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (12 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + (r4 + 64 * r2), None)
tmp19 = tl.load(in_ptr2 + r3, None)
tmp20 = tl.load(in_ptr2 + (r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr2 + (4 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr2 + (8 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr2 + (12 + r0 + 16 * r2), None, eviction_policy=
'evict_last')
tmp33 = tl.load(in_ptr1 + (16 + r4 + 64 * r2), None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp21 = tl_math.exp(tmp20)
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp21 + tmp23
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp24 + tmp26
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp27 + tmp29
tmp31 = tl_math.log(tmp30)
tmp32 = tmp19 - tmp31
tmp34 = tmp32 * tmp33
tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK])
tmp37 = tl.sum(tmp35, 1)[:, None]
tmp38 = -tmp18
tmp39 = 0.0625
tmp40 = tmp38 * tmp39
tmp41 = -tmp37
tmp42 = tmp41 * tmp39
tmp43 = tmp40 + tmp42
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp43, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(64)](arg0_1, buf0, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_1[grid(64)](arg0_1, buf2, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf4 = buf1
del buf1
triton_per_fused__log_softmax_add_div_mul_neg_sum_2[grid(1)](buf4,
buf0, arg1_1, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf0
del buf2
return buf4,
class CrossEntropyLossIITNew(nn.Module):
def __init__(self):
super().__init__()
self.loss = nn.CrossEntropyLoss(reduction='mean')
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
atticusg/cs224u
|
CrossEntropyLossIIT
| false
| 1,493
|
[
"Apache-2.0"
] | 0
|
66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
https://github.com/atticusg/cs224u/tree/66e0f2714e246dcb8836f706ae9ff5613c51ed34
|
ClassicModel
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
class ClassicModel(nn.Module):
def __init__(self, config, inpt_shp):
super(ClassicModel, self).__init__()
self.depth = config.depth
self.nodes = config.n_qubits
self.config = config
self.pre_net = nn.Linear(inpt_shp, self.nodes)
for i in range(self.depth):
setattr(self, f'Linear_{i}', nn.Linear(self.nodes, self.nodes))
setattr(self, f'ReLU_{i}', nn.ReLU())
self.output = nn.Linear(self.nodes, 2)
None
def forward(self, input_features):
input_features = self.pre_net(input_features)
for i in range(self.depth):
input_features = getattr(self, f'Linear_{i}')(input_features)
input_features = getattr(self, f'ReLU_{i}')(input_features)
output = self.output(input_features)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(depth=1, n_qubits=4), 'inpt_shp': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (2, 4), (4, 1))
assert_size_stride(primals_7, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf1)
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf2,
primals_5, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf3 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 2), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_7
return reinterpret_tensor(buf3, (4, 4, 4, 2), (32, 8, 2, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf2, (64, 4), (4, 1), 0
), primals_6, buf4, primals_4
class ClassicModelNew(nn.Module):
def __init__(self, config, inpt_shp):
super(ClassicModelNew, self).__init__()
self.depth = config.depth
self.nodes = config.n_qubits
self.config = config
self.pre_net = nn.Linear(inpt_shp, self.nodes)
for i in range(self.depth):
setattr(self, f'Linear_{i}', nn.Linear(self.nodes, self.nodes))
setattr(self, f'ReLU_{i}', nn.ReLU())
self.output = nn.Linear(self.nodes, 2)
None
def forward(self, input_0):
primals_1 = self.pre_net.weight
primals_2 = self.pre_net.bias
primals_4 = self.Linear_0.weight
primals_5 = self.Linear_0.bias
primals_6 = self.output.weight
primals_7 = self.output.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
austinbeauch/QML
|
ClassicModel
| false
| 1,494
|
[
"Apache-2.0"
] | 0
|
4a2f5b1b0346a1a8bb0a0e6e638cf2225c4c213c
|
https://github.com/austinbeauch/QML/tree/4a2f5b1b0346a1a8bb0a0e6e638cf2225c4c213c
|
LayerNorm
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.eps = eps
self.affine = affine
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
x = F.layer_norm(x, x.shape[1:], eps=self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_mul_native_layer_norm_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr
):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 64.0
tmp18 = tmp16 / tmp17
tmp19 = 1e-05
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tmp22 = tmp0 - tmp10
tmp23 = tmp22 * tmp21
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(out_ptr1 + (r1 + 64 * x0), tmp27, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 1, 1, 1), torch.float32)
buf1 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf3 = reinterpret_tensor(buf1, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_mul_native_layer_norm_0[grid(4)](buf3,
primals_1, primals_2, primals_3, buf0, buf4, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del primals_2
del primals_3
return buf4, primals_1, buf0, buf3
class LayerNormNew(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNormNew, self).__init__()
self.num_features = num_features
self.eps = eps
self.affine = affine
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, input_0):
primals_2 = self.gamma
primals_3 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
audreyeternal/cyclegan
|
LayerNorm
| false
| 1,495
|
[
"MIT"
] | 0
|
8eb3ddb7fd0d9838862334766f1f7aaa5584c2da
|
https://github.com/audreyeternal/cyclegan/tree/8eb3ddb7fd0d9838862334766f1f7aaa5584c2da
|
BinaryLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryLoss(nn.Module):
"""
Computes contrastive loss[1, 2] twice, one time for the distance between query and positive example,
and another for the distance between query and negative example. Both use l2-distance.
[1] http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf, equation 4
[2] https://gist.github.com/harveyslash/725fcc68df112980328951b3426c0e0b#file-contrastive-loss-py
"""
def __init__(self, margin=1.0):
"""
Args:
margin: margin (float, optional): Default: `1.0`.
"""
super(BinaryLoss, self).__init__()
self.margin = margin
def forward(self, query, positive, negative):
distance_positive = F.pairwise_distance(query, positive)
distance_negative = F.pairwise_distance(query, negative)
return torch.pow(distance_positive, 2) + torch.pow(torch.clamp(self
.margin - distance_negative, min=0.0), 2)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
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_clamp_norm_pow_rsub_sub_0(in_ptr0, in_ptr1,
in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp26 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp35 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp40 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp9 * tmp9
tmp11 = tmp5 + tmp10
tmp14 = tmp12 - tmp13
tmp15 = tmp14 + tmp3
tmp16 = tmp15 * tmp15
tmp17 = tmp11 + tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 + tmp3
tmp22 = tmp21 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = tmp24 * tmp24
tmp27 = tmp0 - tmp26
tmp28 = tmp27 + tmp3
tmp29 = tmp28 * tmp28
tmp31 = tmp6 - tmp30
tmp32 = tmp31 + tmp3
tmp33 = tmp32 * tmp32
tmp34 = tmp29 + tmp33
tmp36 = tmp12 - tmp35
tmp37 = tmp36 + tmp3
tmp38 = tmp37 * tmp37
tmp39 = tmp34 + tmp38
tmp41 = tmp18 - tmp40
tmp42 = tmp41 + tmp3
tmp43 = tmp42 * tmp42
tmp44 = tmp39 + tmp43
tmp45 = libdevice.sqrt(tmp44)
tmp46 = 1.0
tmp47 = tmp46 - tmp45
tmp48 = 0.0
tmp49 = triton_helpers.maximum(tmp47, tmp48)
tmp50 = tmp49 * tmp49
tmp51 = tmp25 + tmp50
tl.store(out_ptr0 + x0, tmp51, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_clamp_norm_pow_rsub_sub_0[grid(64)](arg1_1,
arg0_1, arg2_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0,
class BinaryLossNew(nn.Module):
"""
Computes contrastive loss[1, 2] twice, one time for the distance between query and positive example,
and another for the distance between query and negative example. Both use l2-distance.
[1] http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf, equation 4
[2] https://gist.github.com/harveyslash/725fcc68df112980328951b3426c0e0b#file-contrastive-loss-py
"""
def __init__(self, margin=1.0):
"""
Args:
margin: margin (float, optional): Default: `1.0`.
"""
super(BinaryLossNew, self).__init__()
self.margin = margin
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
atypon/specter
|
BinaryLoss
| false
| 1,496
|
[
"Apache-2.0"
] | 0
|
bc1ee723167cf1dbf599603e09539c1823f26c17
|
https://github.com/atypon/specter/tree/bc1ee723167cf1dbf599603e09539c1823f26c17
|
BertSelfAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.utils.data
class BertSelfAttention(nn.Module):
def __init__(self, config):
super(BertSelfAttention, self).__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, attention_mask=None):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf9
return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class BertSelfAttentionNew(nn.Module):
def __init__(self, config):
super(BertSelfAttentionNew, self).__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, input_0):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_6 = self.value.weight
primals_7 = self.value.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
ashutoshbaghel/tgifqa-lxmert
|
BertSelfAttention
| false
| 1,497
|
[
"MIT"
] | 0
|
7969f478d20fbfbba1c0eaaf0b96891654bfcc26
|
https://github.com/ashutoshbaghel/tgifqa-lxmert/tree/7969f478d20fbfbba1c0eaaf0b96891654bfcc26
|
WCE_loss
|
import torch
import torch.nn as nn
class WCE_loss(nn.Module):
def __init__(self):
super(WCE_loss, self).__init__()
def sum_ij(self, x):
return torch.sum(torch.sum(x, dim=3), dim=2)
def forward(self, pred, gt):
N_fg = self.sum_ij(gt)
N_bg = self.sum_ij(1 - gt)
L_fg = -1 * self.sum_ij(torch.log(pred + 1e-16) * gt) / N_fg
L_bg = -1 * self.sum_ij(torch.log(1 - pred + 1e-16) * (1 - gt)) / N_bg
L = L_fg + L_bg
return torch.mean(L)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from 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_add_log_mul_rsub_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp3 = 1e-16
tmp4 = tmp2 + tmp3
tmp5 = tl_math.log(tmp4)
tmp7 = tmp1 - tmp6
tmp8 = tmp5 * tmp7
tmp10 = tmp1 - tmp9
tmp11 = tmp10 + tmp3
tmp12 = tl_math.log(tmp11)
tmp14 = tmp1 - tmp13
tmp15 = tmp12 * tmp14
tmp16 = tmp8 + tmp15
tmp18 = tmp1 - tmp17
tmp19 = tmp18 + tmp3
tmp20 = tl_math.log(tmp19)
tmp22 = tmp1 - tmp21
tmp23 = tmp20 * tmp22
tmp24 = tmp16 + tmp23
tmp26 = tmp1 - tmp25
tmp27 = tmp26 + tmp3
tmp28 = tl_math.log(tmp27)
tmp30 = tmp1 - tmp29
tmp31 = tmp28 * tmp30
tmp32 = tmp24 + tmp31
tl.store(out_ptr0 + x0, tmp32, xmask)
@triton.jit
def triton_per_fused_add_div_log_mean_mul_rsub_sum_1(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 16 * r0, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + 16 * r0, None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 16 * r0), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (1 + 16 * r0), None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 16 * r0), None, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr1 + (2 + 16 * r0), None, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 16 * r0), None, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + (3 + 16 * r0), None, eviction_policy='evict_last'
)
tmp24 = tl.load(in_ptr0 + (4 + 16 * r0), None, eviction_policy='evict_last'
)
tmp27 = tl.load(in_ptr1 + (4 + 16 * r0), None, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr0 + (5 + 16 * r0), None, eviction_policy='evict_last'
)
tmp32 = tl.load(in_ptr1 + (5 + 16 * r0), None, eviction_policy='evict_last'
)
tmp35 = tl.load(in_ptr0 + (6 + 16 * r0), None, eviction_policy='evict_last'
)
tmp38 = tl.load(in_ptr1 + (6 + 16 * r0), None, eviction_policy='evict_last'
)
tmp41 = tl.load(in_ptr0 + (7 + 16 * r0), None, eviction_policy='evict_last'
)
tmp44 = tl.load(in_ptr1 + (7 + 16 * r0), None, eviction_policy='evict_last'
)
tmp48 = tl.load(in_ptr0 + (8 + 16 * r0), None, eviction_policy='evict_last'
)
tmp51 = tl.load(in_ptr1 + (8 + 16 * r0), None, eviction_policy='evict_last'
)
tmp53 = tl.load(in_ptr0 + (9 + 16 * r0), None, eviction_policy='evict_last'
)
tmp56 = tl.load(in_ptr1 + (9 + 16 * r0), None, eviction_policy='evict_last'
)
tmp59 = tl.load(in_ptr0 + (10 + 16 * r0), None, eviction_policy=
'evict_last')
tmp62 = tl.load(in_ptr1 + (10 + 16 * r0), None, eviction_policy=
'evict_last')
tmp65 = tl.load(in_ptr0 + (11 + 16 * r0), None, eviction_policy=
'evict_last')
tmp68 = tl.load(in_ptr1 + (11 + 16 * r0), None, eviction_policy=
'evict_last')
tmp72 = tl.load(in_ptr0 + (12 + 16 * r0), None, eviction_policy=
'evict_last')
tmp75 = tl.load(in_ptr1 + (12 + 16 * r0), None, eviction_policy=
'evict_last')
tmp77 = tl.load(in_ptr0 + (13 + 16 * r0), None, eviction_policy=
'evict_last')
tmp80 = tl.load(in_ptr1 + (13 + 16 * r0), None, eviction_policy=
'evict_last')
tmp83 = tl.load(in_ptr0 + (14 + 16 * r0), None, eviction_policy=
'evict_last')
tmp86 = tl.load(in_ptr1 + (14 + 16 * r0), None, eviction_policy=
'evict_last')
tmp89 = tl.load(in_ptr0 + (15 + 16 * r0), None, eviction_policy=
'evict_last')
tmp92 = tl.load(in_ptr1 + (15 + 16 * r0), None, eviction_policy=
'evict_last')
tmp146 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp147 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last'
)
tmp149 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last'
)
tmp151 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last'
)
tmp1 = 1e-16
tmp2 = tmp0 + tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp3 * tmp4
tmp7 = tmp6 + tmp1
tmp8 = tl_math.log(tmp7)
tmp10 = tmp8 * tmp9
tmp11 = tmp5 + tmp10
tmp13 = tmp12 + tmp1
tmp14 = tl_math.log(tmp13)
tmp16 = tmp14 * tmp15
tmp17 = tmp11 + tmp16
tmp19 = tmp18 + tmp1
tmp20 = tl_math.log(tmp19)
tmp22 = tmp20 * tmp21
tmp23 = tmp17 + tmp22
tmp25 = tmp24 + tmp1
tmp26 = tl_math.log(tmp25)
tmp28 = tmp26 * tmp27
tmp30 = tmp29 + tmp1
tmp31 = tl_math.log(tmp30)
tmp33 = tmp31 * tmp32
tmp34 = tmp28 + tmp33
tmp36 = tmp35 + tmp1
tmp37 = tl_math.log(tmp36)
tmp39 = tmp37 * tmp38
tmp40 = tmp34 + tmp39
tmp42 = tmp41 + tmp1
tmp43 = tl_math.log(tmp42)
tmp45 = tmp43 * tmp44
tmp46 = tmp40 + tmp45
tmp47 = tmp23 + tmp46
tmp49 = tmp48 + tmp1
tmp50 = tl_math.log(tmp49)
tmp52 = tmp50 * tmp51
tmp54 = tmp53 + tmp1
tmp55 = tl_math.log(tmp54)
tmp57 = tmp55 * tmp56
tmp58 = tmp52 + tmp57
tmp60 = tmp59 + tmp1
tmp61 = tl_math.log(tmp60)
tmp63 = tmp61 * tmp62
tmp64 = tmp58 + tmp63
tmp66 = tmp65 + tmp1
tmp67 = tl_math.log(tmp66)
tmp69 = tmp67 * tmp68
tmp70 = tmp64 + tmp69
tmp71 = tmp47 + tmp70
tmp73 = tmp72 + tmp1
tmp74 = tl_math.log(tmp73)
tmp76 = tmp74 * tmp75
tmp78 = tmp77 + tmp1
tmp79 = tl_math.log(tmp78)
tmp81 = tmp79 * tmp80
tmp82 = tmp76 + tmp81
tmp84 = tmp83 + tmp1
tmp85 = tl_math.log(tmp84)
tmp87 = tmp85 * tmp86
tmp88 = tmp82 + tmp87
tmp90 = tmp89 + tmp1
tmp91 = tl_math.log(tmp90)
tmp93 = tmp91 * tmp92
tmp94 = tmp88 + tmp93
tmp95 = tmp71 + tmp94
tmp96 = tmp4 + tmp9
tmp97 = tmp96 + tmp15
tmp98 = tmp97 + tmp21
tmp99 = tmp27 + tmp32
tmp100 = tmp99 + tmp38
tmp101 = tmp100 + tmp44
tmp102 = tmp98 + tmp101
tmp103 = tmp51 + tmp56
tmp104 = tmp103 + tmp62
tmp105 = tmp104 + tmp68
tmp106 = tmp102 + tmp105
tmp107 = tmp75 + tmp80
tmp108 = tmp107 + tmp86
tmp109 = tmp108 + tmp92
tmp110 = tmp106 + tmp109
tmp111 = 1.0
tmp112 = tmp111 - tmp4
tmp113 = tmp111 - tmp9
tmp114 = tmp112 + tmp113
tmp115 = tmp111 - tmp15
tmp116 = tmp114 + tmp115
tmp117 = tmp111 - tmp21
tmp118 = tmp116 + tmp117
tmp119 = tmp111 - tmp27
tmp120 = tmp111 - tmp32
tmp121 = tmp119 + tmp120
tmp122 = tmp111 - tmp38
tmp123 = tmp121 + tmp122
tmp124 = tmp111 - tmp44
tmp125 = tmp123 + tmp124
tmp126 = tmp118 + tmp125
tmp127 = tmp111 - tmp51
tmp128 = tmp111 - tmp56
tmp129 = tmp127 + tmp128
tmp130 = tmp111 - tmp62
tmp131 = tmp129 + tmp130
tmp132 = tmp111 - tmp68
tmp133 = tmp131 + tmp132
tmp134 = tmp126 + tmp133
tmp135 = tmp111 - tmp75
tmp136 = tmp111 - tmp80
tmp137 = tmp135 + tmp136
tmp138 = tmp111 - tmp86
tmp139 = tmp137 + tmp138
tmp140 = tmp111 - tmp92
tmp141 = tmp139 + tmp140
tmp142 = tmp134 + tmp141
tmp143 = -1.0
tmp144 = tmp95 * tmp143
tmp145 = tmp144 / tmp110
tmp148 = tmp146 + tmp147
tmp150 = tmp148 + tmp149
tmp152 = tmp150 + tmp151
tmp153 = tmp152 * tmp143
tmp154 = tmp153 / tmp142
tmp155 = tmp145 + tmp154
tmp156 = tl.broadcast_to(tmp155, [XBLOCK, RBLOCK])
tmp158 = tl.sum(tmp156, 1)[:, None]
tmp159 = 16.0
tmp160 = tmp158 / tmp159
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp160, 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)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_log_mul_rsub_sum_0[grid(64)](arg1_1, arg0_1,
buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = buf4
del buf4
triton_per_fused_add_div_log_mean_mul_rsub_sum_1[grid(1)](buf5,
arg1_1, arg0_1, buf2, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del buf2
return buf5,
class WCE_lossNew(nn.Module):
def __init__(self):
super(WCE_lossNew, self).__init__()
def sum_ij(self, x):
return torch.sum(torch.sum(x, dim=3), dim=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]
|
atch841/pytorch-one-shot-texture-segmentation
|
WCE_loss
| false
| 1,498
|
[
"MIT"
] | 0
|
8b781b861d17eb1e1e7014f54f8fd39dc10dd2b8
|
https://github.com/atch841/pytorch-one-shot-texture-segmentation/tree/8b781b861d17eb1e1e7014f54f8fd39dc10dd2b8
|
MLP
|
import torch
import torch.nn as nn
class SharedDropout(nn.Module):
"""
SharedDropout differs from the vanilla dropout strategy in that the dropout mask is shared across one dimension.
Args:
p (float):
The probability of an element to be zeroed. Default: 0.5.
batch_first (bool):
If ``True``, the input and output tensors are provided as ``[batch_size, seq_len, *]``.
Default: ``True``.
Examples:
>>> x = torch.ones(1, 3, 5)
>>> nn.Dropout()(x)
tensor([[[0., 2., 2., 0., 0.],
[2., 2., 0., 2., 2.],
[2., 2., 2., 2., 0.]]])
>>> SharedDropout()(x)
tensor([[[2., 0., 2., 0., 2.],
[2., 0., 2., 0., 2.],
[2., 0., 2., 0., 2.]]])
"""
def __init__(self, p=0.5, batch_first=True):
super().__init__()
self.p = p
self.batch_first = batch_first
def __repr__(self):
s = f'p={self.p}'
if self.batch_first:
s += f', batch_first={self.batch_first}'
return f'{self.__class__.__name__}({s})'
def forward(self, x):
"""
Args:
x (~torch.Tensor):
A tensor of any shape.
Returns:
The returned tensor is of the same shape as `x`.
"""
if self.training:
if self.batch_first:
mask = self.get_mask(x[:, 0], self.p).unsqueeze(1)
else:
mask = self.get_mask(x[0], self.p)
x = x * mask
return x
@staticmethod
def get_mask(x, p):
return x.new_empty(x.shape).bernoulli_(1 - p) / (1 - p)
class MLP(nn.Module):
"""
Applies a linear transformation together with a non-linear activation to the incoming tensor:
:math:`y = \\mathrm{Activation}(x A^T + b)`
Args:
n_in (~torch.Tensor):
The size of each input feature.
n_out (~torch.Tensor):
The size of each output feature.
dropout (float):
If non-zero, introduces a :class:`SharedDropout` layer on the output with this dropout ratio. Default: 0.
activation (bool):
Whether to use activations. Default: True.
"""
def __init__(self, n_in, n_out, dropout=0, activation=True):
super().__init__()
self.n_in = n_in
self.n_out = n_out
self.linear = nn.Linear(n_in, n_out)
self.activation = nn.LeakyReLU(negative_slope=0.1
) if activation else nn.Identity()
self.dropout = SharedDropout(p=dropout)
self.reset_parameters()
def __repr__(self):
s = f'n_in={self.n_in}, n_out={self.n_out}'
if self.dropout.p > 0:
s += f', dropout={self.dropout.p}'
return f'{self.__class__.__name__}({s})'
def reset_parameters(self):
nn.init.orthogonal_(self.linear.weight)
nn.init.zeros_(self.linear.bias)
def forward(self, x):
"""
Args:
x (~torch.Tensor):
The size of each input feature is `n_in`.
Returns:
A tensor with the size of each output feature `n_out`.
"""
x = self.linear(x)
x = self.activation(x)
x = self.dropout(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 4, 'n_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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(256)](buf0, primals_2, buf1,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf1
class SharedDropout(nn.Module):
"""
SharedDropout differs from the vanilla dropout strategy in that the dropout mask is shared across one dimension.
Args:
p (float):
The probability of an element to be zeroed. Default: 0.5.
batch_first (bool):
If ``True``, the input and output tensors are provided as ``[batch_size, seq_len, *]``.
Default: ``True``.
Examples:
>>> x = torch.ones(1, 3, 5)
>>> nn.Dropout()(x)
tensor([[[0., 2., 2., 0., 0.],
[2., 2., 0., 2., 2.],
[2., 2., 2., 2., 0.]]])
>>> SharedDropout()(x)
tensor([[[2., 0., 2., 0., 2.],
[2., 0., 2., 0., 2.],
[2., 0., 2., 0., 2.]]])
"""
def __init__(self, p=0.5, batch_first=True):
super().__init__()
self.p = p
self.batch_first = batch_first
def __repr__(self):
s = f'p={self.p}'
if self.batch_first:
s += f', batch_first={self.batch_first}'
return f'{self.__class__.__name__}({s})'
def forward(self, x):
"""
Args:
x (~torch.Tensor):
A tensor of any shape.
Returns:
The returned tensor is of the same shape as `x`.
"""
if self.training:
if self.batch_first:
mask = self.get_mask(x[:, 0], self.p).unsqueeze(1)
else:
mask = self.get_mask(x[0], self.p)
x = x * mask
return x
@staticmethod
def get_mask(x, p):
return x.new_empty(x.shape).bernoulli_(1 - p) / (1 - p)
class MLPNew(nn.Module):
"""
Applies a linear transformation together with a non-linear activation to the incoming tensor:
:math:`y = \\mathrm{Activation}(x A^T + b)`
Args:
n_in (~torch.Tensor):
The size of each input feature.
n_out (~torch.Tensor):
The size of each output feature.
dropout (float):
If non-zero, introduces a :class:`SharedDropout` layer on the output with this dropout ratio. Default: 0.
activation (bool):
Whether to use activations. Default: True.
"""
def __init__(self, n_in, n_out, dropout=0, activation=True):
super().__init__()
self.n_in = n_in
self.n_out = n_out
self.linear = nn.Linear(n_in, n_out)
self.activation = nn.LeakyReLU(negative_slope=0.1
) if activation else nn.Identity()
self.dropout = SharedDropout(p=dropout)
self.reset_parameters()
def __repr__(self):
s = f'n_in={self.n_in}, n_out={self.n_out}'
if self.dropout.p > 0:
s += f', dropout={self.dropout.p}'
return f'{self.__class__.__name__}({s})'
def reset_parameters(self):
nn.init.orthogonal_(self.linear.weight)
nn.init.zeros_(self.linear.bias)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
attardi/parser
|
MLP
| false
| 1,499
|
[
"MIT"
] | 0
|
1978ba94ba649ad0a723d71bb2ca225c7e705702
|
https://github.com/attardi/parser/tree/1978ba94ba649ad0a723d71bb2ca225c7e705702
|
GELU
|
import torch
import torch.nn as nn
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return torch.sigmoid(1.702 * x) * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_sigmoid_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 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.702
tmp2 = tmp0 * tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = tmp3 * tmp0
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(256)](arg0_1, buf0, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class GELUNew(nn.Module):
def __init__(self):
super(GELUNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
awgansekoele/outlier-exposure
|
GELU
| false
| 1,500
|
[
"Apache-2.0"
] | 0
|
9557c7915fa466fc54951357519cfba27f7659ad
|
https://github.com/awgansekoele/outlier-exposure/tree/9557c7915fa466fc54951357519cfba27f7659ad
|
folder
|
import torch
from torch import nn
import torch.nn.functional as F
import torch.nn.parallel
class folder(nn.Module):
def __init__(self):
super().__init__()
def forward(self, feature_map):
N, _, H, W = feature_map.size()
feature_map = F.unfold(feature_map, kernel_size=3, padding=1)
feature_map = feature_map.view(N, -1, H, W)
return feature_map
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.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_im2col_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl
.constexpr, XBLOCK: tl.constexpr):
ynumel = 144
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
x4 = xindex // 4
y1 = yindex // 3 % 3
x3 = xindex % 4
y0 = yindex % 3
x6 = xindex
y2 = yindex // 9
y7 = yindex
tmp0 = -1 + x4 + y1
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1, 1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x3 + y0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-5 + x6 + y0 + 4 * y1 + 16 * y2), tmp10 &
xmask & ymask, eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x6 + 16 * y7), tmp11, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 3, 3, 4, 4), (576, 144, 48, 16, 4,
1), torch.float32)
get_raw_stream(0)
triton_poi_fused_im2col_0[grid(144, 16)](arg0_1, buf0, 144, 16,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 36, 4, 4), (576, 16, 4, 1), 0),
class folderNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
avinash-asink/AdelaiDet
|
folder
| false
| 1,501
|
[
"BSD-2-Clause"
] | 0
|
a8722579c8a724b02a36ef0f33a176ba282623fa
|
https://github.com/avinash-asink/AdelaiDet/tree/a8722579c8a724b02a36ef0f33a176ba282623fa
|
Arc2
|
from torch.nn import Module
import torch
import numpy as np
class Arc2(Module):
def __init__(self, num_bends):
super(Arc2, self).__init__()
self.num_bends = num_bends
self.register_buffer('range', torch.arange(0, float(num_bends)))
def a(self, t):
return torch.cos(np.pi * t / 2)
def b(self, t):
return torch.sin(np.pi * t / 2)
def forward(self, t):
return torch.cat([self.a(t), 0.0 * (1.0 - t - self.a(t)), 0.0 * (t -
self.b(t)), self.b(t)])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_bends': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
import numpy as np
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 64
x0 = xindex % 64
x2 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x1), tmp4 & xmask, other=0.0)
tmp6 = 3.141592653589793
tmp7 = tmp5 * tmp6
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp10 = tl_math.cos(tmp9)
tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
tmp12 = tl.where(tmp4, tmp10, tmp11)
tmp13 = tmp0 >= tmp3
tmp14 = tl.full([1], 8, tl.int64)
tmp15 = tmp0 < tmp14
tmp16 = tmp13 & tmp15
tmp17 = tl.load(in_ptr0 + (x0 + 64 * (-4 + x1)), tmp16 & xmask, other=0.0)
tmp18 = 1.0
tmp19 = tmp18 - tmp17
tmp20 = tmp17 * tmp6
tmp21 = tmp20 * tmp8
tmp22 = tl_math.cos(tmp21)
tmp23 = tmp19 - tmp22
tmp24 = 0.0
tmp25 = tmp23 * tmp24
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp16, tmp25, tmp26)
tmp28 = tmp0 >= tmp14
tmp29 = tl.full([1], 12, tl.int64)
tmp30 = tmp0 < tmp29
tmp31 = tmp28 & tmp30
tmp32 = tl.load(in_ptr0 + (x0 + 64 * (-8 + x1)), tmp31 & xmask, other=0.0)
tmp33 = tmp32 * tmp6
tmp34 = tmp33 * tmp8
tmp35 = tl_math.sin(tmp34)
tmp36 = tmp32 - tmp35
tmp37 = tmp36 * tmp24
tmp38 = tl.full(tmp37.shape, 0.0, tmp37.dtype)
tmp39 = tl.where(tmp31, tmp37, tmp38)
tmp40 = tmp0 >= tmp29
tl.full([1], 16, tl.int64)
tmp43 = tl.load(in_ptr0 + (x0 + 64 * (-12 + x1)), tmp40 & xmask, other=0.0)
tmp44 = tmp43 * tmp6
tmp45 = tmp44 * tmp8
tmp46 = tl_math.sin(tmp45)
tmp47 = tl.full(tmp46.shape, 0.0, tmp46.dtype)
tmp48 = tl.where(tmp40, tmp46, tmp47)
tmp49 = tl.where(tmp31, tmp39, tmp48)
tmp50 = tl.where(tmp16, tmp27, tmp49)
tmp51 = tl.where(tmp4, tmp12, tmp50)
tl.store(out_ptr0 + x2, tmp51, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(1024)](arg0_1, buf0, 1024, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class Arc2New(Module):
def __init__(self, num_bends):
super(Arc2New, self).__init__()
self.num_bends = num_bends
self.register_buffer('range', torch.arange(0, float(num_bends)))
def a(self, t):
return torch.cos(np.pi * t / 2)
def b(self, t):
return torch.sin(np.pi * t / 2)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
avecplezir/dnn-mode-connectivity
|
Arc2
| false
| 1,502
|
[
"BSD-2-Clause"
] | 0
|
9a92ca370571f542b33060f637239172a0d08bba
|
https://github.com/avecplezir/dnn-mode-connectivity/tree/9a92ca370571f542b33060f637239172a0d08bba
|
Normalize
|
import torch
import torch.nn as nn
class Normalize(nn.Module):
"""Normalize nn.Module. As at pytorch, simplified"""
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225
], inplace=False, dtype=torch.float32):
super().__init__()
mean = torch.as_tensor(mean, dtype=dtype)
self.mean = nn.Parameter(mean[:, None, None], requires_grad=False)
std = torch.as_tensor(std, dtype=dtype)
self.std = nn.Parameter(std[:, None, None], requires_grad=False)
self.inplace = inplace
def forward(self, tensor: 'torch.Tensor'):
if not self.inplace:
tensor = tensor.clone()
return tensor.sub_(self.mean).div_(self.std)
def __repr__(self):
return f'{self.__class__.__name__} mean={self.mean}, std={self.std})'
def get_inputs():
return [torch.rand([4, 3, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_sub_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 3
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 / tmp3
tl.store(out_ptr0 + x3, tmp4, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 3, 4, 4), (48, 16, 4, 1))
assert_size_stride(arg1_1, (3, 1, 1), (1, 1, 1))
assert_size_stride(arg2_1, (3, 1, 1), (1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 4, 4), (48, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_sub_0[grid(192)](arg0_1, arg1_1, arg2_1, buf0,
192, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0,
class NormalizeNew(nn.Module):
"""Normalize nn.Module. As at pytorch, simplified"""
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225
], inplace=False, dtype=torch.float32):
super().__init__()
mean = torch.as_tensor(mean, dtype=dtype)
self.mean = nn.Parameter(mean[:, None, None], requires_grad=False)
std = torch.as_tensor(std, dtype=dtype)
self.std = nn.Parameter(std[:, None, None], requires_grad=False)
self.inplace = inplace
def __repr__(self):
return f'{self.__class__.__name__} mean={self.mean}, std={self.std})'
def forward(self, input_0):
arg1_1 = self.mean
arg2_1 = self.std
arg0_1 = input_0
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
ayasyrev/pt_utils
|
Normalize
| false
| 1,503
|
[
"Apache-2.0"
] | 0
|
cb29b8fb4a3981248e1055979cc773f719dccdc7
|
https://github.com/ayasyrev/pt_utils/tree/cb29b8fb4a3981248e1055979cc773f719dccdc7
|
FocalLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.modules.loss._WeightedLoss):
def __init__(self, weight=None, gamma=2, reduction='mean'):
super(FocalLoss, self).__init__(weight, reduction=reduction)
self.gamma = gamma
self.weight = weight
def forward(self, input, target):
ce_loss = F.cross_entropy(input, target, reduction=self.reduction,
weight=self.weight)
pt = torch.exp(-ce_loss)
focal_loss = ((1 - pt) ** self.gamma * ce_loss).mean()
focal_loss.requres_grad = True
return focal_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__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = -tmp18
tmp20 = 0.015625
tmp21 = tmp19 * tmp20
tmp22 = -tmp21
tmp23 = tl_math.exp(tmp22)
tmp24 = 1.0
tmp25 = tmp24 - tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp26 * tmp21
tmp28 = tmp27 / tmp24
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp28, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1[grid
(1)](buf2, buf0, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class FocalLossNew(nn.modules.loss._WeightedLoss):
def __init__(self, weight=None, gamma=2, reduction='mean'):
super(FocalLossNew, self).__init__(weight, reduction=reduction)
self.gamma = gamma
self.weight = weight
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
aydindemircioglu/knee.lat
|
FocalLoss
| false
| 1,504
|
[
"MIT"
] | 0
|
555725222f860d4ad8fea7452685803d9e323d43
|
https://github.com/aydindemircioglu/knee.lat/tree/555725222f860d4ad8fea7452685803d9e323d43
|
DQNet
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class DQNet(nn.Module):
"""
Definition: DQNet(obs_size,act_size,hid_size=256)
Regular Deep Q Network with three Linear layers
"""
def __init__(self, obs_size, act_size, hid_size=256):
super().__init__()
self.fc_in = nn.Linear(obs_size, hid_size)
self.fc_out = nn.Linear(hid_size, act_size)
def forward(self, x):
x = F.relu(self.fc_in(x))
return self.fc_out(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 256), (256, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf3, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_4, (256, 4), (1, 256),
0), alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0), primals_4, buf3
class DQNetNew(nn.Module):
"""
Definition: DQNet(obs_size,act_size,hid_size=256)
Regular Deep Q Network with three Linear layers
"""
def __init__(self, obs_size, act_size, hid_size=256):
super().__init__()
self.fc_in = nn.Linear(obs_size, hid_size)
self.fc_out = nn.Linear(hid_size, act_size)
def forward(self, input_0):
primals_1 = self.fc_in.weight
primals_2 = self.fc_in.bias
primals_4 = self.fc_out.weight
primals_5 = self.fc_out.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
ayjabri/DeepRL
|
DQNet
| false
| 1,505
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
Arc
|
from torch.nn import Module
import torch
import numpy as np
class Arc(Module):
def __init__(self, num_bends):
super(Arc, self).__init__()
self.num_bends = num_bends
self.register_buffer('range', torch.arange(0, float(num_bends)))
def a(self, t):
return torch.cos(np.pi * t / 2)
def b(self, t):
return torch.sin(np.pi * t / 2)
def forward(self, t):
return torch.cat([self.a(t), 1.0 - self.a(t) - self.b(t), self.b(t)])
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_bends': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
import numpy as np
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 = 768
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 64
x0 = xindex % 64
x2 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x1), tmp4 & xmask, other=0.0)
tmp6 = 3.141592653589793
tmp7 = tmp5 * tmp6
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp10 = tl_math.cos(tmp9)
tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
tmp12 = tl.where(tmp4, tmp10, tmp11)
tmp13 = tmp0 >= tmp3
tmp14 = tl.full([1], 8, tl.int64)
tmp15 = tmp0 < tmp14
tmp16 = tmp13 & tmp15
tmp17 = tl.load(in_ptr0 + (x0 + 64 * (-4 + x1)), tmp16 & xmask, other=0.0)
tmp18 = tmp17 * tmp6
tmp19 = tmp18 * tmp8
tmp20 = tl_math.cos(tmp19)
tmp21 = 1.0
tmp22 = tmp21 - tmp20
tmp23 = tl_math.sin(tmp19)
tmp24 = tmp22 - tmp23
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp16, tmp24, tmp25)
tmp27 = tmp0 >= tmp14
tl.full([1], 12, tl.int64)
tmp30 = tl.load(in_ptr0 + (x0 + 64 * (-8 + x1)), tmp27 & xmask, other=0.0)
tmp31 = tmp30 * tmp6
tmp32 = tmp31 * tmp8
tmp33 = tl_math.sin(tmp32)
tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype)
tmp35 = tl.where(tmp27, tmp33, tmp34)
tmp36 = tl.where(tmp16, tmp26, tmp35)
tmp37 = tl.where(tmp4, tmp12, tmp36)
tl.store(out_ptr0 + x2, 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)
buf0 = empty_strided_cuda((12, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(768)](arg0_1, buf0, 768, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ArcNew(Module):
def __init__(self, num_bends):
super(ArcNew, self).__init__()
self.num_bends = num_bends
self.register_buffer('range', torch.arange(0, float(num_bends)))
def a(self, t):
return torch.cos(np.pi * t / 2)
def b(self, t):
return torch.sin(np.pi * t / 2)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
avecplezir/dnn-mode-connectivity
|
Arc
| false
| 1,506
|
[
"BSD-2-Clause"
] | 0
|
9a92ca370571f542b33060f637239172a0d08bba
|
https://github.com/avecplezir/dnn-mode-connectivity/tree/9a92ca370571f542b33060f637239172a0d08bba
|
DuelDQNet
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class DuelDQNet(nn.Module):
"""
Definition: DuelDQNet(obs_size, act_size, hid_size=256)
"""
def __init__(self, obs_size, act_size, hid_size=256):
super().__init__()
self.base = nn.Linear(obs_size, hid_size)
self.val = nn.Linear(hid_size, 1)
self.adv = nn.Linear(hid_size, act_size)
def forward(self, x):
x = F.relu(self.base(x))
val = self.val(x)
adv = self.adv(x)
return val + (adv - adv.mean(dim=1, keepdim=True))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_add_mean_sub_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex // 4
x5 = xindex
x3 = xindex // 64
x6 = xindex % 16
tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + x5, xmask)
tmp5 = tl.load(in_ptr2 + (x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr2 + (16 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr2 + (32 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr2 + (48 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp3 = tmp0 + tmp2
tmp7 = tmp5 + tmp6
tmp9 = tmp7 + tmp8
tmp11 = tmp9 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tmp4 - tmp13
tmp15 = tmp3 + tmp14
tl.store(out_ptr0 + x5, tmp15, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 256), (256, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (4, 256), (256, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf5, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 1), (1, 256), 0), out=buf2)
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_6, (256, 4), (1, 256),
0), alpha=1, beta=1, out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mean_sub_1[grid(256)](buf2, primals_5, buf3,
buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
del buf3
del primals_5
return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), primals_6, primals_4, buf5
class DuelDQNetNew(nn.Module):
"""
Definition: DuelDQNet(obs_size, act_size, hid_size=256)
"""
def __init__(self, obs_size, act_size, hid_size=256):
super().__init__()
self.base = nn.Linear(obs_size, hid_size)
self.val = nn.Linear(hid_size, 1)
self.adv = nn.Linear(hid_size, act_size)
def forward(self, input_0):
primals_1 = self.base.weight
primals_2 = self.base.bias
primals_4 = self.val.weight
primals_5 = self.val.bias
primals_6 = self.adv.weight
primals_7 = self.adv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
ayjabri/DeepRL
|
DuelDQNet
| false
| 1,507
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
TripletLossDoubleMargin
|
import torch
import torch.nn as nn
class TripletLossDoubleMargin(nn.Module):
"""
Triplet Loss with positive and negative margins, following the work of [1]
References
----------
[1] Ho, K., Keuper, J., Pfreundt, F. J., & Keuper, M. (2021, January).
Learning embeddings for image clustering: An empirical study of triplet loss approaches.
In 2020 25th International Conference on Pattern Recognition (ICPR) (pp. 87-94). IEEE.
"""
def __init__(self, pos_margin=1.0, neg_margin=3.0):
"""
Constructor of the loss.
Parameters
----------
pos_margin : float, optional
Margin for positive examples. The default is 1.0.
neg_margin : float, optional
Margin for negative examples. The default is 3.0.
Returns
-------
None.
"""
super(TripletLossDoubleMargin, self).__init__()
self.pos_margin = pos_margin
self.neg_margin = neg_margin
def calc_euclidean(self, x1, x2):
return (x1 - x2).pow(2).sum(1)
def forward(self, anchor, positive, negative):
distance_positive = self.calc_euclidean(anchor, positive)
distance_negative = self.calc_euclidean(anchor, negative)
losses = torch.relu(self.neg_margin - distance_negative) + torch.relu(
distance_positive - self.pos_margin)
return losses.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_relu_rsub_sub_sum_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp10 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp15 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp23 = tl.load(in_ptr2 + (r0 + 64 * r1), None)
tmp26 = tl.load(in_ptr2 + (16 + r0 + 64 * r1), None)
tmp30 = tl.load(in_ptr2 + (32 + r0 + 64 * r1), None)
tmp34 = tl.load(in_ptr2 + (48 + r0 + 64 * r1), None)
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 = 3.0
tmp20 = tmp19 - tmp18
tmp21 = tl.full([1, 1], 0, tl.int32)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = tmp0 - tmp23
tmp25 = tmp24 * tmp24
tmp27 = tmp4 - tmp26
tmp28 = tmp27 * tmp27
tmp29 = tmp25 + tmp28
tmp31 = tmp9 - tmp30
tmp32 = tmp31 * tmp31
tmp33 = tmp29 + tmp32
tmp35 = tmp14 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tmp33 + tmp36
tmp38 = 1.0
tmp39 = tmp37 - tmp38
tmp40 = triton_helpers.maximum(tmp21, tmp39)
tmp41 = tmp22 + tmp40
tmp42 = tl.broadcast_to(tmp41, [XBLOCK, RBLOCK])
tmp44 = tl.sum(tmp42, 1)[:, None]
tmp45 = 64.0
tmp46 = tmp44 / tmp45
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp46, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_mean_pow_relu_rsub_sub_sum_0[grid(1)](buf2,
arg0_1, arg2_1, arg1_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf2,
class TripletLossDoubleMarginNew(nn.Module):
"""
Triplet Loss with positive and negative margins, following the work of [1]
References
----------
[1] Ho, K., Keuper, J., Pfreundt, F. J., & Keuper, M. (2021, January).
Learning embeddings for image clustering: An empirical study of triplet loss approaches.
In 2020 25th International Conference on Pattern Recognition (ICPR) (pp. 87-94). IEEE.
"""
def __init__(self, pos_margin=1.0, neg_margin=3.0):
"""
Constructor of the loss.
Parameters
----------
pos_margin : float, optional
Margin for positive examples. The default is 1.0.
neg_margin : float, optional
Margin for negative examples. The default is 3.0.
Returns
-------
None.
"""
super(TripletLossDoubleMarginNew, self).__init__()
self.pos_margin = pos_margin
self.neg_margin = neg_margin
def calc_euclidean(self, x1, x2):
return (x1 - x2).pow(2).sum(1)
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]
|
ax-le/MusicAE
|
TripletLossDoubleMargin
| false
| 1,508
|
[
"BSD-3-Clause"
] | 0
|
9fdc268f6403226b990d9ae5c9f182ed0af82f98
|
https://github.com/ax-le/MusicAE/tree/9fdc268f6403226b990d9ae5c9f182ed0af82f98
|
A2CNet
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class A2CNet(nn.Module):
"""Double heads actor + critic network."""
def __init__(self, obs_size, act_size, hid_size=128):
super().__init__()
self.fc1 = nn.Linear(obs_size, hid_size)
self.policy = nn.Linear(hid_size, act_size)
self.value = nn.Linear(hid_size, 1)
def forward(self, x):
"""Feed forward."""
y = F.relu(self.fc1(x))
return self.policy(y), self.value(y)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (128, 4), (4, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 128), (128, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 128), (128, 1))
assert_size_stride(primals_7, (1,), (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
buf5 = 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, buf5, 8192, XBLOCK=128, 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, 128),
(128, 1), 0), reinterpret_tensor(primals_4, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf2)
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_6, (128, 1), (1, 128),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 128), (128, 1), 0
), primals_6, primals_4, buf5
class A2CNetNew(nn.Module):
"""Double heads actor + critic network."""
def __init__(self, obs_size, act_size, hid_size=128):
super().__init__()
self.fc1 = nn.Linear(obs_size, hid_size)
self.policy = nn.Linear(hid_size, act_size)
self.value = nn.Linear(hid_size, 1)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.policy.weight
primals_5 = self.policy.bias
primals_6 = self.value.weight
primals_7 = self.value.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
ayjabri/DeepRL
|
A2CNet
| false
| 1,509
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
BertOutAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.utils.data
class BertOutAttention(nn.Module):
def __init__(self, config, ctx_dim=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
if ctx_dim is None:
ctx_dim = config.hidden_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(ctx_dim, self.all_head_size)
self.value = nn.Linear(ctx_dim, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, context, attention_mask=None):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(context)
mixed_value_layer = self.value(context)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_8, buf8, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf9
return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class BertOutAttentionNew(nn.Module):
def __init__(self, config, ctx_dim=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
'The hidden size (%d) is not a multiple of the number of attention heads (%d)'
% (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
if ctx_dim is None:
ctx_dim = config.hidden_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(ctx_dim, self.all_head_size)
self.value = nn.Linear(ctx_dim, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, input_0, input_1):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_7 = self.value.weight
primals_8 = self.value.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
ashutoshbaghel/tgifqa-lxmert
|
BertOutAttention
| false
| 1,510
|
[
"MIT"
] | 0
|
7969f478d20fbfbba1c0eaaf0b96891654bfcc26
|
https://github.com/ashutoshbaghel/tgifqa-lxmert/tree/7969f478d20fbfbba1c0eaaf0b96891654bfcc26
|
DiceLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryDiceLoss(nn.Module):
"""Dice loss of binary class
Args:
smooth: A float number to smooth loss, and avoid NaN error, default: 1
p: Denominator value: \\sum{x^p} + \\sum{y^p}, default: 2
predict: A tensor of shape [N, *]
target: A tensor of shape same with predict
reduction: Reduction method to apply, return mean over batch if 'mean',
return sum if 'sum', return a tensor of shape [N,] if 'none'
Returns:
Loss tensor according to arg reduction
Raise:
Exception if unexpected reduction
"""
def __init__(self, smooth=1, p=2, reduction='mean'):
super(BinaryDiceLoss, self).__init__()
self.smooth = smooth
self.p = p
self.reduction = reduction
def forward(self, predict, target):
assert predict.shape[0] == target.shape[0
], "predict & target batch size don't match"
predict = predict.contiguous().view(predict.shape[0], -1)
target = target.contiguous().view(target.shape[0], -1)
num = torch.sum(torch.mul(predict, target), dim=1) + self.smooth
den = torch.sum(predict.pow(self.p) + target.pow(self.p), dim=1
) + self.smooth
loss = 1 - num / den
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
elif self.reduction == 'none':
return loss
else:
raise Exception('Unexpected reduction {}'.format(self.reduction))
class DiceLoss(nn.Module):
"""Dice loss, need one hot encode input
Args:
weight: An array of shape [num_classes,]
ignore_index: class index to ignore
predict: A tensor of shape [N, C, *]
target: A tensor of same shape with predict
other args pass to BinaryDiceLoss
Return:
same as BinaryDiceLoss
"""
def __init__(self, weight=None, ignore_index=None, **kwargs):
super(DiceLoss, self).__init__()
self.kwargs = kwargs
self.weight = weight
self.ignore_index = ignore_index
def forward(self, predict, target):
assert predict.shape == target.shape, 'predict & target shape do not match'
dice = BinaryDiceLoss(**self.kwargs)
total_loss = 0
predict = F.softmax(predict, dim=1)
for i in range(target.shape[1]):
if i != self.ignore_index:
dice_loss = dice(predict[:, i], target[:, i])
if self.weight is not None:
assert self.weight.shape[0] == target.shape[1
], 'Expect weight shape [{}], get[{}]'.format(target
.shape[1], self.weight.shape[0])
dice_loss *= self.weights[i]
total_loss += dice_loss
return total_loss / target.shape[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_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 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_sum_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 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 = tmp0 * tmp0
tmp8 = tmp1 * tmp1
tmp9 = tmp7 + tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_sum_3(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (48 + r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (48 + 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 = tmp0 * tmp0
tmp8 = tmp1 * tmp1
tmp9 = tmp7 + tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_sum_4(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (16 + r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (16 + 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 = tmp0 * tmp0
tmp8 = tmp1 * tmp1
tmp9 = tmp7 + tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_add_mul_pow_sum_5(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (32 + r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (32 + 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 = tmp0 * tmp0
tmp8 = tmp1 * tmp1
tmp9 = tmp7 + tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_add_div_mean_rsub_6(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, 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)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp10 = tl.load(in_ptr2 + r0, None)
tmp12 = tl.load(in_ptr3 + r0, None)
tmp19 = tl.load(in_ptr4 + r0, None)
tmp21 = tl.load(in_ptr5 + r0, None)
tmp28 = tl.load(in_ptr6 + r0, None)
tmp30 = tl.load(in_ptr7 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp5 = tmp2 / tmp4
tmp6 = tmp1 - tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp11 = tmp10 + tmp1
tmp13 = tmp12 + tmp1
tmp14 = tmp11 / tmp13
tmp15 = tmp1 - tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp20 = tmp19 + tmp1
tmp22 = tmp21 + tmp1
tmp23 = tmp20 / tmp22
tmp24 = tmp1 - tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.sum(tmp25, 1)[:, None]
tmp29 = tmp28 + tmp1
tmp31 = tmp30 + tmp1
tmp32 = tmp29 / tmp31
tmp33 = tmp1 - tmp32
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp36 = tl.sum(tmp34, 1)[:, None]
tmp37 = 4.0
tmp38 = tmp9 / tmp37
tmp39 = 0.0
tmp40 = tmp38 + tmp39
tmp41 = tmp18 / tmp37
tmp42 = tmp40 + tmp41
tmp43 = tmp27 / tmp37
tmp44 = tmp42 + tmp43
tmp45 = tmp36 / tmp37
tmp46 = tmp44 + tmp45
tmp47 = 0.25
tmp48 = tmp46 * tmp47
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp48, 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)](arg0_1, buf0, 256, XBLOCK=
128, 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__softmax_1[grid(256)](buf0, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf0
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_mul_pow_sum_2[grid(4)](buf1, arg1_1, buf2,
buf3, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf11 = empty_strided_cuda((4,), (1,), torch.float32)
buf12 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_mul_pow_sum_3[grid(4)](buf1, arg1_1, buf11,
buf12, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4,), (1,), torch.float32)
buf6 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_mul_pow_sum_4[grid(4)](buf1, arg1_1, buf5,
buf6, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf8 = empty_strided_cuda((4,), (1,), torch.float32)
buf9 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_mul_pow_sum_5[grid(4)](buf1, arg1_1, buf8,
buf9, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf1
buf10 = empty_strided_cuda((), (), torch.float32)
buf14 = buf10
del buf10
triton_per_fused_add_div_mean_rsub_6[grid(1)](buf14, buf2, buf3,
buf5, buf6, buf8, buf9, buf11, buf12, 1, 4, XBLOCK=1, num_warps
=2, num_stages=1)
del buf11
del buf12
del buf2
del buf3
del buf5
del buf6
del buf8
del buf9
return buf14,
class BinaryDiceLoss(nn.Module):
"""Dice loss of binary class
Args:
smooth: A float number to smooth loss, and avoid NaN error, default: 1
p: Denominator value: \\sum{x^p} + \\sum{y^p}, default: 2
predict: A tensor of shape [N, *]
target: A tensor of shape same with predict
reduction: Reduction method to apply, return mean over batch if 'mean',
return sum if 'sum', return a tensor of shape [N,] if 'none'
Returns:
Loss tensor according to arg reduction
Raise:
Exception if unexpected reduction
"""
def __init__(self, smooth=1, p=2, reduction='mean'):
super(BinaryDiceLoss, self).__init__()
self.smooth = smooth
self.p = p
self.reduction = reduction
def forward(self, predict, target):
assert predict.shape[0] == target.shape[0
], "predict & target batch size don't match"
predict = predict.contiguous().view(predict.shape[0], -1)
target = target.contiguous().view(target.shape[0], -1)
num = torch.sum(torch.mul(predict, target), dim=1) + self.smooth
den = torch.sum(predict.pow(self.p) + target.pow(self.p), dim=1
) + self.smooth
loss = 1 - num / den
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
elif self.reduction == 'none':
return loss
else:
raise Exception('Unexpected reduction {}'.format(self.reduction))
class DiceLossNew(nn.Module):
"""Dice loss, need one hot encode input
Args:
weight: An array of shape [num_classes,]
ignore_index: class index to ignore
predict: A tensor of shape [N, C, *]
target: A tensor of same shape with predict
other args pass to BinaryDiceLoss
Return:
same as BinaryDiceLoss
"""
def __init__(self, weight=None, ignore_index=None, **kwargs):
super(DiceLossNew, self).__init__()
self.kwargs = kwargs
self.weight = weight
self.ignore_index = ignore_index
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
aureliedj/OilseedRapeSegmentation
|
DiceLoss
| false
| 1,511
|
[
"MIT"
] | 0
|
89056c3295b24354c32b6059854a3a60214c26cb
|
https://github.com/aureliedj/OilseedRapeSegmentation/tree/89056c3295b24354c32b6059854a3a60214c26cb
|
GRUCell
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class GRUCell(nn.Module):
"""Plain vanilla policy gradient network."""
def __init__(self, obs_size, act_size, hid_size=128):
super().__init__()
self.fc1 = nn.GRUCell(obs_size, hid_size)
self.output = nn.Linear(hid_size, act_size, bias=True)
def forward(self, obs):
"""Feed forward."""
output = F.relu(self.fc1(obs))
return self.output(output)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_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_zeros_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = 0.0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (384, 4), (4, 1))
assert_size_stride(primals_3, (384, 128), (128, 1))
assert_size_stride(primals_4, (384,), (1,))
assert_size_stride(primals_5, (384,), (1,))
assert_size_stride(primals_6, (4, 128), (128, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_zeros_0[grid(512)](buf0, 512, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 384), (384, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 384),
(1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 384), (384, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (128, 384), (
1, 128), 0), out=buf2)
del primals_3
buf3 = torch.ops.aten._thnn_fused_gru_cell.default(buf1, buf2, buf0,
primals_4, primals_5)
del buf1
del buf2
del primals_4
del primals_5
buf4 = buf3[0]
buf5 = buf3[1]
del buf3
buf6 = buf4
del buf4
triton_poi_fused_relu_1[grid(512)](buf6, 512, XBLOCK=256, num_warps
=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, buf6, reinterpret_tensor(primals_6,
(128, 4), (1, 128), 0), alpha=1, beta=1, out=buf7)
del primals_7
return buf7, primals_1, buf0, buf5, buf6, primals_6
class GRUCellNew(nn.Module):
"""Plain vanilla policy gradient network."""
def __init__(self, obs_size, act_size, hid_size=128):
super().__init__()
self.fc1 = nn.GRUCell(obs_size, hid_size)
self.output = nn.Linear(hid_size, act_size, bias=True)
def forward(self, input_0):
primals_2 = self.fc1.weight_ih
primals_3 = self.fc1.weight_hh
primals_4 = self.fc1.bias_ih
primals_5 = self.fc1.bias_hh
primals_6 = self.output.weight
primals_7 = self.output.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
ayjabri/DeepRL
|
GRUCell
| false
| 1,512
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
ELU_1
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class ELU_1(nn.ELU):
def __init__(self, *args, **kwargs):
super(ELU_1, self).__init__(*args, **kwargs)
def forward(self, input):
return F.elu(input, self.alpha, self.inplace)
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_elu_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
tmp3 = 1.0
tmp4 = tmp0 * tmp3
tmp5 = libdevice.expm1(tmp4)
tmp6 = tmp5 * tmp3
tmp7 = tl.where(tmp2, tmp4, tmp6)
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_elu_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ELU_1New(nn.ELU):
def __init__(self, *args, **kwargs):
super(ELU_1New, self).__init__(*args, **kwargs)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bantiitnab/kaggle-TGS-salt-identification
|
ELU_1
| false
| 1,513
|
[
"MIT"
] | 0
|
8b3350278b2ee8f01ba2a0734af9514d369f3228
|
https://github.com/bantiitnab/kaggle-TGS-salt-identification/tree/8b3350278b2ee8f01ba2a0734af9514d369f3228
|
TPSELoss
|
import torch
import torch.utils.data
from torch import nn
class TPSELoss(nn.Module):
def __init__(self):
super(TPSELoss, self).__init__()
self.loss = nn.L1Loss()
def forward(self, model_output):
gst_embed, tpse_embed = model_output[4], model_output[5]
gst_embed = gst_embed.detach()
loss = self.loss(tpse_embed, gst_embed)
return loss
def get_inputs():
return [torch.rand([6, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_mean_sub_0(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + (320 + r0), None)
tmp1 = tl.load(in_ptr0 + (256 + r0), None)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.sum(tmp4, 1)[:, None]
tmp7 = 64.0
tmp8 = tmp6 / tmp7
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (6, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_mean_sub_0[grid(1)](buf1, arg0_1, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class TPSELossNew(nn.Module):
def __init__(self):
super(TPSELossNew, self).__init__()
self.loss = nn.L1Loss()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
azahed98/mellotron
|
TPSELoss
| false
| 1,514
|
[
"BSD-3-Clause"
] | 0
|
02998743de820e379e0c7ff44506088d6e65c693
|
https://github.com/azahed98/mellotron/tree/02998743de820e379e0c7ff44506088d6e65c693
|
ActorNet
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class ActorNet(nn.Module):
def __init__(self, obs_size, act_size, high_action=1):
super().__init__()
self.high_action = high_action
self.base = nn.Linear(obs_size, 400)
self.fc1 = nn.Linear(400, 300)
self.fc2 = nn.Linear(300, 300)
self.actions = nn.Linear(300, act_size)
def forward(self, x):
y = F.relu(self.base(x))
y = F.relu(self.fc1(y))
y = F.relu(self.fc2(y))
y = torch.tanh(self.actions(y))
return self.high_action * y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 25600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 400
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 300
x2 = xindex // 1200
x3 = xindex % 1200
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x3 + 1216 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 1280 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 300
x1 = xindex // 300
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 300 * (x1 % 4) + 1216 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_mul_tanh_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (400, 4), (4, 1))
assert_size_stride(primals_2, (400,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (300, 400), (400, 1))
assert_size_stride(primals_5, (300,), (1,))
assert_size_stride(primals_6, (300, 300), (300, 1))
assert_size_stride(primals_7, (300,), (1,))
assert_size_stride(primals_8, (4, 300), (300, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 400), (6400, 1600, 400, 1), 0
)
del buf0
buf12 = empty_strided_cuda((4, 4, 4, 400), (6656, 1664, 400, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(25600)](buf1,
primals_2, buf12, 25600, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 400), (400, 1), 0),
reinterpret_tensor(primals_4, (400, 300), (1, 400), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 300), (4864, 1216, 300, 1),
torch.float32)
buf11 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf2,
primals_5, buf3, buf11, 19200, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_5
buf4 = buf2
del buf2
triton_poi_fused_relu_view_2[grid(19200)](buf3, buf4, 19200, XBLOCK
=256, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_6, (300, 300), (
1, 300), 0), out=buf5)
buf6 = buf3
del buf3
buf10 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf5,
primals_7, buf6, buf10, 19200, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_7
buf7 = buf5
del buf5
triton_poi_fused_relu_view_2[grid(19200)](buf6, buf7, 19200, XBLOCK
=256, num_warps=4, num_stages=1)
del buf6
buf8 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf7, reinterpret_tensor(primals_8,
(300, 4), (1, 300), 0), alpha=1, beta=1, out=buf8)
del primals_9
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_tanh_3[grid(256)](buf8, buf9, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf9, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 400), (400, 1), 0
), buf4, buf7, buf8, primals_8, buf10, primals_6, buf11, primals_4, buf12
class ActorNetNew(nn.Module):
def __init__(self, obs_size, act_size, high_action=1):
super().__init__()
self.high_action = high_action
self.base = nn.Linear(obs_size, 400)
self.fc1 = nn.Linear(400, 300)
self.fc2 = nn.Linear(300, 300)
self.actions = nn.Linear(300, act_size)
def forward(self, input_0):
primals_1 = self.base.weight
primals_2 = self.base.bias
primals_4 = self.fc1.weight
primals_5 = self.fc1.bias
primals_6 = self.fc2.weight
primals_7 = self.fc2.bias
primals_8 = self.actions.weight
primals_9 = self.actions.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]
|
ayjabri/DeepRL
|
ActorNet
| false
| 1,515
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
DiceLoss
|
import torch
import torch.nn as nn
def IoU(logit, truth, smooth=1):
prob = torch.sigmoid(logit)
intersection = torch.sum(prob * truth)
union = torch.sum(prob + truth)
iou = (2 * intersection + smooth) / (union + smooth)
return iou
class DiceLoss(nn.Module):
def __init__(self, smooth=1):
super(DiceLoss, self).__init__()
self.smooth = smooth
def forward(self, logit, truth):
iou = IoU(logit, truth, self.smooth)
loss = 1 - iou
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
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_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)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tmp1 + tmp2
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = 2.0
tmp12 = tmp6 * tmp11
tmp13 = 1.0
tmp14 = tmp12 + tmp13
tmp15 = tmp10 + tmp13
tmp16 = tmp14 / tmp15
tmp17 = tmp13 - tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mul_rsub_sigmoid_sum_0[grid(1)](buf2,
arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
def IoU(logit, truth, smooth=1):
prob = torch.sigmoid(logit)
intersection = torch.sum(prob * truth)
union = torch.sum(prob + truth)
iou = (2 * intersection + smooth) / (union + smooth)
return iou
class DiceLossNew(nn.Module):
def __init__(self, smooth=1):
super(DiceLossNew, self).__init__()
self.smooth = smooth
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
bantiitnab/kaggle-TGS-salt-identification
|
DiceLoss
| false
| 1,516
|
[
"MIT"
] | 0
|
8b3350278b2ee8f01ba2a0734af9514d369f3228
|
https://github.com/bantiitnab/kaggle-TGS-salt-identification/tree/8b3350278b2ee8f01ba2a0734af9514d369f3228
|
BCE_Dice
|
import torch
import torch.nn as nn
def IoU(logit, truth, smooth=1):
prob = torch.sigmoid(logit)
intersection = torch.sum(prob * truth)
union = torch.sum(prob + truth)
iou = (2 * intersection + smooth) / (union + smooth)
return iou
class DiceLoss(nn.Module):
def __init__(self, smooth=1):
super(DiceLoss, self).__init__()
self.smooth = smooth
def forward(self, logit, truth):
iou = IoU(logit, truth, self.smooth)
loss = 1 - iou
return loss
class BCE_Dice(nn.Module):
def __init__(self, smooth=1):
super(BCE_Dice, self).__init__()
self.smooth = smooth
self.dice = DiceLoss(smooth=smooth)
self.bce = nn.BCEWithLogitsLoss()
def forward(self, logit, truth):
dice = self.dice(logit, truth)
bce = self.bce(logit, truth)
return dice + bce
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_binary_cross_entropy_with_logits_div_mul_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)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tmp1 + tmp2
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = 1.0
tmp12 = tmp11 - tmp2
tmp13 = tmp12 * tmp0
tmp14 = 0.0
tmp15 = triton_helpers.minimum(tmp14, tmp0)
tmp16 = tl_math.abs(tmp0)
tmp17 = -tmp16
tmp18 = tl_math.exp(tmp17)
tmp19 = libdevice.log1p(tmp18)
tmp20 = tmp15 - tmp19
tmp21 = tmp13 - tmp20
tmp22 = tl.broadcast_to(tmp21, [RBLOCK])
tmp24 = triton_helpers.promote_to_tensor(tl.sum(tmp22, 0))
tmp25 = 2.0
tmp26 = tmp6 * tmp25
tmp27 = tmp26 + tmp11
tmp28 = tmp10 + tmp11
tmp29 = tmp27 / tmp28
tmp30 = tmp11 - tmp29
tmp31 = 256.0
tmp32 = tmp24 / tmp31
tmp33 = tmp30 + tmp32
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp33, 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_binary_cross_entropy_with_logits_div_mul_rsub_sigmoid_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,
def IoU(logit, truth, smooth=1):
prob = torch.sigmoid(logit)
intersection = torch.sum(prob * truth)
union = torch.sum(prob + truth)
iou = (2 * intersection + smooth) / (union + smooth)
return iou
class DiceLoss(nn.Module):
def __init__(self, smooth=1):
super(DiceLoss, self).__init__()
self.smooth = smooth
def forward(self, logit, truth):
iou = IoU(logit, truth, self.smooth)
loss = 1 - iou
return loss
class BCE_DiceNew(nn.Module):
def __init__(self, smooth=1):
super(BCE_DiceNew, self).__init__()
self.smooth = smooth
self.dice = DiceLoss(smooth=smooth)
self.bce = nn.BCEWithLogitsLoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
bantiitnab/kaggle-TGS-salt-identification
|
BCE_Dice
| false
| 1,517
|
[
"MIT"
] | 0
|
8b3350278b2ee8f01ba2a0734af9514d369f3228
|
https://github.com/bantiitnab/kaggle-TGS-salt-identification/tree/8b3350278b2ee8f01ba2a0734af9514d369f3228
|
VanillaRNN
|
import torch
import torch.nn as nn
class VanillaRNN(nn.Module):
def __init__(self, seq_length, input_dim, num_hidden, num_classes,
batch_size, device='cpu'):
super(VanillaRNN, self).__init__()
self.seq_length = seq_length
self.h_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.w_hx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_hh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_h = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ph = nn.Parameter(torch.Tensor(num_classes, num_hidden).
normal_(mean=0, std=0.0001))
self.b_p = nn.Parameter(torch.Tensor(num_classes, 1).zero_())
def forward(self, x):
h_t = self.h_init
tanh = nn.Tanh()
for step in range(self.seq_length):
h_t = tanh(self.w_hx @ x[:, step].t() + self.w_hh @ h_t + self.b_h)
p_t = self.w_ph @ h_t + self.b_p
return p_t.t()
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'seq_length': 4, 'input_dim': 4, 'num_hidden': 4,
'num_classes': 4, 'batch_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mv_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2,
out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp9 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + 8)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK])
tmp14 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr1 + 12)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK])
tmp19 = tl.load(in_ptr1 + 1)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp22 = tl.load(in_ptr1 + 5)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp26 = tl.load(in_ptr1 + 9)
tmp27 = tl.broadcast_to(tmp26, [XBLOCK])
tmp30 = tl.load(in_ptr1 + 13)
tmp31 = tl.broadcast_to(tmp30, [XBLOCK])
tmp34 = tl.load(in_ptr1 + 2)
tmp35 = tl.broadcast_to(tmp34, [XBLOCK])
tmp37 = tl.load(in_ptr1 + 6)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK])
tmp41 = tl.load(in_ptr1 + 10)
tmp42 = tl.broadcast_to(tmp41, [XBLOCK])
tmp45 = tl.load(in_ptr1 + 14)
tmp46 = tl.broadcast_to(tmp45, [XBLOCK])
tmp49 = tl.load(in_ptr1 + 3)
tmp50 = tl.broadcast_to(tmp49, [XBLOCK])
tmp52 = tl.load(in_ptr1 + 7)
tmp53 = tl.broadcast_to(tmp52, [XBLOCK])
tmp56 = tl.load(in_ptr1 + 11)
tmp57 = tl.broadcast_to(tmp56, [XBLOCK])
tmp60 = tl.load(in_ptr1 + 15)
tmp61 = tl.broadcast_to(tmp60, [XBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp21 = tmp0 * tmp20
tmp24 = tmp4 * tmp23
tmp25 = tmp21 + tmp24
tmp28 = tmp9 * tmp27
tmp29 = tmp25 + tmp28
tmp32 = tmp14 * tmp31
tmp33 = tmp29 + tmp32
tmp36 = tmp0 * tmp35
tmp39 = tmp4 * tmp38
tmp40 = tmp36 + tmp39
tmp43 = tmp9 * tmp42
tmp44 = tmp40 + tmp43
tmp47 = tmp14 * tmp46
tmp48 = tmp44 + tmp47
tmp51 = tmp0 * tmp50
tmp54 = tmp4 * tmp53
tmp55 = tmp51 + tmp54
tmp58 = tmp9 * tmp57
tmp59 = tmp55 + tmp58
tmp62 = tmp14 * tmp61
tmp63 = tmp59 + tmp62
tl.store(out_ptr0 + x0, tmp18, xmask)
tl.store(out_ptr1 + x0, tmp33, xmask)
tl.store(out_ptr2 + x0, tmp48, xmask)
tl.store(out_ptr3 + x0, tmp63, xmask)
@triton.jit
def triton_poi_fused_add_mv_tanh_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_mv_tanh_2(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tl.store(in_out_ptr0 + x2, tmp5, 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, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 1), (1, 1))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_4, primals_1, out=buf0)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf4 = empty_strided_cuda((4,), (1,), torch.float32)
buf7 = empty_strided_cuda((4,), (1,), torch.float32)
buf10 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_mv_0[grid(4)](primals_2, primals_3, buf1, buf4,
buf7, buf10, 4, XBLOCK=4, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mv_tanh_1[grid(16)](buf1, buf0, primals_5,
buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf0
del buf1
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_4, buf2, out=buf3)
buf5 = buf3
del buf3
triton_poi_fused_add_mv_tanh_2[grid(16)](buf5, buf4, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf4
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_4, buf5, out=buf6)
buf8 = buf6
del buf6
triton_poi_fused_add_mv_tanh_2[grid(16)](buf8, buf7, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf7
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_4, buf8, out=buf9)
buf11 = buf9
del buf9
triton_poi_fused_add_mv_tanh_2[grid(16)](buf11, buf10, primals_5,
16, XBLOCK=16, num_warps=1, num_stages=1)
del buf10
del primals_5
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_6, buf11, alpha=1, beta=1,
out=buf12)
del primals_7
return reinterpret_tensor(buf12, (4, 4), (1, 4), 0
), primals_3, buf2, buf5, buf8, buf11, reinterpret_tensor(primals_6,
(4, 4), (1, 4), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_1, (1, 4), (1, 1), 0)
class VanillaRNNNew(nn.Module):
def __init__(self, seq_length, input_dim, num_hidden, num_classes,
batch_size, device='cpu'):
super(VanillaRNNNew, self).__init__()
self.seq_length = seq_length
self.h_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.w_hx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_hh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_h = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ph = nn.Parameter(torch.Tensor(num_classes, num_hidden).
normal_(mean=0, std=0.0001))
self.b_p = nn.Parameter(torch.Tensor(num_classes, 1).zero_())
def forward(self, input_0):
primals_1 = self.h_init
primals_2 = self.w_hx
primals_3 = self.w_hh
primals_5 = self.b_h
primals_4 = self.w_ph
primals_7 = self.b_p
primals_6 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
askliar/deep_learning
|
VanillaRNN
| false
| 1,518
|
[
"MIT"
] | 0
|
e61b2391a3258d18719bf12d9ed1404620ce6c02
|
https://github.com/askliar/deep_learning/tree/e61b2391a3258d18719bf12d9ed1404620ce6c02
|
MLP
|
import torch
import torch.nn as nn
class MLP(nn.Module):
"""
Multi-Layer Perceptron network
"""
def __init__(self, obs_dim, dim_latent):
"""
Constructor
Args:
obs_dim: (int) dimension of observation
latent_dim: (int) dimension of output latent
"""
super().__init__()
self._hidden_dim = 20
self.fc1 = nn.Linear(obs_dim, self._hidden_dim)
self.fc2 = nn.Linear(self._hidden_dim, dim_latent)
self.act = nn.ReLU(inplace=True)
def forward(self, x):
"""
forward method
"""
x = self.act(self.fc1(x))
x = self.act(self.fc2(x))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_dim': 4, 'dim_latent': 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 = 1280
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 20
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + x4, tmp6, xmask)
@triton.jit
def triton_poi_fused_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1280
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 20
x1 = xindex // 20
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 20 * x1 + 80 * (x1 % 4 // 4) + 320 * ((4 *
(x1 // 4 % 4) + x1 % 4) // 16)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_view_2(in_out_ptr0, in_ptr0,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (20, 4), (4, 1))
assert_size_stride(primals_2, (20,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 20), (20, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 20), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 20), (320, 80, 20, 1), 0)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 20), (320, 80, 20, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(1280)](buf1,
primals_2, buf7, 1280, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
triton_poi_fused_view_1[grid(1280)](buf1, buf2, 1280, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (20, 4), (1,
20), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_view_2[grid(256)](buf4,
primals_5, buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf4
del primals_5
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, buf6, primals_4, buf7
class MLPNew(nn.Module):
"""
Multi-Layer Perceptron network
"""
def __init__(self, obs_dim, dim_latent):
"""
Constructor
Args:
obs_dim: (int) dimension of observation
latent_dim: (int) dimension of output latent
"""
super().__init__()
self._hidden_dim = 20
self.fc1 = nn.Linear(obs_dim, self._hidden_dim)
self.fc2 = nn.Linear(self._hidden_dim, dim_latent)
self.act = nn.ReLU(inplace=True)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
baihuaxie/drl-lib
|
MLP
| false
| 1,519
|
[
"MIT"
] | 0
|
3ad344901c3bb59e0bc16bb70202d2cfd538fd77
|
https://github.com/baihuaxie/drl-lib/tree/3ad344901c3bb59e0bc16bb70202d2cfd538fd77
|
ChannelGate2d
|
import torch
import torch.nn as nn
class ChannelGate2d(nn.Module):
def __init__(self, channels, reduction=2):
super(ChannelGate2d, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
padding=0)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
module_input = x
x = self.avg_pool(x)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
x = self.sigmoid(x)
return module_input * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (4, 2, 1, 1), (2, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 1, 1), (2, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(8)](buf3, primals_3, 8,
XBLOCK=8, num_warps=1, num_stages=1)
del primals_3
buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 1, 1), (4, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(16)](buf5, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(256)](primals_1, buf5, buf6,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf6, primals_1, primals_2, primals_4, buf1, buf3, buf5
class ChannelGate2dNew(nn.Module):
def __init__(self, channels, reduction=2):
super(ChannelGate2dNew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
padding=0)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bantiitnab/kaggle-TGS-salt-identification
|
ChannelGate2d
| false
| 1,520
|
[
"MIT"
] | 0
|
8b3350278b2ee8f01ba2a0734af9514d369f3228
|
https://github.com/bantiitnab/kaggle-TGS-salt-identification/tree/8b3350278b2ee8f01ba2a0734af9514d369f3228
|
SpatialGate2d
|
import torch
import torch.nn as nn
class SpatialGate2d(nn.Module):
def __init__(self, in_channels):
super(SpatialGate2d, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 1, kernel_size=1, stride=1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
cal = self.conv1(x)
cal = self.sigmoid(cal)
return cal * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.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 = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr1 + x3, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x3, 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
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_1[grid(256)](buf1, primals_3, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf2, primals_1, primals_3, buf1
class SpatialGate2dNew(nn.Module):
def __init__(self, in_channels):
super(SpatialGate2dNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 1, kernel_size=1, stride=1)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bantiitnab/kaggle-TGS-salt-identification
|
SpatialGate2d
| false
| 1,521
|
[
"MIT"
] | 0
|
8b3350278b2ee8f01ba2a0734af9514d369f3228
|
https://github.com/bantiitnab/kaggle-TGS-salt-identification/tree/8b3350278b2ee8f01ba2a0734af9514d369f3228
|
HingeLoss
|
import torch
class HingeLoss(torch.nn.Module):
def __init__(self):
super(HingeLoss, self).__init__()
def forward(self, x, y, margin=2):
output = (margin - x + y).clamp(min=0)
return output.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_mean_rsub_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 2.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = triton_helpers.maximum(tmp4, 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_clamp_mean_rsub_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 HingeLossNew(torch.nn.Module):
def __init__(self):
super(HingeLossNew, 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]
|
bashish101/ir
|
HingeLoss
| false
| 1,522
|
[
"MIT"
] | 0
|
cc90e86827c19035f38d0d85154f073a86aa9796
|
https://github.com/bashish101/ir/tree/cc90e86827c19035f38d0d85154f073a86aa9796
|
Critic
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, action_input_layer=0, init_type='normal',
activation='leaky_relu', init_std=0.01):
super(Critic, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.activation = activation
self.layers = nn.ModuleList()
input_size = self.state_size + action_size + action_parameter_size
last_hidden_layer_size = input_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(input_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.output_layer = nn.Linear(last_hidden_layer_size, 1)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.output_layer.weight, std=init_std)
nn.init.zeros_(self.output_layer.bias)
def forward(self, state, actions, action_parameters):
x = torch.cat((state, actions, action_parameters), dim=1)
negative_slope = 0.01
num_hidden_layers = len(self.layers)
for i in range(0, num_hidden_layers):
if self.activation == 'relu':
x = F.relu(self.layers[i](x))
elif self.activation == 'leaky_relu':
x = F.leaky_relu(self.layers[i](x), negative_slope)
else:
raise ValueError('Unknown activation function ' + str(self.
activation))
Q = self.output_layer(x)
return Q
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'action_parameter_size': 4}
]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (1, 12), (12, 1))
assert_size_stride(primals_5, (1,), (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)
del primals_1
del primals_2
del primals_3
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 1), (1, 12), 0), alpha=1, beta=1, out=buf2)
del primals_4
del primals_5
return buf2, buf0
class CriticNew(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, action_input_layer=0, init_type='normal',
activation='leaky_relu', init_std=0.01):
super(CriticNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.activation = activation
self.layers = nn.ModuleList()
input_size = self.state_size + action_size + action_parameter_size
last_hidden_layer_size = input_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(input_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.output_layer = nn.Linear(last_hidden_layer_size, 1)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.output_layer.weight, std=init_std)
nn.init.zeros_(self.output_layer.bias)
def forward(self, input_0, input_1, input_2):
primals_4 = self.output_layer.weight
primals_5 = self.output_layer.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bcahlit/MP-DQN
|
Critic
| false
| 1,523
|
[
"MIT"
] | 0
|
d80d34680e20192134f39e5b7c43abbc6bff3ba1
|
https://github.com/bcahlit/MP-DQN/tree/d80d34680e20192134f39e5b7c43abbc6bff3ba1
|
Actor
|
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def hidden_init(layer):
"""
compute the bounds [-lim, lim] for subsequent uniform sampling
with lim = 1/sqrt(nb_output)
"""
fan_in = layer.weight.data.size()[0]
lim = 1.0 / np.sqrt(fan_in)
return -lim, lim
class Actor(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=128,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(Actor, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, action_size)
self.reset_parameters()
def reset_parameters(self):
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-0.003, 0.003)
def forward(self, state):
"""Build an actor (policy) network that maps states -> actions."""
x = self.fc1(state)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return torch.tanh(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
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_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_tanh_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (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, (4, 64), (64, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 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
buf7 = 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, buf7, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_4, (128, 64), (1, 128), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_1[grid(4096)](buf3,
primals_5, buf6, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_6, (64, 4), (1, 64), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_tanh_2[grid(256)](buf5, primals_7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_7
return buf5, 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
), buf5, primals_6, buf6, primals_4, buf7
def hidden_init(layer):
"""
compute the bounds [-lim, lim] for subsequent uniform sampling
with lim = 1/sqrt(nb_output)
"""
fan_in = layer.weight.data.size()[0]
lim = 1.0 / np.sqrt(fan_in)
return -lim, lim
class ActorNew(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=128,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(ActorNew, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, action_size)
self.reset_parameters()
def reset_parameters(self):
self.fc1.weight.data.uniform_(*hidden_init(self.fc1))
self.fc2.weight.data.uniform_(*hidden_init(self.fc2))
self.fc3.weight.data.uniform_(-0.003, 0.003)
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]
|
bar0net/Udacity_DeepReinforcementLearning
|
Actor
| false
| 1,524
|
[
"MIT"
] | 0
|
3b5f98b7c2c1911b351be541fda3aa190bf48456
|
https://github.com/bar0net/Udacity_DeepReinforcementLearning/tree/3b5f98b7c2c1911b351be541fda3aa190bf48456
|
BertOutput
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn
import torch.nn as nn
class BertOutput(nn.Module):
"""BERT output layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, hidden_dropout_prob=
0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-12
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_2, primals_4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](buf1, buf2, buf3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_2[grid(256)](buf1, buf2, buf3,
primals_5, primals_6, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_6
return buf4, primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1
class BertOutputNew(nn.Module):
"""BERT output layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.dense.weight
primals_2 = self.dense.bias
primals_5 = self.LayerNorm.weight
primals_6 = self.LayerNorm.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
bamf-health/MONAI
|
BertOutput
| false
| 1,525
|
[
"Apache-2.0"
] | 0
|
6a2086d21baf4b60c2ab3d400ed5c97cf24a0da9
|
https://github.com/bamf-health/MONAI/tree/6a2086d21baf4b60c2ab3d400ed5c97cf24a0da9
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, init_std=0.01, init_type='normal', activation=
'leaky_relu', squashing_function=False):
super(Actor, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.squashing_function = squashing_function
assert self.squashing_function is False
self.activation = activation
self.layers = nn.ModuleList()
last_hidden_layer_size = self.state_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(self.state_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.action_output_layer = nn.Linear(last_hidden_layer_size, self.
action_size)
self.action_parameters_output_layer = nn.Linear(last_hidden_layer_size,
self.action_parameter_size)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.action_output_layer.weight, std=init_std)
nn.init.zeros_(self.action_output_layer.bias)
nn.init.normal_(self.action_parameters_output_layer.weight, std=
init_std)
nn.init.zeros_(self.action_parameters_output_layer.bias)
self.action_parameters_passthrough_layer = nn.Linear(self.
state_size, self.action_parameter_size)
nn.init.zeros_(self.action_parameters_passthrough_layer.weight)
nn.init.zeros_(self.action_parameters_passthrough_layer.bias)
self.action_parameters_passthrough_layer.weight.requires_grad = False
self.action_parameters_passthrough_layer.bias.requires_grad = False
def forward(self, state):
negative_slope = 0.01
x = state
num_hidden_layers = len(self.layers)
for i in range(0, num_hidden_layers):
if self.activation == 'relu':
x = F.relu(self.layers[i](x))
elif self.activation == 'leaky_relu':
x = F.leaky_relu(self.layers[i](x), negative_slope)
else:
raise ValueError('Unknown activation function ' + str(self.
activation))
actions = self.action_output_layer(x)
action_params = self.action_parameters_output_layer(x)
action_params += self.action_parameters_passthrough_layer(state)
return actions, action_params
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'action_parameter_size': 4}
]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_view_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
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x4, 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 + x4, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf4 = buf3
del buf3
get_raw_stream(0)
triton_poi_fused_add_view_0[grid(256)](buf4, primals_5, buf2,
primals_7, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
del primals_5
del primals_7
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf4, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0)
class ActorNew(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, init_std=0.01, init_type='normal', activation=
'leaky_relu', squashing_function=False):
super(ActorNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.squashing_function = squashing_function
assert self.squashing_function is False
self.activation = activation
self.layers = nn.ModuleList()
last_hidden_layer_size = self.state_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(self.state_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.action_output_layer = nn.Linear(last_hidden_layer_size, self.
action_size)
self.action_parameters_output_layer = nn.Linear(last_hidden_layer_size,
self.action_parameter_size)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.action_output_layer.weight, std=init_std)
nn.init.zeros_(self.action_output_layer.bias)
nn.init.normal_(self.action_parameters_output_layer.weight, std=
init_std)
nn.init.zeros_(self.action_parameters_output_layer.bias)
self.action_parameters_passthrough_layer = nn.Linear(self.
state_size, self.action_parameter_size)
nn.init.zeros_(self.action_parameters_passthrough_layer.weight)
nn.init.zeros_(self.action_parameters_passthrough_layer.bias)
self.action_parameters_passthrough_layer.weight.requires_grad = False
self.action_parameters_passthrough_layer.bias.requires_grad = False
def forward(self, input_0):
primals_2 = self.action_output_layer.weight
primals_3 = self.action_output_layer.bias
primals_4 = self.action_parameters_output_layer.weight
primals_5 = self.action_parameters_output_layer.bias
primals_6 = self.action_parameters_passthrough_layer.weight
primals_7 = self.action_parameters_passthrough_layer.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
bcahlit/MP-DQN
|
Actor
| false
| 1,526
|
[
"MIT"
] | 0
|
d80d34680e20192134f39e5b7c43abbc6bff3ba1
|
https://github.com/bcahlit/MP-DQN/tree/d80d34680e20192134f39e5b7c43abbc6bff3ba1
|
BigRamDuel
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class BigRamDuel(nn.Module):
"""
Definition: DuelDQNet(obs_size, act_size)
"""
def __init__(self, obs_size, act_size):
super().__init__()
self.base = nn.Linear(obs_size, 256)
self.fc1 = nn.Linear(256, 256)
self.drop1 = nn.Dropout()
self.fc2 = nn.Linear(256, 128)
self.drop2 = nn.Dropout()
self.fc3 = nn.Linear(128, 64)
self.val = nn.Linear(64, 1)
self.adv = nn.Linear(64, act_size)
def forward(self, x):
x /= 255
out = F.relu(self.base(x))
out = F.relu(self.fc1(out))
out = self.drop1(out)
out = F.relu(self.fc2(out))
out = self.drop2(out)
out = F.relu(self.fc3(out))
val = self.val(out)
adv = self.adv(out)
return val + (adv - adv.mean(dim=1, keepdim=True))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'obs_size': 4, 'act_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_div_0(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.00392156862745098
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_add_mean_sub_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex // 4
x5 = xindex
x3 = xindex // 64
x6 = xindex % 16
tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + x5, xmask)
tmp5 = tl.load(in_ptr2 + (x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr2 + (16 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr2 + (32 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr2 + (48 + x6 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp3 = tmp0 + tmp2
tmp7 = tmp5 + tmp6
tmp9 = tmp7 + tmp8
tmp11 = tmp9 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tmp4 - tmp13
tmp15 = tmp3 + tmp14
tl.store(out_ptr0 + x5, tmp15, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (256, 4), (4, 1))
assert_size_stride(primals_3, (256,), (1,))
assert_size_stride(primals_4, (256, 256), (256, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (128, 256), (256, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (64, 128), (128, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (1, 64), (64, 1))
assert_size_stride(primals_11, (1,), (1,))
assert_size_stride(primals_12, (4, 64), (64, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](primals_1, buf0, primals_1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 256), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf1
buf15 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16384)](buf2,
primals_3, buf15, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 256), (1, 256), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf3
buf14 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16384)](buf4,
primals_5, buf14, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_6, (256, 128), (1, 256), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf5
buf13 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(8192)](buf6,
primals_7, buf13, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf7 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_8, (128, 64), (1, 128), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf7
buf12 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
triton_poi_fused_relu_threshold_backward_3[grid(4096)](buf8,
primals_9, buf12, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf9 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf8, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_10, (64, 1), (1, 64), 0), out=buf9)
buf10 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf8, (64, 64),
(64, 1), 0), reinterpret_tensor(primals_12, (64, 4), (1, 64), 0
), alpha=1, beta=1, out=buf10)
del primals_13
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mean_sub_4[grid(256)](buf9, primals_11, buf10,
buf11, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf10
del buf9
del primals_11
return (buf11, reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(buf2, (64, 256), (256, 1), 0),
reinterpret_tensor(buf4, (64, 256), (256, 1), 0),
reinterpret_tensor(buf6, (64, 128), (128, 1), 0),
reinterpret_tensor(buf8, (64, 64), (64, 1), 0), primals_12,
primals_10, buf12, primals_8, buf13, primals_6, buf14, primals_4, buf15
)
class BigRamDuelNew(nn.Module):
"""
Definition: DuelDQNet(obs_size, act_size)
"""
def __init__(self, obs_size, act_size):
super().__init__()
self.base = nn.Linear(obs_size, 256)
self.fc1 = nn.Linear(256, 256)
self.drop1 = nn.Dropout()
self.fc2 = nn.Linear(256, 128)
self.drop2 = nn.Dropout()
self.fc3 = nn.Linear(128, 64)
self.val = nn.Linear(64, 1)
self.adv = nn.Linear(64, act_size)
def forward(self, input_0):
primals_2 = self.base.weight
primals_3 = self.base.bias
primals_4 = self.fc1.weight
primals_5 = self.fc1.bias
primals_6 = self.fc2.weight
primals_7 = self.fc2.bias
primals_8 = self.fc3.weight
primals_9 = self.fc3.bias
primals_10 = self.val.weight
primals_11 = self.val.bias
primals_12 = self.adv.weight
primals_13 = self.adv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
ayjabri/DeepRL
|
BigRamDuel
| false
| 1,527
|
[
"MIT"
] | 0
|
0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
https://github.com/ayjabri/DeepRL/tree/0be095e3a3d04f60b4cdc97ed330dffc17b3024a
|
duelingDQNnetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class duelingDQNnetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(duelingDQNnetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1_val = nn.Linear(state_size, fc1_units)
self.fc2_val = nn.Linear(fc1_units, fc2_units)
self.fc3_val = nn.Linear(fc2_units, 1)
self.fc1_adv = nn.Linear(state_size, fc1_units)
self.fc2_adv = nn.Linear(fc1_units, fc2_units)
self.fc3_adv = nn.Linear(fc2_units, action_size)
def forward(self, x):
val = F.relu(self.fc1_val(x))
val = F.relu(self.fc2_val(val))
val = self.fc3_val(val)
adv = F.relu(self.fc1_adv(x))
adv = F.relu(self.fc2_adv(adv))
adv = self.fc3_adv(adv)
return val + adv - adv.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_per_fused_add_mean_sub_1(in_ptr0, in_ptr1, in_ptr2, 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
r2 = rindex // 4
tmp0 = tl.load(in_ptr0 + r0, None)
tmp4 = tl.load(in_ptr1 + r2, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + 0)
tmp6 = tl.broadcast_to(tmp5, [RBLOCK])
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = triton_helpers.promote_to_tensor(tl.sum(tmp1, 0))
tmp7 = tmp4 + tmp6
tmp8 = tmp7 + tmp0
tmp9 = 256.0
tmp10 = tmp3 / tmp9
tmp11 = tmp8 - tmp10
tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp11, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (1, 64), (64, 1))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (64, 4), (4, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (64, 64), (64, 1))
assert_size_stride(primals_11, (64,), (1,))
assert_size_stride(primals_12, (4, 64), (64, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf15 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf15, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
buf14 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf3,
primals_5, buf14, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_6, (64, 1), (1, 64), 0), out=buf4)
buf5 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 64), (1, 4), 0), out=buf5)
del primals_8
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf5
buf13 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf6,
primals_9, buf13, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf7 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_10, (64, 64), (1, 64), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf7
buf12 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf8,
primals_11, buf12, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_11
buf9 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf8, (64, 64),
(64, 1), 0), reinterpret_tensor(primals_12, (64, 4), (1, 64), 0
), alpha=1, beta=1, out=buf9)
del primals_13
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_add_mean_sub_1[grid(1)](buf9, buf4, primals_7,
buf11, 1, 256, num_warps=2, num_stages=1)
del buf4
del buf9
del primals_7
return buf11, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(
buf3, (64, 64), (64, 1), 0), reinterpret_tensor(buf6, (64, 64), (64,
1), 0), reinterpret_tensor(buf8, (64, 64), (64, 1), 0
), primals_12, buf12, primals_10, buf13, primals_6, buf14, primals_4, buf15
class duelingDQNnetworkNew(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(duelingDQNnetworkNew, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1_val = nn.Linear(state_size, fc1_units)
self.fc2_val = nn.Linear(fc1_units, fc2_units)
self.fc3_val = nn.Linear(fc2_units, 1)
self.fc1_adv = nn.Linear(state_size, fc1_units)
self.fc2_adv = nn.Linear(fc1_units, fc2_units)
self.fc3_adv = nn.Linear(fc2_units, action_size)
def forward(self, input_0):
primals_1 = self.fc1_val.weight
primals_2 = self.fc1_val.bias
primals_4 = self.fc2_val.weight
primals_5 = self.fc2_val.bias
primals_6 = self.fc3_val.weight
primals_7 = self.fc3_val.bias
primals_8 = self.fc1_adv.weight
primals_9 = self.fc1_adv.bias
primals_10 = self.fc2_adv.weight
primals_11 = self.fc2_adv.bias
primals_12 = self.fc3_adv.weight
primals_13 = self.fc3_adv.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]
|
beibeiJ/deep-reinforcement-learning
|
duelingDQNnetwork
| false
| 1,528
|
[
"MIT"
] | 0
|
ab1b0f4ada8da69af2e38d3e2e82e3ae55837c60
|
https://github.com/beibeiJ/deep-reinforcement-learning/tree/ab1b0f4ada8da69af2e38d3e2e82e3ae55837c60
|
LocAndConf
|
import torch
import torch.nn as nn
from math import sqrt as sqrt
from itertools import product as product
class LocAndConf(nn.Module):
def __init__(self, c_in, c_out, num_classes):
super(LocAndConf, self).__init__()
self.c_in = c_in
self.c_out = c_out
self.num_classes = num_classes
self.conv_loc = nn.Conv2d(c_in, c_out * 4, kernel_size=3, padding=1)
self.conv_conf = nn.Conv2d(c_in, c_out * num_classes, kernel_size=3,
padding=1)
def forward(self, x):
loc = self.conv_loc(x)
conf = self.conv_conf(x)
return loc, conf
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4, 'c_out': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math import sqrt as sqrt
from itertools import product as product
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (16, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (16, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (16,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 16, 4, 4), (256, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(1024)](buf1, primals_2, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 16, 4, 4), (256, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(1024)](buf3, primals_5, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
return buf1, buf3, primals_1, primals_3, primals_4
class LocAndConfNew(nn.Module):
def __init__(self, c_in, c_out, num_classes):
super(LocAndConfNew, self).__init__()
self.c_in = c_in
self.c_out = c_out
self.num_classes = num_classes
self.conv_loc = nn.Conv2d(c_in, c_out * 4, kernel_size=3, padding=1)
self.conv_conf = nn.Conv2d(c_in, c_out * num_classes, kernel_size=3,
padding=1)
def forward(self, input_0):
primals_1 = self.conv_loc.weight
primals_2 = self.conv_loc.bias
primals_4 = self.conv_conf.weight
primals_5 = self.conv_conf.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
beichen2012/ssd.pytorch
|
LocAndConf
| false
| 1,529
|
[
"MIT"
] | 0
|
90b68a6903d2bef4c358e295d88b25e6fc6daf54
|
https://github.com/beichen2012/ssd.pytorch/tree/90b68a6903d2bef4c358e295d88b25e6fc6daf54
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor, self).__init__()
self.l1 = nn.Linear(state_dim, 256)
self.l2 = nn.Linear(256, 256)
self.l3 = nn.Linear(256, action_dim)
self.max_action = max_action
def forward(self, state):
a = F.relu(self.l1(state))
a = F.relu(self.l2(a))
return self.max_action * torch.tanh(self.l3(a))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4, 'action_dim': 4, 'max_action': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_mul_tanh_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = 4.0
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (256, 256), (256, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (4, 256), (256, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf7, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 256), (1, 256), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf3,
primals_5, buf6, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 256),
(256, 1), 0), reinterpret_tensor(primals_6, (256, 4), (1, 256),
0), alpha=1, beta=1, out=buf4)
del primals_7
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_tanh_1[grid(256)](buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), reinterpret_tensor(buf3, (64, 256), (256, 1), 0
), buf4, primals_6, buf6, primals_4, buf7
class ActorNew(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(ActorNew, self).__init__()
self.l1 = nn.Linear(state_dim, 256)
self.l2 = nn.Linear(256, 256)
self.l3 = nn.Linear(256, action_dim)
self.max_action = max_action
def forward(self, input_0):
primals_1 = self.l1.weight
primals_2 = self.l1.bias
primals_4 = self.l2.weight
primals_5 = self.l2.bias
primals_6 = self.l3.weight
primals_7 = self.l3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
baturaysaglam/DISCOVER
|
Actor
| false
| 1,530
|
[
"MIT"
] | 0
|
423158c84a5935ca5755ccad06ea5fe20fb57d76
|
https://github.com/baturaysaglam/DISCOVER/tree/423158c84a5935ca5755ccad06ea5fe20fb57d76
|
PositionEncoder
|
from _paritybench_helpers import _mock_config
import torch
import numpy as np
import torch.nn as nn
class PositionEncoder(nn.Module):
"""
Encodes the information into vectors
There are 2 pieces of information that goes into the encoded information:
1. Word Embedding
2. Position Embedding
This set of codes would encode the position information
"""
@staticmethod
def pos_emb(pos, dim, d_model):
return pos / np.power(10000, 2 * (dim // 2) / d_model)
@staticmethod
def cal_pos_emb(pos, d_emb_dim, d_model):
return [PositionEncoder.pos_emb(pos, dim, d_model) for dim in range
(d_emb_dim)]
@staticmethod
def get_position_embedding(max_index, d_model, d_emb_dim, requires_grad
=False):
position_embedding = np.array([PositionEncoder.cal_pos_emb(pos,
d_emb_dim, d_model) for pos in range(max_index + 1)])
position_embedding[:, 0::2] = np.sin(position_embedding[:, 0::2])
position_embedding[:, 1::2] = np.cos(position_embedding[:, 1::2])
position_embedding = torch.FloatTensor(position_embedding)
position_embedding.requires_grad = requires_grad
return position_embedding
def __init__(self, config, max_index):
super(PositionEncoder, self).__init__()
self.config = config
self.max_index = max_index
self.d_model = self.config.d_model
self.d_emb_dim = self.config.emb_dim
self.requires_grad = self.config.train_pos_emb
self.freeze = True if self.requires_grad is False else False
self.pos_embd_weights = PositionEncoder.get_position_embedding(
max_index=self.max_index, d_model=self.config.d_model,
d_emb_dim=self.d_emb_dim, requires_grad=self.requires_grad)
self.position_encoding = nn.Embedding.from_pretrained(self.
pos_embd_weights, freeze=self.freeze)
def forward(self, src_seq):
"""
Ref:
https://pytorch.org/docs/stable/nn.html
Does encoding for the input:
1. position encoding (The position encoding are based on the time stamp)
<--------- POS Embedding --------->
Input:
src_seq :
Output:
encoded_pos_features :
"""
position_index = src_seq.long()
encoded_pos_features = self.position_encoding(position_index)
return encoded_pos_features
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(d_model=4, emb_dim=4, train_pos_emb
=False), 'max_index': 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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__to_copy_embedding_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tmp0.to(tl.int64)
tmp2 = tl.full([XBLOCK], 5, tl.int32)
tmp3 = tmp1 + tmp2
tmp4 = tmp1 < 0
tmp5 = tl.where(tmp4, tmp3, tmp1)
tl.device_assert((0 <= tmp5) & (tmp5 < 5) | ~xmask,
'index out of bounds: 0 <= tmp5 < 5')
tmp7 = tl.load(in_ptr1 + (x0 + 4 * tmp5), xmask)
tl.store(out_ptr0 + x2, tmp7, 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, (5, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_embedding_0[grid(1024)](arg0_1, arg1_1,
buf0, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class PositionEncoderNew(nn.Module):
"""
Encodes the information into vectors
There are 2 pieces of information that goes into the encoded information:
1. Word Embedding
2. Position Embedding
This set of codes would encode the position information
"""
@staticmethod
def pos_emb(pos, dim, d_model):
return pos / np.power(10000, 2 * (dim // 2) / d_model)
@staticmethod
def cal_pos_emb(pos, d_emb_dim, d_model):
return [PositionEncoderNew.pos_emb(pos, dim, d_model) for dim in
range(d_emb_dim)]
@staticmethod
def get_position_embedding(max_index, d_model, d_emb_dim, requires_grad
=False):
position_embedding = np.array([PositionEncoderNew.cal_pos_emb(pos,
d_emb_dim, d_model) for pos in range(max_index + 1)])
position_embedding[:, 0::2] = np.sin(position_embedding[:, 0::2])
position_embedding[:, 1::2] = np.cos(position_embedding[:, 1::2])
position_embedding = torch.FloatTensor(position_embedding)
position_embedding.requires_grad = requires_grad
return position_embedding
def __init__(self, config, max_index):
super(PositionEncoderNew, self).__init__()
self.config = config
self.max_index = max_index
self.d_model = self.config.d_model
self.d_emb_dim = self.config.emb_dim
self.requires_grad = self.config.train_pos_emb
self.freeze = True if self.requires_grad is False else False
self.pos_embd_weights = PositionEncoderNew.get_position_embedding(
max_index=self.max_index, d_model=self.config.d_model,
d_emb_dim=self.d_emb_dim, requires_grad=self.requires_grad)
self.position_encoding = nn.Embedding.from_pretrained(self.
pos_embd_weights, freeze=self.freeze)
def forward(self, input_0):
arg1_1 = self.position_encoding.weight
arg0_1 = input_0
output = call([arg0_1, arg1_1])
return output[0]
|
benedictleedm/sgnlp
|
PositionEncoder
| false
| 1,531
|
[
"MIT"
] | 0
|
03f0fda8c517d9ca4baf737ce4c46b2495bbd3ba
|
https://github.com/benedictleedm/sgnlp/tree/03f0fda8c517d9ca4baf737ce4c46b2495bbd3ba
|
GeM
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.nn.parameter import Parameter
def gem(x, p=3, eps=1e-06):
return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(
1.0 / p)
class GeM(nn.Module):
def __init__(self, p=3.0, eps=1e-06, freeze_p=True):
super(GeM, self).__init__()
self.p = p if freeze_p else Parameter(torch.ones(1) * p)
self.eps = eps
self.freeze_p = freeze_p
def forward(self, x):
return gem(x, p=self.p, eps=self.eps)
def __repr__(self):
if isinstance(self.p, float):
p = self.p
else:
p = self.p.data.tolist()[0]
return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(p
) + ', ' + 'eps=' + str(self.eps) + ', ' + 'freeze_p=' + str(self
.freeze_p) + ')'
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 libdevice
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_avg_pool2d_clamp_pow_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp35 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp40 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp45 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp50 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp55 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp60 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp65 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp70 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp75 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp1 = 1e-06
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tmp2 * tmp2
tmp4 = tmp3 * tmp2
tmp6 = triton_helpers.maximum(tmp5, tmp1)
tmp7 = tmp6 * tmp6
tmp8 = tmp7 * tmp6
tmp9 = tmp8 + tmp4
tmp11 = triton_helpers.maximum(tmp10, tmp1)
tmp12 = tmp11 * tmp11
tmp13 = tmp12 * tmp11
tmp14 = tmp13 + tmp9
tmp16 = triton_helpers.maximum(tmp15, tmp1)
tmp17 = tmp16 * tmp16
tmp18 = tmp17 * tmp16
tmp19 = tmp18 + tmp14
tmp21 = triton_helpers.maximum(tmp20, tmp1)
tmp22 = tmp21 * tmp21
tmp23 = tmp22 * tmp21
tmp24 = tmp23 + tmp19
tmp26 = triton_helpers.maximum(tmp25, tmp1)
tmp27 = tmp26 * tmp26
tmp28 = tmp27 * tmp26
tmp29 = tmp28 + tmp24
tmp31 = triton_helpers.maximum(tmp30, tmp1)
tmp32 = tmp31 * tmp31
tmp33 = tmp32 * tmp31
tmp34 = tmp33 + tmp29
tmp36 = triton_helpers.maximum(tmp35, tmp1)
tmp37 = tmp36 * tmp36
tmp38 = tmp37 * tmp36
tmp39 = tmp38 + tmp34
tmp41 = triton_helpers.maximum(tmp40, tmp1)
tmp42 = tmp41 * tmp41
tmp43 = tmp42 * tmp41
tmp44 = tmp43 + tmp39
tmp46 = triton_helpers.maximum(tmp45, tmp1)
tmp47 = tmp46 * tmp46
tmp48 = tmp47 * tmp46
tmp49 = tmp48 + tmp44
tmp51 = triton_helpers.maximum(tmp50, tmp1)
tmp52 = tmp51 * tmp51
tmp53 = tmp52 * tmp51
tmp54 = tmp53 + tmp49
tmp56 = triton_helpers.maximum(tmp55, tmp1)
tmp57 = tmp56 * tmp56
tmp58 = tmp57 * tmp56
tmp59 = tmp58 + tmp54
tmp61 = triton_helpers.maximum(tmp60, tmp1)
tmp62 = tmp61 * tmp61
tmp63 = tmp62 * tmp61
tmp64 = tmp63 + tmp59
tmp66 = triton_helpers.maximum(tmp65, tmp1)
tmp67 = tmp66 * tmp66
tmp68 = tmp67 * tmp66
tmp69 = tmp68 + tmp64
tmp71 = triton_helpers.maximum(tmp70, tmp1)
tmp72 = tmp71 * tmp71
tmp73 = tmp72 * tmp71
tmp74 = tmp73 + tmp69
tmp76 = triton_helpers.maximum(tmp75, tmp1)
tmp77 = tmp76 * tmp76
tmp78 = tmp77 * tmp76
tmp79 = tmp78 + tmp74
tmp80 = 0.0625
tmp81 = tmp79 * tmp80
tmp82 = 0.3333333333333333
tmp83 = libdevice.pow(tmp81, tmp82)
tl.store(in_out_ptr0 + x0, tmp83, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_avg_pool2d_clamp_pow_0[grid(16)](buf1, arg0_1, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
return buf1,
def gem(x, p=3, eps=1e-06):
return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(
1.0 / p)
class GeMNew(nn.Module):
def __init__(self, p=3.0, eps=1e-06, freeze_p=True):
super(GeMNew, self).__init__()
self.p = p if freeze_p else Parameter(torch.ones(1) * p)
self.eps = eps
self.freeze_p = freeze_p
def __repr__(self):
if isinstance(self.p, float):
p = self.p
else:
p = self.p.data.tolist()[0]
return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(p
) + ', ' + 'eps=' + str(self.eps) + ', ' + 'freeze_p=' + str(self
.freeze_p) + ')'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
beesk135/ReID-Survey
|
GeM
| false
| 1,532
|
[
"MIT"
] | 0
|
d1467c0ce5d3ca78640196360a05df9ff9f9f42a
|
https://github.com/beesk135/ReID-Survey/tree/d1467c0ce5d3ca78640196360a05df9ff9f9f42a
|
CoreNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CoreNetwork(nn.Module):
"""The core network.
An RNN that maintains an internal state by integrating
information extracted from the history of past observations.
It encodes the agent's knowledge of the environment through
a state vector `h_t` that gets updated at every time step `t`.
Concretely, it takes the glimpse representation `g_t` as input,
and combines it with its internal state `h_t_prev` at the previous
time step, to produce the new internal state `h_t` at the current
time step.
In other words:
`h_t = relu( fc(h_t_prev) + fc(g_t) )`
Args:
input_size: input size of the rnn.
hidden_size: hidden size of the rnn.
g_t: a 2D tensor of shape (B, hidden_size). The glimpse
representation returned by the glimpse network for the
current timestep `t`.
h_t_prev: a 2D tensor of shape (B, hidden_size). The
hidden state vector for the previous timestep `t-1`.
Returns:
h_t: a 2D tensor of shape (B, hidden_size). The hidden
state vector for the current timestep `t`.
"""
def __init__(self, input_size, hidden_size):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size, hidden_size)
self.h2h = nn.Linear(hidden_size, hidden_size)
def forward(self, g_t, h_t_prev):
h1 = self.i2h(g_t)
h2 = self.h2h(h_t_prev)
h_t = F.relu(h1 + h2)
return h_t
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime 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_add_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp9 = 0.0
tmp10 = tmp8 <= tmp9
tl.store(in_out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_relu_threshold_backward_0[grid(256)](buf2,
primals_2, buf1, primals_5, buf3, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del buf1
del primals_2
del primals_5
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), buf3
class CoreNetworkNew(nn.Module):
"""The core network.
An RNN that maintains an internal state by integrating
information extracted from the history of past observations.
It encodes the agent's knowledge of the environment through
a state vector `h_t` that gets updated at every time step `t`.
Concretely, it takes the glimpse representation `g_t` as input,
and combines it with its internal state `h_t_prev` at the previous
time step, to produce the new internal state `h_t` at the current
time step.
In other words:
`h_t = relu( fc(h_t_prev) + fc(g_t) )`
Args:
input_size: input size of the rnn.
hidden_size: hidden size of the rnn.
g_t: a 2D tensor of shape (B, hidden_size). The glimpse
representation returned by the glimpse network for the
current timestep `t`.
h_t_prev: a 2D tensor of shape (B, hidden_size). The
hidden state vector for the previous timestep `t-1`.
Returns:
h_t: a 2D tensor of shape (B, hidden_size). The hidden
state vector for the current timestep `t`.
"""
def __init__(self, input_size, hidden_size):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size, hidden_size)
self.h2h = nn.Linear(hidden_size, hidden_size)
def forward(self, input_0, input_1):
primals_1 = self.i2h.weight
primals_2 = self.i2h.bias
primals_4 = self.h2h.weight
primals_5 = self.h2h.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
bennzo/DT-RAM-PyTorch
|
CoreNetwork
| false
| 1,533
|
[
"MIT"
] | 0
|
b364662ab7650ffd26cf129673752521e004b13a
|
https://github.com/bennzo/DT-RAM-PyTorch/tree/b364662ab7650ffd26cf129673752521e004b13a
|
MultiHeadAttention
|
import torch
import torch.utils.data
from torch import nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
"""
input:
query --- [N, T_q, query_dim]
key --- [N, T_k, key_dim]
output:
out --- [N, T_q, num_units]
"""
def __init__(self, query_dim, key_dim, num_units, num_heads):
super().__init__()
self.num_units = num_units
self.num_heads = num_heads
self.key_dim = key_dim
self.W_query = nn.Linear(in_features=query_dim, out_features=
num_units, bias=False)
self.W_key = nn.Linear(in_features=key_dim, out_features=num_units,
bias=False)
self.W_value = nn.Linear(in_features=key_dim, out_features=
num_units, bias=False)
def forward(self, query, key):
querys = self.W_query(query)
keys = self.W_key(key)
values = self.W_value(key)
split_size = self.num_units // self.num_heads
querys = torch.stack(torch.split(querys, split_size, dim=2), dim=0)
keys = torch.stack(torch.split(keys, split_size, dim=2), dim=0)
values = torch.stack(torch.split(values, split_size, dim=2), dim=0)
scores = torch.matmul(querys, keys.transpose(2, 3))
scores = scores / self.key_dim ** 0.5
scores = F.softmax(scores, dim=3)
out = torch.matmul(scores, values)
out = torch.cat(torch.split(out, 1, dim=0), dim=3).squeeze(0)
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'query_dim': 4, 'key_dim': 4, 'num_units': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 4
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x4 = xindex
tmp0 = x3
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x0 + 16 * (x1 + 4 * x2)), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * (-4 + x1 + 4 * x2)), tmp9 &
xmask, eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * (-8 + x1 + 4 * x2)), tmp14 &
xmask, eviction_policy='evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 16, tl.int64)
tmp19 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * (-12 + x1 + 4 * x2)),
tmp16 & xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tmp23 = 0.7071067811865476
tmp24 = tmp22 * tmp23
tl.store(out_ptr0 + x4, tmp24, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_stack_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x0 + 16 * x1), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * (-4 + x1)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * (-8 + x1)), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 16, tl.int64)
tmp19 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * (-12 + x1)), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tl.store(out_ptr0 + x2, tmp22, xmask)
@triton.jit
def triton_poi_fused_cat_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x1, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 2, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (16 + x1), tmp9 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 3, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (32 + x1), tmp14 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 4, tl.int64)
tmp19 = tl.load(in_ptr0 + (48 + x1), tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tl.store(out_ptr0 + x2, tmp22, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(64)](buf0, buf3, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(64)](buf1, buf4, 64, XBLOCK=64, num_warps=1,
num_stages=1)
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 1), 0)
del buf1
triton_poi_fused_stack_3[grid(64)](buf2, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_cat_4[grid(64)](buf9, buf10, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf9
return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_4, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class MultiHeadAttentionNew(nn.Module):
"""
input:
query --- [N, T_q, query_dim]
key --- [N, T_k, key_dim]
output:
out --- [N, T_q, num_units]
"""
def __init__(self, query_dim, key_dim, num_units, num_heads):
super().__init__()
self.num_units = num_units
self.num_heads = num_heads
self.key_dim = key_dim
self.W_query = nn.Linear(in_features=query_dim, out_features=
num_units, bias=False)
self.W_key = nn.Linear(in_features=key_dim, out_features=num_units,
bias=False)
self.W_value = nn.Linear(in_features=key_dim, out_features=
num_units, bias=False)
def forward(self, input_0, input_1):
primals_1 = self.W_query.weight
primals_3 = self.W_key.weight
primals_5 = self.W_value.weight
primals_2 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
azahed98/mellotron
|
MultiHeadAttention
| false
| 1,534
|
[
"BSD-3-Clause"
] | 0
|
02998743de820e379e0c7ff44506088d6e65c693
|
https://github.com/azahed98/mellotron/tree/02998743de820e379e0c7ff44506088d6e65c693
|
StoppingNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Bernoulli
class StoppingNetwork(nn.Module):
"""The stopping network.
Uses the internal state `h_t` of the core network
to determine whether the network integrated enough
information to make a confident classification.
Practically, take the internal state `h_t` as input
and outputs a binary action `a_t` which states
whether the network should stop or continue with
the glimpses.
Args:
input_size: input size of the fc layer.
output_size: output size of the fc layer.
h_t: the hidden state vector of the core network
for the current time step `t`.
Returns:
a_t: a 2D vector of shape (B, 1).
The stopping action for the current time step `t`.
"""
def __init__(self, input_size, output_size):
super().__init__()
self.fc = nn.Linear(input_size, input_size)
self.fc_at = nn.Linear(input_size, 1)
def forward(self, h_t):
feat = F.relu(self.fc(h_t.detach()))
a_t_pi = F.hardtanh(input=self.fc_at(feat), min_val=-10, max_val=10)
a_t_pi = torch.sigmoid(a_t_pi)
a_t = Bernoulli(probs=a_t_pi).sample()
a_t = a_t.detach()
log_pi = Bernoulli(probs=a_t_pi).log_prob(a_t)
return log_pi, a_t
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 import device
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_bernoulli_hardtanh_hardtanh_backward_sigmoid_1(in_out_ptr0
, 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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp12 = tl.load(in_out_ptr0 + x0, xmask)
tmp3 = tmp0 + tmp2
tmp4 = -10.0
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp6 = 10.0
tmp7 = triton_helpers.minimum(tmp5, tmp6)
tmp8 = tl.sigmoid(tmp7)
tmp9 = tmp3 <= tmp4
tmp10 = tmp3 >= tmp6
tmp11 = tmp9 | tmp10
tmp13 = tmp12 < tmp8
tmp14 = tmp13.to(tl.float32)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
tl.store(in_out_ptr0 + x0, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (1, 4), (4, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_3, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 1), (1, 4), 0), out=buf2)
buf4 = torch.ops.aten.rand.default([4, 4, 4, 1], dtype=torch.
float32, device=device(type='cuda', index=0), pin_memory=False)
buf5 = buf4
del buf4
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.bool)
buf6 = buf5
del buf5
triton_poi_fused_bernoulli_hardtanh_hardtanh_backward_sigmoid_1[grid
(64)](buf6, buf2, primals_5, buf3, buf7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf2
del primals_5
return buf6, buf3, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0
), buf3, buf7, primals_4, buf8
class StoppingNetworkNew(nn.Module):
"""The stopping network.
Uses the internal state `h_t` of the core network
to determine whether the network integrated enough
information to make a confident classification.
Practically, take the internal state `h_t` as input
and outputs a binary action `a_t` which states
whether the network should stop or continue with
the glimpses.
Args:
input_size: input size of the fc layer.
output_size: output size of the fc layer.
h_t: the hidden state vector of the core network
for the current time step `t`.
Returns:
a_t: a 2D vector of shape (B, 1).
The stopping action for the current time step `t`.
"""
def __init__(self, input_size, output_size):
super().__init__()
self.fc = nn.Linear(input_size, input_size)
self.fc_at = nn.Linear(input_size, 1)
def forward(self, input_0):
primals_2 = self.fc.weight
primals_3 = self.fc.bias
primals_4 = self.fc_at.weight
primals_5 = self.fc_at.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
bennzo/DT-RAM-PyTorch
|
StoppingNetwork
| false
| 1,535
|
[
"MIT"
] | 0
|
b364662ab7650ffd26cf129673752521e004b13a
|
https://github.com/bennzo/DT-RAM-PyTorch/tree/b364662ab7650ffd26cf129673752521e004b13a
|
SACActorNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SACActorNetwork(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super(SACActorNetwork, self).__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, state):
features1 = F.relu(self._h1(torch.squeeze(state, 1).float()))
features2 = F.relu(self._h2(features1))
a = self._h3(features2)
return a
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': [4, 4], 'output_shape': [4, 4],
'n_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_3, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3,
primals_5, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(
buf3, (64, 4), (4, 1), 0), primals_6, buf5, primals_4, buf6
class SACActorNetworkNew(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super(SACActorNetworkNew, self).__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, input_0):
primals_2 = self._h1.weight
primals_3 = self._h1.bias
primals_4 = self._h2.weight
primals_5 = self._h2.bias
primals_6 = self._h3.weight
primals_7 = self._h3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
benvoe/mushroom-rl-benchmark
|
SACActorNetwork
| false
| 1,536
|
[
"MIT"
] | 0
|
217d8c077bf6f3febaed92821a2cf183c83f703b
|
https://github.com/benvoe/mushroom-rl-benchmark/tree/217d8c077bf6f3febaed92821a2cf183c83f703b
|
FeedForwardNetwork
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class FeedForwardNetwork(nn.Module):
"""
Based on the paper, each layer has 2 subayers:
A multi-headed attention mechanism &
a position-wise fully connected feed-forward network
Each layer employs a residual connection, y = f(x) + id(x) = f(x) + x, followed by layer normalization
This python file would define the position-wise fully connected feed-forward network:
A two layer feed-forward module
FFN(x) = max(0, x* w_1 + b_1) * w_2 + b_2
"""
def __init__(self, config):
super().__init__()
self.config = config
self.d_model = self.config.d_model
self.d_feed_forward = self.config.d_feed_forward
self.w_1 = nn.Linear(self.d_model, self.d_feed_forward)
self.w_2 = nn.Linear(self.d_feed_forward, self.d_model)
self.non_linearity = nn.ReLU()
self.layer_norm = nn.LayerNorm(normalized_shape=self.d_model)
self.dropout = nn.Dropout(p=self.config.dropout_rate, inplace=True)
nn.init.xavier_normal_(self.w_1.weight)
nn.init.xavier_normal_(self.w_2.weight)
def forward(self, x):
"""
FFN(x) = max(0, x* w_1 + b_1) * w_2 + b_2
a residual connection, y = f(x) + id(x) = f(x) + x
"""
output_layer_1 = self.w_1(x)
output_layer_1 = self.non_linearity(output_layer_1)
self.dropout(output_layer_1)
output_layer_2 = self.w_2(output_layer_1)
del output_layer_1
torch.cuda.empty_cache()
self.dropout(output_layer_2)
final_output = self.layer_norm(output_layer_2 + x)
del output_layer_2
del x
torch.cuda.empty_cache()
return final_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(d_model=4, d_feed_forward=4,
dropout_rate=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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_add_native_layer_norm_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1e-05
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf6, 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, 1), (16, 4, 1, 64), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_native_layer_norm_1[grid(64)](buf2, primals_3,
buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_2[grid(256)](buf2, primals_3,
buf3, buf4, primals_6, primals_7, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf3
del buf4
del primals_7
return buf5, primals_3, primals_6, reinterpret_tensor(buf1, (64, 4), (4,
1), 0), buf2, primals_4, buf6
class FeedForwardNetworkNew(nn.Module):
"""
Based on the paper, each layer has 2 subayers:
A multi-headed attention mechanism &
a position-wise fully connected feed-forward network
Each layer employs a residual connection, y = f(x) + id(x) = f(x) + x, followed by layer normalization
This python file would define the position-wise fully connected feed-forward network:
A two layer feed-forward module
FFN(x) = max(0, x* w_1 + b_1) * w_2 + b_2
"""
def __init__(self, config):
super().__init__()
self.config = config
self.d_model = self.config.d_model
self.d_feed_forward = self.config.d_feed_forward
self.w_1 = nn.Linear(self.d_model, self.d_feed_forward)
self.w_2 = nn.Linear(self.d_feed_forward, self.d_model)
self.non_linearity = nn.ReLU()
self.layer_norm = nn.LayerNorm(normalized_shape=self.d_model)
self.dropout = nn.Dropout(p=self.config.dropout_rate, inplace=True)
nn.init.xavier_normal_(self.w_1.weight)
nn.init.xavier_normal_(self.w_2.weight)
def forward(self, input_0):
primals_1 = self.w_1.weight
primals_2 = self.w_1.bias
primals_4 = self.w_2.weight
primals_5 = self.w_2.bias
primals_6 = self.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
benedictleedm/sgnlp
|
FeedForwardNetwork
| false
| 1,537
|
[
"MIT"
] | 0
|
03f0fda8c517d9ca4baf737ce4c46b2495bbd3ba
|
https://github.com/benedictleedm/sgnlp/tree/03f0fda8c517d9ca4baf737ce4c46b2495bbd3ba
|
MLP
|
import torch
class MLP(torch.nn.Module):
def __init__(self, insize, outsize=128, nonlinear=torch.nn.ReLU,
activation=torch.nn.ReLU, hidden_layer_size=1, node_size=256):
super(MLP, self).__init__()
self.net = torch.nn.Sequential()
self.net.add_module('fc_1', torch.nn.Linear(insize, node_size))
self.net.add_module('nonlinear_1', nonlinear())
for i in range(hidden_layer_size - 1):
self.net.add_module('fc_' + str(i + 2), torch.nn.Linear(
node_size, node_size))
self.net.add_module('nonlinear_' + str(i + 2), nonlinear())
self.net.add_module('head', torch.nn.Linear(node_size, outsize))
self.net.add_module('activation', activation())
def forward(self, x):
return self.net(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'insize': 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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 256), (256, 1))
assert_size_stride(primals_5, (128,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf5, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 128), (1, 256), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf4 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf3,
primals_5, buf4, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), buf4, primals_4, buf5
class MLPNew(torch.nn.Module):
def __init__(self, insize, outsize=128, nonlinear=torch.nn.ReLU,
activation=torch.nn.ReLU, hidden_layer_size=1, node_size=256):
super(MLPNew, self).__init__()
self.net = torch.nn.Sequential()
self.net.add_module('fc_1', torch.nn.Linear(insize, node_size))
self.net.add_module('nonlinear_1', nonlinear())
for i in range(hidden_layer_size - 1):
self.net.add_module('fc_' + str(i + 2), torch.nn.Linear(
node_size, node_size))
self.net.add_module('nonlinear_' + str(i + 2), nonlinear())
self.net.add_module('head', torch.nn.Linear(node_size, outsize))
self.net.add_module('activation', activation())
def forward(self, input_0):
primals_1 = self.net.fc_1.weight
primals_2 = self.net.fc_1.bias
primals_4 = self.net.head.weight
primals_5 = self.net.head.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bengisug/multiagent-particle-envs
|
MLP
| false
| 1,538
|
[
"MIT"
] | 0
|
c87280f18fbaf885932fe6da4d600ab474fd83fe
|
https://github.com/bengisug/multiagent-particle-envs/tree/c87280f18fbaf885932fe6da4d600ab474fd83fe
|
Classification
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Classification(torch.nn.Module):
def __init__(self, num_class, hidden_dim):
super(Classification, self).__init__()
self.num_class = num_class
self.label = nn.Linear(hidden_dim, num_class)
def forward(self, input):
outp = self.label(input)
class_score = F.log_softmax(outp.view(-1, self.num_class), dim=1)
return class_score
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_class': 4, 'hidden_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=
128, num_warps=4, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused__log_softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf1
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf2
class ClassificationNew(torch.nn.Module):
def __init__(self, num_class, hidden_dim):
super(ClassificationNew, self).__init__()
self.num_class = num_class
self.label = nn.Linear(hidden_dim, num_class)
def forward(self, input_0):
primals_1 = self.label.weight
primals_2 = self.label.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bentherien/measevalcompetition
|
Classification
| false
| 1,539
|
[
"MIT"
] | 0
|
1d285991eb26403682a633a728629a9900923d80
|
https://github.com/bentherien/measevalcompetition/tree/1d285991eb26403682a633a728629a9900923d80
|
LocationNetwork
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
class LocationNetwork(nn.Module):
"""The location network.
Uses the internal state `h_t` of the core network to
produce the location coordinates `l_t` for the next
time step.
Concretely, feeds the hidden state `h_t` through a fc
layer followed by a tanh to clamp the output beween
[-1, 1]. This produces a 2D vector of means used to
parametrize a two-component Gaussian with a fixed
variance from which the location coordinates `l_t`
for the next time step are sampled.
Hence, the location `l_t` is chosen stochastically
from a distribution conditioned on an affine
transformation of the hidden state vector `h_t`.
Args:
input_size: input size of the fc layer.
output_size: output size of the fc layer.
std: standard deviation of the normal distribution.
h_t: the hidden state vector of the core network for
the current time step `t`.
Returns:
mu: a 2D vector of shape (B, 2).
l_t: a 2D vector of shape (B, 2).
"""
def __init__(self, input_size, output_size, std):
super().__init__()
self.std = std
hid_size = input_size // 2
self.fc = nn.Linear(input_size, hid_size)
self.fc_lt = nn.Linear(hid_size, output_size)
def forward(self, h_t):
feat = F.relu(self.fc(h_t.detach()))
mu = torch.tanh(self.fc_lt(feat))
l_t = torch.distributions.Normal(mu, self.std).rsample()
l_t = l_t.detach()
log_pi = Normal(mu, self.std).log_prob(l_t)
log_pi = torch.sum(log_pi, dim=1)
l_t = torch.clamp(l_t, -1, 1)
return log_pi, l_t
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4, 'std': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
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_add_div_log_mul_neg_pow_sub_sum_tanh_1(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp2 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp27 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp29 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp39 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp41 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp1 = libdevice.tanh(tmp0)
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tmp1 + tmp4
tmp6 = tmp5 - tmp1
tmp7 = tmp6 * tmp6
tmp8 = -tmp7
tmp9 = 0.03125
tmp10 = tmp8 * tmp9
tmp11 = 1.3862943649291992
tmp12 = tmp10 - tmp11
tmp13 = 0.9189385332046727
tmp14 = tmp12 - tmp13
tmp16 = libdevice.tanh(tmp15)
tmp18 = tmp17 * tmp3
tmp19 = tmp16 + tmp18
tmp20 = tmp19 - tmp16
tmp21 = tmp20 * tmp20
tmp22 = -tmp21
tmp23 = tmp22 * tmp9
tmp24 = tmp23 - tmp11
tmp25 = tmp24 - tmp13
tmp26 = tmp14 + tmp25
tmp28 = libdevice.tanh(tmp27)
tmp30 = tmp29 * tmp3
tmp31 = tmp28 + tmp30
tmp32 = tmp31 - tmp28
tmp33 = tmp32 * tmp32
tmp34 = -tmp33
tmp35 = tmp34 * tmp9
tmp36 = tmp35 - tmp11
tmp37 = tmp36 - tmp13
tmp38 = tmp26 + tmp37
tmp40 = libdevice.tanh(tmp39)
tmp42 = tmp41 * tmp3
tmp43 = tmp40 + tmp42
tmp44 = tmp43 - tmp40
tmp45 = tmp44 * tmp44
tmp46 = -tmp45
tmp47 = tmp46 * tmp9
tmp48 = tmp47 - tmp11
tmp49 = tmp48 - tmp13
tmp50 = tmp38 + tmp49
tl.store(out_ptr0 + x2, tmp50, xmask)
@triton.jit
def triton_poi_fused_add_clamp_mul_tanh_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
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tmp1 + tmp4
tmp6 = -1.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = 1.0
tmp9 = triton_helpers.minimum(tmp7, tmp8)
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4), (4, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (4, 2), (2, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 2), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 2), (32, 8, 2, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(128)](buf1,
primals_3, buf8, 128, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 2), (
2, 1), 0), reinterpret_tensor(primals_4, (2, 4), (1, 2), 0),
alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = torch.ops.aten.normal_functional.default(buf3)
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_log_mul_neg_pow_sub_sum_tanh_1[grid(64)](buf2,
buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf7 = buf3
del buf3
triton_poi_fused_add_clamp_mul_tanh_2[grid(256)](buf2, buf5, buf7,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf6, buf7, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 2), (2, 1), 0
), buf2, buf5, primals_4, buf8
class LocationNetworkNew(nn.Module):
"""The location network.
Uses the internal state `h_t` of the core network to
produce the location coordinates `l_t` for the next
time step.
Concretely, feeds the hidden state `h_t` through a fc
layer followed by a tanh to clamp the output beween
[-1, 1]. This produces a 2D vector of means used to
parametrize a two-component Gaussian with a fixed
variance from which the location coordinates `l_t`
for the next time step are sampled.
Hence, the location `l_t` is chosen stochastically
from a distribution conditioned on an affine
transformation of the hidden state vector `h_t`.
Args:
input_size: input size of the fc layer.
output_size: output size of the fc layer.
std: standard deviation of the normal distribution.
h_t: the hidden state vector of the core network for
the current time step `t`.
Returns:
mu: a 2D vector of shape (B, 2).
l_t: a 2D vector of shape (B, 2).
"""
def __init__(self, input_size, output_size, std):
super().__init__()
self.std = std
hid_size = input_size // 2
self.fc = nn.Linear(input_size, hid_size)
self.fc_lt = nn.Linear(hid_size, output_size)
def forward(self, input_0):
primals_2 = self.fc.weight
primals_3 = self.fc.bias
primals_4 = self.fc_lt.weight
primals_5 = self.fc_lt.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
bennzo/DT-RAM-PyTorch
|
LocationNetwork
| false
| 1,540
|
[
"MIT"
] | 0
|
b364662ab7650ffd26cf129673752521e004b13a
|
https://github.com/bennzo/DT-RAM-PyTorch/tree/b364662ab7650ffd26cf129673752521e004b13a
|
A2CNetwork
|
import torch
import torch.nn as nn
class A2CNetwork(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super(A2CNetwork, self).__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('tanh'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('tanh'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, state, **kwargs):
features1 = torch.tanh(self._h1(torch.squeeze(state, 1).float()))
features2 = torch.tanh(self._h2(features1))
a = self._h3(features2)
return a
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': [4, 4], 'output_shape': [4, 4],
'n_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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1, buf3, primals_6, primals_4
class A2CNetworkNew(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super(A2CNetworkNew, self).__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('tanh'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('tanh'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, input_0):
primals_2 = self._h1.weight
primals_3 = self._h1.bias
primals_4 = self._h2.weight
primals_5 = self._h2.bias
primals_6 = self._h3.weight
primals_7 = self._h3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
benvoe/mushroom-rl-benchmark
|
A2CNetwork
| false
| 1,541
|
[
"MIT"
] | 0
|
217d8c077bf6f3febaed92821a2cf183c83f703b
|
https://github.com/benvoe/mushroom-rl-benchmark/tree/217d8c077bf6f3febaed92821a2cf183c83f703b
|
BertMixedLayer
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn
import torch.nn as nn
class BertAttention(nn.Module):
"""BERT attention layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, context):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(context)
mixed_value_layer = self.value(context)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
attention_probs = self.dropout(nn.Softmax(dim=-1)(attention_scores))
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
class BertOutput(nn.Module):
"""BERT output layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertMixedLayer(nn.Module):
"""BERT cross attention layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.att = BertAttention(config)
self.output = BertOutput(config)
def forward(self, x, y):
output = self.att(x, y)
return self.output(output, x)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(num_attention_heads=4, hidden_size=
4, attention_probs_dropout_prob=0.5, hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
import torch.nn
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_5(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_6(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1e-12
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_8, buf8, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_10, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_10
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](buf11, primals_3,
buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_6[grid(64)](buf11, primals_3,
buf12, buf13, primals_11, primals_12, buf14, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf12
del buf13
del primals_12
return buf14, primals_3, primals_11, reinterpret_tensor(primals_6, (16,
4), (4, 1), 0), buf7, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0
), reinterpret_tensor(buf10, (16, 4), (4, 1), 0), buf11, primals_9
class BertAttention(nn.Module):
"""BERT attention layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, context):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(context)
mixed_value_layer = self.value(context)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
attention_probs = self.dropout(nn.Softmax(dim=-1)(attention_scores))
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
class BertOutput(nn.Module):
"""BERT output layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertMixedLayerNew(nn.Module):
"""BERT cross attention layer.
Based on: BERT (pytorch-transformer)
https://github.com/huggingface/transformers
"""
def __init__(self, config) ->None:
super().__init__()
self.att = BertAttention(config)
self.output = BertOutput(config)
def forward(self, input_0, input_1):
primals_1 = self.att.query.weight
primals_2 = self.att.query.bias
primals_4 = self.att.key.weight
primals_5 = self.att.key.bias
primals_7 = self.att.value.weight
primals_8 = self.att.value.bias
primals_9 = self.output.dense.weight
primals_10 = self.output.dense.bias
primals_11 = self.output.LayerNorm.weight
primals_12 = self.output.LayerNorm.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
bamf-health/MONAI
|
BertMixedLayer
| false
| 1,542
|
[
"Apache-2.0"
] | 0
|
6a2086d21baf4b60c2ab3d400ed5c97cf24a0da9
|
https://github.com/bamf-health/MONAI/tree/6a2086d21baf4b60c2ab3d400ed5c97cf24a0da9
|
SACCriticNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SACCriticNetwork(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super().__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, state, action):
state_action = torch.cat((state.float(), action.float()), dim=1)
features1 = F.relu(self._h1(state_action))
features2 = F.relu(self._h2(features1))
q = self._h3(features2)
return torch.squeeze(q)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': [4, 4], 'output_shape': [4, 4],
'n_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 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_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (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_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((128, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (128, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = reinterpret_tensor(buf1, (4, 8, 4, 4), (128, 16, 4, 1), 0)
del buf1
buf7 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(512)](buf2,
primals_4, buf7, 512, XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((128, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (128, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 8, 4, 4), (128, 16, 4, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(512)](buf4,
primals_6, buf6, 512, XBLOCK=128, num_warps=4, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((128, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(buf4, (128, 4),
(4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf5)
del primals_8
return reinterpret_tensor(buf5, (4, 8, 4, 4), (128, 16, 4, 1), 0
), reinterpret_tensor(buf0, (128, 4), (4, 1), 0), reinterpret_tensor(
buf2, (128, 4), (4, 1), 0), reinterpret_tensor(buf4, (128, 4), (4,
1), 0), primals_7, buf6, primals_5, buf7
class SACCriticNetworkNew(nn.Module):
def __init__(self, input_shape, output_shape, n_features, **kwargs):
super().__init__()
n_input = input_shape[-1]
n_output = output_shape[0]
self._h1 = nn.Linear(n_input, n_features)
self._h2 = nn.Linear(n_features, n_features)
self._h3 = nn.Linear(n_features, n_output)
nn.init.xavier_uniform_(self._h1.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h2.weight, gain=nn.init.
calculate_gain('relu'))
nn.init.xavier_uniform_(self._h3.weight, gain=nn.init.
calculate_gain('linear'))
def forward(self, input_0, input_1):
primals_3 = self._h1.weight
primals_4 = self._h1.bias
primals_5 = self._h2.weight
primals_6 = self._h2.bias
primals_7 = self._h3.weight
primals_8 = self._h3.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
benvoe/mushroom-rl-benchmark
|
SACCriticNetwork
| false
| 1,543
|
[
"MIT"
] | 0
|
217d8c077bf6f3febaed92821a2cf183c83f703b
|
https://github.com/benvoe/mushroom-rl-benchmark/tree/217d8c077bf6f3febaed92821a2cf183c83f703b
|
Time2Vec
|
import torch
from torch import nn
class Time2Vec(nn.Module):
def __init__(self, input_dim=4, embed_dim=248, act_function=torch.sin):
assert embed_dim % input_dim == 0
super(Time2Vec, self).__init__()
self.enabled = embed_dim > 0
if self.enabled:
self.embed_dim = embed_dim // input_dim
self.input_dim = input_dim
self.embed_weight = nn.parameter.Parameter(torch.randn(self.
input_dim, self.embed_dim))
self.embed_bias = nn.parameter.Parameter(torch.randn(self.
embed_dim))
self.act_function = act_function
def forward(self, x):
if self.enabled:
x = torch.diag_embed(x)
x_affine = torch.matmul(x, self.embed_weight) + self.embed_bias
x_affine_0, x_affine_remain = torch.split(x_affine, [1, self.
embed_dim - 1], dim=-1)
x_affine_remain = self.act_function(x_affine_remain)
x_output = torch.cat([x_affine_0, x_affine_remain], dim=-1)
x_output = x_output.view(x_output.size(0), x_output.size(1), -1)
else:
x_output = x
return x_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import 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_diag_embed_view_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp3 = tl.load(in_ptr0 + (x0 + 4 * (x1 // 4)), xmask)
tmp0 = x0
tmp1 = x2 // 4 % 4
tmp2 = tmp0 == tmp1
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 15872
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 62
x1 = xindex // 62
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 + (62 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 62, tl.int64)
tmp13 = tl.load(in_ptr0 + (1 + 62 * x1 + (-1 + x0)), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp14 = tl.load(in_ptr1 + (1 + (-1 + x0)), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tmp13 + tmp14
tmp16 = tl_math.sin(tmp15)
tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype)
tmp18 = tl.where(tmp10, tmp16, tmp17)
tmp19 = tl.where(tmp4, tmp9, tmp18)
tl.store(out_ptr0 + x2, tmp19, xmask)
@triton.jit
def triton_poi_fused_cos_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 15616
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 61
x1 = xindex // 61
x2 = xindex
tmp0 = tl.load(in_ptr0 + (1 + x0 + 62 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (1 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl_math.cos(tmp2)
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 62), (62, 1))
assert_size_stride(primals_3, (62,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((256, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_diag_embed_view_0[grid(1024)](primals_1, buf0,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((256, 62), (62, 1), torch.float32)
extern_kernels.mm(buf0, primals_2, out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4, 62), (3968, 992, 248, 62, 1),
torch.float32)
triton_poi_fused_cat_1[grid(15872)](buf1, primals_3, buf2, 15872,
XBLOCK=256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4, 61), (3904, 976, 244, 61, 1),
torch.float32)
triton_poi_fused_cos_2[grid(15616)](buf1, primals_3, buf3, 15616,
XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_3
return reinterpret_tensor(buf2, (4, 4, 992), (3968, 992, 1), 0
), buf3, reinterpret_tensor(buf0, (4, 256), (1, 4), 0)
class Time2VecNew(nn.Module):
def __init__(self, input_dim=4, embed_dim=248, act_function=torch.sin):
assert embed_dim % input_dim == 0
super(Time2VecNew, self).__init__()
self.enabled = embed_dim > 0
if self.enabled:
self.embed_dim = embed_dim // input_dim
self.input_dim = input_dim
self.embed_weight = nn.parameter.Parameter(torch.randn(self.
input_dim, self.embed_dim))
self.embed_bias = nn.parameter.Parameter(torch.randn(self.
embed_dim))
self.act_function = act_function
def forward(self, input_0):
primals_2 = self.embed_weight
primals_3 = self.embed_bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bernhein/spacetimeformer
|
Time2Vec
| false
| 1,544
|
[
"MIT"
] | 0
|
de252b68085943d979606fe69e177ac2a14586e7
|
https://github.com/bernhein/spacetimeformer/tree/de252b68085943d979606fe69e177ac2a14586e7
|
HardSwish
|
import torch
import torch.nn as nn
class HardSwish(nn.Module):
def __init__(self):
super().__init__()
self.relu6 = nn.ReLU6()
def forward(self, x):
return self.relu6(x + 3.0) / 6.0 * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_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 = 0.16666666666666666
tmp8 = tmp6 * tmp7
tmp9 = tmp8 * tmp0
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=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HardSwishNew(nn.Module):
def __init__(self):
super().__init__()
self.relu6 = nn.ReLU6()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
binyao2020/ElegantRL
|
HardSwish
| false
| 1,545
|
[
"Apache-2.0"
] | 0
|
bf79f0d071d00cd93be03f1ca005020c3ab8dfe0
|
https://github.com/binyao2020/ElegantRL/tree/bf79f0d071d00cd93be03f1ca005020c3ab8dfe0
|
RMSELoss
|
import torch
import torch as th
import torch.nn as nn
class RMSELoss(nn.Module):
def __init__(self, reduction='mean', eps=1e-06):
super().__init__()
self.mse = nn.MSELoss(reduction=reduction)
self.eps = eps
def forward(self, yhat, y):
loss = th.sqrt(self.mse(yhat, y) + self.eps)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mse_loss_sqrt_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = 256.0
tmp8 = tmp6 / tmp7
tmp9 = 1e-06
tmp10 = tmp8 + tmp9
tmp11 = libdevice.sqrt(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_mse_loss_sqrt_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 RMSELossNew(nn.Module):
def __init__(self, reduction='mean', eps=1e-06):
super().__init__()
self.mse = nn.MSELoss(reduction=reduction)
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]
|
bio-ontology-research-group/OntoML
|
RMSELoss
| false
| 1,546
|
[
"BSD-3-Clause"
] | 0
|
4cdc17dc7ee26464db96c67838c3e77dba5318f9
|
https://github.com/bio-ontology-research-group/OntoML/tree/4cdc17dc7ee26464db96c67838c3e77dba5318f9
|
GumbelQuantize
|
import torch
from torch import nn
from torch import einsum
import torch.nn.functional as F
class GumbelQuantize(nn.Module):
"""
Gumbel Softmax trick quantizer
Categorical Reparameterization with Gumbel-Softmax, Jang et al. 2016
https://arxiv.org/abs/1611.01144
"""
def __init__(self, num_hiddens, n_embed, embedding_dim,
straight_through=False):
super().__init__()
self.embedding_dim = embedding_dim
self.n_embed = n_embed
self.straight_through = straight_through
self.temperature = 1.0
self.kld_scale = 0.0005
self.proj = nn.Conv2d(num_hiddens, n_embed, 1)
self.embed = nn.Embedding(n_embed, embedding_dim)
def forward(self, z):
hard = self.straight_through if self.training else True
logits = self.proj(z)
soft_one_hot = F.gumbel_softmax(logits, tau=self.temperature, dim=1,
hard=hard)
z_q = einsum('b n h w, n d -> b d h w', soft_one_hot, self.embed.weight
)
qy = F.softmax(logits, dim=1)
diff = self.kld_scale * torch.sum(qy * torch.log(qy * self.n_embed +
1e-10), dim=1).mean()
ind = soft_one_hot.argmax(dim=1)
return z_q, diff, ind
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_hiddens': 4, 'n_embed': 4, 'embedding_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_add_log_neg_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
tmp7 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp21 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp22 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tl_math.log(tmp1)
tmp3 = -tmp2
tmp4 = tmp0 + tmp3
tmp5 = 1.0
tmp6 = tmp4 * tmp5
tmp9 = tl_math.log(tmp8)
tmp10 = -tmp9
tmp11 = tmp7 + tmp10
tmp12 = tmp11 * tmp5
tmp13 = triton_helpers.maximum(tmp6, tmp12)
tmp16 = tl_math.log(tmp15)
tmp17 = -tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp18 * tmp5
tmp20 = triton_helpers.maximum(tmp13, tmp19)
tmp23 = tl_math.log(tmp22)
tmp24 = -tmp23
tmp25 = tmp21 + tmp24
tmp26 = tmp25 * tmp5
tmp27 = triton_helpers.maximum(tmp20, tmp26)
tmp28 = tmp6 - tmp27
tmp29 = tmp28 * tmp5
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp12 - tmp27
tmp32 = tmp31 * tmp5
tmp33 = tl_math.exp(tmp32)
tmp34 = tmp30 + tmp33
tmp35 = tmp19 - tmp27
tmp36 = tmp35 * tmp5
tmp37 = tl_math.exp(tmp36)
tmp38 = tmp34 + tmp37
tmp39 = tmp26 - tmp27
tmp40 = tmp39 * tmp5
tmp41 = tl_math.exp(tmp40)
tmp42 = tmp38 + tmp41
tl.store(out_ptr0 + x2, tmp27, xmask)
tl.store(out_ptr1 + x2, tmp42, xmask)
@triton.jit
def triton_poi_fused__softmax_add_log_neg_2(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_out_ptr0 + x3, xmask)
tmp7 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.log(tmp1)
tmp3 = -tmp2
tmp4 = tmp0 + tmp3
tmp5 = 1.0
tmp6 = tmp4 * tmp5
tmp8 = tmp6 - tmp7
tmp9 = tmp8 * tmp5
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp17 = triton_helpers.maximum(tmp15, tmp16)
tmp19 = triton_helpers.maximum(tmp17, tmp18)
tmp20 = tmp0 - tmp19
tmp21 = tl_math.exp(tmp20)
tl.store(in_out_ptr0 + x3, tmp12, xmask)
tl.store(out_ptr0 + x3, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_argmax_max_scatter_sub_3(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp17 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp32 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 > tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = tl.full([1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 > tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 > tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tmp47 = tmp46 == tmp10
tmp48 = 1.0
tmp49 = 0.0
tmp50 = tl.where(tmp47, tmp48, tmp49)
tmp51 = tmp50 - tmp0
tmp52 = tmp51 + tmp0
tmp53 = tmp46 == tmp11
tmp54 = tl.where(tmp53, tmp48, tmp49)
tmp55 = tmp54 - tmp1
tmp56 = tmp55 + tmp1
tmp57 = tmp52 > tmp56
tmp58 = tmp52 == tmp56
tmp59 = tmp52 != tmp52
tmp60 = tmp56 != tmp56
tmp61 = tmp59 > tmp60
tmp62 = tmp57 | tmp61
tmp63 = tmp59 & tmp60
tmp64 = tmp58 | tmp63
tmp65 = tmp64 & tmp12
tmp66 = tmp62 | tmp65
tmp67 = tl.where(tmp66, tmp52, tmp56)
tmp68 = tl.where(tmp66, tmp10, tmp11)
tmp69 = tmp46 == tmp26
tmp70 = tl.where(tmp69, tmp48, tmp49)
tmp71 = tmp70 - tmp17
tmp72 = tmp71 + tmp17
tmp73 = tmp67 > tmp72
tmp74 = tmp67 == tmp72
tmp75 = tmp67 != tmp67
tmp76 = tmp72 != tmp72
tmp77 = tmp75 > tmp76
tmp78 = tmp73 | tmp77
tmp79 = tmp75 & tmp76
tmp80 = tmp74 | tmp79
tmp81 = tmp68 < tmp26
tmp82 = tmp80 & tmp81
tmp83 = tmp78 | tmp82
tmp84 = tl.where(tmp83, tmp67, tmp72)
tmp85 = tl.where(tmp83, tmp68, tmp26)
tmp86 = tmp46 == tmp41
tmp87 = tl.where(tmp86, tmp48, tmp49)
tmp88 = tmp87 - tmp32
tmp89 = tmp88 + tmp32
tmp90 = tmp84 > tmp89
tmp91 = tmp84 == tmp89
tmp92 = tmp84 != tmp84
tmp93 = tmp89 != tmp89
tmp94 = tmp92 > tmp93
tmp95 = tmp90 | tmp94
tmp96 = tmp92 & tmp93
tmp97 = tmp91 | tmp96
tmp98 = tmp85 < tmp41
tmp99 = tmp97 & tmp98
tmp100 = tmp95 | tmp99
tl.where(tmp100, tmp84, tmp89)
tmp102 = tl.where(tmp100, tmp85, tmp41)
tl.store(out_ptr0 + x2, tmp46, xmask)
tl.store(out_ptr1 + x2, tmp102, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y1 = yindex // 4
y0 = yindex % 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y1), xmask & ymask, eviction_policy
='evict_last')
tmp6 = tl.load(in_ptr1 + (x2 + 16 * y3), xmask & ymask)
tmp1 = y0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp7 = tmp5 - tmp6
tmp8 = tmp7 + tmp6
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp8, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_per_fused_add_log_mean_mul_sum_6(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)
tmp7 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp13 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp19 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp1 = 4.0
tmp2 = tmp0 * tmp1
tmp3 = 1e-10
tmp4 = tmp2 + tmp3
tmp5 = tl_math.log(tmp4)
tmp6 = tmp0 * tmp5
tmp8 = tmp7 * tmp1
tmp9 = tmp8 + tmp3
tmp10 = tl_math.log(tmp9)
tmp11 = tmp7 * tmp10
tmp12 = tmp6 + tmp11
tmp14 = tmp13 * tmp1
tmp15 = tmp14 + tmp3
tmp16 = tl_math.log(tmp15)
tmp17 = tmp13 * tmp16
tmp18 = tmp12 + tmp17
tmp20 = tmp19 * tmp1
tmp21 = tmp20 + tmp3
tmp22 = tl_math.log(tmp21)
tmp23 = tmp19 * tmp22
tmp24 = tmp18 + tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.sum(tmp25, 1)[:, None]
tmp28 = 64.0
tmp29 = tmp27 / tmp28
tmp30 = 0.0005
tmp31 = tmp29 * tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp31, None)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf3 = torch.ops.aten.exponential.default(buf2)
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused__softmax_add_log_neg_1[grid(64)](buf1, buf4, buf5,
buf6, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf7 = buf4
del buf4
buf11 = buf2
del buf2
triton_poi_fused__softmax_add_log_neg_2[grid(256)](buf7, buf1, buf5,
buf6, buf11, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.int64)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.int64)
triton_poi_fused_add_argmax_max_scatter_sub_3[grid(64)](buf7, buf8,
buf14, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
triton_poi_fused_clone_4[grid(16, 16)](buf8, buf7, buf9, 16, 16,
XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del buf8
buf10 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf9, (1, 64, 4), (0, 4, 1),
0), reinterpret_tensor(primals_4, (1, 4, 4), (16, 4, 1), 0),
out=buf10)
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_5[grid(256)](buf11, buf12, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf11
buf13 = empty_strided_cuda((), (), torch.float32)
buf15 = buf13
del buf13
triton_per_fused_add_log_mean_mul_sum_6[grid(1)](buf15, buf12, 1,
64, XBLOCK=1, num_warps=2, num_stages=1)
del buf12
return reinterpret_tensor(buf10, (4, 4, 4, 4), (64, 1, 16, 4), 0
), buf15, buf14, primals_1, primals_3, buf1, buf7, reinterpret_tensor(
buf9, (1, 4, 64), (256, 1, 4), 0), reinterpret_tensor(primals_4, (1,
4, 4), (16, 1, 4), 0)
class GumbelQuantizeNew(nn.Module):
"""
Gumbel Softmax trick quantizer
Categorical Reparameterization with Gumbel-Softmax, Jang et al. 2016
https://arxiv.org/abs/1611.01144
"""
def __init__(self, num_hiddens, n_embed, embedding_dim,
straight_through=False):
super().__init__()
self.embedding_dim = embedding_dim
self.n_embed = n_embed
self.straight_through = straight_through
self.temperature = 1.0
self.kld_scale = 0.0005
self.proj = nn.Conv2d(num_hiddens, n_embed, 1)
self.embed = nn.Embedding(n_embed, embedding_dim)
def forward(self, input_0):
primals_1 = self.proj.weight
primals_2 = self.proj.bias
primals_4 = self.embed.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1], output[2]
|
baudm/deep-vector-quantization
|
GumbelQuantize
| false
| 1,547
|
[
"MIT"
] | 0
|
211bda99a6c750c1e65aff082aa865fed8677b8a
|
https://github.com/baudm/deep-vector-quantization/tree/211bda99a6c750c1e65aff082aa865fed8677b8a
|
TwoMLPHead
|
import torch
import torch.utils.data
from torch import nn
from torchvision.transforms import functional as F
import torch.nn.functional as F
class TwoMLPHead(nn.Module):
"""
Heads for FPN for classification
"""
def __init__(self, in_channels, representation_size):
super(TwoMLPHead, self).__init__()
self.fc6 = nn.Linear(in_channels, representation_size)
self.fc7 = nn.Linear(representation_size, representation_size)
def forward(self, x):
x = x.flatten(start_dim=1)
x = F.relu(self.fc6(x))
x = F.relu(self.fc7(x))
return x
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'representation_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
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_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(16)](buf1, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf2)
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16)](buf3,
primals_5, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf3, primals_1, buf1, buf4, primals_4
class TwoMLPHeadNew(nn.Module):
"""
Heads for FPN for classification
"""
def __init__(self, in_channels, representation_size):
super(TwoMLPHeadNew, self).__init__()
self.fc6 = nn.Linear(in_channels, representation_size)
self.fc7 = nn.Linear(representation_size, representation_size)
def forward(self, input_0):
primals_1 = self.fc6.weight
primals_3 = self.fc6.bias
primals_2 = self.fc7.weight
primals_5 = self.fc7.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
billchenxi/vision
|
TwoMLPHead
| false
| 1,548
|
[
"BSD-3-Clause"
] | 0
|
5608b06a6fbc9c84284dad9f07a16df61da10f85
|
https://github.com/billchenxi/vision/tree/5608b06a6fbc9c84284dad9f07a16df61da10f85
|
QNetwork
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
"""
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
input_size = state_size
output_size = action_size
hidden_size = [256, 128, 64, 32]
self.fc1 = nn.Linear(input_size, hidden_size[0])
self.fc2 = nn.Linear(hidden_size[0], hidden_size[1])
self.fc3 = nn.Linear(hidden_size[1], hidden_size[2])
self.fc4 = nn.Linear(hidden_size[2], hidden_size[3])
self.logits = nn.Linear(hidden_size[3], output_size)
def forward(self, state):
x = self.fc1(state)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
x = F.relu(x)
x = self.fc4(x)
x = F.relu(x)
x = self.logits(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (256, 4), (4, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 256), (256, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (64, 128), (128, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (32, 64), (64, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (4, 32), (32, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf0
buf12 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1,
primals_2, buf12, 16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_4, (256, 128), (1, 256), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf11 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf3,
primals_5, buf11, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_6, (128, 64), (1, 128), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf4
buf10 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch
.bool)
triton_poi_fused_relu_threshold_backward_2[grid(4096)](buf5,
primals_7, buf10, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_8, (64, 32), (1, 64), 0), out=buf6)
buf7 = reinterpret_tensor(buf6, (4, 4, 4, 32), (512, 128, 32, 1), 0)
del buf6
buf9 = empty_strided_cuda((4, 4, 4, 32), (512, 128, 32, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(2048)](buf7,
primals_9, buf9, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf7, (64, 32),
(32, 1), 0), reinterpret_tensor(primals_10, (32, 4), (1, 32), 0
), alpha=1, beta=1, out=buf8)
del primals_11
return reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 256), (256, 1), 0
), reinterpret_tensor(buf3, (64, 128), (128, 1), 0
), reinterpret_tensor(buf5, (64, 64), (64, 1), 0), reinterpret_tensor(
buf7, (64, 32), (32, 1), 0
), primals_10, buf9, primals_8, buf10, primals_6, buf11, primals_4, buf12
class QNetworkNew(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
"""
super(QNetworkNew, self).__init__()
self.seed = torch.manual_seed(seed)
input_size = state_size
output_size = action_size
hidden_size = [256, 128, 64, 32]
self.fc1 = nn.Linear(input_size, hidden_size[0])
self.fc2 = nn.Linear(hidden_size[0], hidden_size[1])
self.fc3 = nn.Linear(hidden_size[1], hidden_size[2])
self.fc4 = nn.Linear(hidden_size[2], hidden_size[3])
self.logits = nn.Linear(hidden_size[3], output_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_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_10 = self.logits.weight
primals_11 = self.logits.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]
|
bhattsachin/deep-reinforcement-learning
|
QNetwork
| false
| 1,549
|
[
"MIT"
] | 0
|
4d75b012495009bf156273e170d75caf400fa7aa
|
https://github.com/bhattsachin/deep-reinforcement-learning/tree/4d75b012495009bf156273e170d75caf400fa7aa
|
GlobalpoolFC
|
import torch
from torch import nn
class GlobalpoolFC(nn.Module):
def __init__(self, num_in, num_class):
super(GlobalpoolFC, self).__init__()
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.fc = nn.Linear(num_in, num_class)
def forward(self, x):
rep = self.pool(x)
y = rep.reshape(rep.shape[0], -1)
y = self.fc(y)
return rep, y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_in': 4, 'num_class': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_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)
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, 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 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf1, (4, 4), (4,
1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf2)
del primals_2
del primals_3
return buf1, buf2, reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
class GlobalpoolFCNew(nn.Module):
def __init__(self, num_in, num_class):
super(GlobalpoolFCNew, self).__init__()
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.fc = nn.Linear(num_in, num_class)
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], output[1]
|
blackcow/Fair-AT
|
GlobalpoolFC
| false
| 1,550
|
[
"Apache-2.0"
] | 0
|
62fc269fedd4b63c4b48ae390d494b3832e65fa8
|
https://github.com/blackcow/Fair-AT/tree/62fc269fedd4b63c4b48ae390d494b3832e65fa8
|
FairLoss
|
import torch
from torch import nn
class FairLoss(nn.Module):
def __init__(self, lamda):
super(FairLoss, self).__init__()
self.lamda = lamda
def forward(self, rep):
logits = torch.mm(rep, torch.transpose(rep, 0, 1))
logits = logits - torch.diag_embed(torch.diag(logits))
logits = logits.abs().sum()
return logits * self.lamda
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'lamda': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_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_diag_embed_mul_sub_sum_0(in_out_ptr0, in_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
r0 = rindex % 4
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp4 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
tmp1 = r0
tmp2 = r1
tmp3 = tmp1 == tmp2
tmp5 = 0.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 - tmp6
tmp8 = tl_math.abs(tmp7)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tmp12 = 4.0
tmp13 = tmp11 * tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
0), out=buf0)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_abs_diag_embed_mul_sub_sum_0[grid(1)](buf2, buf0,
1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
return buf2,
class FairLossNew(nn.Module):
def __init__(self, lamda):
super(FairLossNew, self).__init__()
self.lamda = lamda
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
blackcow/Fair-AT
|
FairLoss
| false
| 1,551
|
[
"Apache-2.0"
] | 0
|
62fc269fedd4b63c4b48ae390d494b3832e65fa8
|
https://github.com/blackcow/Fair-AT/tree/62fc269fedd4b63c4b48ae390d494b3832e65fa8
|
MockOpposite
|
import torch
import torch.nn as nn
class MockOpposite(nn.Module):
def __init__(self):
"""Initialize the model"""
super(MockOpposite, self).__init__()
def forward(self, input):
"""A single forward pass of the model. Returns input - 1.
Args:
input: The input to the model as a tensor of
batch_size X input_size
"""
output = input.clone().detach()
output[input == 1] = 0
output[input == 0] = 1
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_index_put_lift_fresh_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 == tmp1
tmp3 = 0.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tmp5 = tmp0 == tmp3
tmp6 = tl.where(tmp5, tmp1, tmp4)
tl.store(in_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, 4), (64, 16, 4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_index_put_lift_fresh_0[grid(256)](buf1, arg0_1,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf1,
class MockOppositeNew(nn.Module):
def __init__(self):
"""Initialize the model"""
super(MockOppositeNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
blagojce95/ai-research-mamo-framework
|
MockOpposite
| false
| 1,552
|
[
"Apache-2.0"
] | 0
|
7f3b5a5a9fb8b19c9eef453b81b03b6046a33bf2
|
https://github.com/blagojce95/ai-research-mamo-framework/tree/7f3b5a5a9fb8b19c9eef453b81b03b6046a33bf2
|
PatchMerging
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
from torch import optim as optim
class PatchMerging(nn.Module):
"""Patch Merging Layer.
Args:
input_resolution (tuple[int]): Resolution of input feature.
dim (int): Number of input channels.
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
"""
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
self.norm = norm_layer(4 * dim)
def forward(self, x):
""" Forward function.
Args:
x: Input feature, tensor size (B, H*W, C).
H, W: Spatial resolution of the input feature.
"""
B, L, C = x.shape
H = int(sqrt(L))
W = H
x = x.view(B, H, W, C)
pad_input = H % 2 == 1 or W % 2 == 1
if pad_input:
x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
x0 = x[:, 0::2, 0::2, :]
x1 = x[:, 1::2, 0::2, :]
x2 = x[:, 0::2, 1::2, :]
x3 = x[:, 1::2, 1::2, :]
x = torch.cat([x0, x1, x2, x3], -1)
x = x.view(B, -1, 4 * C)
x = self.norm(x)
x = self.reduction(x)
return x
def extra_repr(self) ->str:
return f'input_resolution={self.input_resolution}, dim={self.dim}'
def flops(self):
H, W = self.input_resolution
flops = H * W * self.dim
flops += H // 2 * (W // 2) * 4 * self.dim * 2 * self.dim
return flops
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_resolution': 4, '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 torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_cat_native_layer_norm_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr
):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp46 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp48 = tl.load(in_ptr2 + r1, None, eviction_policy='evict_last')
tmp0 = r1
tl.full([1, 1], 0, tl.int64)
tmp3 = tl.full([1, 1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (16 * x0 + r1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1, 1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (8 + 16 * x0 + (-4 + r1)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1, 1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr0 + (4 + 16 * x0 + (-8 + r1)), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1, 1], 16, tl.int64)
tmp19 = tl.load(in_ptr0 + (12 + 16 * x0 + (-12 + r1)), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK, RBLOCK])
tl.where(xmask, tmp23, 0)
tmp26 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp28 = tl.where(xmask, tmp26, 0)
tmp29 = tl.sum(tmp28, 1)[:, None]
tmp30 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp31 = tmp30.to(tl.float32)
tmp32 = tmp29 / tmp31
tmp33 = tmp23 - tmp32
tmp34 = tmp33 * tmp33
tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK])
tmp37 = tl.where(xmask, tmp35, 0)
tmp38 = tl.sum(tmp37, 1)[:, None]
tmp39 = 16.0
tmp40 = tmp38 / tmp39
tmp41 = 1e-05
tmp42 = tmp40 + tmp41
tmp43 = libdevice.rsqrt(tmp42)
tmp44 = tmp22 - tmp32
tmp45 = tmp44 * tmp43
tmp47 = tmp45 * tmp46
tmp49 = tmp47 + tmp48
tl.store(out_ptr0 + (r1 + 16 * x0), tmp22, xmask)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp43, xmask)
tl.store(out_ptr2 + (r1 + 16 * x0), tmp49, xmask)
tl.store(out_ptr1 + x0, tmp32, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (8, 16), (16, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 16), (16, 16, 16, 1), torch.float32
)
buf1 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
buf2 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf4 = reinterpret_tensor(buf2, (4, 1, 1), (1, 1, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 1, 16), (16, 16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_cat_native_layer_norm_0[grid(4)](buf4, primals_1,
primals_2, primals_3, buf0, buf1, buf5, 4, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del primals_1
del primals_2
del primals_3
buf6 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (4, 16), (16, 1), 0),
reinterpret_tensor(primals_4, (16, 8), (1, 16), 0), out=buf6)
return reinterpret_tensor(buf6, (4, 1, 8), (8, 8, 1), 0
), buf0, buf1, buf4, reinterpret_tensor(buf5, (4, 16), (16, 1), 0
), primals_4
class PatchMergingNew(nn.Module):
"""Patch Merging Layer.
Args:
input_resolution (tuple[int]): Resolution of input feature.
dim (int): Number of input channels.
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
"""
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
self.norm = norm_layer(4 * dim)
def extra_repr(self) ->str:
return f'input_resolution={self.input_resolution}, dim={self.dim}'
def flops(self):
H, W = self.input_resolution
flops = H * W * self.dim
flops += H // 2 * (W // 2) * 4 * self.dim * 2 * self.dim
return flops
def forward(self, input_0):
primals_4 = self.reduction.weight
primals_2 = self.norm.weight
primals_3 = self.norm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
billpsomas/ibot
|
PatchMerging
| false
| 1,553
|
[
"Apache-2.0"
] | 0
|
c6fbce7e2a59780f39ad7304ed9a8b1acf038d2d
|
https://github.com/billpsomas/ibot/tree/c6fbce7e2a59780f39ad7304ed9a8b1acf038d2d
|
MyModel
|
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
def forward(self, x):
return x + 1
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class MyModelNew(nn.Module):
def __init__(self):
super(MyModelNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
blagojce95/ai-research-mamo-framework
|
MyModel
| false
| 1,554
|
[
"Apache-2.0"
] | 0
|
7f3b5a5a9fb8b19c9eef453b81b03b6046a33bf2
|
https://github.com/blagojce95/ai-research-mamo-framework/tree/7f3b5a5a9fb8b19c9eef453b81b03b6046a33bf2
|
GreedyTop1
|
import torch
from typing import Optional
import torch as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
class GreedyTop1(pt.nn.Module):
"""
Implements picking the highest scoring next word with support for vocabulary selection and target factors.
"""
def forward(self, scores: 'pt.Tensor', vocab_slice_ids:
'Optional[pt.Tensor]'=None, target_factors: 'Optional[pt.Tensor]'=None
) ->pt.Tensor:
best_word_index = pt.argmin(scores, dim=-1, keepdim=True)
if vocab_slice_ids is not None:
best_word_index = vocab_slice_ids.index_select(0,
best_word_index.squeeze(1)).unsqueeze(1)
if target_factors is not None:
factor_index = target_factors[:, :, 1].int()
best_word_index = pt.cat((best_word_index, factor_index), dim=1)
return best_word_index
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 as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
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_argmin_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')
tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp32 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 < tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = tl.full([1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 < tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 < tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tl.store(out_ptr0 + x0, tmp46, 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.int64)
get_raw_stream(0)
triton_poi_fused_argmin_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class GreedyTop1New(pt.nn.Module):
"""
Implements picking the highest scoring next word with support for vocabulary selection and target factors.
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
blchu/sockeye
|
GreedyTop1
| false
| 1,555
|
[
"Apache-2.0"
] | 0
|
28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
https://github.com/blchu/sockeye/tree/28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
PyTorchLHUC
|
import torch
import torch as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
class PyTorchLHUC(pt.nn.Module):
"""
Learning Hidden Unit Contribution
David Vilar. "Learning Hidden Unit Contribution for Adapting Neural
Machine Translation Models" NAACL 2018
:param num_hidden: Number of hidden units of the layer to be modified.
"""
def __init__(self, num_hidden: 'int') ->None:
super().__init__()
self.weight = pt.nn.Parameter(pt.Tensor(num_hidden))
def forward(self, data: 'pt.Tensor') ->pt.Tensor:
weight = 2 * pt.sigmoid(self.weight)
return weight * data
def weights_from_mxnet_block(self, block_mx: "'LHUC'"):
self.weight.data[:] = pt.as_tensor(block_mx.weight.data().asnumpy())
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_hidden': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
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, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + x2, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp5 = tmp3 * tmp4
tl.store(out_ptr0 + x2, tmp5, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(256)](primals_1, primals_2,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
return buf0, primals_1, primals_2
class PyTorchLHUCNew(pt.nn.Module):
"""
Learning Hidden Unit Contribution
David Vilar. "Learning Hidden Unit Contribution for Adapting Neural
Machine Translation Models" NAACL 2018
:param num_hidden: Number of hidden units of the layer to be modified.
"""
def __init__(self, num_hidden: 'int') ->None:
super().__init__()
self.weight = pt.nn.Parameter(pt.Tensor(num_hidden))
def weights_from_mxnet_block(self, block_mx: "'LHUC'"):
self.weight.data[:] = pt.as_tensor(block_mx.weight.data().asnumpy())
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
blchu/sockeye
|
PyTorchLHUC
| false
| 1,556
|
[
"Apache-2.0"
] | 0
|
28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
https://github.com/blchu/sockeye/tree/28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
SE
|
import torch
from itertools import chain as chain
import torch.utils.data
import torch.nn as nn
class SwishEfficient(torch.autograd.Function):
"""Swish activation function: x * sigmoid(x)."""
@staticmethod
def forward(ctx, x):
result = x * torch.sigmoid(x)
ctx.save_for_backward(x)
return result
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
sigmoid_x = torch.sigmoid(x)
return grad_output * (sigmoid_x * (1 + x * (1 - sigmoid_x)))
class Swish(nn.Module):
"""Swish activation function: x * sigmoid(x)."""
def __init__(self):
super(Swish, self).__init__()
def forward(self, x):
return SwishEfficient.apply(x)
class SE(nn.Module):
"""Squeeze-and-Excitation (SE) block w/ Swish: AvgPool, FC, Swish, FC, Sigmoid."""
def _round_width(self, width, multiplier, min_width=8, divisor=8):
"""
Round width of filters based on width multiplier
Args:
width (int): the channel dimensions of the input.
multiplier (float): the multiplication factor.
min_width (int): the minimum width after multiplication.
divisor (int): the new width should be dividable by divisor.
"""
if not multiplier:
return width
width *= multiplier
min_width = min_width or divisor
width_out = max(min_width, int(width + divisor / 2) // divisor *
divisor)
if width_out < 0.9 * width:
width_out += divisor
return int(width_out)
def __init__(self, dim_in, ratio, relu_act=True):
"""
Args:
dim_in (int): the channel dimensions of the input.
ratio (float): the channel reduction ratio for squeeze.
relu_act (bool): whether to use ReLU activation instead
of Swish (default).
divisor (int): the new width should be dividable by divisor.
"""
super(SE, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))
dim_fc = self._round_width(dim_in, ratio)
self.fc1 = nn.Conv3d(dim_in, dim_fc, 1, bias=True)
self.fc1_act = nn.ReLU() if relu_act else Swish()
self.fc2 = nn.Conv3d(dim_fc, dim_in, 1, bias=True)
self.fc2_sig = nn.Sigmoid()
def forward(self, x):
x_in = x
for module in self.children():
x = module(x)
return x_in * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'ratio': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from itertools import chain as chain
import torch.utils.data
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 64.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (16, 4, 1, 1, 1), (4, 1, 1, 1, 1))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (4, 16, 1, 1, 1), (16, 1, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(4)](buf1, primals_1, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 1,
1, 1), (0, 1, 0, 0, 0), 0), primals_2, 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(buf2, (1, 16, 1, 1, 1), (16, 1, 1, 1, 1))
buf3 = reinterpret_tensor(buf2, (16, 1, 1, 1), (1, 16, 16, 16), 0)
del buf2
buf7 = empty_strided_cuda((16, 1, 1, 1), (1, 1, 1, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16)](buf3,
primals_3, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf4 = extern_kernels.convolution(reinterpret_tensor(buf3, (1, 16,
1, 1, 1), (0, 1, 0, 0, 0), 0), primals_4, 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(buf4, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(4)](buf5, primals_5, 4, XBLOCK=
4, num_warps=1, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(256)](primals_1, buf5, buf6,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf6, primals_1, primals_2, primals_4, reinterpret_tensor(buf1,
(1, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0), reinterpret_tensor(buf3, (1,
16, 1, 1, 1), (16, 1, 1, 1, 1), 0), buf5, buf7
class SwishEfficient(torch.autograd.Function):
"""Swish activation function: x * sigmoid(x)."""
@staticmethod
def forward(ctx, x):
result = x * torch.sigmoid(x)
ctx.save_for_backward(x)
return result
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
sigmoid_x = torch.sigmoid(x)
return grad_output * (sigmoid_x * (1 + x * (1 - sigmoid_x)))
class Swish(nn.Module):
"""Swish activation function: x * sigmoid(x)."""
def __init__(self):
super(Swish, self).__init__()
def forward(self, x):
return SwishEfficient.apply(x)
class SENew(nn.Module):
"""Squeeze-and-Excitation (SE) block w/ Swish: AvgPool, FC, Swish, FC, Sigmoid."""
def _round_width(self, width, multiplier, min_width=8, divisor=8):
"""
Round width of filters based on width multiplier
Args:
width (int): the channel dimensions of the input.
multiplier (float): the multiplication factor.
min_width (int): the minimum width after multiplication.
divisor (int): the new width should be dividable by divisor.
"""
if not multiplier:
return width
width *= multiplier
min_width = min_width or divisor
width_out = max(min_width, int(width + divisor / 2) // divisor *
divisor)
if width_out < 0.9 * width:
width_out += divisor
return int(width_out)
def __init__(self, dim_in, ratio, relu_act=True):
"""
Args:
dim_in (int): the channel dimensions of the input.
ratio (float): the channel reduction ratio for squeeze.
relu_act (bool): whether to use ReLU activation instead
of Swish (default).
divisor (int): the new width should be dividable by divisor.
"""
super(SENew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))
dim_fc = self._round_width(dim_in, ratio)
self.fc1 = nn.Conv3d(dim_in, dim_fc, 1, bias=True)
self.fc1_act = nn.ReLU() if relu_act else Swish()
self.fc2 = nn.Conv3d(dim_fc, dim_in, 1, bias=True)
self.fc2_sig = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
billcai/SlowFast
|
SE
| false
| 1,557
|
[
"Apache-2.0"
] | 0
|
778888e63351e55861801996b37c7ff9a3746587
|
https://github.com/billcai/SlowFast/tree/778888e63351e55861801996b37c7ff9a3746587
|
SimpleNormLayer
|
import torch
import torch.nn as nn
class SimpleNormLayer(nn.Module):
"""Simple normalization layer that divides the output of a
preceding layer by a specified number
Parameters
----------
normalization_strength: float
The number with which input is normalized/dived by
"""
def __init__(self, normalization_strength):
super(SimpleNormLayer, self).__init__()
self.normalization_strength = normalization_strength
def forward(self, input_features):
"""Computes normalized output
Parameters
----------
input_features: torch.Tensor
Input tensor of featuers of any shape
Returns
-------
normalized_features: torch.Tensor
Normalized input features
"""
return input_features / self.normalization_strength
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'normalization_strength': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_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.25
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SimpleNormLayerNew(nn.Module):
"""Simple normalization layer that divides the output of a
preceding layer by a specified number
Parameters
----------
normalization_strength: float
The number with which input is normalized/dived by
"""
def __init__(self, normalization_strength):
super(SimpleNormLayerNew, self).__init__()
self.normalization_strength = normalization_strength
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bokutotu/cgnet
|
SimpleNormLayer
| false
| 1,558
|
[
"BSD-3-Clause"
] | 0
|
a35170001d969d51548dd01522b1ab93e43741b4
|
https://github.com/bokutotu/cgnet/tree/a35170001d969d51548dd01522b1ab93e43741b4
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self, feature_num):
super(Net, self).__init__()
self.layer_1 = nn.Linear(feature_num, 500)
self.layer_2 = nn.Linear(500, 20)
def forward(self, x):
x = F.relu(self.layer_1(x))
x = self.layer_2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'feature_num': 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_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 32000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 500
x2 = xindex // 2000
x3 = xindex % 2000
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x3 + 2016 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 2048 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 500
x1 = xindex // 500
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 500 * (x1 % 4) + 2016 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (500, 4), (4, 1))
assert_size_stride(primals_2, (500,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (20, 500), (500, 1))
assert_size_stride(primals_5, (20,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 500), (500, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 500), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 500), (8064, 2016, 500, 1),
torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 500), (8192, 2048, 500, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(32000)](buf0,
primals_2, buf1, buf4, 32000, XBLOCK=128, num_warps=4, num_stages=1
)
del primals_2
buf2 = buf0
del buf0
triton_poi_fused_relu_view_1[grid(32000)](buf1, buf2, 32000, XBLOCK
=256, num_warps=4, num_stages=1)
del buf1
buf3 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
extern_kernels.addmm(primals_5, buf2, reinterpret_tensor(primals_4,
(500, 20), (1, 500), 0), alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 20), (320, 80, 20, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, primals_4, buf4
class NetNew(nn.Module):
def __init__(self, feature_num):
super(NetNew, self).__init__()
self.layer_1 = nn.Linear(feature_num, 500)
self.layer_2 = nn.Linear(500, 20)
def forward(self, input_0):
primals_1 = self.layer_1.weight
primals_2 = self.layer_1.bias
primals_4 = self.layer_2.weight
primals_5 = self.layer_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bm2-lab/MDML
|
Net
| false
| 1,559
|
[
"MIT"
] | 0
|
222fb22b2ee53dd3c1a6f2e99a88f71e9635e3a0
|
https://github.com/bm2-lab/MDML/tree/222fb22b2ee53dd3c1a6f2e99a88f71e9635e3a0
|
PyTorchSSRU
|
import torch
from typing import Tuple
from abc import abstractmethod
import torch as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
class AutoregressiveLayer(pt.nn.Module):
@property
@abstractmethod
def num_state_tensors(self) ->int:
""" Number of state tensors returned by the layer """
raise NotImplementedError
@property
@abstractmethod
def needs_mask(self) ->bool:
""" Whether the layer makes use of a mask tensor or not """
raise NotImplementedError
@abstractmethod
def get_state_shape(self, batch_size) ->Tuple:
"""
:param batch_size: current batch size
:return: dimensions of each output state (assuming all of them have the same shape)
"""
raise NotImplementedError
@abstractmethod
def forward(self, inputs: 'pt.Tensor', previous_states: 'pt.Tensor', *args
) ->Tuple:
"""
:param inputs: layer input
:param previous_states: Previous states array or list of arrays
:param args: layer-specific arguments and/or arguments to be ignored
:return: layer output and new states
"""
raise NotImplementedError
class PyTorchSSRU(AutoregressiveLayer):
"""
Simpler Simple Recurrent Unit
Kim et al, "From Research to Production and Back: Ludicrously Fast Neural Machine Translation" WNGT 2019
Variant of an LSTM cell aimed at reducing computational dependency across time steps.
Formally described as:
(1) f[t] = sigmoid(W1[t] * x[t] + b[t])
(2) c[t] = f[t] . c[t-1] + (1 - f[t]) . W2[t] * x[t]
(3) h = ReLU(c[t])
where:
. represents elementwise multiplication;
x[t] is the input at time step t;
f[t] is the output of the forget gate at time step t;
c[t] is the cell state at time step t;
h is the output of the unit.
:param model_size: number of hidden units
:param inference_only: flag used to indicate execution at inference time
"""
def __init__(self, model_size: 'int', inference_only: 'bool') ->None:
super().__init__()
self.model_size = model_size
self.inference_only = inference_only
self.cell_state_transform = (self._inference_cell_state_transform if
inference_only else self._training_cell_state_transform)
self.forget_gate = pt.nn.Linear(in_features=model_size,
out_features=model_size, bias=True)
self.forget_gate_act = pt.nn.Sigmoid()
self.linear = pt.nn.Linear(in_features=model_size, out_features=
model_size, bias=False)
self.relu = pt.nn.ReLU(inplace=False)
@property
def num_state_tensors(self) ->int:
""" Number of state tensors returned by the layer """
return 1
@property
def needs_mask(self) ->bool:
""" Whether the layer makes use of a mask tensor or not """
return False
def get_state_shape(self, batch_size: 'int') ->Tuple:
"""
:param batch_size: current batch size
:return: dimensions of each output state (assuming all of them have the same shape)
"""
return 1, batch_size, self.model_size
@staticmethod
@pt.jit.script_if_tracing
def _training_cell_state_transform(previous_cell_state, weighted_inputs,
forget_rates) ->Tuple[pt.Tensor, pt.Tensor]:
"""Update SSRU cell at training time"""
steps = weighted_inputs.size()[0]
cell_state = previous_cell_state.squeeze(0)
states = []
for t in range(steps):
cell_state = forget_rates[t, :, :] * cell_state + weighted_inputs[
t, :, :]
states.append(cell_state)
states = pt.stack(states, dim=0)
return states, cell_state.unsqueeze(0)
@staticmethod
def _inference_cell_state_transform(previous_cell_state,
weighted_inputs, forget_rates) ->Tuple[pt.Tensor, pt.Tensor]:
"""Update SSRU cell at inference time"""
new_step_state = forget_rates * previous_cell_state + weighted_inputs
return new_step_state, new_step_state
def forward(self, inputs: 'pt.Tensor', previous_states: 'pt.Tensor', **args
) ->Tuple[pt.Tensor, pt.Tensor]:
"""
:param inputs: input data. Shape: (max_length, batch, input_depth).
:param previous_states: previous cell states. Shape: (max_length, batch, input_depth)
:return: cell output and new cell states. Both with shape (max_length, batch, input_depth).
"""
forget_rates = self.forget_gate_act(self.forget_gate(inputs))
weighted_inputs = (1 - forget_rates) * self.linear(inputs)
cell_state, last_step_state = self.cell_state_transform(previous_states
, weighted_inputs, forget_rates)
return self.relu(cell_state), last_step_state
def weights_from_mxnet_block(self, block_mx: "'SSRU'"):
self.forget_gate.weight.data[:] = pt.as_tensor(block_mx.forget_gate
.weight.data().asnumpy())
self.forget_gate.bias.data[:] = pt.as_tensor(block_mx.forget_gate.
bias.data().asnumpy())
self.linear.weight.data[:] = pt.as_tensor(block_mx.linear.weight.
data().asnumpy())
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'model_size': 4, 'inference_only': 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 typing import Tuple
from abc import abstractmethod
import torch as pt
import torch.distributed
import torch.distributed.elastic.multiprocessing.errors
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mul_relu_rsub_sigmoid_threshold_backward_0(in_ptr0,
in_ptr1, in_ptr2, 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)
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp6 = tl.load(in_ptr2 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp4 - tmp1
tmp7 = tmp5 * tmp6
tmp8 = tmp3 + 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, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp10, xmask)
tl.store(out_ptr2 + x0, tmp12, 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, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_mul_relu_rsub_sigmoid_threshold_backward_0[grid
(256)](buf0, primals_5, buf1, buf2, buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf3, buf2, primals_5, reinterpret_tensor(primals_3, (64, 4), (4,
1), 0), buf0, buf1, buf4
class AutoregressiveLayer(pt.nn.Module):
@property
@abstractmethod
def num_state_tensors(self) ->int:
""" Number of state tensors returned by the layer """
raise NotImplementedError
@property
@abstractmethod
def needs_mask(self) ->bool:
""" Whether the layer makes use of a mask tensor or not """
raise NotImplementedError
@abstractmethod
def get_state_shape(self, batch_size) ->Tuple:
"""
:param batch_size: current batch size
:return: dimensions of each output state (assuming all of them have the same shape)
"""
raise NotImplementedError
@abstractmethod
def forward(self, inputs: 'pt.Tensor', previous_states: 'pt.Tensor', *args
) ->Tuple:
"""
:param inputs: layer input
:param previous_states: Previous states array or list of arrays
:param args: layer-specific arguments and/or arguments to be ignored
:return: layer output and new states
"""
raise NotImplementedError
class PyTorchSSRUNew(AutoregressiveLayer):
"""
Simpler Simple Recurrent Unit
Kim et al, "From Research to Production and Back: Ludicrously Fast Neural Machine Translation" WNGT 2019
Variant of an LSTM cell aimed at reducing computational dependency across time steps.
Formally described as:
(1) f[t] = sigmoid(W1[t] * x[t] + b[t])
(2) c[t] = f[t] . c[t-1] + (1 - f[t]) . W2[t] * x[t]
(3) h = ReLU(c[t])
where:
. represents elementwise multiplication;
x[t] is the input at time step t;
f[t] is the output of the forget gate at time step t;
c[t] is the cell state at time step t;
h is the output of the unit.
:param model_size: number of hidden units
:param inference_only: flag used to indicate execution at inference time
"""
def __init__(self, model_size: 'int', inference_only: 'bool') ->None:
super().__init__()
self.model_size = model_size
self.inference_only = inference_only
self.cell_state_transform = (self._inference_cell_state_transform if
inference_only else self._training_cell_state_transform)
self.forget_gate = pt.nn.Linear(in_features=model_size,
out_features=model_size, bias=True)
self.forget_gate_act = pt.nn.Sigmoid()
self.linear = pt.nn.Linear(in_features=model_size, out_features=
model_size, bias=False)
self.relu = pt.nn.ReLU(inplace=False)
@property
def num_state_tensors(self) ->int:
""" Number of state tensors returned by the layer """
return 1
@property
def needs_mask(self) ->bool:
""" Whether the layer makes use of a mask tensor or not """
return False
def get_state_shape(self, batch_size: 'int') ->Tuple:
"""
:param batch_size: current batch size
:return: dimensions of each output state (assuming all of them have the same shape)
"""
return 1, batch_size, self.model_size
@staticmethod
@pt.jit.script_if_tracing
def _training_cell_state_transform(previous_cell_state, weighted_inputs,
forget_rates) ->Tuple[pt.Tensor, pt.Tensor]:
"""Update SSRU cell at training time"""
steps = weighted_inputs.size()[0]
cell_state = previous_cell_state.squeeze(0)
states = []
for t in range(steps):
cell_state = forget_rates[t, :, :] * cell_state + weighted_inputs[
t, :, :]
states.append(cell_state)
states = pt.stack(states, dim=0)
return states, cell_state.unsqueeze(0)
@staticmethod
def _inference_cell_state_transform(previous_cell_state,
weighted_inputs, forget_rates) ->Tuple[pt.Tensor, pt.Tensor]:
"""Update SSRU cell at inference time"""
new_step_state = forget_rates * previous_cell_state + weighted_inputs
return new_step_state, new_step_state
def weights_from_mxnet_block(self, block_mx: "'SSRU'"):
self.forget_gate.weight.data[:] = pt.as_tensor(block_mx.forget_gate
.weight.data().asnumpy())
self.forget_gate.bias.data[:] = pt.as_tensor(block_mx.forget_gate.
bias.data().asnumpy())
self.linear.weight.data[:] = pt.as_tensor(block_mx.linear.weight.
data().asnumpy())
def forward(self, input_0, input_1):
primals_1 = self.forget_gate.weight
primals_2 = self.forget_gate.bias
primals_4 = self.linear.weight
primals_3 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
blchu/sockeye
|
PyTorchSSRU
| false
| 1,560
|
[
"Apache-2.0"
] | 0
|
28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
https://github.com/blchu/sockeye/tree/28044a44ee409c9b3df1711c0b16bdebdd463b2e
|
ShiftedSoftplus
|
import torch
import numpy as np
import torch.nn as nn
class ShiftedSoftplus(nn.Module):
""" Shifted softplus (SSP) activation function
SSP originates from the softplus function:
y = \\ln\\left(1 + e^{-x}\\right)
Schütt et al. (2018) introduced a shifting factor to the function in order
to ensure that SSP(0) = 0 while having infinite order of continuity:
y = \\ln\\left(1 + e^{-x}\\right) - \\ln(2)
SSP allows to obtain smooth potential energy surfaces and second derivatives
that are required for training with forces as well as the calculation of
vibrational modes (Schütt et al. 2018).
References
----------
K.T. Schütt. P.-J. Kindermans, H. E. Sauceda, S. Chmiela,
A. Tkatchenko, K.-R. Müller. (2018)
SchNet - a deep learning architecture for molecules and materials.
The Journal of Chemical Physics.
https://doi.org/10.1063/1.5019779
"""
def __init__(self):
super(ShiftedSoftplus, self).__init__()
def forward(self, input_tensor):
""" Applies the shifted softplus function element-wise
Parameters
----------
input_tensor: torch.Tensor
Input tensor of size (n_examples, *) where `*` means, any number of
additional dimensions.
Returns
-------
Output: torch.Tensor
Same size (n_examples, *) as the input.
"""
return nn.functional.softplus(input_tensor) - np.log(2.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.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_log_softplus_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 20.0
tmp2 = tmp0 > tmp1
tmp3 = tl_math.exp(tmp0)
tmp4 = libdevice.log1p(tmp3)
tmp5 = tl.where(tmp2, tmp0, tmp4)
tmp6 = 0.6931471805599453
tmp7 = tmp5 - tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_log_softplus_sub_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ShiftedSoftplusNew(nn.Module):
""" Shifted softplus (SSP) activation function
SSP originates from the softplus function:
y = \\ln\\left(1 + e^{-x}\\right)
Schütt et al. (2018) introduced a shifting factor to the function in order
to ensure that SSP(0) = 0 while having infinite order of continuity:
y = \\ln\\left(1 + e^{-x}\\right) - \\ln(2)
SSP allows to obtain smooth potential energy surfaces and second derivatives
that are required for training with forces as well as the calculation of
vibrational modes (Schütt et al. 2018).
References
----------
K.T. Schütt. P.-J. Kindermans, H. E. Sauceda, S. Chmiela,
A. Tkatchenko, K.-R. Müller. (2018)
SchNet - a deep learning architecture for molecules and materials.
The Journal of Chemical Physics.
https://doi.org/10.1063/1.5019779
"""
def __init__(self):
super(ShiftedSoftplusNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bokutotu/cgnet
|
ShiftedSoftplus
| false
| 1,561
|
[
"BSD-3-Clause"
] | 0
|
a35170001d969d51548dd01522b1ab93e43741b4
|
https://github.com/bokutotu/cgnet/tree/a35170001d969d51548dd01522b1ab93e43741b4
|
PatchEmbed
|
import torch
from itertools import chain as chain
import torch.utils.data
import torch.nn as nn
class PatchEmbed(nn.Module):
"""
PatchEmbed.
"""
def __init__(self, dim_in=3, dim_out=768, kernel=(1, 16, 16), stride=(1,
4, 4), padding=(1, 7, 7), conv_2d=False):
super().__init__()
if conv_2d:
conv = nn.Conv2d
else:
conv = nn.Conv3d
self.proj = conv(dim_in, dim_out, kernel_size=kernel, stride=stride,
padding=padding)
def forward(self, x):
x = self.proj(x)
return x.flatten(2).transpose(1, 2)
def get_inputs():
return [torch.rand([4, 3, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from itertools import chain as chain
import torch.utils.data
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_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16896 % 768
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (768, 3, 1, 16, 16), (768, 256, 256, 16, 1))
assert_size_stride(primals_2, (768,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64, 64), (786432, 262144, 4096,
64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
4, 4), padding=(1, 7, 7), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 768, 66, 16, 16), (12976128, 16896,
256, 16, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(51904512)](buf1, primals_2,
51904512, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 16896, 768), (12976128, 1, 16896), 0
), primals_1, primals_3
class PatchEmbedNew(nn.Module):
"""
PatchEmbed.
"""
def __init__(self, dim_in=3, dim_out=768, kernel=(1, 16, 16), stride=(1,
4, 4), padding=(1, 7, 7), conv_2d=False):
super().__init__()
if conv_2d:
conv = nn.Conv2d
else:
conv = nn.Conv3d
self.proj = conv(dim_in, dim_out, kernel_size=kernel, stride=stride,
padding=padding)
def forward(self, input_0):
primals_1 = self.proj.weight
primals_2 = self.proj.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
billcai/SlowFast
|
PatchEmbed
| false
| 1,562
|
[
"Apache-2.0"
] | 0
|
778888e63351e55861801996b37c7ff9a3746587
|
https://github.com/billcai/SlowFast/tree/778888e63351e55861801996b37c7ff9a3746587
|
NeighborNormLayer
|
import torch
import torch.nn as nn
class NeighborNormLayer(nn.Module):
"""Normalization layer that divides the output of a
preceding layer by the number of neighbor features.
Unlike the SimpleNormLayer, this layer allows for
dynamically changing number of neighbors during training.
"""
def __init__(self):
super(NeighborNormLayer, self).__init__()
def forward(self, input_features, n_neighbors):
"""Computes normalized output
Parameters
----------
input_features: torch.Tensor
Input tensor of featuers of shape
(n_frames, n_beads, n_feats)
n_neighbors: int
the number of neighbors
Returns
-------
normalized_features: torch.Tensor
Normalized input features
"""
return input_features / n_neighbors
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_poi_fused_div_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 / tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class NeighborNormLayerNew(nn.Module):
"""Normalization layer that divides the output of a
preceding layer by the number of neighbor features.
Unlike the SimpleNormLayer, this layer allows for
dynamically changing number of neighbors during training.
"""
def __init__(self):
super(NeighborNormLayerNew, 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]
|
bokutotu/cgnet
|
NeighborNormLayer
| false
| 1,563
|
[
"BSD-3-Clause"
] | 0
|
a35170001d969d51548dd01522b1ab93e43741b4
|
https://github.com/bokutotu/cgnet/tree/a35170001d969d51548dd01522b1ab93e43741b4
|
MultiheadSimilarity
|
import torch
import torch.utils.data
from torch import nn
class MultiheadSimilarity(nn.Module):
def __init__(self, d_model, num_head, seq_len, in_proj=True):
super().__init__()
self.num_head = num_head
self.seq_len = seq_len
self.d_head = d_model // num_head
self.in_proj = in_proj
if self.in_proj:
self.q_in_proj = nn.Linear(d_model, seq_len * d_model, bias=True)
self.q_proj = nn.Linear(d_model, d_model, bias=True)
self.k_proj = nn.Linear(d_model, d_model, bias=True)
self.v_proj = nn.Linear(d_model, d_model, bias=True)
self.out_proj = nn.Linear(seq_len * d_model, d_model, bias=True)
def forward(self, q, kv):
bs, d_model = q.shape
nbs = bs * self.num_head
if self.in_proj:
q_ = self.q_in_proj(q)
q_ = q_.contiguous().view(bs, self.seq_len, d_model).transpose(0, 1
)
kv = q_ + kv
q = self.q_proj(q)
q = q.contiguous().view(nbs, self.d_head).unsqueeze(-1)
k = self.k_proj(kv)
k = k.contiguous().view(self.seq_len, nbs, self.d_head).transpose(0, 1)
similarity = torch.bmm(k, q) * float(self.d_head) ** -0.5
v = self.v_proj(kv)
v = v.contiguous().view(self.seq_len, nbs, self.d_head).transpose(0, 1)
v = (v * similarity).view(bs, self.num_head, self.seq_len, self.d_head)
output = self.out_proj(v.flatten(1))
return output
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 1])]
def get_init_inputs():
return [[], {'d_model': 4, 'num_head': 4, 'seq_len': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_clone_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex // 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + x4, tmp4, 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)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, in_ptr1, in_ptr2, 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
y3 = yindex
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (y3 + 16 * x2), xmask & ymask, eviction_policy
='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = 1.0
tmp5 = tmp3 * tmp4
tmp6 = tmp2 * tmp5
tl.store(out_ptr0 + (x2 + 4 * y3), tmp6, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (16, 4), (4, 1))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 16),
(1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_1, reinterpret_tensor(
primals_5, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_5
del primals_6
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_clone_0[grid(64)](buf0, primals_3, primals_4,
buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
del primals_4
buf3 = reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
del buf0
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0)
del buf3
triton_poi_fused_add_1[grid(64)](buf4, primals_8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 4, 1), (1, 16, 0),
0), reinterpret_tensor(buf1, (16, 1, 1), (1, 1, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(16, 4)](buf6, primals_10, buf5, buf7,
16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_12, reinterpret_tensor(buf7, (4, 16),
(16, 1), 0), reinterpret_tensor(primals_11, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf8)
del primals_12
return buf8, primals_1, primals_10, reinterpret_tensor(buf2, (16, 4), (
4, 1), 0), buf5, buf6, reinterpret_tensor(buf7, (4, 16), (16, 1), 0
), primals_11, primals_9, reinterpret_tensor(buf4, (16, 1, 4), (1,
1, 16), 0), reinterpret_tensor(buf1, (16, 1, 1), (1, 1, 1), 0
), primals_7
class MultiheadSimilarityNew(nn.Module):
def __init__(self, d_model, num_head, seq_len, in_proj=True):
super().__init__()
self.num_head = num_head
self.seq_len = seq_len
self.d_head = d_model // num_head
self.in_proj = in_proj
if self.in_proj:
self.q_in_proj = nn.Linear(d_model, seq_len * d_model, bias=True)
self.q_proj = nn.Linear(d_model, d_model, bias=True)
self.k_proj = nn.Linear(d_model, d_model, bias=True)
self.v_proj = nn.Linear(d_model, d_model, bias=True)
self.out_proj = nn.Linear(seq_len * d_model, d_model, bias=True)
def forward(self, input_0, input_1):
primals_2 = self.q_in_proj.weight
primals_3 = self.q_in_proj.bias
primals_1 = self.q_proj.weight
primals_6 = self.q_proj.bias
primals_5 = self.k_proj.weight
primals_8 = self.k_proj.bias
primals_7 = self.v_proj.weight
primals_10 = self.v_proj.bias
primals_11 = self.out_proj.weight
primals_12 = self.out_proj.bias
primals_9 = input_0
primals_4 = 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]
|
bladewaltz1/clipvid-tmp
|
MultiheadSimilarity
| false
| 1,564
|
[
"MIT"
] | 0
|
8a4a990c318fdfbf6dac443abd3bc16637abba3d
|
https://github.com/bladewaltz1/clipvid-tmp/tree/8a4a990c318fdfbf6dac443abd3bc16637abba3d
|
ResidualBlock
|
import torch
from torch import nn
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels, self.out_channels = in_channels, out_channels
self.blocks = nn.Identity()
self.shortcut = nn.Identity()
self.should_apply_shortcut = self.in_channels != self.out_channels
def forward(self, x):
if self.should_apply_shortcut:
residual = self.shortcut(x)
else:
residual = x
x = self.blocks(x)
x += residual
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_add_0(in_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 = tmp0 + tmp0
tl.store(out_ptr1 + x0, tmp1, 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)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](arg0_1, arg0_1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return arg0_1,
class ResidualBlockNew(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels, self.out_channels = in_channels, out_channels
self.blocks = nn.Identity()
self.shortcut = nn.Identity()
self.should_apply_shortcut = self.in_channels != self.out_channels
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
boxiXia/pytorch_sac
|
ResidualBlock
| false
| 1,565
|
[
"MIT"
] | 0
|
ad570845c482498769217b398c22fafaff2ff2f1
|
https://github.com/boxiXia/pytorch_sac/tree/ad570845c482498769217b398c22fafaff2ff2f1
|
ChannelAttention
|
import torch
import torch.nn as nn
class ChannelAttention(nn.Module):
def __init__(self, in_planes=96, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)
self.relu1 = nn.ReLU()
self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))
max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))
out = avg_out + max_out
out = self.sigmoid(out)
return x * out
def get_inputs():
return [torch.rand([4, 96, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 384
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 96
x1 = xindex // 96
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.store(out_ptr0 + (x0 + 96 * r2 + 1536 * x1), tmp0, xmask)
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 24
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
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_adaptive_max_pool2d_2(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 96
x1 = xindex // 96
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 1536 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (96 + x0 + 1536 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (192 + x0 + 1536 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (288 + x0 + 1536 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (384 + x0 + 1536 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (480 + x0 + 1536 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (576 + x0 + 1536 * x1), xmask)
tmp13 = tl.load(in_ptr0 + (672 + x0 + 1536 * x1), xmask)
tmp15 = tl.load(in_ptr0 + (768 + x0 + 1536 * x1), xmask)
tmp17 = tl.load(in_ptr0 + (864 + x0 + 1536 * x1), xmask)
tmp19 = tl.load(in_ptr0 + (960 + x0 + 1536 * x1), xmask)
tmp21 = tl.load(in_ptr0 + (1056 + x0 + 1536 * x1), xmask)
tmp23 = tl.load(in_ptr0 + (1152 + x0 + 1536 * x1), xmask)
tmp25 = tl.load(in_ptr0 + (1248 + x0 + 1536 * x1), xmask)
tmp27 = tl.load(in_ptr0 + (1344 + x0 + 1536 * x1), xmask)
tmp29 = tl.load(in_ptr0 + (1440 + x0 + 1536 * x1), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tl.store(out_ptr0 + x2, tmp30, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 384
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 96
y1 = yindex // 96
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 96 * x2 + 1536 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y3, ymask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + y3, ymask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.sigmoid(tmp3)
tmp5 = tmp0 * tmp4
tl.store(out_ptr0 + (x2 + 16 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_sigmoid_sigmoid_backward_4(in_out_ptr0, in_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = 1.0
tmp5 = tmp4 - tmp3
tmp6 = tmp3 * tmp5
tl.store(in_out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 96, 4, 4), (1536, 16, 4, 1))
assert_size_stride(primals_2, (6, 96, 1, 1), (96, 1, 1, 1))
assert_size_stride(primals_3, (96, 6, 1, 1), (6, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 96, 4, 4), (1536, 1, 384, 96), torch.
float32)
buf1 = empty_strided_cuda((4, 96, 1, 1), (96, 1, 384, 384), torch.
float32)
buf2 = reinterpret_tensor(buf1, (4, 96, 1, 1), (96, 1, 96, 96), 0)
del buf1
get_raw_stream(0)
triton_per_fused_mean_0[grid(384)](buf2, primals_1, buf0, 384, 16,
XBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf3 = extern_kernels.convolution(buf2, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 6, 1, 1), (6, 1, 6, 6))
buf4 = buf3
del buf3
triton_poi_fused_relu_1[grid(24)](buf4, 24, XBLOCK=32, num_warps=1,
num_stages=1)
buf5 = extern_kernels.convolution(buf4, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 96, 1, 1), (96, 1, 96, 96))
buf6 = empty_strided_cuda((4, 96, 1, 1), (96, 1, 96, 96), torch.float32
)
triton_poi_fused_adaptive_max_pool2d_2[grid(384)](buf0, buf6, 384,
XBLOCK=128, num_warps=4, num_stages=1)
buf7 = extern_kernels.convolution(buf6, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 6, 1, 1), (6, 1, 6, 6))
buf8 = buf7
del buf7
triton_poi_fused_relu_1[grid(24)](buf8, 24, XBLOCK=32, num_warps=1,
num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 96, 1, 1), (96, 1, 96, 96))
buf10 = empty_strided_cuda((4, 96, 4, 4), (1536, 16, 4, 1), torch.
float32)
triton_poi_fused_add_mul_sigmoid_3[grid(384, 16)](buf0, buf5, buf9,
buf10, 384, 16, XBLOCK=1, YBLOCK=256, num_warps=4, num_stages=1)
buf11 = buf5
del buf5
triton_poi_fused_add_sigmoid_sigmoid_backward_4[grid(384)](buf11,
buf9, 384, XBLOCK=256, num_warps=4, num_stages=1)
del buf9
return buf10, buf0, primals_2, primals_3, buf2, buf4, buf6, buf8, buf11
class ChannelAttentionNew(nn.Module):
def __init__(self, in_planes=96, ratio=16):
super(ChannelAttentionNew, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)
self.relu1 = nn.ReLU()
self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)
self.sigmoid = nn.Sigmoid()
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]
|
biolee3/SAMDNet
|
ChannelAttention
| false
| 1,566
|
[
"MIT"
] | 0
|
9a0d70f976e22d512046b4aa5727dd26422d0aff
|
https://github.com/biolee3/SAMDNet/tree/9a0d70f976e22d512046b4aa5727dd26422d0aff
|
MiniBatchStddevLayer
|
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.autograd as autograd
import torch.utils.cpp_extension
class AllGatherLayer(autograd.Function):
"""All gather layer with backward propagation path.
Indeed, this module is to make ``dist.all_gather()`` in the backward graph.
Such kind of operation has been widely used in Moco and other contrastive
learning algorithms.
"""
@staticmethod
def forward(ctx, x):
"""Forward function."""
ctx.save_for_backward(x)
output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(output, x)
return tuple(output)
@staticmethod
def backward(ctx, *grad_outputs):
"""Backward function."""
x, = ctx.saved_tensors
grad_out = torch.zeros_like(x)
grad_out = grad_outputs[dist.get_rank()]
return grad_out
class MiniBatchStddevLayer(nn.Module):
"""Minibatch standard deviation.
Args:
group_size (int, optional): The size of groups in batch dimension.
Defaults to 4.
eps (float, optional): Epsilon value to avoid computation error.
Defaults to 1e-8.
gather_all_batch (bool, optional): Whether gather batch from all GPUs.
Defaults to False.
"""
def __init__(self, group_size=4, eps=1e-08, gather_all_batch=False):
super().__init__()
self.group_size = group_size
self.eps = eps
self.gather_all_batch = gather_all_batch
if self.gather_all_batch:
assert torch.distributed.is_initialized(
), 'Only in distributed training can the tensors be all gathered.'
def forward(self, x):
"""Forward function.
Args:
x (Tensor): Input tensor with shape (n, c, h, w).
Returns:
Tensor: Forward results.
"""
if self.gather_all_batch:
x = torch.cat(AllGatherLayer.apply(x), dim=0)
assert x.shape[0] <= self.group_size or x.shape[0
] % self.group_size == 0, f'Batch size be smaller than or equal to group size. Otherwise, batch size should be divisible by the group size.But got batch size {x.shape[0]}, group size {self.group_size}'
n, c, h, w = x.shape
group_size = min(n, self.group_size)
y = torch.reshape(x, (group_size, -1, c, h, w))
y = y - y.mean(dim=0, keepdim=True)
y = y.pow(2).mean(dim=0, keepdim=False)
y = torch.sqrt(y + self.eps)
y = y.mean(dim=(1, 2, 3), keepdim=True)
y = y.repeat(group_size, 1, h, w)
return torch.cat([x, y], dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.distributed as dist
import torch.autograd as autograd
import torch.utils.cpp_extension
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_mean_pow_repeat_sqrt_sub_0(in_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
r1 = rindex % 16
r2 = rindex // 16
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (64 + r0), None)
tmp3 = tl.load(in_ptr0 + (128 + r0), None)
tmp5 = tl.load(in_ptr0 + (192 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-08
tmp22 = tmp20 + tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.sum(tmp24, 1)[:, None]
tmp27 = 64.0
tmp28 = tmp26 / tmp27
tl.store(out_ptr1 + tl.broadcast_to(r1 + 80 * r2, [XBLOCK, RBLOCK]),
tmp28, None)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tl.store(out_ptr0 + (x0 + 80 * x1), tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf3 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32)
buf2 = reinterpret_tensor(buf3, (4, 1, 4, 4), (80, 16, 4, 1), 64)
get_raw_stream(0)
triton_per_fused_add_mean_pow_repeat_sqrt_sub_0[grid(1)](arg0_1,
buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf1 = reinterpret_tensor(buf3, (4, 4, 4, 4), (80, 16, 4, 1), 0)
triton_poi_fused_cat_1[grid(256)](arg0_1, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf3,
class AllGatherLayer(autograd.Function):
"""All gather layer with backward propagation path.
Indeed, this module is to make ``dist.all_gather()`` in the backward graph.
Such kind of operation has been widely used in Moco and other contrastive
learning algorithms.
"""
@staticmethod
def forward(ctx, x):
"""Forward function."""
ctx.save_for_backward(x)
output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(output, x)
return tuple(output)
@staticmethod
def backward(ctx, *grad_outputs):
"""Backward function."""
x, = ctx.saved_tensors
grad_out = torch.zeros_like(x)
grad_out = grad_outputs[dist.get_rank()]
return grad_out
class MiniBatchStddevLayerNew(nn.Module):
"""Minibatch standard deviation.
Args:
group_size (int, optional): The size of groups in batch dimension.
Defaults to 4.
eps (float, optional): Epsilon value to avoid computation error.
Defaults to 1e-8.
gather_all_batch (bool, optional): Whether gather batch from all GPUs.
Defaults to False.
"""
def __init__(self, group_size=4, eps=1e-08, gather_all_batch=False):
super().__init__()
self.group_size = group_size
self.eps = eps
self.gather_all_batch = gather_all_batch
if self.gather_all_batch:
assert torch.distributed.is_initialized(
), 'Only in distributed training can the tensors be all gathered.'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bladesaber/mmgeneration
|
MiniBatchStddevLayer
| false
| 1,567
|
[
"Apache-2.0"
] | 0
|
158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
https://github.com/bladesaber/mmgeneration/tree/158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
SigmoidFocalLoss
|
import torch
import torch.nn as nn
from torch.nn import functional as F
def sigmoid_focal_loss(inputs: 'torch.Tensor', targets: 'torch.Tensor',
alpha: 'float'=-1, gamma: 'float'=2, reduction: 'str'='none'
) ->torch.Tensor:
"""
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
alpha: (optional) Weighting factor in range (0,1) to balance
positive vs negative examples. Default = -1 (no weighting).
gamma: Exponent of the modulating factor (1 - p_t) to
balance easy vs hard examples.
reduction: 'none' | 'mean' | 'sum'
'none': No reduction will be applied to the output.
'mean': The output will be averaged.
'sum': The output will be summed.
Returns:
Loss tensor with the reduction option applied.
"""
p = torch.sigmoid(inputs)
ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction
='none')
p_t = p * targets + (1 - p) * (1 - targets)
loss = ce_loss * (1 - p_t) ** gamma
if alpha >= 0:
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
loss = alpha_t * loss
if reduction == 'mean':
loss = loss.mean()
elif reduction == 'sum':
loss = loss.sum()
return loss
class SigmoidFocalLoss(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, preds, targets):
return sigmoid_focal_loss(preds, targets, self.alpha, self.gamma,
self.reduction)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
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
from torch.nn import functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp8 = tl.load(in_ptr1 + r0, None)
tmp1 = 0.25
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp0
tmp5 = 0.75
tmp6 = tmp4 * tmp5
tmp7 = tmp2 + tmp6
tmp9 = tmp4 * tmp8
tmp10 = 0.0
tmp11 = triton_helpers.minimum(tmp10, tmp8)
tmp12 = tl_math.abs(tmp8)
tmp13 = -tmp12
tmp14 = tl_math.exp(tmp13)
tmp15 = libdevice.log1p(tmp14)
tmp16 = tmp11 - tmp15
tmp17 = tmp9 - tmp16
tmp18 = tl.sigmoid(tmp8)
tmp19 = tmp18 * tmp0
tmp20 = tmp3 - tmp18
tmp21 = tmp20 * tmp4
tmp22 = tmp19 + tmp21
tmp23 = tmp3 - tmp22
tmp24 = tmp23 * tmp23
tmp25 = tmp17 * tmp24
tmp26 = tmp7 * tmp25
tmp27 = tl.broadcast_to(tmp26, [RBLOCK])
tmp29 = triton_helpers.promote_to_tensor(tl.sum(tmp27, 0))
tmp30 = 256.0
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 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0[
grid(1)](buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def sigmoid_focal_loss(inputs: 'torch.Tensor', targets: 'torch.Tensor',
alpha: 'float'=-1, gamma: 'float'=2, reduction: 'str'='none'
) ->torch.Tensor:
"""
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
alpha: (optional) Weighting factor in range (0,1) to balance
positive vs negative examples. Default = -1 (no weighting).
gamma: Exponent of the modulating factor (1 - p_t) to
balance easy vs hard examples.
reduction: 'none' | 'mean' | 'sum'
'none': No reduction will be applied to the output.
'mean': The output will be averaged.
'sum': The output will be summed.
Returns:
Loss tensor with the reduction option applied.
"""
p = torch.sigmoid(inputs)
ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction
='none')
p_t = p * targets + (1 - p) * (1 - targets)
loss = ce_loss * (1 - p_t) ** gamma
if alpha >= 0:
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
loss = alpha_t * loss
if reduction == 'mean':
loss = loss.mean()
elif reduction == 'sum':
loss = loss.sum()
return loss
class SigmoidFocalLossNew(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.alpha = alpha
self.gamma = gamma
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]
|
botkop/lark
|
SigmoidFocalLoss
| false
| 1,568
|
[
"Apache-2.0"
] | 0
|
edb2defdb514213fc121418578b0d9006a55f3a0
|
https://github.com/botkop/lark/tree/edb2defdb514213fc121418578b0d9006a55f3a0
|
LSTM
|
import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self, seq_length, input_dim, num_hidden, num_classes,
batch_size, device='cpu'):
super(LSTM, self).__init__()
self.seq_length = seq_length
self.h_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.c_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.w_gx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_gh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_g = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ix = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_ih = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_i = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_fx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_fh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_f = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ox = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_oh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_o = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ph = nn.Parameter(torch.Tensor(num_classes, num_hidden).
normal_(mean=0, std=0.0001))
self.b_p = nn.Parameter(torch.Tensor(num_classes, 1).zero_())
def forward(self, x):
h_t = self.h_init
c_t = self.c_init
tanh = nn.Tanh()
sigmoid = nn.Sigmoid()
for step in range(self.seq_length):
g_t = tanh(self.w_gx @ x[:, step].t() + self.w_gh @ h_t + self.b_g)
i_t = sigmoid(self.w_ix @ x[:, step].t() + self.w_ih @ h_t +
self.b_i)
f_t = sigmoid(self.w_fx @ x[:, step].t() + self.w_fh @ h_t +
self.b_f)
o_t = sigmoid(self.w_ox @ x[:, step].t() + self.w_oh @ h_t +
self.b_o)
c_t = g_t * i_t + c_t * f_t
h_t = tanh(c_t) * o_t
p_t = self.w_ph @ h_t + self.b_p
return p_t.t()
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'seq_length': 4, 'input_dim': 4, 'num_hidden': 4,
'num_classes': 4, 'batch_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mv_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6,
out_ptr7, out_ptr8, out_ptr9, out_ptr10, out_ptr11, out_ptr12,
out_ptr13, out_ptr14, out_ptr15, 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 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp9 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + 8)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK])
tmp14 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr1 + 12)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK])
tmp19 = tl.load(in_ptr1 + 1)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp22 = tl.load(in_ptr1 + 5)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp26 = tl.load(in_ptr1 + 9)
tmp27 = tl.broadcast_to(tmp26, [XBLOCK])
tmp30 = tl.load(in_ptr1 + 13)
tmp31 = tl.broadcast_to(tmp30, [XBLOCK])
tmp34 = tl.load(in_ptr1 + 2)
tmp35 = tl.broadcast_to(tmp34, [XBLOCK])
tmp37 = tl.load(in_ptr1 + 6)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK])
tmp41 = tl.load(in_ptr1 + 10)
tmp42 = tl.broadcast_to(tmp41, [XBLOCK])
tmp45 = tl.load(in_ptr1 + 14)
tmp46 = tl.broadcast_to(tmp45, [XBLOCK])
tmp49 = tl.load(in_ptr1 + 3)
tmp50 = tl.broadcast_to(tmp49, [XBLOCK])
tmp52 = tl.load(in_ptr1 + 7)
tmp53 = tl.broadcast_to(tmp52, [XBLOCK])
tmp56 = tl.load(in_ptr1 + 11)
tmp57 = tl.broadcast_to(tmp56, [XBLOCK])
tmp60 = tl.load(in_ptr1 + 15)
tmp61 = tl.broadcast_to(tmp60, [XBLOCK])
tmp64 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp66 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp69 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp72 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp96 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last')
tmp98 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp101 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp104 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp128 = tl.load(in_ptr4 + 4 * x0, xmask, eviction_policy='evict_last')
tmp130 = tl.load(in_ptr4 + (1 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp133 = tl.load(in_ptr4 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp136 = tl.load(in_ptr4 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp21 = tmp0 * tmp20
tmp24 = tmp4 * tmp23
tmp25 = tmp21 + tmp24
tmp28 = tmp9 * tmp27
tmp29 = tmp25 + tmp28
tmp32 = tmp14 * tmp31
tmp33 = tmp29 + tmp32
tmp36 = tmp0 * tmp35
tmp39 = tmp4 * tmp38
tmp40 = tmp36 + tmp39
tmp43 = tmp9 * tmp42
tmp44 = tmp40 + tmp43
tmp47 = tmp14 * tmp46
tmp48 = tmp44 + tmp47
tmp51 = tmp0 * tmp50
tmp54 = tmp4 * tmp53
tmp55 = tmp51 + tmp54
tmp58 = tmp9 * tmp57
tmp59 = tmp55 + tmp58
tmp62 = tmp14 * tmp61
tmp63 = tmp59 + tmp62
tmp65 = tmp64 * tmp2
tmp67 = tmp66 * tmp6
tmp68 = tmp65 + tmp67
tmp70 = tmp69 * tmp11
tmp71 = tmp68 + tmp70
tmp73 = tmp72 * tmp16
tmp74 = tmp71 + tmp73
tmp75 = tmp64 * tmp20
tmp76 = tmp66 * tmp23
tmp77 = tmp75 + tmp76
tmp78 = tmp69 * tmp27
tmp79 = tmp77 + tmp78
tmp80 = tmp72 * tmp31
tmp81 = tmp79 + tmp80
tmp82 = tmp64 * tmp35
tmp83 = tmp66 * tmp38
tmp84 = tmp82 + tmp83
tmp85 = tmp69 * tmp42
tmp86 = tmp84 + tmp85
tmp87 = tmp72 * tmp46
tmp88 = tmp86 + tmp87
tmp89 = tmp64 * tmp50
tmp90 = tmp66 * tmp53
tmp91 = tmp89 + tmp90
tmp92 = tmp69 * tmp57
tmp93 = tmp91 + tmp92
tmp94 = tmp72 * tmp61
tmp95 = tmp93 + tmp94
tmp97 = tmp96 * tmp2
tmp99 = tmp98 * tmp6
tmp100 = tmp97 + tmp99
tmp102 = tmp101 * tmp11
tmp103 = tmp100 + tmp102
tmp105 = tmp104 * tmp16
tmp106 = tmp103 + tmp105
tmp107 = tmp96 * tmp20
tmp108 = tmp98 * tmp23
tmp109 = tmp107 + tmp108
tmp110 = tmp101 * tmp27
tmp111 = tmp109 + tmp110
tmp112 = tmp104 * tmp31
tmp113 = tmp111 + tmp112
tmp114 = tmp96 * tmp35
tmp115 = tmp98 * tmp38
tmp116 = tmp114 + tmp115
tmp117 = tmp101 * tmp42
tmp118 = tmp116 + tmp117
tmp119 = tmp104 * tmp46
tmp120 = tmp118 + tmp119
tmp121 = tmp96 * tmp50
tmp122 = tmp98 * tmp53
tmp123 = tmp121 + tmp122
tmp124 = tmp101 * tmp57
tmp125 = tmp123 + tmp124
tmp126 = tmp104 * tmp61
tmp127 = tmp125 + tmp126
tmp129 = tmp128 * tmp2
tmp131 = tmp130 * tmp6
tmp132 = tmp129 + tmp131
tmp134 = tmp133 * tmp11
tmp135 = tmp132 + tmp134
tmp137 = tmp136 * tmp16
tmp138 = tmp135 + tmp137
tmp139 = tmp128 * tmp20
tmp140 = tmp130 * tmp23
tmp141 = tmp139 + tmp140
tmp142 = tmp133 * tmp27
tmp143 = tmp141 + tmp142
tmp144 = tmp136 * tmp31
tmp145 = tmp143 + tmp144
tmp146 = tmp128 * tmp35
tmp147 = tmp130 * tmp38
tmp148 = tmp146 + tmp147
tmp149 = tmp133 * tmp42
tmp150 = tmp148 + tmp149
tmp151 = tmp136 * tmp46
tmp152 = tmp150 + tmp151
tmp153 = tmp128 * tmp50
tmp154 = tmp130 * tmp53
tmp155 = tmp153 + tmp154
tmp156 = tmp133 * tmp57
tmp157 = tmp155 + tmp156
tmp158 = tmp136 * tmp61
tmp159 = tmp157 + tmp158
tl.store(out_ptr0 + x0, tmp18, xmask)
tl.store(out_ptr1 + x0, tmp33, xmask)
tl.store(out_ptr2 + x0, tmp48, xmask)
tl.store(out_ptr3 + x0, tmp63, xmask)
tl.store(out_ptr4 + x0, tmp74, xmask)
tl.store(out_ptr5 + x0, tmp81, xmask)
tl.store(out_ptr6 + x0, tmp88, xmask)
tl.store(out_ptr7 + x0, tmp95, xmask)
tl.store(out_ptr8 + x0, tmp106, xmask)
tl.store(out_ptr9 + x0, tmp113, xmask)
tl.store(out_ptr10 + x0, tmp120, xmask)
tl.store(out_ptr11 + x0, tmp127, xmask)
tl.store(out_ptr12 + x0, tmp138, xmask)
tl.store(out_ptr13 + x0, tmp145, xmask)
tl.store(out_ptr14 + x0, tmp152, xmask)
tl.store(out_ptr15 + x0, tmp159, xmask)
@triton.jit
def triton_poi_fused_add_mul_mv_sigmoid_tanh_1(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10,
in_ptr11, in_ptr12, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr10 + x0, xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr11 + x1, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = tl.sigmoid(tmp10)
tmp12 = tmp5 * tmp11
tmp16 = tmp14 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp20 = tmp13 * tmp19
tmp21 = tmp12 + tmp20
tmp22 = libdevice.tanh(tmp21)
tmp25 = tmp23 + tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.sigmoid(tmp27)
tmp29 = tmp22 * tmp28
tl.store(out_ptr0 + x2, tmp21, xmask)
tl.store(out_ptr1 + x2, tmp29, xmask)
@triton.jit
def triton_poi_fused_add_mul_mv_sigmoid_tanh_2(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8,
in_ptr9, in_ptr10, in_ptr11, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, xmask)
tmp9 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_out_ptr0 + x2, xmask)
tmp14 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr7 + x2, xmask)
tmp17 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr9 + x0, xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr10 + x2, xmask)
tmp26 = tl.load(in_ptr11 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = tl.sigmoid(tmp10)
tmp12 = tmp5 * tmp11
tmp16 = tmp14 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp20 = tmp13 * tmp19
tmp21 = tmp12 + tmp20
tmp22 = libdevice.tanh(tmp21)
tmp25 = tmp23 + tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.sigmoid(tmp27)
tmp29 = tmp22 * tmp28
tl.store(in_out_ptr0 + x2, tmp21, xmask)
tl.store(out_ptr0 + x2, tmp29, xmask)
@triton.jit
def triton_poi_fused_add_mul_mv_sigmoid_tanh_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10,
in_ptr11, in_ptr12, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, xmask)
tmp9 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr6 + x2, xmask)
tmp14 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr8 + x2, xmask)
tmp17 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr10 + x0, xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr11 + x2, xmask)
tmp26 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = tl.sigmoid(tmp10)
tmp12 = tmp5 * tmp11
tmp16 = tmp14 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp20 = tmp13 * tmp19
tmp21 = tmp12 + tmp20
tmp22 = libdevice.tanh(tmp21)
tmp25 = tmp23 + tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.sigmoid(tmp27)
tmp29 = tmp22 * tmp28
tl.store(out_ptr0 + x2, tmp21, xmask)
tl.store(out_ptr1 + x2, tmp29, xmask)
@triton.jit
def triton_poi_fused_add_mul_mv_sigmoid_tanh_4(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8,
in_ptr9, in_ptr10, in_ptr11, in_ptr12, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, xmask)
tmp9 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr6 + x2, xmask)
tmp14 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr8 + x2, xmask)
tmp17 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr10 + x0, xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr11 + x2, xmask)
tmp26 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = tl.sigmoid(tmp10)
tmp12 = tmp5 * tmp11
tmp16 = tmp14 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp20 = tmp13 * tmp19
tmp21 = tmp12 + tmp20
tmp22 = libdevice.tanh(tmp21)
tmp25 = tmp23 + tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.sigmoid(tmp27)
tmp29 = tmp22 * tmp28
tl.store(in_out_ptr0 + x2, tmp22, xmask)
tl.store(out_ptr0 + x2, tmp29, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = args
args.clear()
assert_size_stride(primals_1, (4, 1), (1, 1))
assert_size_stride(primals_2, (4, 1), (1, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 1), (1, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4, 1), (1, 1))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4, 1), (1, 1))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4, 4), (4, 1))
assert_size_stride(primals_15, (4, 1), (1, 1))
assert_size_stride(primals_16, (4, 4), (4, 1))
assert_size_stride(primals_17, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_5, primals_1, out=buf0)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf11 = empty_strided_cuda((4,), (1,), torch.float32)
buf21 = empty_strided_cuda((4,), (1,), torch.float32)
buf31 = empty_strided_cuda((4,), (1,), torch.float32)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
buf13 = empty_strided_cuda((4,), (1,), torch.float32)
buf23 = empty_strided_cuda((4,), (1,), torch.float32)
buf33 = empty_strided_cuda((4,), (1,), torch.float32)
buf5 = empty_strided_cuda((4,), (1,), torch.float32)
buf15 = empty_strided_cuda((4,), (1,), torch.float32)
buf25 = empty_strided_cuda((4,), (1,), torch.float32)
buf35 = empty_strided_cuda((4,), (1,), torch.float32)
buf7 = empty_strided_cuda((4,), (1,), torch.float32)
buf17 = empty_strided_cuda((4,), (1,), torch.float32)
buf27 = empty_strided_cuda((4,), (1,), torch.float32)
buf37 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_mv_0[grid(4)](primals_3, primals_4, primals_7,
primals_10, primals_13, buf1, buf11, buf21, buf31, buf3, buf13,
buf23, buf33, buf5, buf15, buf25, buf35, buf7, buf17, buf27,
buf37, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_8, primals_1, out=buf2)
buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_11, primals_1, out=buf4)
buf6 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_14, primals_1, out=buf6)
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_mv_sigmoid_tanh_1[grid(16)](buf1, buf0,
primals_6, buf3, buf2, primals_9, primals_2, buf5, buf4,
primals_12, buf7, buf6, primals_15, buf8, buf9, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf1
del buf3
del buf5
del buf7
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_5, buf9, out=buf10)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_8, buf9, out=buf12)
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_11, buf9, out=buf14)
buf16 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_14, buf9, out=buf16)
buf18 = buf8
del buf8
buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_mv_sigmoid_tanh_2[grid(16)](buf18, buf11,
buf10, primals_6, buf13, buf12, primals_9, buf15, buf14,
primals_12, buf17, buf16, primals_15, buf19, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf11
del buf13
del buf15
del buf17
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_5, buf19, out=buf20)
buf22 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_8, buf19, out=buf22)
buf24 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_11, buf19, out=buf24)
buf26 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_14, buf19, out=buf26)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_mv_sigmoid_tanh_3[grid(16)](buf21, buf20,
primals_6, buf23, buf22, primals_9, buf18, buf25, buf24,
primals_12, buf27, buf26, primals_15, buf28, buf29, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del buf21
del buf23
del buf25
del buf27
buf30 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_5, buf29, out=buf30)
buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_8, buf29, out=buf32)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_11, buf29, out=buf34)
buf36 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_14, buf29, out=buf36)
buf38 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf39 = buf38
del buf38
buf40 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_mv_sigmoid_tanh_4[grid(16)](buf39, buf31,
buf30, primals_6, buf33, buf32, primals_9, buf28, buf35, buf34,
primals_12, buf37, buf36, primals_15, buf40, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf31
del buf33
del buf35
del buf37
buf41 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_17, primals_16, buf40, alpha=1, beta=1,
out=buf41)
del primals_17
return (reinterpret_tensor(buf41, (4, 4), (1, 4), 0), primals_2,
primals_3, primals_4, primals_6, primals_7, primals_9, primals_10,
primals_12, primals_13, primals_15, buf0, buf2, buf4, buf6, buf10,
buf12, buf14, buf16, buf18, buf20, buf22, buf24, buf26, buf28,
buf30, buf32, buf34, buf36, buf39, reinterpret_tensor(primals_16, (
4, 4), (1, 4), 0), reinterpret_tensor(buf40, (4, 4), (1, 4), 0),
reinterpret_tensor(primals_14, (4, 4), (1, 4), 0),
reinterpret_tensor(buf29, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_11, (4, 4), (1, 4), 0), reinterpret_tensor(primals_8, (4, 4
), (1, 4), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0),
reinterpret_tensor(buf19, (4, 4), (1, 4), 0), reinterpret_tensor(
buf9, (4, 4), (1, 4), 0), reinterpret_tensor(primals_1, (1, 4), (1,
1), 0))
class LSTMNew(nn.Module):
def __init__(self, seq_length, input_dim, num_hidden, num_classes,
batch_size, device='cpu'):
super(LSTMNew, self).__init__()
self.seq_length = seq_length
self.h_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.c_init = nn.Parameter(torch.zeros(num_hidden, 1),
requires_grad=False)
self.w_gx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_gh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_g = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ix = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_ih = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_i = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_fx = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_fh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_f = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ox = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, input_dim).normal_(mean=0, std=0.0001)))
self.w_oh = nn.Parameter(nn.init.orthogonal_(torch.Tensor(
num_hidden, num_hidden).normal_(mean=0, std=0.0001)))
self.b_o = nn.Parameter(torch.Tensor(num_hidden, 1).zero_())
self.w_ph = nn.Parameter(torch.Tensor(num_classes, num_hidden).
normal_(mean=0, std=0.0001))
self.b_p = nn.Parameter(torch.Tensor(num_classes, 1).zero_())
def forward(self, input_0):
primals_1 = self.h_init
primals_2 = self.c_init
primals_3 = self.w_gx
primals_4 = self.w_gh
primals_6 = self.b_g
primals_5 = self.w_ix
primals_7 = self.w_ih
primals_9 = self.b_i
primals_8 = self.w_fx
primals_10 = self.w_fh
primals_12 = self.b_f
primals_11 = self.w_ox
primals_13 = self.w_oh
primals_15 = self.b_o
primals_14 = self.w_ph
primals_17 = self.b_p
primals_16 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17])
return output[0]
|
askliar/deep_learning
|
LSTM
| false
| 1,569
|
[
"MIT"
] | 0
|
e61b2391a3258d18719bf12d9ed1404620ce6c02
|
https://github.com/askliar/deep_learning/tree/e61b2391a3258d18719bf12d9ed1404620ce6c02
|
PatchEmbed
|
import torch
import torch.nn as nn
from torch import optim as optim
class PatchEmbed(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super().__init__()
num_patches = img_size // patch_size * (img_size // patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = num_patches
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size,
stride=patch_size)
def forward(self, x):
_B, _C, _H, _W = x.shape
return self.proj(x)
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
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 % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 2304
xnumel = 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]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 256 * y3), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 768 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 768
y1 = yindex // 768
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 768 * x2 + 12288 * y1), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 16 * y3), tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_2, (768, 3, 16, 16), (768, 256, 16, 1))
assert_size_stride(primals_3, (768,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(12, 4096)](primals_1, buf0, 12, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((768, 3, 16, 16), (768, 1, 48, 3), torch.
float32)
triton_poi_fused_1[grid(2304, 256)](primals_2, buf1, 2304, 256,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf0, buf1, stride=(16, 16),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 768, 4, 4), (12288, 1, 3072, 768))
buf3 = empty_strided_cuda((4, 768, 4, 4), (12288, 16, 4, 1), torch.
float32)
triton_poi_fused_convolution_2[grid(3072, 16)](buf2, primals_3,
buf3, 3072, 16, XBLOCK=16, YBLOCK=32, num_warps=4, num_stages=1)
del buf2
del primals_3
return buf3, buf0, buf1
class PatchEmbedNew(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super().__init__()
num_patches = img_size // patch_size * (img_size // patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = num_patches
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size,
stride=patch_size)
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]
|
billpsomas/ibot
|
PatchEmbed
| false
| 1,570
|
[
"Apache-2.0"
] | 0
|
c6fbce7e2a59780f39ad7304ed9a8b1acf038d2d
|
https://github.com/billpsomas/ibot/tree/c6fbce7e2a59780f39ad7304ed9a8b1acf038d2d
|
FocalLoss
|
import torch
import torch.nn as nn
class FocalLoss(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.bce = nn.BCEWithLogitsLoss(reduction='none')
self.alpha = alpha
self.gamma = gamma
if reduction == 'mean':
self.reduction = torch.mean
else:
self.reduction = torch.sum
def forward(self, preds, targets):
bce_loss = self.bce(preds, targets)
probas = torch.sigmoid(preds)
loss = torch.where(targets >= 0.5, self.alpha * (1.0 - probas) **
self.gamma * bce_loss, probas ** self.gamma * bce_loss)
loss = self.reduction(loss)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
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_binary_cross_entropy_with_logits_ge_mean_mul_pow_rsub_sigmoid_where_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 0.5
tmp2 = tmp0 >= tmp1
tmp4 = tl.sigmoid(tmp3)
tmp5 = 1.0
tmp6 = tmp5 - tmp4
tmp7 = tmp6 * tmp6
tmp8 = 0.25
tmp9 = tmp7 * tmp8
tmp10 = tmp5 - tmp0
tmp11 = tmp10 * tmp3
tmp12 = 0.0
tmp13 = triton_helpers.minimum(tmp12, tmp3)
tmp14 = tl_math.abs(tmp3)
tmp15 = -tmp14
tmp16 = tl_math.exp(tmp15)
tmp17 = libdevice.log1p(tmp16)
tmp18 = tmp13 - tmp17
tmp19 = tmp11 - tmp18
tmp20 = tmp9 * tmp19
tmp21 = tmp4 * tmp4
tmp22 = tmp21 * tmp19
tmp23 = tl.where(tmp2, tmp20, tmp22)
tmp24 = tl.broadcast_to(tmp23, [RBLOCK])
tmp26 = triton_helpers.promote_to_tensor(tl.sum(tmp24, 0))
tmp27 = 256.0
tmp28 = tmp26 / tmp27
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp28, 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_binary_cross_entropy_with_logits_ge_mean_mul_pow_rsub_sigmoid_where_0[
grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class FocalLossNew(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.bce = nn.BCEWithLogitsLoss(reduction='none')
self.alpha = alpha
self.gamma = gamma
if reduction == 'mean':
self.reduction = torch.mean
else:
self.reduction = torch.sum
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
botkop/lark
|
FocalLoss
| false
| 1,571
|
[
"Apache-2.0"
] | 0
|
edb2defdb514213fc121418578b0d9006a55f3a0
|
https://github.com/botkop/lark/tree/edb2defdb514213fc121418578b0d9006a55f3a0
|
SReLU
|
import torch
import torch.nn as nn
class SReLU(nn.Module):
"""Shifted ReLU"""
def __init__(self, nc):
super(SReLU, self).__init__()
self.srelu_bias = nn.Parameter(torch.Tensor(1, nc, 1, 1))
self.srelu_relu = nn.ReLU(inplace=True)
nn.init.constant_(self.srelu_bias, -1.0)
def forward(self, x):
return self.srelu_relu(x - self.srelu_bias) + self.srelu_bias
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nc': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_relu_sub_threshold_backward_0(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = tmp4 + tmp1
tmp6 = 0.0
tmp7 = tmp4 <= tmp6
tl.store(out_ptr0 + x3, tmp5, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_relu_sub_threshold_backward_0[grid(256)](primals_2
, primals_1, buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1
)
del primals_1
del primals_2
return buf0, buf1
class SReLUNew(nn.Module):
"""Shifted ReLU"""
def __init__(self, nc):
super(SReLUNew, self).__init__()
self.srelu_bias = nn.Parameter(torch.Tensor(1, nc, 1, 1))
self.srelu_relu = nn.ReLU(inplace=True)
nn.init.constant_(self.srelu_bias, -1.0)
def forward(self, input_0):
primals_1 = self.srelu_bias
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
bpicnbnk/ISONet
|
SReLU
| false
| 1,572
|
[
"MIT"
] | 0
|
993150fa215dbc92460142ade59a3a5ec4a0efd9
|
https://github.com/bpicnbnk/ISONet/tree/993150fa215dbc92460142ade59a3a5ec4a0efd9
|
AdaptiveInstanceNorm
|
import torch
import torch.nn as nn
from torch.nn.init import _calculate_correct_fan
import torch.utils.cpp_extension
def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in',
lr_mul=1.0):
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul)
return module
class EqualizedLR:
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
"""
def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0
):
self.name = name
self.mode = mode
self.gain = gain
self.lr_mul = lr_mul
def compute_weight(self, module):
"""Compute weight with equalized learning rate.
Args:
module (nn.Module): A module that is wrapped with equalized lr.
Returns:
torch.Tensor: Updated weight.
"""
weight = getattr(module, self.name + '_orig')
if weight.ndim == 5:
fan = _calculate_correct_fan(weight[0], self.mode)
else:
assert weight.ndim <= 4
fan = _calculate_correct_fan(weight, self.mode)
weight = weight * torch.tensor(self.gain, device=weight.device
) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device)
) * self.lr_mul
return weight
def __call__(self, module, inputs):
"""Standard interface for forward pre hooks."""
setattr(module, self.name, self.compute_weight(module))
@staticmethod
def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0):
"""Apply function.
This function is to register an equalized learning rate hook in an
``nn.Module``.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
for _, hook in module._forward_pre_hooks.items():
if isinstance(hook, EqualizedLR):
raise RuntimeError(
f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.'
)
fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul)
weight = module._parameters[name]
delattr(module, name)
module.register_parameter(name + '_orig', weight)
setattr(module, name, weight.data)
module.register_forward_pre_hook(fn)
return fn
class EqualizedLRLinearModule(nn.Linear):
"""Equalized LR LinearModule.
In this module, we adopt equalized lr in ``nn.Linear``. The equalized
learning rate is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Note that, the initialization of ``self.weight`` will be overwritten as
:math:`\\mathcal{N}(0, 1)`.
Args:
equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``.
If ``None``, equalized learning rate is ignored. Defaults to
dict(mode='fan_in').
"""
def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs):
super().__init__(*args, **kwargs)
self.with_equalized_lr = equalized_lr_cfg is not None
if self.with_equalized_lr:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if self.with_equalized_lr:
equalized_lr(self, **equalized_lr_cfg)
self._init_linear_weights()
def _init_linear_weights(self):
"""Initialize linear weights as described in PGGAN."""
nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul)
if self.bias is not None:
nn.init.constant_(self.bias, 0.0)
class AdaptiveInstanceNorm(nn.Module):
"""Adaptive Instance Normalization Module.
Ref: https://github.com/rosinality/style-based-gan-pytorch/blob/master/model.py # noqa
Args:
in_channel (int): The number of input's channel.
style_dim (int): Style latent dimension.
"""
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.affine = EqualizedLRLinearModule(style_dim, in_channel * 2)
self.affine.bias.data[:in_channel] = 1
self.affine.bias.data[in_channel:] = 0
def forward(self, input, style):
"""Forward function.
Args:
input (Tensor): Input tensor with shape (n, c, h, w).
style (Tensor): Input style tensor with shape (n, c).
Returns:
Tensor: Forward results.
"""
style = self.affine(style).unsqueeze(2).unsqueeze(3)
gamma, beta = style.chunk(2, 1)
out = self.norm(input)
out = gamma * out + beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn.init import _calculate_correct_fan
import torch.utils.cpp_extension
assert_size_stride = torch._C._dynamo.guards.assert_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_lift_fresh_mul_sqrt_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 = 1.4142135381698608
tmp2 = tmp0 * tmp1
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = 1.0
tmp6 = tmp4 * tmp5
tl.store(out_ptr0 + x0, tmp6, 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_lift_fresh_mul_sqrt_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 equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in',
lr_mul=1.0):
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul)
return module
class EqualizedLR:
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
"""
def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0
):
self.name = name
self.mode = mode
self.gain = gain
self.lr_mul = lr_mul
def compute_weight(self, module):
"""Compute weight with equalized learning rate.
Args:
module (nn.Module): A module that is wrapped with equalized lr.
Returns:
torch.Tensor: Updated weight.
"""
weight = getattr(module, self.name + '_orig')
if weight.ndim == 5:
fan = _calculate_correct_fan(weight[0], self.mode)
else:
assert weight.ndim <= 4
fan = _calculate_correct_fan(weight, self.mode)
weight = weight * torch.tensor(self.gain, device=weight.device
) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device)
) * self.lr_mul
return weight
def __call__(self, module, inputs):
"""Standard interface for forward pre hooks."""
setattr(module, self.name, self.compute_weight(module))
@staticmethod
def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0):
"""Apply function.
This function is to register an equalized learning rate hook in an
``nn.Module``.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
for _, hook in module._forward_pre_hooks.items():
if isinstance(hook, EqualizedLR):
raise RuntimeError(
f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.'
)
fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul)
weight = module._parameters[name]
delattr(module, name)
module.register_parameter(name + '_orig', weight)
setattr(module, name, weight.data)
module.register_forward_pre_hook(fn)
return fn
class EqualizedLRLinearModule(nn.Linear):
"""Equalized LR LinearModule.
In this module, we adopt equalized lr in ``nn.Linear``. The equalized
learning rate is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Note that, the initialization of ``self.weight`` will be overwritten as
:math:`\\mathcal{N}(0, 1)`.
Args:
equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``.
If ``None``, equalized learning rate is ignored. Defaults to
dict(mode='fan_in').
"""
def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs):
super().__init__(*args, **kwargs)
self.with_equalized_lr = equalized_lr_cfg is not None
if self.with_equalized_lr:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if self.with_equalized_lr:
equalized_lr(self, **equalized_lr_cfg)
self._init_linear_weights()
def _init_linear_weights(self):
"""Initialize linear weights as described in PGGAN."""
nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul)
if self.bias is not None:
nn.init.constant_(self.bias, 0.0)
class AdaptiveInstanceNormNew(nn.Module):
"""Adaptive Instance Normalization Module.
Ref: https://github.com/rosinality/style-based-gan-pytorch/blob/master/model.py # noqa
Args:
in_channel (int): The number of input's channel.
style_dim (int): Style latent dimension.
"""
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.affine = EqualizedLRLinearModule(style_dim, in_channel * 2)
self.affine.bias.data[:in_channel] = 1
self.affine.bias.data[in_channel:] = 0
def forward(self, input_0, input_1):
primals_2 = self.affine.bias
primals_1 = self.affine.weight_orig
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
bladesaber/mmgeneration
|
AdaptiveInstanceNorm
| false
| 1,573
|
[
"Apache-2.0"
] | 0
|
158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
https://github.com/bladesaber/mmgeneration/tree/158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
PANNsLoss
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class PANNsLoss(nn.Module):
def __init__(self):
super().__init__()
@staticmethod
def stabilize_input(cwo):
cwo = torch.where(torch.isnan(cwo), torch.zeros_like(cwo), cwo)
cwo = torch.where(torch.isinf(cwo), torch.zeros_like(cwo), cwo)
cwo = cwo.clamp(0, 1)
return cwo
def forward(self, input, target):
cwo = self.stabilize_input(input)
return F.binary_cross_entropy(cwo, target)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._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_binary_cross_entropy_clamp_isinf_isnan_where_zeros_like_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 - tmp1
tmp4 = libdevice.isnan(tmp3).to(tl.int1)
tmp5 = 0.0
tmp6 = tl.where(tmp4, tmp5, tmp3)
tmp7 = libdevice.isinf(tmp6).to(tl.int1)
tmp8 = tl.where(tmp7, tmp5, tmp6)
tmp9 = triton_helpers.maximum(tmp8, tmp5)
tmp10 = triton_helpers.minimum(tmp9, tmp1)
tmp11 = -tmp10
tmp12 = libdevice.log1p(tmp11)
tmp13 = -100.0
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp2 * tmp14
tmp16 = tl_math.log(tmp10)
tmp17 = triton_helpers.maximum(tmp16, tmp13)
tmp18 = tmp0 * tmp17
tmp19 = tmp15 - tmp18
tmp20 = tl.broadcast_to(tmp19, [RBLOCK])
tmp22 = triton_helpers.promote_to_tensor(tl.sum(tmp20, 0))
tmp23 = 256.0
tmp24 = tmp22 / tmp23
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp24, 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_binary_cross_entropy_clamp_isinf_isnan_where_zeros_like_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 PANNsLossNew(nn.Module):
def __init__(self):
super().__init__()
@staticmethod
def stabilize_input(cwo):
cwo = torch.where(torch.isnan(cwo), torch.zeros_like(cwo), cwo)
cwo = torch.where(torch.isinf(cwo), torch.zeros_like(cwo), cwo)
cwo = cwo.clamp(0, 1)
return cwo
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
botkop/lark
|
PANNsLoss
| false
| 1,574
|
[
"Apache-2.0"
] | 0
|
edb2defdb514213fc121418578b0d9006a55f3a0
|
https://github.com/botkop/lark/tree/edb2defdb514213fc121418578b0d9006a55f3a0
|
SigmoidFocalLossStar
|
import torch
import torch.nn as nn
from torch.nn import functional as F
def sigmoid_focal_loss_star(inputs: 'torch.Tensor', targets: 'torch.Tensor',
alpha: 'float'=-1, gamma: 'float'=1, reduction: 'str'='none'
) ->torch.Tensor:
"""
FL* described in RetinaNet paper Appendix: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
alpha: (optional) Weighting factor in range (0,1) to balance
positive vs negative examples. Default = -1 (no weighting).
gamma: Gamma parameter described in FL*. Default = 1 (no weighting).
reduction: 'none' | 'mean' | 'sum'
'none': No reduction will be applied to the output.
'mean': The output will be averaged.
'sum': The output will be summed.
Returns:
Loss tensor with the reduction option applied.
"""
shifted_inputs = gamma * (inputs * (2 * targets - 1))
loss = -F.logsigmoid(shifted_inputs) / gamma
if alpha >= 0:
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
loss *= alpha_t
if reduction == 'mean':
loss = loss.mean()
elif reduction == 'sum':
loss = loss.sum()
return loss
class SigmoidFocalLossStar(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, preds, targets):
return sigmoid_focal_loss_star(preds, targets, self.alpha, self.
gamma, self.reduction)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
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
from torch.nn import functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_log_sigmoid_forward_mean_mul_neg_rsub_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 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp7 = tmp6 * tmp2
tmp8 = 0.0
tmp9 = triton_helpers.minimum(tmp8, tmp7)
tmp10 = tl_math.abs(tmp7)
tmp11 = -tmp10
tmp12 = tl_math.exp(tmp11)
tmp13 = libdevice.log1p(tmp12)
tmp14 = tmp9 - tmp13
tmp15 = -tmp14
tmp16 = 0.5
tmp17 = tmp15 * tmp16
tmp18 = 0.25
tmp19 = tmp1 * tmp18
tmp20 = tmp4 - tmp1
tmp21 = 0.75
tmp22 = tmp20 * tmp21
tmp23 = tmp19 + tmp22
tmp24 = tmp17 * tmp23
tmp25 = tl.broadcast_to(tmp24, [RBLOCK])
tmp27 = triton_helpers.promote_to_tensor(tl.sum(tmp25, 0))
tmp28 = 256.0
tmp29 = tmp27 / tmp28
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp29, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_log_sigmoid_forward_mean_mul_neg_rsub_sub_0[
grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
def sigmoid_focal_loss_star(inputs: 'torch.Tensor', targets: 'torch.Tensor',
alpha: 'float'=-1, gamma: 'float'=1, reduction: 'str'='none'
) ->torch.Tensor:
"""
FL* described in RetinaNet paper Appendix: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
alpha: (optional) Weighting factor in range (0,1) to balance
positive vs negative examples. Default = -1 (no weighting).
gamma: Gamma parameter described in FL*. Default = 1 (no weighting).
reduction: 'none' | 'mean' | 'sum'
'none': No reduction will be applied to the output.
'mean': The output will be averaged.
'sum': The output will be summed.
Returns:
Loss tensor with the reduction option applied.
"""
shifted_inputs = gamma * (inputs * (2 * targets - 1))
loss = -F.logsigmoid(shifted_inputs) / gamma
if alpha >= 0:
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
loss *= alpha_t
if reduction == 'mean':
loss = loss.mean()
elif reduction == 'sum':
loss = loss.sum()
return loss
class SigmoidFocalLossStarNew(nn.Module):
def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='mean'):
super().__init__()
self.alpha = alpha
self.gamma = gamma
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]
|
botkop/lark
|
SigmoidFocalLossStar
| false
| 1,575
|
[
"Apache-2.0"
] | 0
|
edb2defdb514213fc121418578b0d9006a55f3a0
|
https://github.com/botkop/lark/tree/edb2defdb514213fc121418578b0d9006a55f3a0
|
ModMBStddevLayer
|
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.autograd as autograd
import torch.utils.cpp_extension
class AllGatherLayer(autograd.Function):
"""All gather layer with backward propagation path.
Indeed, this module is to make ``dist.all_gather()`` in the backward graph.
Such kind of operation has been widely used in Moco and other contrastive
learning algorithms.
"""
@staticmethod
def forward(ctx, x):
"""Forward function."""
ctx.save_for_backward(x)
output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(output, x)
return tuple(output)
@staticmethod
def backward(ctx, *grad_outputs):
"""Backward function."""
x, = ctx.saved_tensors
grad_out = torch.zeros_like(x)
grad_out = grad_outputs[dist.get_rank()]
return grad_out
class ModMBStddevLayer(nn.Module):
"""Modified MiniBatch Stddev Layer.
This layer is modified from ``MiniBatchStddevLayer`` used in PGGAN. In
StyleGAN2, the authors add a new feature, `channel_groups`, into this
layer.
Note that to accelerate the training procedure, we also add a new feature
of ``sync_std`` to achieve multi-nodes/machine training. This feature is
still in beta version and we have tested it on 256 scales.
Args:
group_size (int, optional): The size of groups in batch dimension.
Defaults to 4.
channel_groups (int, optional): The size of groups in channel
dimension. Defaults to 1.
sync_std (bool, optional): Whether to use synchronized std feature.
Defaults to False.
sync_groups (int | None, optional): The size of groups in node
dimension. Defaults to None.
eps (float, optional): Epsilon value to avoid computation error.
Defaults to 1e-8.
"""
def __init__(self, group_size=4, channel_groups=1, sync_std=False,
sync_groups=None, eps=1e-08):
super().__init__()
self.group_size = group_size
self.eps = eps
self.channel_groups = channel_groups
self.sync_std = sync_std
self.sync_groups = group_size if sync_groups is None else sync_groups
if self.sync_std:
assert torch.distributed.is_initialized(
), 'Only in distributed training can the sync_std be activated.'
mmcv.print_log('Adopt synced minibatch stddev layer', 'mmgen')
def forward(self, x):
"""Forward function.
Args:
x (Tensor): Input feature map with shape of (N, C, H, W).
Returns:
Tensor: Output feature map with shape of (N, C+1, H, W).
"""
if self.sync_std:
all_features = torch.cat(AllGatherLayer.apply(x), dim=0)
rank, ws = get_dist_info()
local_bs = all_features.shape[0] // ws
start_idx = local_bs * rank
if start_idx + self.sync_groups > all_features.shape[0]:
start_idx = all_features.shape[0] - self.sync_groups
end_idx = min(local_bs * rank + self.sync_groups, all_features.
shape[0])
x = all_features[start_idx:end_idx]
assert x.shape[0] <= self.group_size or x.shape[0
] % self.group_size == 0, f'Batch size be smaller than or equal to group size. Otherwise, batch size should be divisible by the group size.But got batch size {x.shape[0]}, group size {self.group_size}'
assert x.shape[1
] % self.channel_groups == 0, f'"channel_groups" must be divided by the feature channels. channel_groups: {self.channel_groups}, feature channels: {x.shape[1]}'
n, c, h, w = x.shape
group_size = min(n, self.group_size)
y = torch.reshape(x, (group_size, -1, self.channel_groups, c //
self.channel_groups, h, w))
y = torch.var(y, dim=0, unbiased=False)
y = torch.sqrt(y + self.eps)
y = y.mean(dim=(2, 3, 4), keepdim=True).squeeze(2)
y = y.repeat(group_size, 1, h, w)
return torch.cat([x, y], dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.distributed as dist
import torch.autograd as autograd
import torch.utils.cpp_extension
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_mean_repeat_sqrt_var_0(in_ptr0, out_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
r1 = rindex % 16
r2 = rindex // 16
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (64 + r0), None)
tmp3 = tl.load(in_ptr0 + (128 + r0), None)
tmp5 = tl.load(in_ptr0 + (192 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-08
tmp22 = tmp20 + tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.sum(tmp24, 1)[:, None]
tmp27 = 64.0
tmp28 = tmp26 / tmp27
tl.store(out_ptr1 + tl.broadcast_to(r1 + 80 * r2, [XBLOCK, RBLOCK]),
tmp28, None)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tl.store(out_ptr0 + (x0 + 80 * x1), tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf3 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32)
buf2 = reinterpret_tensor(buf3, (4, 1, 4, 4), (80, 16, 4, 1), 64)
get_raw_stream(0)
triton_per_fused_add_mean_repeat_sqrt_var_0[grid(1)](arg0_1, buf2,
1, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf1 = reinterpret_tensor(buf3, (4, 4, 4, 4), (80, 16, 4, 1), 0)
triton_poi_fused_cat_1[grid(256)](arg0_1, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf3,
class AllGatherLayer(autograd.Function):
"""All gather layer with backward propagation path.
Indeed, this module is to make ``dist.all_gather()`` in the backward graph.
Such kind of operation has been widely used in Moco and other contrastive
learning algorithms.
"""
@staticmethod
def forward(ctx, x):
"""Forward function."""
ctx.save_for_backward(x)
output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(output, x)
return tuple(output)
@staticmethod
def backward(ctx, *grad_outputs):
"""Backward function."""
x, = ctx.saved_tensors
grad_out = torch.zeros_like(x)
grad_out = grad_outputs[dist.get_rank()]
return grad_out
class ModMBStddevLayerNew(nn.Module):
"""Modified MiniBatch Stddev Layer.
This layer is modified from ``MiniBatchStddevLayer`` used in PGGAN. In
StyleGAN2, the authors add a new feature, `channel_groups`, into this
layer.
Note that to accelerate the training procedure, we also add a new feature
of ``sync_std`` to achieve multi-nodes/machine training. This feature is
still in beta version and we have tested it on 256 scales.
Args:
group_size (int, optional): The size of groups in batch dimension.
Defaults to 4.
channel_groups (int, optional): The size of groups in channel
dimension. Defaults to 1.
sync_std (bool, optional): Whether to use synchronized std feature.
Defaults to False.
sync_groups (int | None, optional): The size of groups in node
dimension. Defaults to None.
eps (float, optional): Epsilon value to avoid computation error.
Defaults to 1e-8.
"""
def __init__(self, group_size=4, channel_groups=1, sync_std=False,
sync_groups=None, eps=1e-08):
super().__init__()
self.group_size = group_size
self.eps = eps
self.channel_groups = channel_groups
self.sync_std = sync_std
self.sync_groups = group_size if sync_groups is None else sync_groups
if self.sync_std:
assert torch.distributed.is_initialized(
), 'Only in distributed training can the sync_std be activated.'
mmcv.print_log('Adopt synced minibatch stddev layer', 'mmgen')
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bladesaber/mmgeneration
|
ModMBStddevLayer
| false
| 1,576
|
[
"Apache-2.0"
] | 0
|
158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
https://github.com/bladesaber/mmgeneration/tree/158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
CriticArchitecture
|
import torch
import numpy as np
from abc import ABC
import torch.nn.functional as F
from torch import nn
from torch.nn import init
def fan_in_init(tensor):
fan_in = tensor.size(1)
v = 1.0 / np.sqrt(fan_in)
init.uniform_(tensor, -v, v)
class Architecture(nn.Module, ABC):
def __init__(self):
super().__init__()
class CriticArchitecture(Architecture):
def __init__(self, input_size, hidden_layers, output_size,
output_activation):
"""
Initialize a Critic for low dimensional environment.
num_feature: number of features of input.
"""
super().__init__()
self._input_size = input_size
self._hidden_layers = hidden_layers
self._output_size = output_size
self.fc1 = nn.Linear(self._input_size[0], self._hidden_layers[0])
fan_in_init(self.fc1.weight)
self.fc2 = nn.Linear(self._hidden_layers[0] + self._output_size[0],
self._hidden_layers[1])
fan_in_init(self.fc2.weight)
self.head = nn.Linear(self._hidden_layers[1], 1)
init.uniform_(self.head.weight, -0.003, 0.003)
init.uniform_(self.head.bias, -0.003, 0.003)
def forward(self, states, actions):
x = F.relu(self.fc1(states))
x = torch.cat((x, actions), 1)
x = F.relu(self.fc2(x))
x = self.head(x)
return x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_size': [4, 4], 'hidden_layers': [4, 4],
'output_size': [4, 4], 'output_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
import numpy as np
from abc import ABC
from torch import nn
from torch.nn import init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp15 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp12 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.where(tmp4, tmp11, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 8), (8, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (1, 4), (4, 1))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 4),
(1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](buf0, primals_2, primals_4, buf1,
32, XBLOCK=32, num_warps=1, num_stages=1)
del primals_4
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_5, (8, 4), (1, 8
), 0), out=buf2)
buf3 = buf2
del buf2
triton_poi_fused_relu_1[grid(16)](buf3, primals_6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_8, buf3, reinterpret_tensor(primals_7,
(4, 1), (1, 4), 0), alpha=1, beta=1, out=buf5)
del primals_8
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(16)](buf0,
primals_2, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf0
del primals_2
return buf5, primals_3, buf1, buf3, primals_7, primals_5, buf6
def fan_in_init(tensor):
fan_in = tensor.size(1)
v = 1.0 / np.sqrt(fan_in)
init.uniform_(tensor, -v, v)
class Architecture(nn.Module, ABC):
def __init__(self):
super().__init__()
class CriticArchitectureNew(Architecture):
def __init__(self, input_size, hidden_layers, output_size,
output_activation):
"""
Initialize a Critic for low dimensional environment.
num_feature: number of features of input.
"""
super().__init__()
self._input_size = input_size
self._hidden_layers = hidden_layers
self._output_size = output_size
self.fc1 = nn.Linear(self._input_size[0], self._hidden_layers[0])
fan_in_init(self.fc1.weight)
self.fc2 = nn.Linear(self._hidden_layers[0] + self._output_size[0],
self._hidden_layers[1])
fan_in_init(self.fc2.weight)
self.head = nn.Linear(self._hidden_layers[1], 1)
init.uniform_(self.head.weight, -0.003, 0.003)
init.uniform_(self.head.bias, -0.003, 0.003)
def forward(self, input_0, input_1):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_5 = self.fc2.weight
primals_6 = self.fc2.bias
primals_7 = self.head.weight
primals_8 = self.head.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
bootml/agent
|
CriticArchitecture
| false
| 1,577
|
[
"Apache-2.0"
] | 0
|
84235db931d6e4ef956962961c619994898ebdd5
|
https://github.com/bootml/agent/tree/84235db931d6e4ef956962961c619994898ebdd5
|
SelfGating
|
import torch
import torch.utils.data
import torch as th
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
class SelfGating(nn.Module):
def __init__(self, input_dim):
super(SelfGating, self).__init__()
self.fc = nn.Linear(input_dim, input_dim)
def forward(self, input_tensor):
"""Feature gating as used in S3D-G.
"""
spatiotemporal_average = th.mean(input_tensor, dim=[2, 3, 4])
weights = self.fc(spatiotemporal_average)
weights = th.sigmoid(weights)
return weights[:, :, None, None, None] * input_tensor
def get_inputs():
return [torch.rand([4, 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
import torch.utils.data
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 64.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 64, XBLOCK=8,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, buf1, reinterpret_tensor(primals_2,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del primals_2
del primals_3
buf3 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_mul_1[grid(1024)](buf2, primals_1, buf3, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
return buf3, primals_1, buf1, buf2
class SelfGatingNew(nn.Module):
def __init__(self, input_dim):
super(SelfGatingNew, self).__init__()
self.fc = nn.Linear(input_dim, input_dim)
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]
|
bryant1410/MIL-NCE_HowTo100M
|
SelfGating
| false
| 1,578
|
[
"Apache-2.0"
] | 0
|
9ba876bd67160e24a5ce379a07d18a8036be0d36
|
https://github.com/bryant1410/MIL-NCE_HowTo100M/tree/9ba876bd67160e24a5ce379a07d18a8036be0d36
|
LearnedPositionalEmbedding
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class LearnedPositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
Padding ids are ignored by either offsetting based on padding_idx
or by setting padding_idx to None and ensuring that the appropriate
position ids are passed to the forward function.
"""
def __init__(self, num_embeddings: 'int', embedding_dim: 'int',
padding_idx: 'int'):
if padding_idx is not None:
num_embeddings_ = num_embeddings + padding_idx + 1
else:
num_embeddings_ = num_embeddings
super().__init__(num_embeddings_, embedding_dim, padding_idx)
self.max_positions = num_embeddings
def forward(self, input: 'torch.Tensor'):
"""Input is expected to be of size [bsz x seqlen]."""
if input.size(1) > self.max_positions:
raise ValueError(
f'Sequence length {input.size(1)} above maximum sequence length of {self.max_positions}'
)
mask = input.ne(self.padding_idx).int()
positions = (torch.cumsum(mask, dim=1).type_as(mask) * mask).long(
) + self.padding_idx
return F.embedding(positions, self.weight, self.padding_idx, self.
max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_embeddings': 4, 'embedding_dim': 4, 'padding_idx': 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_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused__to_copy_cumsum_ne_0(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = 4.0
tmp2 = tmp0 != tmp1
tmp3 = tmp2.to(tl.int32)
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4.to(tl.int64)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp7, = tl.associative_scan((tmp6,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp7, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_mul_ne_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
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp2 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0.to(tl.int32)
tmp3 = 4.0
tmp4 = tmp2 != tmp3
tmp5 = tmp4.to(tl.int32)
tmp6 = tmp1 * tmp5
tmp7 = tmp6.to(tl.int64)
tmp8 = tl.full([1], 4, tl.int64)
tmp9 = tmp7 + tmp8
tl.store(in_out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_poi_fused_embedding_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 9, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 9) | ~xmask,
'index out of bounds: 0 <= tmp4 < 9')
tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask)
tl.store(out_ptr0 + x2, tmp6, 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, (9, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int64)
get_raw_stream(0)
triton_per_fused__to_copy_cumsum_ne_0[grid(64)](primals_1, buf0, 64,
4, XBLOCK=8, num_warps=2, num_stages=1)
buf1 = buf0
del buf0
triton_poi_fused__to_copy_add_mul_ne_1[grid(256)](buf1, primals_1,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_embedding_2[grid(1024)](buf1, primals_2, buf2,
1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf2, buf1
class LearnedPositionalEmbeddingNew(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
Padding ids are ignored by either offsetting based on padding_idx
or by setting padding_idx to None and ensuring that the appropriate
position ids are passed to the forward function.
"""
def __init__(self, num_embeddings: 'int', embedding_dim: 'int',
padding_idx: 'int'):
if padding_idx is not None:
num_embeddings_ = num_embeddings + padding_idx + 1
else:
num_embeddings_ = num_embeddings
super().__init__(num_embeddings_, embedding_dim, padding_idx)
self.max_positions = num_embeddings
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
boxiangliu/esm
|
LearnedPositionalEmbedding
| false
| 1,579
|
[
"MIT"
] | 0
|
3c143d99103e0ea38a9455f30a73cd9c87376606
|
https://github.com/boxiangliu/esm/tree/3c143d99103e0ea38a9455f30a73cd9c87376606
|
simple_mlp
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class simple_mlp(nn.Module):
def __init__(self, feature_dim, layer, hidden):
super(simple_mlp, self).__init__()
self.layer = layer
self.linear1 = nn.Linear(feature_dim, hidden)
if layer == 2:
self.linear2 = nn.Linear(hidden, hidden)
self.linear3 = nn.Linear(hidden, 1)
def forward(self, x, weights=None):
hidden = F.relu(self.linear1(x))
if self.layer == 2:
hidden = F.relu(self.linear2(hidden))
out = self.linear3(hidden)
return out, hidden
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'feature_dim': 4, 'layer': 1, 'hidden': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 4), (4, 1))
assert_size_stride(primals_5, (1,), (1,))
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_relu_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 1), (16, 4, 1, 1), 0
), buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, primals_4
class simple_mlpNew(nn.Module):
def __init__(self, feature_dim, layer, hidden):
super(simple_mlpNew, self).__init__()
self.layer = layer
self.linear1 = nn.Linear(feature_dim, hidden)
if layer == 2:
self.linear2 = nn.Linear(hidden, hidden)
self.linear3 = nn.Linear(hidden, 1)
def forward(self, input_0):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_4 = self.linear3.weight
primals_5 = self.linear3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
broadinstitute/TCRP
|
simple_mlp
| false
| 1,580
|
[
"MIT"
] | 0
|
9e580dbf0c9d0ec5e5b1a949087df5a3724fa35b
|
https://github.com/broadinstitute/TCRP/tree/9e580dbf0c9d0ec5e5b1a949087df5a3724fa35b
|
MaskedInstanceNorm1d
|
import torch
import torch.cuda
from torch import nn
import torch.distributed
import torch.utils.data
import torch.optim
class MaskedInstanceNorm1d(nn.Module):
"""Instance norm + masking."""
MAX_CNT = 100000.0
def __init__(self, d_channel: 'int', unbiased: 'bool'=True, affine:
'bool'=False):
super().__init__()
self.d_channel = d_channel
self.unbiased = unbiased
self.affine = affine
if self.affine:
gamma = torch.ones(d_channel, dtype=torch.float)
beta = torch.zeros_like(gamma)
self.register_parameter('gamma', nn.Parameter(gamma))
self.register_parameter('beta', nn.Parameter(beta))
def forward(self, x: 'torch.Tensor', x_mask: 'torch.Tensor'
) ->torch.Tensor:
"""`x`: [B,C,T], `x_mask`: [B,T] => [B,C,T]."""
x_mask = x_mask.unsqueeze(1).type_as(x)
cnt = x_mask.sum(dim=-1, keepdim=True)
cnt_for_mu = cnt.clamp(1.0, self.MAX_CNT)
mu = (x * x_mask).sum(dim=-1, keepdim=True) / cnt_for_mu
sigma = (x - mu) ** 2
cnt_fot_sigma = (cnt - int(self.unbiased)).clamp(1.0, self.MAX_CNT)
sigma = (sigma * x_mask).sum(dim=-1, keepdim=True) / cnt_fot_sigma
sigma = (sigma + 1e-08).sqrt()
y = (x - mu) / sigma
if self.affine:
gamma = self.gamma.unsqueeze(0).unsqueeze(-1)
beta = self.beta.unsqueeze(0).unsqueeze(-1)
y = y * gamma + beta
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_channel': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.cuda
from torch import nn
import torch.distributed
import torch.utils.data
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_clamp_div_mul_pow_sqrt_sub_sum_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 % 64
x0 = xindex % 16
x2 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (4 * x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x3), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0 + 64 * x2), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x3), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0 + 64 * x2), xmask, eviction_policy
='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0 + 64 * x2), xmask,
eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tmp15 = tmp1 + tmp4
tmp16 = tmp15 + tmp8
tmp17 = tmp16 + tmp12
tmp18 = 1.0
tmp19 = triton_helpers.maximum(tmp17, tmp18)
tmp20 = 100000.0
tmp21 = triton_helpers.minimum(tmp19, tmp20)
tmp22 = tmp14 / tmp21
tmp23 = tmp0 - tmp22
tmp24 = tmp23 * tmp23
tmp25 = tmp24 * tmp1
tmp26 = tmp3 - tmp22
tmp27 = tmp26 * tmp26
tmp28 = tmp27 * tmp4
tmp29 = tmp25 + tmp28
tmp30 = tmp7 - tmp22
tmp31 = tmp30 * tmp30
tmp32 = tmp31 * tmp8
tmp33 = tmp29 + tmp32
tmp34 = tmp11 - tmp22
tmp35 = tmp34 * tmp34
tmp36 = tmp35 * tmp12
tmp37 = tmp33 + tmp36
tmp38 = tmp17 - tmp18
tmp39 = triton_helpers.maximum(tmp38, tmp18)
tmp40 = triton_helpers.minimum(tmp39, tmp20)
tmp41 = tmp37 / tmp40
tmp42 = 1e-08
tmp43 = tmp41 + tmp42
tmp44 = libdevice.sqrt(tmp43)
tl.store(out_ptr0 + x4, tmp22, xmask)
tl.store(in_out_ptr0 + x4, tmp44, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_sqrt_sub_sum_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 256
x4 = xindex // 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 / tmp3
tl.store(out_ptr0 + x5, tmp4, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 256),
torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 256),
torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_clamp_div_mul_pow_sqrt_sub_sum_0[grid(256)](buf2,
arg1_1, arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_add_clamp_div_sqrt_sub_sum_1[grid(1024)](arg1_1,
buf0, buf2, buf3, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
del buf0
del buf2
return buf3,
class MaskedInstanceNorm1dNew(nn.Module):
"""Instance norm + masking."""
MAX_CNT = 100000.0
def __init__(self, d_channel: 'int', unbiased: 'bool'=True, affine:
'bool'=False):
super().__init__()
self.d_channel = d_channel
self.unbiased = unbiased
self.affine = affine
if self.affine:
gamma = torch.ones(d_channel, dtype=torch.float)
beta = torch.zeros_like(gamma)
self.register_parameter('gamma', nn.Parameter(gamma))
self.register_parameter('beta', nn.Parameter(beta))
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
bugface/NeMo
|
MaskedInstanceNorm1d
| false
| 1,581
|
[
"Apache-2.0"
] | 0
|
431c561380a120e9e164a4c9deed8f1ca9acace5
|
https://github.com/bugface/NeMo/tree/431c561380a120e9e164a4c9deed8f1ca9acace5
|
LayerNorm
|
import torch
from torch import nn
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
out = (x - mean) / (std + self.eps)
out = self.gamma * out + self.beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 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')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp2 - tmp10
tmp13 = tmp12 * tmp12
tmp14 = tmp3 - tmp10
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp10
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp7 - tmp10
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = 3.0
tmp24 = tmp22 / tmp23
tmp25 = libdevice.sqrt(tmp24)
tmp26 = 1e-12
tmp27 = tmp25 + tmp26
tmp28 = tmp11 / tmp27
tmp29 = tmp0 * tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_mul_std_sub_0[grid(256)](primals_2,
primals_1, primals_3, buf0, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_2
del primals_3
return buf0, primals_1
class LayerNormNew(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNormNew, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, input_0):
primals_2 = self.gamma
primals_3 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bsgiovanini/transformer
|
LayerNorm
| false
| 1,582
|
[
"Apache-2.0"
] | 0
|
e128fa862f1b3d17d7b92df169a2bbee3f08366f
|
https://github.com/bsgiovanini/transformer/tree/e128fa862f1b3d17d7b92df169a2bbee3f08366f
|
Actor
|
import torch
import numpy as np
import torch.nn as nn
def fanin_init(size, fanin=None):
fanin = fanin or size[0]
v = 1.0 / np.sqrt(fanin)
return torch.Tensor(size).uniform_(-v, v)
class Actor(nn.Module):
def __init__(self, s_dim, a_dim):
super(Actor, self).__init__()
self.forward1 = nn.Linear(s_dim, 400)
self.Relu = nn.ReLU()
self.forward2 = nn.Linear(400, 300)
self.forward3 = nn.Linear(300, a_dim)
self.tanh = nn.Tanh()
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = fanin_init(m.weight.data.size())
self.forward2.weight.data.uniform_(-0.003, 0.003)
def forward(self, x):
x = self.forward1(x)
x = self.tanh(x)
x = self.forward2(x)
x = self.Relu(x)
x = self.forward3(x)
x = self.tanh(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'s_dim': 4, 'a_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
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 25600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 400
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 300
x2 = xindex // 1200
x3 = xindex % 1200
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x3 + 1216 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 1280 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 300
x1 = xindex // 300
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 300 * (x1 % 4) + 1216 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_tanh_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 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (400, 4), (4, 1))
assert_size_stride(primals_2, (400,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (300, 400), (400, 1))
assert_size_stride(primals_5, (300,), (1,))
assert_size_stride(primals_6, (4, 300), (300, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 400), (6400, 1600, 400, 1), 0
)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(25600)](buf1, primals_2, 25600, XBLOCK
=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 400), (400, 1), 0),
reinterpret_tensor(primals_4, (400, 300), (1, 400), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 300), (4864, 1216, 300, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf2,
primals_5, buf3, buf7, 19200, XBLOCK=256, num_warps=4, num_stages=1
)
del primals_5
buf4 = buf2
del buf2
triton_poi_fused_relu_view_2[grid(19200)](buf3, buf4, 19200, XBLOCK
=256, num_warps=4, num_stages=1)
del buf3
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_6, (300, 4), (1,
300), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused_tanh_3[grid(256)](buf6, primals_7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_7
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf4, buf6, primals_6, buf7, primals_4
def fanin_init(size, fanin=None):
fanin = fanin or size[0]
v = 1.0 / np.sqrt(fanin)
return torch.Tensor(size).uniform_(-v, v)
class ActorNew(nn.Module):
def __init__(self, s_dim, a_dim):
super(ActorNew, self).__init__()
self.forward1 = nn.Linear(s_dim, 400)
self.Relu = nn.ReLU()
self.forward2 = nn.Linear(400, 300)
self.forward3 = nn.Linear(300, a_dim)
self.tanh = nn.Tanh()
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = fanin_init(m.weight.data.size())
self.forward2.weight.data.uniform_(-0.003, 0.003)
def forward(self, input_0):
primals_1 = self.forward1.weight
primals_2 = self.forward1.bias
primals_4 = self.forward2.weight
primals_5 = self.forward2.bias
primals_6 = self.forward3.weight
primals_7 = self.forward3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
brooky56/DeepRL-UR-motion-planning
|
Actor
| false
| 1,583
|
[
"MIT"
] | 0
|
0cc523da6d8a55896773f1f57feed1f0c77fea78
|
https://github.com/brooky56/DeepRL-UR-motion-planning/tree/0cc523da6d8a55896773f1f57feed1f0c77fea78
|
ScaleDotProductAttention
|
import math
import torch
from torch import nn
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.5
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x3, tmp17, 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 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg1_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(arg0_1, (16, 4, 4), (16, 4, 1), 0),
out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf3
)
del arg2_1
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0), buf2
class ScaleDotProductAttentionNew(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttentionNew, self).__init__()
self.softmax = nn.Softmax()
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0], output[1]
|
bsgiovanini/transformer
|
ScaleDotProductAttention
| false
| 1,584
|
[
"Apache-2.0"
] | 0
|
e128fa862f1b3d17d7b92df169a2bbee3f08366f
|
https://github.com/bsgiovanini/transformer/tree/e128fa862f1b3d17d7b92df169a2bbee3f08366f
|
EqualLinearActModule
|
import torch
import torch.nn as nn
from copy import deepcopy
from functools import partial
from torch.nn.init import _calculate_correct_fan
import torch.utils.cpp_extension
def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in',
lr_mul=1.0):
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul)
return module
class EqualizedLR:
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
"""
def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0
):
self.name = name
self.mode = mode
self.gain = gain
self.lr_mul = lr_mul
def compute_weight(self, module):
"""Compute weight with equalized learning rate.
Args:
module (nn.Module): A module that is wrapped with equalized lr.
Returns:
torch.Tensor: Updated weight.
"""
weight = getattr(module, self.name + '_orig')
if weight.ndim == 5:
fan = _calculate_correct_fan(weight[0], self.mode)
else:
assert weight.ndim <= 4
fan = _calculate_correct_fan(weight, self.mode)
weight = weight * torch.tensor(self.gain, device=weight.device
) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device)
) * self.lr_mul
return weight
def __call__(self, module, inputs):
"""Standard interface for forward pre hooks."""
setattr(module, self.name, self.compute_weight(module))
@staticmethod
def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0):
"""Apply function.
This function is to register an equalized learning rate hook in an
``nn.Module``.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
for _, hook in module._forward_pre_hooks.items():
if isinstance(hook, EqualizedLR):
raise RuntimeError(
f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.'
)
fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul)
weight = module._parameters[name]
delattr(module, name)
module.register_parameter(name + '_orig', weight)
setattr(module, name, weight.data)
module.register_forward_pre_hook(fn)
return fn
class EqualizedLRLinearModule(nn.Linear):
"""Equalized LR LinearModule.
In this module, we adopt equalized lr in ``nn.Linear``. The equalized
learning rate is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Note that, the initialization of ``self.weight`` will be overwritten as
:math:`\\mathcal{N}(0, 1)`.
Args:
equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``.
If ``None``, equalized learning rate is ignored. Defaults to
dict(mode='fan_in').
"""
def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs):
super().__init__(*args, **kwargs)
self.with_equalized_lr = equalized_lr_cfg is not None
if self.with_equalized_lr:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if self.with_equalized_lr:
equalized_lr(self, **equalized_lr_cfg)
self._init_linear_weights()
def _init_linear_weights(self):
"""Initialize linear weights as described in PGGAN."""
nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul)
if self.bias is not None:
nn.init.constant_(self.bias, 0.0)
class EqualLinearActModule(nn.Module):
"""Equalized LR Linear Module with Activation Layer.
This module is modified from ``EqualizedLRLinearModule`` defined in PGGAN.
The major features updated in this module is adding support for activation
layers used in StyleGAN2.
Args:
equalized_lr_cfg (dict | None, optional): Config for equalized lr.
Defaults to dict(gain=1., lr_mul=1.).
bias (bool, optional): Whether to use bias item. Defaults to True.
bias_init (float, optional): The value for bias initialization.
Defaults to ``0.``.
act_cfg (dict | None, optional): Config for activation layer.
Defaults to None.
"""
def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0),
bias=True, bias_init=0.0, act_cfg=None, **kwargs):
super().__init__()
self.with_activation = act_cfg is not None
self.linear = EqualizedLRLinearModule(*args, bias=False,
equalized_lr_cfg=equalized_lr_cfg, **kwargs)
if equalized_lr_cfg is not None:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if bias:
self.bias = nn.Parameter(torch.zeros(self.linear.out_features).
fill_(bias_init))
else:
self.bias = None
if self.with_activation:
act_cfg = deepcopy(act_cfg)
if act_cfg['type'] == 'fused_bias':
self.act_type = act_cfg.pop('type')
assert self.bias is not None
self.activate = partial(fused_bias_leakyrelu, **act_cfg)
else:
self.act_type = 'normal'
self.activate = build_activation_layer(act_cfg)
else:
self.act_type = None
def forward(self, x):
"""Forward function.
Args:
x (Tensor): Input feature map with shape of (N, C, ...).
Returns:
Tensor: Output feature map.
"""
if x.ndim >= 3:
x = x.reshape(x.size(0), -1)
x = self.linear(x)
if self.with_activation and self.act_type == 'fused_bias':
x = self.activate(x, self.bias * self.lr_mul)
elif self.bias is not None and self.with_activation:
x = self.activate(x + self.bias * self.lr_mul)
elif self.bias is not None:
x = x + self.bias * self.lr_mul
elif self.with_activation:
x = self.activate(x)
return x
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from copy import deepcopy
from functools import partial
from torch.nn.init import _calculate_correct_fan
import torch.utils.cpp_extension
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_sqrt_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sqrt_0[grid(16)](primals_2, buf0, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, primals_1, reinterpret_tensor(buf0, (4,
4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del buf1
return buf2, buf0, primals_1
def equalized_lr(module, name='weight', gain=2 ** 0.5, mode='fan_in',
lr_mul=1.0):
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
EqualizedLR.apply(module, name, gain=gain, mode=mode, lr_mul=lr_mul)
return module
class EqualizedLR:
"""Equalized Learning Rate.
This trick is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
The general idea is to dynamically rescale the weight in training instead
of in initializing so that the variance of the responses in each layer is
guaranteed with some statistical properties.
Note that this function is always combined with a convolution module which
is initialized with :math:`\\mathcal{N}(0, 1)`.
Args:
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
"""
def __init__(self, name='weight', gain=2 ** 0.5, mode='fan_in', lr_mul=1.0
):
self.name = name
self.mode = mode
self.gain = gain
self.lr_mul = lr_mul
def compute_weight(self, module):
"""Compute weight with equalized learning rate.
Args:
module (nn.Module): A module that is wrapped with equalized lr.
Returns:
torch.Tensor: Updated weight.
"""
weight = getattr(module, self.name + '_orig')
if weight.ndim == 5:
fan = _calculate_correct_fan(weight[0], self.mode)
else:
assert weight.ndim <= 4
fan = _calculate_correct_fan(weight, self.mode)
weight = weight * torch.tensor(self.gain, device=weight.device
) * torch.sqrt(torch.tensor(1.0 / fan, device=weight.device)
) * self.lr_mul
return weight
def __call__(self, module, inputs):
"""Standard interface for forward pre hooks."""
setattr(module, self.name, self.compute_weight(module))
@staticmethod
def apply(module, name, gain=2 ** 0.5, mode='fan_in', lr_mul=1.0):
"""Apply function.
This function is to register an equalized learning rate hook in an
``nn.Module``.
Args:
module (nn.Module): Module to be wrapped.
name (str | optional): The name of weights. Defaults to 'weight'.
mode (str, optional): The mode of computing ``fan`` which is the
same as ``kaiming_init`` in pytorch. You can choose one from
['fan_in', 'fan_out']. Defaults to 'fan_in'.
Returns:
nn.Module: Module that is registered with equalized lr hook.
"""
for _, hook in module._forward_pre_hooks.items():
if isinstance(hook, EqualizedLR):
raise RuntimeError(
f'Cannot register two equalized_lr hooks on the same parameter {name} in {module} module.'
)
fn = EqualizedLR(name, gain=gain, mode=mode, lr_mul=lr_mul)
weight = module._parameters[name]
delattr(module, name)
module.register_parameter(name + '_orig', weight)
setattr(module, name, weight.data)
module.register_forward_pre_hook(fn)
return fn
class EqualizedLRLinearModule(nn.Linear):
"""Equalized LR LinearModule.
In this module, we adopt equalized lr in ``nn.Linear``. The equalized
learning rate is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Note that, the initialization of ``self.weight`` will be overwritten as
:math:`\\mathcal{N}(0, 1)`.
Args:
equalized_lr_cfg (dict | None, optional): Config for ``EqualizedLR``.
If ``None``, equalized learning rate is ignored. Defaults to
dict(mode='fan_in').
"""
def __init__(self, *args, equalized_lr_cfg=dict(mode='fan_in'), **kwargs):
super().__init__(*args, **kwargs)
self.with_equalized_lr = equalized_lr_cfg is not None
if self.with_equalized_lr:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if self.with_equalized_lr:
equalized_lr(self, **equalized_lr_cfg)
self._init_linear_weights()
def _init_linear_weights(self):
"""Initialize linear weights as described in PGGAN."""
nn.init.normal_(self.weight, 0, 1.0 / self.lr_mul)
if self.bias is not None:
nn.init.constant_(self.bias, 0.0)
class EqualLinearActModuleNew(nn.Module):
"""Equalized LR Linear Module with Activation Layer.
This module is modified from ``EqualizedLRLinearModule`` defined in PGGAN.
The major features updated in this module is adding support for activation
layers used in StyleGAN2.
Args:
equalized_lr_cfg (dict | None, optional): Config for equalized lr.
Defaults to dict(gain=1., lr_mul=1.).
bias (bool, optional): Whether to use bias item. Defaults to True.
bias_init (float, optional): The value for bias initialization.
Defaults to ``0.``.
act_cfg (dict | None, optional): Config for activation layer.
Defaults to None.
"""
def __init__(self, *args, equalized_lr_cfg=dict(gain=1.0, lr_mul=1.0),
bias=True, bias_init=0.0, act_cfg=None, **kwargs):
super().__init__()
self.with_activation = act_cfg is not None
self.linear = EqualizedLRLinearModule(*args, bias=False,
equalized_lr_cfg=equalized_lr_cfg, **kwargs)
if equalized_lr_cfg is not None:
self.lr_mul = equalized_lr_cfg.get('lr_mul', 1.0)
else:
self.lr_mul = 1.0
if bias:
self.bias = nn.Parameter(torch.zeros(self.linear.out_features).
fill_(bias_init))
else:
self.bias = None
if self.with_activation:
act_cfg = deepcopy(act_cfg)
if act_cfg['type'] == 'fused_bias':
self.act_type = act_cfg.pop('type')
assert self.bias is not None
self.activate = partial(fused_bias_leakyrelu, **act_cfg)
else:
self.act_type = 'normal'
self.activate = build_activation_layer(act_cfg)
else:
self.act_type = None
def forward(self, input_0):
primals_3 = self.bias
primals_1 = self.linear.weight_orig
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bladesaber/mmgeneration
|
EqualLinearActModule
| false
| 1,585
|
[
"Apache-2.0"
] | 0
|
158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
https://github.com/bladesaber/mmgeneration/tree/158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
NPairLoss
|
import torch
class NPairLoss(torch.nn.Module):
def __init__(self, l2=0.05):
"""
Basic N-Pair Loss as proposed in 'Improved Deep Metric Learning with Multi-class N-pair Loss Objective'
Args:
l2: float, weighting parameter for weight penality due to embeddings not being normalized.
Returns:
Nothing!
"""
super(NPairLoss, self).__init__()
self.l2 = l2
def npair_distance(self, anchor, positive, negatives):
"""
Compute basic N-Pair loss.
Args:
anchor, positive, negative: torch.Tensor(), resp. embeddings for anchor, positive and negative samples.
Returns:
n-pair loss (torch.Tensor())
"""
return torch.log(1 + torch.sum(torch.exp(anchor.reshape(1, -1).mm((
negatives - positive).transpose(0, 1)))))
def weightsum(self, anchor, positive):
"""
Compute weight penalty.
NOTE: Only need to penalize anchor and positive since the negatives are created based on these.
Args:
anchor, positive: torch.Tensor(), resp. embeddings for anchor and positive samples.
Returns:
torch.Tensor(), Weight penalty
"""
return torch.sum(anchor ** 2 + positive ** 2)
def forward(self, batch):
"""
Args:
batch: torch.Tensor() [(BS x embed_dim)], batch of embeddings
Returns:
n-pair loss (torch.Tensor(), batch-averaged)
"""
loss = torch.stack([self.npair_distance(npair[0], npair[1], npair[2
:]) for npair in batch])
loss = loss + self.l2 * torch.mean(torch.stack([self.weightsum(
npair[0], npair[1]) for npair in batch]))
return torch.mean(loss)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
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 + (8 + x2), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_per_fused_exp_sum_1(in_ptr0, out_ptr0, 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)
tmp1 = tl_math.exp(tmp0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp4, None)
@triton.jit
def triton_poi_fused_sub_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
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 + (24 + x2), xmask)
tmp1 = tl.load(in_ptr0 + (20 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_sub_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
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 + (40 + x2), xmask)
tmp1 = tl.load(in_ptr0 + (36 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_sub_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
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 + (56 + x2), xmask)
tmp1 = tl.load(in_ptr0 + (52 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_per_fused_add_pow_stack_sum_5(in_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr0 + (4 + r0), None)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.sum(tmp5, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_add_pow_stack_sum_6(in_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + (16 + r0), None)
tmp2 = tl.load(in_ptr0 + (20 + r0), None)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.sum(tmp5, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_add_pow_stack_sum_7(in_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + (32 + r0), None)
tmp2 = tl.load(in_ptr0 + (36 + r0), None)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.sum(tmp5, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_add_pow_stack_sum_8(in_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + (48 + r0), None)
tmp2 = tl.load(in_ptr0 + (52 + r0), None)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.sum(tmp5, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_add_mean_mul_stack_9(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, 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
tmp5 = tl.load(in_ptr0 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp16 = tl.load(in_ptr1 + 0)
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp26 = tl.load(in_ptr2 + 0)
tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK])
tmp35 = tl.load(in_ptr3 + 0)
tmp36 = tl.broadcast_to(tmp35, [XBLOCK, RBLOCK])
tmp44 = tl.load(in_ptr4 + r0, None)
tmp0 = r0
tl.full([1, 1], 0, tl.int64)
tmp3 = tl.full([1, 1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp7 = 1.0
tmp8 = tmp6 + tmp7
tmp9 = tl_math.log(tmp8)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tmp13 = tl.full([1, 1], 2, tl.int64)
tmp14 = tmp0 < tmp13
tmp15 = tmp12 & tmp14
tmp18 = tmp17 + tmp7
tmp19 = tl_math.log(tmp18)
tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
tmp21 = tl.where(tmp15, tmp19, tmp20)
tmp22 = tmp0 >= tmp13
tmp23 = tl.full([1, 1], 3, tl.int64)
tmp24 = tmp0 < tmp23
tmp25 = tmp22 & tmp24
tmp28 = tmp27 + tmp7
tmp29 = tl_math.log(tmp28)
tmp30 = tl.full(tmp29.shape, 0.0, tmp29.dtype)
tmp31 = tl.where(tmp25, tmp29, tmp30)
tmp32 = tmp0 >= tmp23
tl.full([1, 1], 4, tl.int64)
tmp37 = tmp36 + tmp7
tmp38 = tl_math.log(tmp37)
tmp39 = tl.full(tmp38.shape, 0.0, tmp38.dtype)
tmp40 = tl.where(tmp32, tmp38, tmp39)
tmp41 = tl.where(tmp25, tmp31, tmp40)
tmp42 = tl.where(tmp15, tmp21, tmp41)
tmp43 = tl.where(tmp4, tmp11, tmp42)
tmp45 = tl.broadcast_to(tmp44, [XBLOCK, RBLOCK])
tmp47 = tl.sum(tmp45, 1)[:, None]
tmp48 = 4.0
tmp49 = tmp47 / tmp48
tmp50 = 0.05
tmp51 = tmp49 * tmp50
tmp52 = tmp43 + tmp51
tmp53 = tl.broadcast_to(tmp52, [XBLOCK, RBLOCK])
tmp55 = tl.sum(tmp53, 1)[:, None]
tmp56 = tmp55 / tmp48
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp56, None)
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((2, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sub_0[grid(8)](arg0_1, buf0, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((1, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(arg0_1, (1, 4), (4, 1), 0),
reinterpret_tensor(buf0, (4, 2), (1, 4), 0), out=buf1)
buf2 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_exp_sum_1[grid(1)](buf1, buf2, 1, 2, XBLOCK=1,
num_warps=2, num_stages=1)
buf3 = buf0
del buf0
triton_poi_fused_sub_2[grid(8)](arg0_1, buf3, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf4 = buf1
del buf1
extern_kernels.mm(reinterpret_tensor(arg0_1, (1, 4), (4, 1), 16),
reinterpret_tensor(buf3, (4, 2), (1, 4), 0), out=buf4)
buf5 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_exp_sum_1[grid(1)](buf4, buf5, 1, 2, XBLOCK=1,
num_warps=2, num_stages=1)
buf6 = buf3
del buf3
triton_poi_fused_sub_3[grid(8)](arg0_1, buf6, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf7 = buf4
del buf4
extern_kernels.mm(reinterpret_tensor(arg0_1, (1, 4), (4, 1), 32),
reinterpret_tensor(buf6, (4, 2), (1, 4), 0), out=buf7)
buf8 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_exp_sum_1[grid(1)](buf7, buf8, 1, 2, XBLOCK=1,
num_warps=2, num_stages=1)
buf9 = buf6
del buf6
triton_poi_fused_sub_4[grid(8)](arg0_1, buf9, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf10 = buf7
del buf7
extern_kernels.mm(reinterpret_tensor(arg0_1, (1, 4), (4, 1), 48),
reinterpret_tensor(buf9, (4, 2), (1, 4), 0), out=buf10)
del buf9
buf11 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_exp_sum_1[grid(1)](buf10, buf11, 1, 2, XBLOCK=1,
num_warps=2, num_stages=1)
del buf10
buf21 = empty_strided_cuda((4,), (1,), torch.float32)
buf17 = reinterpret_tensor(buf21, (1,), (1,), 0)
triton_per_fused_add_pow_stack_sum_5[grid(1)](arg0_1, buf17, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
buf18 = reinterpret_tensor(buf21, (1,), (1,), 1)
triton_per_fused_add_pow_stack_sum_6[grid(1)](arg0_1, buf18, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
buf19 = reinterpret_tensor(buf21, (1,), (1,), 2)
triton_per_fused_add_pow_stack_sum_7[grid(1)](arg0_1, buf19, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
buf20 = reinterpret_tensor(buf21, (1,), (1,), 3)
triton_per_fused_add_pow_stack_sum_8[grid(1)](arg0_1, buf20, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
buf22 = empty_strided_cuda((), (), torch.float32)
buf23 = buf22
del buf22
buf24 = buf23
del buf23
triton_per_fused_add_mean_mul_stack_9[grid(1)](buf24, buf2, buf5,
buf8, buf11, buf21, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf11
del buf17
del buf18
del buf19
del buf2
del buf20
del buf21
del buf5
del buf8
return buf24,
class NPairLossNew(torch.nn.Module):
def __init__(self, l2=0.05):
"""
Basic N-Pair Loss as proposed in 'Improved Deep Metric Learning with Multi-class N-pair Loss Objective'
Args:
l2: float, weighting parameter for weight penality due to embeddings not being normalized.
Returns:
Nothing!
"""
super(NPairLossNew, self).__init__()
self.l2 = l2
def npair_distance(self, anchor, positive, negatives):
"""
Compute basic N-Pair loss.
Args:
anchor, positive, negative: torch.Tensor(), resp. embeddings for anchor, positive and negative samples.
Returns:
n-pair loss (torch.Tensor())
"""
return torch.log(1 + torch.sum(torch.exp(anchor.reshape(1, -1).mm((
negatives - positive).transpose(0, 1)))))
def weightsum(self, anchor, positive):
"""
Compute weight penalty.
NOTE: Only need to penalize anchor and positive since the negatives are created based on these.
Args:
anchor, positive: torch.Tensor(), resp. embeddings for anchor and positive samples.
Returns:
torch.Tensor(), Weight penalty
"""
return torch.sum(anchor ** 2 + positive ** 2)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bm2-lab/MDML
|
NPairLoss
| false
| 1,586
|
[
"MIT"
] | 0
|
222fb22b2ee53dd3c1a6f2e99a88f71e9635e3a0
|
https://github.com/bm2-lab/MDML/tree/222fb22b2ee53dd3c1a6f2e99a88f71e9635e3a0
|
FunctionalRelu6
|
import torch
class FunctionalRelu6(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.relu6(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_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 = 0.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = 6.0
tmp4 = triton_helpers.minimum(tmp2, tmp3)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_hardtanh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class FunctionalRelu6New(torch.nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bunderhi/torch2trt
|
FunctionalRelu6
| false
| 1,587
|
[
"MIT"
] | 0
|
fa5e31e742a0f0c9a9ee38909a6fa56bb07ba96d
|
https://github.com/bunderhi/torch2trt/tree/fa5e31e742a0f0c9a9ee38909a6fa56bb07ba96d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.