关于pytorch中函数调用的问题和源码解读

最近用到 softmax 函数,但是发现 softmax 的写法五花八门,记录如下

# torch._C._VariableFunctions
torch.softmax(x, dim=-1)
# class
softmax = torch.nn.Softmax(dim=-1)
x=softmax(x)
# function
x = torch.nn.functional.softmax(x, dim=-1)

简单测试了一下,用 torch.nn.Softmax 类是最慢的,另外两个差不多


torch.nn.Softmax 源码如下,可以看到这是个类,而他这里的 return F.softmax(input, self.dim, _stacklevel=5) 调用的是 torch.nn.functional.softmax

class Softmax(Module):
    r"""Applies the Softmax function to an n-dimensional input Tensor
    rescaling them so that the elements of the n-dimensional output Tensor
    lie in the range [0,1] and sum to 1.

    Softmax is defined as:

    .. math::
        \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}

    When the input Tensor is a sparse tensor then the unspecifed
    values are treated as ``-inf`&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch源码解读是一个系列文章,从底层的Tensor库开始,逐步解析神经网络算符、自动微分引擎和Python扩展等核心源码。这个系列共有五篇文章,每篇都有大量的代码和解析。如果在阅读过程发现理解不当或表达不准确的地方,可以在评论区指出。\[1\] 在PyTorch框架,有一个非常重要且实用的包叫做torchvision。该包由三个子包组成:torchvision.datasets、torchvision.models和torchvision.transforms。这三个子包的具体介绍可以参考PyTorch官方文档的链接:https://pytorch.org/docs/master/torchvision/datasets.html。\[2\] 最后一篇博客介绍了如何在Python调用C++代码进行高效计算,以及如何与前面的C++代码进行交互。首先简单介绍了Python的C扩展通常的写法,然后以核心数据结构Tensor和Storage为例,展示了它们如何转换为Python类型。最后还稍微介绍了一下Python自动微分函数的实现。\[3\] 整个PyTorch源码的目录结构如下: - aten: C++ Tensor库 - c10: 包含一些Tensor实现 - caffe2: caffe2 - tools: 包含自动微分相关函数生成工具等 - torch: Python模块,包含了C++相关源码Python模块的实现 这个系列文章对PyTorch源码进行了详细解读,可以帮助读者更好地理解PyTorch的内部实现和工作原理。 #### 引用[.reference_title] - *1* *3* [PyTorch源码浅析:简介](https://blog.csdn.net/Xixo0628/article/details/112602624)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [PyTorch源码解读(四)torchvision.models](https://blog.csdn.net/sinat_42239797/article/details/94329987)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值