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)
相关推荐
喵手28 分钟前
Python爬虫实战:构建各地统计局数据发布板块的自动化索引爬虫(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集各地统计局数据发布数据·统计局数据采集
LinQingYanga1 小时前
极客时间多模态大模型训练营毕业总结(2026年2月8日)
人工智能
pccai-vip1 小时前
过去24小时AI创业趋势分析
人工智能
SEO_juper1 小时前
AI SEO实战:整合传统技术与AI生成搜索的优化框架
人工智能·chatgpt·facebook·seo·geo·aeo
pp起床1 小时前
Gen_AI 补充内容 Logit Lens 和 Patchscopes
人工智能·深度学习·机器学习
方见华Richard1 小时前
自指-认知几何架构 可行性边界白皮书(务实版)
人工智能·经验分享·交互·原型模式·空间计算
冬奇Lab1 小时前
AI时代的"工具自由":我是如何进入细糠时代的
人工智能·ai编程
天天爱吃肉82181 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
m0_715575341 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
CODECOLLECT1 小时前
技术解析|MDM移动设备管理系统无终身买断制度的底层逻辑
人工智能