目录

torch.Storage

在 PyTorch 中,常规张量是一个由以下组件定义的多维数组:

  • Storage:张量的实际数据,以连续的一维字节数组形式存储。

  • dtype: 张量中元素的数据类型,例如 torch.float32 或 torch.int64。

  • shape: 一个元组,表示张量在每个维度上的大小。

  • 步长:在每个维度中从一个元素移动到下一个元素所需的步长。

  • 偏移量:张量数据在存储中开始的起始点。对于新创建的张量,这通常为 0。

这些组件共同定义了一个张量的结构和数据,其中存储保存实际数据,其余部分则作为元数据。

未类型化存储 API

一个 torch.UntypedStorage 是一个连续的一维元素数组。它的长度等于张量的字节数。 存储作为张量的基础数据容器。通常,使用诸如 zeros()zeros_like()new_zeros() 等常规构造器在 PyTorch 中创建的张量将产生张量存储和张量本身之间一一对应的张量。

但是,一个存储可以被多个张量共享。 例如,任何张量的视图(通过 view() 或某些但不是全部类型的索引 如整数和切片)将指向与原始张量相同的底层存储。 在序列化和反序列化共享相同存储的张量时,这种关系会被保留,并且这些张量 继续指向同一个存储。有趣的是,反序列化多个指向单个存储的张量 可能比反序列化多个独立张量更快。

张量存储可以通过 untyped_storage() 方法进行访问。这将返回一个类型为 torch.UntypedStorage 的对象。 幸运的是,存储具有通过 torch.UntypedStorage.data_ptr() 方法访问的唯一标识符。 在常规设置中,具有相同数据存储的两个张量将具有相同的存储 data_ptr。 然而,张量本身可以指向两个独立的存储,一个用于其数据属性,另一个用于其梯度 属性。每个都需要自己的 data_ptr()。通常情况下,不能保证 torch.Tensor.data_ptr()torch.UntypedStorage.data_ptr() 匹配,并且不应假设它们是正确的。

未类型化的存储在某种程度上独立于构建在其上的张量。实际上,这意味着具有不同数据类型或形状的张量可以指向相同的存储。 这也意味着张量的存储可以被更改,如下例所示:

>>> t = torch.ones(3)
>>> s0 = t.untyped_storage()
>>> s0
 0
 0
 128
 63
 0
 0
 128
 63
 0
 0
 128
 63
[torch.storage.UntypedStorage(device=cpu) of size 12]
>>> s1 = s0.clone()
>>> s1.fill_(0)
 0
 0
 0
 0
 0
 0
 0
 0
 0
 0
 0
 0
[torch.storage.UntypedStorage(device=cpu) of size 12]
>>> # Fill the tensor with a zeroed storage
>>> t.set_(s1, storage_offset=t.storage_offset(), stride=t.stride(), size=t.size())
tensor([0., 0., 0.])

警告

请注意,如本示例所示,直接修改张量的存储并不是一种推荐的做法。这种低级别的操作仅用于教学目的,以展示张量与其底层存储之间的关系。通常,使用标准的torch.Tensor方法会更高效且更安全,例如clone()fill_(),可以达到相同的效果。

除了 data_ptr,未类型化的存储还具有其他属性,例如 filename (如果存储指向磁盘上的文件),deviceis_cuda 用于设备检查。存储也可以通过方法如 copy_fill_pin_memory 进行原地或非原地操作。更多信息,请查看下面的API 参考。请注意,修改存储是一个低级API,并伴随着风险! 这些API中的大部分也存在于张量级别:如果存在,应优先使用它们而不是对应的存储 版本。

特殊情况

我们提到,一个具有非None的grad属性的张量实际上内部包含两部分数据。 在这种情况下,untyped_storage()将返回data属性的存储空间, 而梯度的存储可以通过tensor.grad.untyped_storage()获得。

>>> t = torch.zeros(3, requires_grad=True)
>>> t.sum().backward()
>>> assert list(t.untyped_storage()) == [0] * 12  # the storage of the tensor is just 0s
>>> assert list(t.grad.untyped_storage()) != [0] * 12  # the storage of the gradient isn't
There are also special cases where tensors do not have a typical storage, or no storage at all:
  • "meta" 设备上的张量:在 "meta" 设备上的张量用于形状推断 并且不包含实际数据。

  • 假张量:PyTorch 编译器使用的另一种内部工具是 FakeTensor,它基于类似的想法。

张量子类或类似张量的对象也可能表现出异常行为。通常情况下,我们并不期望有太多使用场景需要在存储层进行操作!

class torch.UntypedStorage(*args, **kwargs)[source][source]
bfloat16()[source]

将此存储转换为bfloat16类型。

bool()[source]

将此存储转换为布尔类型。

byte()[source]

将此存储转换为字节类型。

byteswap(dtype)[source]

在底层数据中交换字节。

char()[source]

将此存储转换为字符类型。

clone()[source]

返回此存储的副本。

complex_double()[source]

将此存储转换为复数双精度类型。

complex_float()[source]

将此存储转换为复数浮点类型。

copy_()
cpu()[source]

如果这个存储不在CPU上,返回它的CPU副本。

cuda(device=None, non_blocking=False)[source]

返回此对象在CUDA内存中的副本。

如果该对象已经在CUDA内存中并且位于正确的设备上,那么不会执行复制操作,并返回原始对象。

Parameters
  • 设备 (int) – 目标GPU的ID。默认为当前设备。

  • non_blocking (bool) – 如果 True 且源在锁定内存中, 复制将异步于主机。否则, 该参数无效。

Return type

联合[_存储基类, 类型化存储]

data_ptr()
device: device
double()[source]

将此存储转换为双精度类型。

element_size()
property filename: Optional[str]

返回与此存储关联的文件名。

文件名将是一个字符串,如果存储在CPU上,并通过 from_file()shared 作为 True 创建。否则此属性为 None

fill_()
float()[source]

将此存储转换为浮点类型。

float8_e4m3fn()[source]

将此存储转换为float8_e4m3fn类型

float8_e4m3fnuz()[source]

将此存储转换为 float8_e4m3fnuz 类型

float8_e5m2()[source]

将此存储转换为float8_e5m2类型

float8_e5m2fnuz()[source]

将此存储转换为 float8_e5m2fnuz 类型

static from_buffer()
static from_file(filename, shared=False, size=0) Storage

创建一个由内存映射文件支持的CPU存储。

如果 sharedTrue,那么所有进程之间将共享内存。 所有更改都将写入文件。如果 sharedFalse,那么存储上的更改不会影响文件。

size 是存储中的元素数量。如果 sharedFalse, 则文件必须至少包含 size * sizeof(Type) 字节 (Type 是存储类型,在 UnTypedStorage 的情况下,文件必须至少包含 size 字节)。如果 sharedTrue,则在需要时会创建该文件。

Parameters
  • 文件名 (str) – 要映射的文件名

  • 共享 (布尔值) – 是否共享内存(是否将 MAP_SHAREDMAP_PRIVATE 传递给底层的 mmap(2) 调用

  • 大小 (int) – 存储中的元素数量

get_device()[source]
Return type

整数

half()[source]

将此存储转换为半精度类型。

hpu(device=None, non_blocking=False)[source]

返回此对象在HPU内存中的副本。

如果该对象已经在HPU内存中并且位于正确的设备上,那么不会执行复制操作,并返回原始对象。

Parameters
  • 设备 (int) – 目标HPU的ID。默认为当前设备。

  • non_blocking (bool) – 如果 True 且源在锁定内存中, 复制将异步于主机。否则, 该参数无效。

Return type

联合[_存储基类, 类型化存储]

int()[source]

将此存储转换为 int 类型。

property is_cuda
property is_hpu
is_pinned(device='cuda')[source]

确定CPU存储是否已在设备上固定。

Parameters

device (strtorch.device) – 要固定内存的设备。默认值: 'cuda'.

Returns

一个布尔变量。

is_shared()
is_sparse: bool = False
is_sparse_csr: bool = False
long()[source]

将此存储转换为长整型。

mps()[source]

如果此存储尚未位于 MPS 上,则返回其 MPS 拷贝。

nbytes()
new()
pin_memory(device='cuda')[source]

如果尚未固定,将 CPU 存储复制到固定内存中。

Parameters

device (strtorch.device) – 要固定内存的设备。默认值: 'cuda'.

Returns

一个固定在 CPU 上的存储。

resizable()
resize_()
share_memory_(*args, **kwargs)[source][source]

将存储移动到共享内存。

对于已经位于共享内存中的存储以及不需要跨进程共享的 CUDA 存储,此操作不会产生任何效果。共享内存中的存储无法调整大小。

请注意,为缓解类似 此问题 从同一对象的多个线程调用此函数是线程安全的。 但是,在没有适当同步的情况下,调用 self 上的任何其他函数并不是线程安全的。请参阅 多进程最佳实践 以获取更多详细信息。

注意

当共享内存中对存储的所有引用都被删除时,相关的共享内存对象也将被删除。PyTorch 有一个特殊的清理过程,以确保即使当前进程意外退出,这一操作也能完成。

值得注意的是 share_memory_()from_file()shared = True 的区别

  1. share_memory_ 使用 shm_open(3) 创建一个 POSIX 共享内存对象,而 from_file() 使用 open(2) 打开用户传递的文件名。

  2. 两者都使用 mmap(2) 调用MAP_SHARED 将文件/对象映射到当前虚拟地址空间

  3. share_memory_ 将在映射后调用 shm_unlink(3) ,以确保当没有进程打开该对象时释放共享内存 对象。 torch.from_file(shared=True) 不会取消链接 文件。此文件是持久的,直到用户将其删除才会保留。

Returns

self

short()[source]

将此存储转换为 short 类型。

size()[source]
Return type

整数

to(*, device, non_blocking=False)[source]
tolist()[source]

返回一个包含此存储区元素的列表。

type(dtype=None, non_blocking=False)[source]
Return type

联合[_存储基类, 类型化存储]

untyped()[source]

旧版类型化存储

警告

为了提供历史背景,PyTorch 以前使用过类型化存储类,但现在已弃用,应避免使用。以下内容详细介绍了该 API,以防你遇到它,尽管其使用是高度不推荐的。 除了 torch.UntypedStorage 之外的所有存储类将在未来被移除,并且 torch.UntypedStorage 将在所有情况下使用。

torch.Storage 是与默认数据类型 (torch.get_default_dtype()) 对应的存储类的别名。例如,如果默认数据类型是 torch.float,则 torch.Storage 解析为 torch.FloatStorage

torch.<type>Storagetorch.cuda.<type>Storage 类, 如 torch.FloatStorage, torch.IntStorage 等,实际上从未被实例化。调用它们的构造函数会创建一个带有适当 torch.dtypetorch.devicetorch.TypedStoragetorch.<type>Storage 类具有与 torch.TypedStorage 相同的所有类方法。

一个 torch.TypedStorage 是一个连续的、一维的特定 torch.dtype 元素数组。它可以被赋予任何 torch.dtype,内部数据将被适当地解释。torch.TypedStorage 包含一个 torch.UntypedStorage,它以未分类的字节数组形式保存数据。

每个步幅为 torch.Tensor 的元素包含一个 torch.TypedStorage, 它存储了所有 torch.Tensor 视图的数据。

class torch.TypedStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
bfloat16()[source][source]

将此存储转换为bfloat16类型。

bool()[source][source]

将此存储转换为布尔类型。

byte()[source][source]

将此存储转换为字节类型。

char()[source][source]

将此存储转换为字符类型。

clone()[source][source]

返回此存储的副本。

complex_double()[source][source]

将此存储转换为复数双精度类型。

complex_float()[source][source]

将此存储转换为复数浮点类型。

copy_(source, non_blocking=None)[source][source]
cpu()[source][source]

如果这个存储不在CPU上,返回它的CPU副本。

cuda(device=None, non_blocking=False)[source][source]

返回此对象在CUDA内存中的副本。

如果该对象已经在CUDA内存中并且位于正确的设备上,那么不会执行复制操作,并返回原始对象。

Parameters
  • 设备 (int) – 目标GPU的ID。默认为当前设备。

  • non_blocking (bool) – 如果 True 且源在锁定内存中, 复制将异步于主机。否则, 该参数无效。

Return type

自我

data_ptr()[source][source]
property device
double()[source][source]

将此存储转换为双精度类型。

dtype: dtype
element_size()[source][source]
property filename: Optional[str]

返回与此存储关联的文件名,如果该存储是从文件内存映射创建的。 或 None 如果存储不是通过内存映射文件创建的。

fill_(value)[source][source]
float()[source][source]

将此存储转换为浮点类型。

float8_e4m3fn()[source][source]

将此存储转换为float8_e4m3fn类型

float8_e4m3fnuz()[source][source]

将此存储转换为 float8_e4m3fnuz 类型

float8_e5m2()[source][source]

将此存储转换为float8_e5m2类型

float8_e5m2fnuz()[source][source]

将此存储转换为 float8_e5m2fnuz 类型

classmethod from_buffer(*args, **kwargs)[source][source]
classmethod from_file(filename, shared=False, size=0) Storage[source][source]

创建一个由内存映射文件支持的CPU存储。

如果 sharedTrue,那么所有进程之间将共享内存。 所有更改都将写入文件。如果 sharedFalse,那么存储上的更改不会影响文件。

size 是存储中的元素数量。如果 sharedFalse, 那么文件必须包含至少 size * sizeof(Type) 字节 (Type 是存储的类型)。如果 sharedTrue 文件将在需要时创建。

Parameters
  • 文件名 (str) – 要映射的文件名

  • 共享 (布尔值) –

    是否共享内存(无论是将MAP_SHARED还是MAP_PRIVATE传递给 底层的mmap(2) 调用

  • 大小 (int) – 存储中的元素数量

get_device()[source][source]
Return type

整数

half()[source][source]

将此存储转换为半精度类型。

hpu(device=None, non_blocking=False)[source][source]

返回此对象在HPU内存中的副本。

如果该对象已经在HPU内存中并且位于正确的设备上,那么不会执行复制操作,并返回原始对象。

Parameters
  • 设备 (int) – 目标HPU的ID。默认为当前设备。

  • non_blocking (bool) – 如果 True 且源在锁定内存中, 复制将异步于主机。否则, 该参数无效。

Return type

自我

int()[source][source]

将此存储转换为 int 类型。

property is_cuda
property is_hpu
is_pinned(device='cuda')[source][source]

确定 CPU TypedStorage 是否已在设备上固定。

Parameters

device (strtorch.device) – 要固定内存的设备。默认值: 'cuda'

Returns

一个布尔变量。

is_shared()[source][source]
is_sparse: bool = False
long()[source][source]

将此存储转换为长整型。

nbytes()[source][source]
pickle_storage_type()[source][source]
pin_memory(device='cuda')[source][source]

将 CPU TypedStorage 复制到固定内存中,如果它尚未固定的话。

Parameters

device (strtorch.device) – 要固定内存的设备。默认值: 'cuda'.

Returns

一个固定在 CPU 上的存储。

resizable()[source][source]
resize_(size)[source][source]
share_memory_()[source][source]

查看 torch.UntypedStorage.share_memory_()

short()[source][source]

将此存储转换为 short 类型。

size()[source][source]
to(*, device, non_blocking=False)[source][source]

返回此对象在设备内存中的副本。

如果该对象已经在正确的设备上,则不会执行复制操作,并返回原始对象。

Parameters
  • device (int) – 目标设备.

  • non_blocking (bool) – 如果 True 且源在锁定内存中, 复制将异步于主机。否则, 该参数无效。

Return type

自我

tolist()[source][source]

返回一个包含此存储区元素的列表。

type(dtype=None, non_blocking=False)[source][source]

如果未提供 dtype,则返回类型,否则将此对象转换为指定的类型。

如果已经是正确的类型,则不会执行复制操作,并返回原始对象。

Parameters
  • dtype (类型字符串) – 所需的类型

  • non_blocking (bool) – 如果 True,并且源在固定内存中而目标在GPU上或相反,则复制操作相对于主机是异步执行的。否则,该参数没有效果。

  • **kwargs – 为了兼容性,可能包含键 async 来代替 non_blocking 参数。参数 async 已弃用。

Return type

联合[_存储基础, 类型化存储, 字符串]

untyped()[source][source]

返回内部 torch.UntypedStorage

class torch.DoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.float64[source]
class torch.FloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.float32[source]
class torch.HalfStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.float16[source]
class torch.LongStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.int64[source]
class torch.IntStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.int32[source]
class torch.ShortStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.int16[source]
class torch.CharStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.int8[source]
class torch.ByteStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.uint8[source]
class torch.BoolStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.bool[source]
class torch.BFloat16Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.bfloat16[source]
class torch.ComplexDoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.complex128[source]
class torch.ComplexFloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.complex64[source]
class torch.QUInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.quint8[source]
class torch.QInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.qint8[source]
class torch.QInt32Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.qint32[source]
class torch.QUInt4x2Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.quint4x2[source]
class torch.QUInt2x4Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)[source][source]
dtype: torch.dtype = torch.quint2x4[source]

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源