import torch
import torch.nn as nn
import numpy as np

class RepClassModule(nn.Module):
    def __init__(self):
        super(RepClassModule, self).__init__()

def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1, bias=False):
    result = nn.Sequential()
    result.add_module('conv', nn.Conv1d(in_channels=in_channels, out_channels=out_channels,
                                                  kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias))
    result.add_module('bn', nn.BatchNorm1d(num_features=out_channels))
    return result

def conv_ln(in_channels, out_channels, out_dim, kernel_size, stride, padding, groups=1, bias=False):
    result = nn.Sequential()
    result.add_module('conv', nn.Conv1d(in_channels=in_channels, out_channels=out_channels,
                                                  kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias))
    # result.add_module('bn', nn.LayerNorm(normalized_shape=[out_channels, out_dim]))
    result.add_module('bn', nn.LayerNorm(normalized_shape=out_dim))
    return result

class RepVGGplusBlock1d(RepClassModule):

    def __init__(self, in_channels, out_channels, kernel_size,
                 stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros',
                 deploy=False,
                 use_post_se=False,
                 **kwargs
                 ):
        super(RepVGGplusBlock1d, self).__init__()
        self.deploy = deploy
        self.groups = groups
        self.in_channels = in_channels

        kernel_size=3
        padding=1
        stride=1
        # self.bias = bias
        # bias = True
        assert kernel_size == 3
        assert padding == 1

        if deploy:
            self.rbr_reparam = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
                                      padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
        else:
            if out_channels == in_channels and stride == 1:
                self.rbr_identity = nn.BatchNorm1d(num_features=out_channels)
            else:
                self.rbr_identity = None
            self.rbr_dense = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias)
            padding_11 = padding - kernel_size // 2
            self.rbr_1x1 = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=padding_11, groups=groups, bias=bias)
            self.weight = self.rbr_dense[0].weight
            self.bias = self.rbr_dense[0].bias

    def forward(self, x, L2=None):

        if self.deploy:
            return self.rbr_reparam(x)

        if self.rbr_identity is None:
            id_out = 0
        else:
            id_out = self.rbr_identity(x)
        out = self.rbr_dense(x) + self.rbr_1x1(x) + id_out

        if L2 is not None:
            #   Custom L2
            t3 = (self.rbr_dense.bn.weight / ((self.rbr_dense.bn.running_var + self.rbr_dense.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
            t1 = (self.rbr_1x1.bn.weight / ((self.rbr_1x1.bn.running_var + self.rbr_1x1.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
            K3 = self.rbr_dense.conv.weight
            K1 = self.rbr_1x1.conv.weight

            l2_loss_circle = (K3 ** 2).sum() - (K3[:, :, 1:2, 1:2] ** 2).sum()
            eq_kernel = K3[:,:,1:2,1:2] * t3 + K1 * t1
            l2_loss_eq_kernel = (eq_kernel ** 2 / (t3 ** 2 + t1 ** 2)).sum()

            return out, L2 + l2_loss_circle + l2_loss_eq_kernel
        else:
            return out


    #   This func derives the equivalent kernel and bias in a DIFFERENTIABLE way.
    #   You can get the equivalent kernel and bias at any time and do whatever you want,
    #   for example, apply some penalties or constraints during training, just like you do to the other models.
    #   May be useful for quantization or pruning.
    def get_equivalent_kernel_bias(self):
        kernel3x1, bias3x1 = self._fuse_bn_tensor(self.rbr_dense)
        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
        kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
        return kernel3x1 + self._pad_1x1_to_3x1_tensor(kernel1x1) + kernelid, bias3x1 + bias1x1 + biasid

    def _pad_1x1_to_3x1_tensor(self, kernel1x1):
        if kernel1x1 is None:
            return 0
        else:
            return torch.nn.functional.pad(kernel1x1, [1, 1])

    def _fuse_bn_tensor(self, branch):
        if branch is None:
            return 0, 0
        if isinstance(branch, nn.Sequential):
            #   For the 1x1 or 3x3 branch
            kernel, running_mean, running_var, gamma, beta, eps = branch.conv.weight, branch.bn.running_mean, branch.bn.running_var, branch.bn.weight, branch.bn.bias, branch.bn.eps
            # 检查卷积层是否有偏置
            if hasattr(branch.conv, 'bias') and branch.conv.bias is not None:
                conv_bias = branch.conv.bias
            else:
                conv_bias = torch.zeros_like(beta)
        else:
            #   For the identity branch
            assert isinstance(branch, nn.BatchNorm1d)
            if not hasattr(self, 'id_tensor'):
                #   Construct and store the identity kernel in case it is used multiple times
                input_dim = self.in_channels // self.groups
                kernel_value = np.zeros((self.in_channels, input_dim, 3), dtype=np.float32)
                for i in range(self.in_channels):
                    kernel_value[i, i % input_dim, 1] = 1
                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
            kernel, running_mean, running_var, gamma, beta, eps = self.id_tensor, branch.running_mean, branch.running_var, branch.weight, branch.bias, branch.eps
            conv_bias = torch.zeros_like(beta)
        std = (running_var + eps).sqrt()
        t = (gamma / std).reshape(-1, 1, 1)
        return kernel * t, ((conv_bias - running_mean) * gamma / std) + beta

    def switch_to_deploy(self):
        if hasattr(self, 'rbr_reparam'):
            return
        kernel, bias = self.get_equivalent_kernel_bias()
        self.rbr_reparam = nn.Conv1d(in_channels=self.rbr_dense.conv.in_channels,
                                     out_channels=self.rbr_dense.conv.out_channels,
                                     kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
                                     padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation,
                                     groups=self.rbr_dense.conv.groups, bias=True)
        self.rbr_reparam.weight.data = kernel
        self.rbr_reparam.bias.data = bias
        self.__delattr__('rbr_dense')
        self.__delattr__('rbr_1x1')
        if hasattr(self, 'rbr_identity'):
            self.__delattr__('rbr_identity')
        if hasattr(self, 'id_tensor'):
            self.__delattr__('id_tensor')
        self.deploy = True
        self.weight = self.rbr_reparam.weight
        self.bias = self.rbr_reparam.bias

class RepVGGplusBlock1d_ln(RepClassModule):

    def __init__(self, in_channels, out_channels, kernel_size,
                 stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros',
                 deploy=False,
                 use_post_se=False,
                 out_dim=48,
                 **kwargs
                 ):
        super(RepVGGplusBlock1d_ln, self).__init__()
        self.deploy = deploy
        self.groups = groups
        self.in_channels = in_channels

        kernel_size=3
        padding=1
        stride=1
        # self.bias = bias
        # bias = True
        assert kernel_size == 3
        assert padding == 1

        if deploy:
            self.rbr_reparam = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
                                      padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
        else:
            if out_channels == in_channels and stride == 1:
                self.rbr_identity = nn.LayerNorm(normalized_shape=[out_channels, out_dim])
            else:
                self.rbr_identity = None
            self.rbr_dense = conv_ln(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, out_dim=out_dim)
            padding_11 = padding - kernel_size // 2
            self.rbr_1x1 = conv_ln(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=padding_11, groups=groups, bias=bias, out_dim=out_dim)
            self.weight = self.rbr_dense[0].weight
            self.bias = self.rbr_dense[0].bias

    def forward(self, x, L2=None):

        if self.deploy:
            return self.rbr_reparam(x)

        if self.rbr_identity is None:
            id_out = 0
        else:
            id_out = self.rbr_identity(x)
        out = self.rbr_dense(x) + self.rbr_1x1(x) + id_out

        if L2 is not None:
            #   Custom L2
            t3 = (self.rbr_dense.bn.weight / ((self.rbr_dense.bn.running_var + self.rbr_dense.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
            t1 = (self.rbr_1x1.bn.weight / ((self.rbr_1x1.bn.running_var + self.rbr_1x1.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
            K3 = self.rbr_dense.conv.weight
            K1 = self.rbr_1x1.conv.weight

            l2_loss_circle = (K3 ** 2).sum() - (K3[:, :, 1:2, 1:2] ** 2).sum()
            eq_kernel = K3[:,:,1:2,1:2] * t3 + K1 * t1
            l2_loss_eq_kernel = (eq_kernel ** 2 / (t3 ** 2 + t1 ** 2)).sum()

            return out, L2 + l2_loss_circle + l2_loss_eq_kernel
        else:
            return out


    #   This func derives the equivalent kernel and bias in a DIFFERENTIABLE way.
    #   You can get the equivalent kernel and bias at any time and do whatever you want,
    #   for example, apply some penalties or constraints during training, just like you do to the other models.
    #   May be useful for quantization or pruning.
    def get_equivalent_kernel_bias(self):
        kernel3x1, bias3x1 = self._fuse_bn_tensor(self.rbr_dense)
        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
        kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
        return kernel3x1 + self._pad_1x1_to_3x1_tensor(kernel1x1) + kernelid, bias3x1 + bias1x1 + biasid

    def _pad_1x1_to_3x1_tensor(self, kernel1x1):
        if kernel1x1 is None:
            return 0
        else:
            return torch.nn.functional.pad(kernel1x1, [1, 1])

    def _fuse_bn_tensor(self, branch):
        if branch is None:
            return 0, 0
        if isinstance(branch, nn.Sequential):
            #   For the 1x1 or 3x3 branch
            kernel, running_mean, running_var, gamma, beta, eps = branch.conv.weight, branch.bn.running_mean, branch.bn.running_var, branch.bn.weight, branch.bn.bias, branch.bn.eps
            # 检查卷积层是否有偏置
            if hasattr(branch.conv, 'bias') and branch.conv.bias is not None:
                conv_bias = branch.conv.bias
            else:
                conv_bias = torch.zeros_like(beta)
        else:
            #   For the identity branch
            assert isinstance(branch, nn.LayerNorm)
            if not hasattr(self, 'id_tensor'):
                #   Construct and store the identity kernel in case it is used multiple times
                input_dim = self.in_channels // self.groups
                kernel_value = np.zeros((self.in_channels, input_dim, 3), dtype=np.float32)
                for i in range(self.in_channels):
                    kernel_value[i, i % input_dim, 1] = 1
                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
            kernel, running_mean, running_var, gamma, beta, eps = self.id_tensor, branch.running_mean, branch.running_var, branch.weight, branch.bias, branch.eps
            conv_bias = torch.zeros_like(beta)
        std = (running_var + eps).sqrt()
        t = (gamma / std).reshape(-1, 1, 1)
        return kernel * t, ((conv_bias - running_mean) * gamma / std) + beta

    def switch_to_deploy(self):
        if hasattr(self, 'rbr_reparam'):
            return
        kernel, bias = self.get_equivalent_kernel_bias()
        self.rbr_reparam = nn.Conv1d(in_channels=self.rbr_dense.conv.in_channels,
                                     out_channels=self.rbr_dense.conv.out_channels,
                                     kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
                                     padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation,
                                     groups=self.rbr_dense.conv.groups, bias=True)
        self.rbr_reparam.weight.data = kernel
        self.rbr_reparam.bias.data = bias
        self.__delattr__('rbr_dense')
        self.__delattr__('rbr_1x1')
        if hasattr(self, 'rbr_identity'):
            self.__delattr__('rbr_identity')
        if hasattr(self, 'id_tensor'):
            self.__delattr__('id_tensor')
        self.deploy = True
        self.weight = self.rbr_reparam.weight
        self.bias = self.rbr_reparam.bias


class linear_bn(nn.Module):
    def __init__(self, in_features, out_features, out_channels, bias=False, **kwargs):
        super(linear_bn, self).__init__()
        self.linear = nn.Linear(in_features=in_features, out_features=out_features, bias=bias, **kwargs)
        self.bn = nn.BatchNorm1d(num_features=out_channels, **kwargs)
        self.output_shape = (out_features, int(out_features/out_channels))

    def forward(self, x):
        x = self.linear(x)
        if self.output_shape[1]==1:
            x.reshape(x.shape[0], self.output_shape[0])
        else:
            x.reshape(x.shape[0], self.output_shape[0], self.output_shape[1])
        x = self.bn(x)
        return x

# 重参数线性层
class RepVGGLinearBlock1d(RepClassModule):

    def __init__(self, in_features, out_features, out_channels, bias=False, deploy=False, **kwargs):
        super(RepVGGLinearBlock1d, self).__init__()

        self.deploy = deploy
        self.in_features = in_features
        self.out_features = out_features
        self.out_channels = out_channels


        if deploy:
            self.rbr_reparam = nn.Linear(in_features=in_features, out_features=out_features, bias=bias)
        else:
            if in_features == out_features:
                self.rbr_identity = nn.BatchNorm1d(num_features=out_channels, **kwargs)
            else:
                self.rbr_identity = None
            self.rbr_dense = linear_bn(in_features=in_features, out_features=out_features, out_channels=out_channels, bias=bias, **kwargs)

            self.weight = self.rbr_dense.linear.weight
            self.bias = self.rbr_dense.linear.bias

    def forward(self, x, L2=None):

        if self.deploy:
            return self.rbr_reparam(x)

        if self.rbr_identity is None:
            id_out = 0
        else:
            id_out = self.rbr_identity(x)
        out = self.rbr_dense(x) + id_out

        return out

    def get_equivalent_weight_bias(self):
        op_weight, op_bias = self._fuse_bn_tensor(self.rbr_dense)
        id_weight, id_bias = self._fuse_bn_tensor(self.rbr_identity)
        return op_weight+id_weight, op_bias+id_bias

    def _fuse_bn_tensor(self, branch):
        if branch is None:
            return 0, 0
        elif isinstance(branch, linear_bn):
            weight, running_mean, running_var, gamma, beta, eps = branch.linear.weight, branch.bn.running_mean, branch.bn.running_var, branch.bn.weight, branch.bn.bias, branch.bn.eps
            if hasattr(branch.linear, 'bias') and branch.linear.bias is not None:
                bias = branch.linear.bias
            else:
                bias = torch.zeros(branch.linear.weight.shape[0], device=weight.device, dtype=weight.dtype)
            std = (running_var + eps).sqrt()

            # 处理权重维度不匹配
            weight_shape_mismatch = weight.shape[0] != gamma.shape[0]
            # 处理偏置维度不匹配
            bias_shape_mismatch = bias.shape[0] != beta.shape[0]

            # 处理通道维度不匹配情况
            if weight_shape_mismatch or bias_shape_mismatch:
                repeat_factor = weight.shape[0] // gamma.shape[0]
                gamma = gamma.repeat_interleave(repeat_factor)
                beta = beta.repeat_interleave(repeat_factor)
                running_mean = running_mean.repeat_interleave(repeat_factor)
                running_var = running_var.repeat_interleave(repeat_factor)
                std = (running_var + eps).sqrt()

        else:
            if not hasattr(self, 'id_tensor'):
                #   Construct and store the identity kernel in case it is used multiple times
                kernel_value = np.zeros((self.out_features, self.in_features), dtype=np.float32)
                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
            weight, running_mean, running_var, gamma, beta, eps = self.id_tensor, branch.running_mean, branch.running_var, branch.weight, branch.bias, branch.eps
            bias = torch.zeros_like(beta)
            std = (running_var + eps).sqrt()



        # 根据操作类型调整reshape维度
        t = (gamma / std)
        # 确保t的维度与weight兼容
        if weight.dim() > 1:
            reshape_dims = [t.shape[0]] + [1] * (weight.dim() - 1)
            t = t.reshape(*reshape_dims)

        # 确保所有参与计算的张量维度匹配
        assert t.shape[0] == weight.shape[0] , f"权重维度不匹配: t.shape={t.shape}, weight.shape={weight.shape}"
        assert bias.shape[0] == beta.shape[0], f"偏置维度不匹配: bias.shape={bias.shape}, beta.shape={beta.shape}"

        return weight * t, ((bias - running_mean) * gamma / std) + beta

    def switch_to_deploy(self):
        if hasattr(self, 'rbr_reparam'):
            return
        weight, bias = self.get_equivalent_kernel_bias()
        self.rbr_reparam = nn.Linear(in_features=self.in_features, out_features=self.out_features, bias=True)

        self.rbr_reparam.weight.data = weight
        self.rbr_reparam.bias.data = bias
        self.__delattr__('rbr_dense')
        if hasattr(self, 'rbr_identity'):
            self.__delattr__('rbr_identity')
        if hasattr(self, 'id_tensor'):
            self.__delattr__('id_tensor')
        self.deploy = True
        self.weight = self.rbr_reparam.weight
        self.bias = self.rbr_reparam.bias

# 支持多个卷积核，注意，outputgroup仅针对输出分组
class RepVGGplusBlock1dV2(RepClassModule):

    def __init__(self, in_channels, out_channels, kernel_size,
                 stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros',
                 deploy=False,
                 use_post_se=False,
                 out_groups=1,
                 **kwargs
                 ):
        super(RepVGGplusBlock1dV2, self).__init__()
        self.deploy = deploy
        self.groups = groups
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = kernel_size
        self.out_groups = out_groups

        stride = 1
        # padding=1
        assert kernel_size % 2 != 0, "kernel_size must be odd"
        assert dilation == 1, "dilation must be 1"
        self.padding = padding = (kernel_size - 1) // 2

        if deploy:
            self.rbr_reparam = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
                                      padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
        else:
            self.model = nn.ModuleList()

            if out_groups==1:
                if out_channels == in_channels and stride == 1:
                    rbr_identity = nn.BatchNorm1d(num_features=in_channels)
                    self.model.append(rbr_identity)
                    self.identity = True
                else:
                    rbr_identity = None
                    self.identity = False

            else:
                if out_channels == in_channels*out_groups and stride == 1:
                    rbr_identity = nn.BatchNorm1d(num_features=in_channels)
                    self.model.append(rbr_identity)
                    self.identity = True
                else:
                    rbr_identity = None
                    self.identity = False

            for k_size in range(1, kernel_size+1, 2):
            # for k_size in range(1, kernel_size, 2):
                padding_k = (k_size - 1) // 2
                self.model.append(conv_bn(in_channels=in_channels, out_channels=out_channels,
                        kernel_size=k_size, stride=stride,
                        padding=padding_k, groups=groups, bias=bias))

            self.weight = self.model[-1][0].weight
            self.bias = self.model[-1][0].bias

    def forward(self, x, L2=None):

        if self.deploy:
            return self.rbr_reparam(x)

        out=0
        if self.out_groups==1:
            for m in self.model:
                out += m(x)
        else:
            if self.identity:
                id_out = self.model[0](x)
                for m in self.model[1:]:
                    out += m(x)
                out += id_out.repeat(1, self.out_groups, 1)
            else:
                for m in self.model:
                    out += m(x)

        return out

    #   This func derives the equivalent kernel and bias in a DIFFERENTIABLE way.
    #   You can get the equivalent kernel and bias at any time and do whatever you want,
    #   for example, apply some penalties or constraints during training, just like you do to the other models.
    #   May be useful for quantization or pruning.
    def get_equivalent_kernel_bias(self):
        k=[]
        b=[]
        for m in self.model:
            kernel, bias = self._fuse_bn_tensor(m)
            kernel=self._pad_to_kernel_size_tensor(kernel)
            k.append(kernel)
            b.append(bias)
        return torch.sum(torch.stack(k), dim=0), torch.sum(torch.stack(b), dim=0)

        # kernel3x1, bias3x1 = self._fuse_bn_tensor(self.rbr_dense)
        # kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
        # kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
        # return kernel3x1 + self._pad_1x1_to_3x1_tensor(kernel1x1) + kernelid, bias3x1 + bias1x1 + biasid

    def _pad_to_kernel_size_tensor(self, kernel):
        if kernel is None:
            return 0
        else:
            current_size = kernel.shape[-1]
            if current_size >= self.kernel_size:
                return kernel

            total_padding = self.kernel_size - current_size
            pad_left = total_padding // 2
            pad_right = total_padding - pad_left

            return torch.nn.functional.pad(kernel, [pad_left, pad_right])

    def _pad_1x1_to_3x1_tensor(self, kernel1x1):
        if kernel1x1 is None:
            return 0
        else:
            return torch.nn.functional.pad(kernel1x1, [1, 1])

    def _fuse_bn_tensor(self, branch):
        if branch is None:
            return 0, 0
        if isinstance(branch, nn.Sequential):
            #   For the 1x1 or 3x3 branch
            kernel, running_mean, running_var, gamma, beta, eps = branch.conv.weight, branch.bn.running_mean, branch.bn.running_var, branch.bn.weight, branch.bn.bias, branch.bn.eps
            # 检查卷积层是否有偏置
            if hasattr(branch.conv, 'bias') and branch.conv.bias is not None:
                conv_bias = branch.conv.bias
            else:
                conv_bias = torch.zeros_like(beta)
        else:
            #   For the identity branch
            assert isinstance(branch, nn.BatchNorm1d)
            if not hasattr(self, 'id_tensor'):
                #   Construct and store the identity kernel in case it is used multiple times
                input_dim = self.in_channels // self.groups
                kernel_value = np.zeros((self.in_channels, input_dim, 3), dtype=np.float32)
                for i in range(self.in_channels):
                    kernel_value[i, i % input_dim, 1] = 1
                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
            kernel, running_mean, running_var, gamma, beta, eps = self.id_tensor, branch.running_mean, branch.running_var, branch.weight, branch.bias, branch.eps
            conv_bias = torch.zeros_like(beta)
                        # if self.out_groups != 1:
            #     #   如果是分组输出，需要将kernel和bias进行分组处理，这个部分维度可能有点问题
            #     kernel = kernel.repeat(1, self.out_groups, 1)
            #     conv_bias = conv_bias.repeat(self.out_groups)
            #     running_mean = running_mean.repeat(self.out_groups)
            #     running_var = running_var.repeat(self.out_groups)
            #     gamma = gamma.repeat(self.out_groups)
            #     beta = beta.repeat(self.out_groups)
            #     eps = eps.repeat(self.out_groups)

        std = (running_var + eps).sqrt()
        t = (gamma / std).reshape(-1, 1, 1)
        return kernel * t, ((conv_bias - running_mean) * gamma / std) + beta

    def switch_to_deploy(self):
        if hasattr(self, 'rbr_reparam'):
            return
        kernel, bias = self.get_equivalent_kernel_bias()
        self.rbr_reparam = nn.Conv1d(in_channels=self.in_channels,
                                     out_channels=self.out_channels,
                                     kernel_size=self.kernel_size, stride=1,
                                     padding=self.padding, dilation=1,
                                     groups=1, bias=True)
        self.rbr_reparam.weight.data = kernel
        self.rbr_reparam.bias.data = bias
        self.__delattr__('model')
        if hasattr(self, 'id_tensor'):
            self.__delattr__('id_tensor')
        self.deploy = True
        self.weight = self.rbr_reparam.weight
        self.bias = self.rbr_reparam.bias
