【pytorch】relu的实现逻辑

笔者最近在尝试实现AlexNet的底层算子,基于pytorch的框架,本文主要记录一下pytorch中是如何实现relu算子的。

首先最外层是位于torch\nn\modules\activation.py,主要代码如下:

py 复制代码
    __constants__ = ["inplace"]
    inplace: bool

    def __init__(self, inplace: bool = False):
        super().__init__()
        self.inplace = inplace

    def forward(self, input: Tensor) -> Tensor:
        return F.relu(input, inplace=self.inplace)

    def extra_repr(self) -> str:
        inplace_str = "inplace=True" if self.inplace else ""
        return inplace_str

调用的是位于torch\nn\functional.py的如下代码:

py 复制代码
def relu(input: Tensor, inplace: bool = False) -> Tensor:  # noqa: D400,D402
    r"""relu(input, inplace=False) -> Tensor

    Applies the rectified linear unit function element-wise. See
    :class:`~torch.nn.ReLU` for more details.
    """
    if has_torch_function_unary(input):
        return handle_torch_function(relu, (input,), input, inplace=inplace)
    if inplace:
        result = torch.relu_(input)
    else:
        result = torch.relu(input)
    return result

然后调用的是aten\src\ATen\native\Activation.cpp的如下代码:

复制代码
Tensor relu(const Tensor & self) {
  TORCH_CHECK(self.scalar_type() != at::kBool, "Boolean inputs not supported for relu");
  return at::clamp_min(self, 0);
}

可以看到,主要就是一个大小的比较。

pytorch调试工具

先说问题,只能看到python的处理逻辑,不能看到底层的C++的处理逻辑。

如何使用,参考的是这篇文章。注意,pdb虽然是python内置的包,但是仍然需要通过import pdb导入才能使用。

还有一个问题就是,pytorch是如何通过python代码调用C++代码的,留到下一篇博文更新。

相关推荐
openYuanrong分布式计算引擎4 分钟前
openYuanrong 打造 Agent 时代的企业级分布式底座
人工智能·分布式·ai·serverless
云端漫步19875 分钟前
HarmonyOS NEXT AI 智能生活助手:PromptManager 设计与实现
人工智能·生活·harmonyos
我是大卫15 分钟前
从零到答辩全链路:花1小时用TRAE Work搞定100页案例报告+40页答辩PPT
人工智能·trae
极序时代GEO品牌优化23 分钟前
杭州极序时代|面向地域、设备与用户画像的动态GEO
人工智能·python·算法·极序时代geo
崔高杰24 分钟前
【自动阅读笔记】Inference-Time Scaling for Generalist Reward Modeling
人工智能·笔记·机器学习
风途科技~27 分钟前
隧道氮氧化物检测仪|实时监测 NO、NO₂浓度,助力公路隧道通风智能调控
大数据·人工智能
senmuleishi38 分钟前
持续发力嵌入式AI IDE,攻坚大科学装置电源解决方案
ide·人工智能
刘婉晴41 分钟前
【大模型安全】OWASP 大语言模型十大风险
人工智能·安全·语言模型
mlidongfeng43 分钟前
[AI][C++26] SIMD 编程模型思考
开发语言·c++·人工智能
关于不上作者榜就原神启动那件事1 小时前
从 MDC 到 Agent:我手搓的文档路由协议,在 Spring AI Alibaba 里找到了正式实现
java·人工智能·spring·ai·agent