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)
相关推荐
2zcode1 小时前
基于Matlab的深度学习智能行人检测与统计系统
人工智能·深度学习·目标跟踪
宇寒风暖1 小时前
Flask 框架全面详解
笔记·后端·python·学习·flask·知识
哪 吒1 小时前
【2025C卷】华为OD机试九日集训第3期 - 按算法分类,由易到难,提升编程能力和解题技巧
python·算法·华为od·华为od机试·2025c卷
weixin_464078071 小时前
机器学习sklearn:过滤
人工智能·机器学习·sklearn
weixin_464078071 小时前
机器学习sklearn:降维
人工智能·机器学习·sklearn
数据与人工智能律师1 小时前
智能合约漏洞导致的损失,法律责任应如何分配
大数据·网络·人工智能·算法·区块链
张艾拉 Fun AI Everyday1 小时前
小宿科技:AI Agent 的卖铲人
人工智能·aigc·创业创新·ai-native
zhongqu_3dnest2 小时前
三维火灾调查重建:科技赋能,探寻真相
人工智能
飞哥数智坊2 小时前
AI编程实战:写作助手进化,Trae+Kimi-K2两小时搞定“带样式复制”
人工智能·trae
木枷2 小时前
c2rust使用
人工智能·物联网·edge