【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++代码的,留到下一篇博文更新。

相关推荐
程序员龙叔9 分钟前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
IT_陈寒1 小时前
Redis的SETNX并发问题让我加了三天班
前端·人工智能·后端
用户5191495848453 小时前
Windows 渗透测试载荷加载器 POC 工具集
人工智能·aigc
大树883 小时前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
用户8356290780513 小时前
使用 Python 操作 Word 内容控件
后端·python
通信小呆呆3 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
程序猿追3 小时前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
施小赞3 小时前
普通 RAG vs GraphRAG 核心对比
人工智能·ai
EAIReport3 小时前
RuoYi-AI 企业级AI开发平台实战详解
人工智能
HelloWorld__来都来了3 小时前
【每日学术速报】2026-06-15
人工智能·具身智能