pytorch 自定义函数

pytorch 自定义函数

介绍:https://zhuanlan.zhihu.com/p/344802526

主要构建 static method forward 和 backward

比如 layernorm: 参考:https://github.com/zhangyi-3/KBNet/blob/main/basicsr/models/archs/kb_utils.py

导数的推导:https://blog.csdn.net/qinduohao333/article/details/132309091

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F


class LayerNormFunction(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, weight, bias, eps):
        ctx.eps = eps
        N, C, H, W = x.size()
        mu = x.mean(1, keepdim=True)
        var = (x - mu).pow(2).mean(1, keepdim=True)
        # print('mu, var', mu.mean(), var.mean())
        # d.append([mu.mean(), var.mean()])
        y = (x - mu) / (var + eps).sqrt()
        weight, bias, y = weight.contiguous(), bias.contiguous(), y.contiguous()  # avoid cuda error
        ctx.save_for_backward(y, var, weight)
        y = weight.view(1, C, 1, 1) * y + bias.view(1, C, 1, 1)
        return y

    @staticmethod
    def backward(ctx, grad_output):
        eps = ctx.eps

        N, C, H, W = grad_output.size()
        # y, var, weight = ctx.saved_variables
        y, var, weight = ctx.saved_tensors
        g = grad_output * weight.view(1, C, 1, 1)
        mean_g = g.mean(dim=1, keepdim=True)

        mean_gy = (g * y).mean(dim=1, keepdim=True)
        gx = 1. / torch.sqrt(var + eps) * (g - y * mean_gy - mean_g)
        return gx, (grad_output * y).sum(dim=3).sum(dim=2).sum(dim=0), grad_output.sum(dim=3).sum(dim=2).sum(
            dim=0), None


class LayerNorm2d(nn.Module):

    def __init__(self, channels, eps=1e-6, requires_grad=True):
        super(LayerNorm2d, self).__init__()
        self.register_parameter('weight', nn.Parameter(torch.ones(channels), requires_grad=requires_grad))
        self.register_parameter('bias', nn.Parameter(torch.zeros(channels), requires_grad=requires_grad))
        self.eps = eps

    def forward(self, x):
        return LayerNormFunction.apply(x, self.weight, self.bias, self.eps)
相关推荐
掘金安东尼4 分钟前
本地模型 + 云端模型的 Hybrid Inference 架构设计:下一代智能系统的底层范式
人工智能
强盛小灵通专卖员4 分钟前
煤矿传送带异物检测:深度学习引领煤矿安全新革命!
人工智能·目标检测·sci·研究生·煤矿安全·延毕·传送带
王哈哈^_^5 分钟前
Ubuntu系统CUDA完整安装指南
linux·运维·服务器·pytorch·ubuntu
学历真的很重要13 分钟前
PyTorch 零基础入门:从张量到 GPU 加速完全指南
人工智能·pytorch·后端·深度学习·语言模型·职场和发展
CodeLongBear14 分钟前
Python数据分析 -- Pandas基础入门学习笔记:从核心概念到实操代码
python·conda·pandas
mit6.82414 分钟前
[Column] Perplexity 如何构建 AI 版 Google | 模型无关架构 | Vespa AI检索
人工智能
xier_ran30 分钟前
深度学习:梯度检验(Gradient Checking)
人工智能·深度学习·梯度检验
B站_计算机毕业设计之家32 分钟前
python手写数字识别计分系统+CNN模型+YOLOv5模型 深度学习 计算机毕业设计(建议收藏)✅
python·深度学习·yolo·计算机视觉·数据分析·cnn
尼古拉斯·纯情暖男·天真·阿玮38 分钟前
基于卷积神经网络的手写数字识别
人工智能·神经网络·cnn
2401_8414956444 分钟前
MoE算法深度解析:从理论架构到行业实践
人工智能·深度学习·机器学习·自然语言处理·大语言模型·moe·混合专家模型