forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish switchablenorm Operator #12' (#30) from ZZZJ/GPUCodeForces:switchablenorm into main
This commit is contained in:
commit
7553119247
|
|
@ -1,137 +0,0 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
from frn_torch import N, C, H, W, EPS
|
||||
|
||||
assert (H * W) % 4 == 0, "Instance size (H * W) must be a multiple of 4 for float4 vectorization"
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(frn_weight.clone())
|
||||
self.bias = nn.Parameter(frn_bias.clone())
|
||||
|
||||
self.eps = EPS
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
torch::Tensor frn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
float eps);
|
||||
"""
|
||||
|
||||
cuda_source = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <float.h>
|
||||
#include <cmath>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define WARP_SIZE 32
|
||||
|
||||
__device__ __forceinline__ float warp_reduce_sum(float val) {
|
||||
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
return val;
|
||||
}
|
||||
|
||||
__global__ void frn_fused_vectorized_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ weight,
|
||||
const float* __restrict__ bias,
|
||||
float* __restrict__ y,
|
||||
int N, int C, int H, int W, float eps
|
||||
) {
|
||||
__shared__ float s_warp_sum_sqs[BLOCK_SIZE / WARP_SIZE];
|
||||
|
||||
int nc_idx = blockIdx.x;
|
||||
if (nc_idx >= N * C) return;
|
||||
|
||||
int sample_idx = nc_idx / C;
|
||||
int channel_idx = nc_idx % C;
|
||||
int instance_size = H * W;
|
||||
const int instance_size_div4 = instance_size / 4;
|
||||
|
||||
int instance_offset = (sample_idx * C + channel_idx) * instance_size;
|
||||
|
||||
const float4* x4_ptr = reinterpret_cast<const float4*>(x + instance_offset);
|
||||
float4* y4_ptr = reinterpret_cast<float4*>(y + instance_offset);
|
||||
|
||||
float thread_sum_sq = 0.0f;
|
||||
for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) {
|
||||
float4 val4 = x4_ptr[i_vec];
|
||||
thread_sum_sq += val4.x * val4.x;
|
||||
thread_sum_sq += val4.y * val4.y;
|
||||
thread_sum_sq += val4.z * val4.z;
|
||||
thread_sum_sq += val4.w * val4.w;
|
||||
}
|
||||
|
||||
float warp_sum_sq = warp_reduce_sum(thread_sum_sq);
|
||||
|
||||
int warp_id = threadIdx.x / WARP_SIZE;
|
||||
int lane_id = threadIdx.x % WARP_SIZE;
|
||||
if (lane_id == 0) s_warp_sum_sqs[warp_id] = warp_sum_sq;
|
||||
__syncthreads();
|
||||
|
||||
warp_sum_sq = (threadIdx.x < BLOCK_SIZE / WARP_SIZE) ? s_warp_sum_sqs[lane_id] : 0.0f;
|
||||
if (warp_id == 0) warp_sum_sq = warp_reduce_sum(warp_sum_sq);
|
||||
|
||||
if (threadIdx.x == 0) {
|
||||
float mean_sq = warp_sum_sq / instance_size;
|
||||
s_warp_sum_sqs[0] = rsqrtf(mean_sq + eps);
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
float inv_stddev = s_warp_sum_sqs[0];
|
||||
|
||||
float w = weight[channel_idx];
|
||||
float b = bias[channel_idx];
|
||||
|
||||
for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) {
|
||||
float4 x_val4 = x4_ptr[i_vec];
|
||||
|
||||
// FRN: y = x * inv_stddev * gamma + beta
|
||||
x_val4.x = x_val4.x * inv_stddev * w + b;
|
||||
x_val4.y = x_val4.y * inv_stddev * w + b;
|
||||
x_val4.z = x_val4.z * inv_stddev * w + b;
|
||||
x_val4.w = x_val4.w * inv_stddev * w + b;
|
||||
|
||||
y4_ptr[i_vec] = x_val4;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor frn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
float eps) {
|
||||
|
||||
const int N = input.size(0);
|
||||
const int C = input.size(1);
|
||||
const int H = input.size(2);
|
||||
const int W = input.size(3);
|
||||
auto output = torch::empty_like(input);
|
||||
|
||||
const int blocks = N * C;
|
||||
const int threads = BLOCK_SIZE;
|
||||
size_t shared_mem_size = (threads / WARP_SIZE) * sizeof(float);
|
||||
|
||||
frn_fused_vectorized_kernel<<<blocks, threads, shared_mem_size>>>(
|
||||
input.data_ptr<float>(),
|
||||
weight.contiguous().view(-1).data_ptr<float>(),
|
||||
bias.contiguous().view(-1).data_ptr<float>(),
|
||||
output.data_ptr<float>(), N, C, H, W, eps);
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
self.frn_op = load_inline(
|
||||
name="frn_fused_op_vectorized_final",
|
||||
cpp_sources=cpp_source, cuda_sources=cuda_source,
|
||||
functions=["frn_forward_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn_op.frn_forward_cuda(
|
||||
x.contiguous(), self.weight, self.bias, self.eps
|
||||
)
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
# frn_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 定义维度常量
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-6
|
||||
|
||||
class FRN(nn.Module):
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1))
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True)
|
||||
x_normalized = x / torch.sqrt(nu2 + self.eps)
|
||||
return x_normalized * self.weight + self.bias
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.frn = FRN(C, EPS)
|
||||
with torch.no_grad():
|
||||
self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1))
|
||||
self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
frn_weight = torch.ones(1, C, 1, 1)
|
||||
frn_bias = torch.zeros(1, C, 1, 1)
|
||||
return [frn_weight, frn_bias]
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups.
|
||||
|
||||
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
|
||||
|
||||
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
|
||||
|
||||
```python
|
||||
# frn_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 定义维度常量
|
||||
N, C, H, W = 32, 64, 56, 56
|
||||
EPS = 1e-6
|
||||
|
||||
class FRN(nn.Module):
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1))
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True)
|
||||
x_normalized = x / torch.sqrt(nu2 + self.eps)
|
||||
return x_normalized * self.weight + self.bias
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, frn_weight, frn_bias):
|
||||
super().__init__()
|
||||
self.frn = FRN(C, EPS)
|
||||
with torch.no_grad():
|
||||
self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1))
|
||||
self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.frn(x)
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
frn_weight = torch.ones(1, C, 1, 1)
|
||||
frn_bias = torch.zeros(1, C, 1, 1)
|
||||
return [frn_weight, frn_bias]
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups.
|
||||
|
||||
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
|
||||
|
||||
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
|
||||
|
||||
```python
|
||||
# switchablenorm_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
N, C, H, W = 16, 64, 32, 32
|
||||
EPS = 1e-5
|
||||
|
||||
class SN(nn.Module):
|
||||
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) # gamma
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) # beta
|
||||
|
||||
self.w_in = nn.Parameter(torch.ones(num_channels))
|
||||
self.w_ln = nn.Parameter(torch.ones(num_channels))
|
||||
self.w_bn = nn.Parameter(torch.ones(num_channels))
|
||||
|
||||
self.register_buffer('running_mean', torch.zeros(num_channels))
|
||||
self.register_buffer('running_var', torch.ones(num_channels))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
ln_mean = x.mean(dim=[1, 2, 3], keepdim=True)
|
||||
ln_var = x.var(dim=[1, 2, 3], keepdim=True)
|
||||
|
||||
|
||||
in_mean = x.mean(dim=[2, 3], keepdim=True)
|
||||
in_var = x.var(dim=[2, 3], keepdim=True)
|
||||
|
||||
|
||||
bn_mean = self.running_mean.view(1, C, 1, 1)
|
||||
bn_var = self.running_var.view(1, C, 1, 1)
|
||||
|
||||
w_sum = self.w_in.abs() + self.w_ln.abs() + self.w_bn.abs()
|
||||
w_in_norm = (self.w_in.abs() / w_sum).view(1, C, 1, 1)
|
||||
w_ln_norm = (self.w_ln.abs() / w_sum).view(1, C, 1, 1)
|
||||
w_bn_norm = (self.w_bn.abs() / w_sum).view(1, C, 1, 1)
|
||||
|
||||
mean = w_in_norm * in_mean + w_ln_norm * ln_mean + w_bn_norm * bn_mean
|
||||
|
||||
|
||||
var_in_M2 = in_var + in_mean.pow(2)
|
||||
var_ln_M2 = ln_var + ln_mean.pow(2)
|
||||
var_bn_M2 = bn_var + bn_mean.pow(2)
|
||||
|
||||
aggregated_var_M2 = w_in_norm * var_in_M2 + w_ln_norm * var_ln_M2 + w_bn_norm * var_bn_M2
|
||||
var = aggregated_var_M2 - mean.pow(2)
|
||||
|
||||
|
||||
x_norm = (x - mean) / torch.sqrt(var + self.eps)
|
||||
return x_norm * self.weight + self.bias
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, weight, bias, w_in, w_ln, w_bn):
|
||||
super().__init__()
|
||||
self.sn = SN(C, EPS)
|
||||
|
||||
with torch.no_grad():
|
||||
self.sn.weight.data.copy_(weight)
|
||||
self.sn.bias.data.copy_(bias)
|
||||
self.sn.w_in.data.copy_(w_in.squeeze())
|
||||
self.sn.w_ln.data.copy_(w_ln.squeeze())
|
||||
self.sn.w_bn.data.copy_(w_bn.squeeze())
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.sn(x)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
|
||||
w_in = torch.ones(C)
|
||||
w_ln = torch.ones(C)
|
||||
w_bn = torch.ones(C)
|
||||
weight = torch.ones(1, C, 1, 1)
|
||||
bias = torch.zeros(1, C, 1, 1)
|
||||
return [weight, bias, w_in, w_ln, w_bn]
|
||||
|
|
@ -4,8 +4,8 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from frn_torch import Model, get_inputs, get_init_inputs
|
||||
from frn_cuda import ModelNew
|
||||
from switchablenorm_torch import Model, get_inputs, get_init_inputs
|
||||
from switchablenorm_cuda import ModelNew
|
||||
|
||||
def run_benchmark():
|
||||
# 检查 CUDA 是否可用
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
# switchablenorm_cuda.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
from switchablenorm_torch import N, C, H, W, EPS
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
|
||||
def __init__(self, weight, bias, w_in, w_ln, w_bn):
|
||||
super().__init__()
|
||||
self.register_buffer('weight', weight)
|
||||
self.register_buffer('bias', bias)
|
||||
self.register_buffer('w_in', w_in)
|
||||
self.register_buffer('w_ln', w_ln)
|
||||
self.register_buffer('w_bn', w_bn)
|
||||
self.eps = EPS
|
||||
self.register_buffer('running_mean', torch.zeros(C))
|
||||
self.register_buffer('running_var', torch.ones(C))
|
||||
self._compile_cuda_kernel()
|
||||
|
||||
def _compile_cuda_kernel(self):
|
||||
cpp_source = """
|
||||
#include <torch/extension.h>
|
||||
|
||||
torch::Tensor sn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
torch::Tensor w_in, torch::Tensor w_ln, torch::Tensor w_bn,
|
||||
torch::Tensor running_mean, torch::Tensor running_var,
|
||||
float eps, int N, int C, int H, int W);
|
||||
"""
|
||||
|
||||
cuda_source = f"""
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
#include <torch/extension.h>
|
||||
|
||||
#define BLOCK_SIZE 256
|
||||
#define WARP_SIZE 32
|
||||
|
||||
__device__ __forceinline__ float warp_reduce_sum(float val) {{
|
||||
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2)
|
||||
val += __shfl_down_sync(0xffffffff, val, offset);
|
||||
return val;
|
||||
}}
|
||||
|
||||
__global__ void sn_normalize_kernel(
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ ln_mean_ptr, const float* __restrict__ ln_var_ptr,
|
||||
const float* __restrict__ in_mean_ptr, const float* __restrict__ in_var_ptr,
|
||||
const float* __restrict__ bn_mean_ptr, const float* __restrict__ bn_var_ptr,
|
||||
const float* __restrict__ weight_ptr, const float* __restrict__ bias_ptr,
|
||||
const float* __restrict__ w_in_ptr, const float* __restrict__ w_ln_ptr, const float* __restrict__ w_bn_ptr,
|
||||
float* __restrict__ output,
|
||||
int N, int C, int H, int W, float eps
|
||||
) {{
|
||||
int n_elements = N * C * H * W;
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx >= n_elements) return;
|
||||
|
||||
int nc_idx = idx / (H * W);
|
||||
int sample_idx = nc_idx / C;
|
||||
int channel_idx = nc_idx % C;
|
||||
|
||||
float w_in = w_in_ptr[channel_idx];
|
||||
float w_ln = w_ln_ptr[channel_idx];
|
||||
float w_bn = w_bn_ptr[channel_idx];
|
||||
|
||||
float w_sum = fabsf(w_in) + fabsf(w_ln) + fabsf(w_bn);
|
||||
float w_in_norm = fabsf(w_in) / w_sum;
|
||||
float w_ln_norm = fabsf(w_ln) / w_sum;
|
||||
float w_bn_norm = fabsf(w_bn) / w_sum;
|
||||
|
||||
float mean_ln = ln_mean_ptr[sample_idx];
|
||||
float var_ln = ln_var_ptr[sample_idx];
|
||||
|
||||
float mean_in = in_mean_ptr[nc_idx];
|
||||
float var_in = in_var_ptr[nc_idx];
|
||||
|
||||
float mean_bn = bn_mean_ptr[channel_idx];
|
||||
float var_bn = bn_var_ptr[channel_idx];
|
||||
|
||||
float agg_mean = w_in_norm * mean_in + w_ln_norm * mean_ln + w_bn_norm * mean_bn;
|
||||
|
||||
float m2_in = var_in + mean_in * mean_in;
|
||||
float m2_ln = var_ln + mean_ln * mean_ln;
|
||||
float m2_bn = var_bn + mean_bn * mean_bn;
|
||||
|
||||
float agg_m2 = w_in_norm * m2_in + w_ln_norm * m2_ln + w_bn_norm * m2_bn;
|
||||
float agg_var = agg_m2 - agg_mean * agg_mean;
|
||||
|
||||
float val = x[idx];
|
||||
float gamma = weight_ptr[channel_idx];
|
||||
float beta = bias_ptr[channel_idx];
|
||||
|
||||
float inv_std = rsqrtf(agg_var + eps);
|
||||
float normalized = (val - agg_mean) * inv_std;
|
||||
|
||||
output[idx] = normalized * gamma + beta;
|
||||
}}
|
||||
|
||||
|
||||
torch::Tensor sn_forward_cuda(
|
||||
torch::Tensor input, torch::Tensor weight, torch::Tensor bias,
|
||||
torch::Tensor w_in, torch::Tensor w_ln, torch::Tensor w_bn,
|
||||
torch::Tensor running_mean, torch::Tensor running_var,
|
||||
float eps, int N, int C, int H, int W) {{
|
||||
|
||||
|
||||
torch::Tensor in_mean = input.mean({{2, 3}}, true).squeeze(-1).squeeze(-1).contiguous();
|
||||
torch::Tensor in_var = input.var({{2, 3}}, true).squeeze(-1).squeeze(-1).contiguous();
|
||||
|
||||
torch::Tensor ln_mean = input.mean({{1, 2, 3}}, true).squeeze(-1).squeeze(-1).squeeze(-1).contiguous();
|
||||
torch::Tensor ln_var = input.var({{1, 2, 3}}, true).squeeze(-1).squeeze(-1).squeeze(-1).contiguous();
|
||||
|
||||
auto output = torch::empty_like(input).contiguous();
|
||||
|
||||
int n_elements = input.numel();
|
||||
const int blocks = (n_elements + BLOCK_SIZE - 1) / BLOCK_SIZE;
|
||||
|
||||
sn_normalize_kernel<<<blocks, BLOCK_SIZE>>>(
|
||||
input.data_ptr<float>(),
|
||||
ln_mean.data_ptr<float>(), ln_var.data_ptr<float>(),
|
||||
in_mean.data_ptr<float>(), in_var.data_ptr<float>(),
|
||||
running_mean.data_ptr<float>(), running_var.data_ptr<float>(),
|
||||
weight.data_ptr<float>(), bias.data_ptr<float>(),
|
||||
w_in.data_ptr<float>(), w_ln.data_ptr<float>(), w_bn.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
N, C, H, W, eps
|
||||
);
|
||||
|
||||
return output;
|
||||
}}
|
||||
"""
|
||||
|
||||
self.sn_op = load_inline(
|
||||
name="sn_fused_op_logic_correct_v3",
|
||||
cpp_sources=cpp_source,
|
||||
cuda_sources=cuda_source,
|
||||
functions=["sn_forward_cuda"],
|
||||
extra_cuda_cflags=["-O3", "--use_fast_math"],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
weight = self.weight.squeeze().contiguous()
|
||||
bias = self.bias.squeeze().contiguous()
|
||||
w_in = self.w_in.contiguous()
|
||||
w_ln = self.w_ln.contiguous()
|
||||
w_bn = self.w_bn.contiguous()
|
||||
running_mean = self.running_mean.contiguous()
|
||||
running_var = self.running_var.contiguous()
|
||||
|
||||
N, C, H, W = x.size(0), x.size(1), x.size(2), x.size(3)
|
||||
|
||||
return self.sn_op.sn_forward_cuda(
|
||||
x.contiguous(), weight, bias, w_in, w_ln, w_bn,
|
||||
running_mean, running_var, self.eps, N, C, H, W
|
||||
)
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
# switchablenorm_torch.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 定义输入尺寸 (N, C, H, W)
|
||||
N, C, H, W = 16, 64, 32, 32
|
||||
EPS = 1e-5
|
||||
|
||||
class SN(nn.Module):
|
||||
|
||||
def __init__(self, num_channels, eps):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
|
||||
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) # gamma
|
||||
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) # beta
|
||||
|
||||
self.w_in = nn.Parameter(torch.ones(num_channels))
|
||||
self.w_ln = nn.Parameter(torch.ones(num_channels))
|
||||
self.w_bn = nn.Parameter(torch.ones(num_channels))
|
||||
|
||||
self.register_buffer('running_mean', torch.zeros(num_channels))
|
||||
self.register_buffer('running_var', torch.ones(num_channels))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
ln_mean = x.mean(dim=[1, 2, 3], keepdim=True)
|
||||
ln_var = x.var(dim=[1, 2, 3], keepdim=True)
|
||||
|
||||
|
||||
in_mean = x.mean(dim=[2, 3], keepdim=True)
|
||||
in_var = x.var(dim=[2, 3], keepdim=True)
|
||||
|
||||
|
||||
bn_mean = self.running_mean.view(1, C, 1, 1)
|
||||
bn_var = self.running_var.view(1, C, 1, 1)
|
||||
|
||||
w_sum = self.w_in.abs() + self.w_ln.abs() + self.w_bn.abs()
|
||||
w_in_norm = (self.w_in.abs() / w_sum).view(1, C, 1, 1)
|
||||
w_ln_norm = (self.w_ln.abs() / w_sum).view(1, C, 1, 1)
|
||||
w_bn_norm = (self.w_bn.abs() / w_sum).view(1, C, 1, 1)
|
||||
|
||||
mean = w_in_norm * in_mean + w_ln_norm * ln_mean + w_bn_norm * bn_mean
|
||||
|
||||
|
||||
var_in_M2 = in_var + in_mean.pow(2)
|
||||
var_ln_M2 = ln_var + ln_mean.pow(2)
|
||||
var_bn_M2 = bn_var + bn_mean.pow(2)
|
||||
|
||||
aggregated_var_M2 = w_in_norm * var_in_M2 + w_ln_norm * var_ln_M2 + w_bn_norm * var_bn_M2
|
||||
var = aggregated_var_M2 - mean.pow(2)
|
||||
|
||||
|
||||
x_norm = (x - mean) / torch.sqrt(var + self.eps)
|
||||
return x_norm * self.weight + self.bias
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, weight, bias, w_in, w_ln, w_bn):
|
||||
super().__init__()
|
||||
self.sn = SN(C, EPS)
|
||||
|
||||
with torch.no_grad():
|
||||
self.sn.weight.data.copy_(weight)
|
||||
self.sn.bias.data.copy_(bias)
|
||||
self.sn.w_in.data.copy_(w_in.squeeze())
|
||||
self.sn.w_ln.data.copy_(w_ln.squeeze())
|
||||
self.sn.w_bn.data.copy_(w_bn.squeeze())
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.sn(x)
|
||||
|
||||
|
||||
def get_inputs():
|
||||
|
||||
x = torch.randn(N, C, H, W, dtype=torch.float32)
|
||||
return [x]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
|
||||
w_in = torch.ones(C)
|
||||
w_ln = torch.ones(C)
|
||||
w_bn = torch.ones(C)
|
||||
weight = torch.ones(1, C, 1, 1)
|
||||
bias = torch.zeros(1, C, 1, 1)
|
||||
return [weight, bias, w_in, w_ln, w_bn]
|
||||
Loading…
Reference in New Issue