【问题标题】:Does pytorch broadcast consume less memory than expand?pytorch广播消耗的内存比扩展少吗?
【发布时间】:2021-04-30 03:56:09
【问题描述】:

使用广播的 pytorch 操作消耗的内存是否比扩展少?比如下面两个程序在内存使用上是不同的吗?

import torch
x = torch.randn(20,1)
y = torch.randn(1,20)
z = x*y
import torch
x = torch.randn(20,1).expand(-1,20)
y = torch.randn(1,20).expand(20,-1)
z = x*y

【问题讨论】:

    标签: python numpy pytorch array-broadcasting


    【解决方案1】:

    根据torch.expand的文档页面:

    扩展张量不会分配新内存,只会在现有张量上创建一个新视图

    您可以通过分析调用自己进行试验(在 Colab 中):

    >>> x = torch.randn(200,1)
    >>> y = torch.randn(1,200)
    >>> %memit z = x*y
    peak memory: 286.85 MiB, increment: 0.31 MiB
    
    >>> x = torch.randn(200,1).expand(-1,200)
    >>> y = torch.randn(1,200).expand(200,-1)
    >>> %memit z = x*y
    peak memory: 286.86 MiB, increment: 0.00 MiB
    

    %memitmemory_profiler提供的神奇功能:

    pip install memory_profiler
    
    %load_ext memory_profiler
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      相关资源
      最近更新 更多