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

相关推荐
渡众机器人几秒前
智慧城市交通管理中的云端多车调度与控制
大数据·人工智能·自动驾驶·智慧城市·多车编队·交通管理·城市交通
Envyᥫᩣ15 分钟前
Python中的机器学习:从入门到实战
python·前端框架
AI浩18 分钟前
用于视觉的MetaFormer基线模型
人工智能·目标检测·计算机视觉
西贝爱学习19 分钟前
py 元组,列表,函数的学习和使用
python
weijie.zwj36 分钟前
LLM基础概念:Prompt
人工智能·python·langchain
沉下心来学鲁班42 分钟前
欺诈文本分类检测(十七):支持分类原因训练
人工智能·语言模型·分类·微调
high_tea42 分钟前
pytest - 多线程提速
python·pytest
学习前端的小z43 分钟前
【AIGC】ChatGPT提示词助力自媒体内容创作升级
人工智能·chatgpt·aigc
Stringzhua1 小时前
bilibili实现批量发送弹幕功能
python
懒大王爱吃狼1 小时前
Python教程: 类命名空间
开发语言·python·python基础·pip·python教程·python编程·python学习