diff --git a/totrans/doc22_025.md b/totrans/doc22_025.md index 240143e5bec3d300bff9b4039559d0ed80a6c16e..0a3f4a39b7f935f535a8e46ddd3e80c27d299462 100644 --- a/totrans/doc22_025.md +++ b/totrans/doc22_025.md @@ -272,7 +272,7 @@ tensor([1.+1.j, 1.+1.j, 1.+1.j]) 以下实用函数与序列化相关: ```py -torch.serialization.register_package(priority, tagger, deserializer)¶ +torch.serialization.register_package(priority, tagger, deserializer) ``` 为标记和反序列化存储对象注册可调用对象,并附带优先级。标记在保存时将设备与存储对象关联,而在加载时反序列化将存储对象移动到适当的设备上。`tagger`和`deserializer`按照它们的`priority`给出的顺序运行,直到一个标记器/反序列化器返回一个不是 None 的值。 @@ -309,7 +309,7 @@ torch.serialization.register_package(priority, tagger, deserializer)¶ ``` ```py -torch.serialization.get_default_load_endianness()¶ +torch.serialization.get_default_load_endianness() ``` 获取用于加载文件的回退字节顺序 @@ -325,7 +325,7 @@ Optional[LoadEndianness] default_load_endian ```py -torch.serialization.set_default_load_endianness(endianness)¶ +torch.serialization.set_default_load_endianness(endianness) ``` 设置用于加载文件的回退字节顺序 diff --git a/totrans/doc22_031.md b/totrans/doc22_031.md index f8db98725817d2a2927d6684b0dff2a4eabde97f..e3e6086908f80b75b0e2eedea1256dcdfeec94ce 100644 --- a/totrans/doc22_031.md +++ b/totrans/doc22_031.md @@ -128,7 +128,7 @@ torch 包含用于多维张量的数据结构,并定义了这些张量上的 | `set_rng_state` | 设置随机数生成器状态。 | ```py -torch.default_generator Returns the default CPU torch.Generator¶ +torch.default_generator Returns the default CPU torch.Generator ``` | `bernoulli` | 从伯努利分布中抽取二进制随机数(0 或 1)。 | @@ -614,19 +614,19 @@ False ## 符号数字 ```py -class torch.SymInt(node)¶ +class torch.SymInt(node) ``` 像一个整数(包括魔术方法),但重定向包装节点上的所有操作。这特别用于在符号形状工作流程中符号记录操作。 ```py -class torch.SymFloat(node)¶ +class torch.SymFloat(node) ``` 像一个浮点数(包括魔术方法),但重定向包装节点上的所有操作。这特别用于在符号形状工作流程中符号记录操作。 ```py -class torch.SymBool(node)¶ +class torch.SymBool(node) ``` 像一个布尔值(包括魔术方法),但重定向包装节点上的所有操作。这特别用于在符号形状工作流程中符号记录操作。 @@ -668,7 +668,7 @@ class torch.SymBool(node)¶ ## 操作符标签 ```py -class torch.Tag¶ +class torch.Tag ``` 成员: @@ -694,5 +694,5 @@ pt2 兼容标签 视图复制 ```py -property name¶ +property name ``` diff --git a/totrans/doc22_034.md b/totrans/doc22_034.md index 54dcbe0061e8eb890dd155ab2f1fef6ef82b2d26..549873556ed1093406881eb48c570d6ad3b87d80 100644 --- a/totrans/doc22_034.md +++ b/totrans/doc22_034.md @@ -138,7 +138,7 @@ tensor([[ 2.0000, -2.0000], ## 张量类参考 ```py -class torch.Tensor¶ +class torch.Tensor ``` 有几种主要方法可以创建张量,取决于您的用例。 @@ -152,7 +152,7 @@ class torch.Tensor¶ + 要创建一个与另一个张量相似类型但不同大小的张量,请使用 `tensor.new_*` 创建操作。 ```py -Tensor.T¶ +Tensor.T ``` 返回一个维度被颠倒的张量视图。 @@ -164,7 +164,7 @@ Tensor.T¶ 在维度不为 2 的张量上使用 `Tensor.T()` 来颠倒它们的形状已被弃用,并且在将来的版本中会引发错误。考虑使用 `mT` 来转置矩阵批次或者使用 x.permute(*torch.arange(x.ndim - 1, -1, -1)) 来颠倒张量的维度。 ```py -Tensor.H¶ +Tensor.H ``` 返回一个共轭和转置的矩阵(2-D 张量)视图。 @@ -176,7 +176,7 @@ Tensor.H¶ `mH`:也适用于矩阵批次的属性。 ```py -Tensor.mT¶ +Tensor.mT ``` 返回一个最后两个维度被转置的张量视图。 @@ -184,7 +184,7 @@ Tensor.mT¶ `x.mT` 等同于 `x.transpose(-2, -1)`。 ```py -Tensor.mH¶ +Tensor.mH ``` 访问此属性等同于调用 `adjoint()`。 diff --git a/totrans/doc22_035.md b/totrans/doc22_035.md index 39718ee0749b587a21d82ae5535decdd41c5bccf..3205a22c05b88a4d85ab0a692f774caca4a3be3b 100644 --- a/totrans/doc22_035.md +++ b/totrans/doc22_035.md @@ -7,7 +7,7 @@ ## torch.dtype ```py -class torch.dtype¶ +class torch.dtype ``` `torch.dtype`是表示`torch.Tensor`的数据类型的对象。PyTorch 有 12 种不同的数据类型: @@ -119,7 +119,7 @@ torch.float32 ``` ## torch.device ```py -class torch.device¶ +class torch.device ``` `torch.device`是表示`torch.Tensor`分配或将要分配的设备的对象。 @@ -209,7 +209,7 @@ device(type='cuda', index=1) ``` ## torch.layout ```py -class torch.layout¶ +class torch.layout ``` 警告 @@ -236,7 +236,7 @@ class torch.layout¶ ## torch.memory_format ```py -class torch.memory_format¶ +class torch.memory_format ``` `torch.memory_format` 是一个表示 `torch.Tensor` 分配或将要分配的内存格式的对象。 diff --git a/totrans/doc22_037.md b/totrans/doc22_037.md index c400ea287b5e1c85da042b4254c25f23574281f8..574a6e33b6d0055ccfe7399d18d253d186d9dce0 100644 --- a/totrans/doc22_037.md +++ b/totrans/doc22_037.md @@ -43,7 +43,7 @@ ## 自动转换 ```py -class torch.autocast(device_type, dtype=None, enabled=True, cache_enabled=None)¶ +class torch.autocast(device_type, dtype=None, enabled=True, cache_enabled=None) ``` `autocast` 的实例充当上下文管理器或装饰器,允许脚本的区域以混合精度运行。 @@ -201,7 +201,7 @@ with torch.autocast(device_type="cuda"): + **cache_enabled**(*bool*,*可选*)- 是否启用自动转换内部的权重缓存。默认值:`True` ```py -class torch.cuda.amp.autocast(enabled=True, dtype=torch.float16, cache_enabled=True)¶ +class torch.cuda.amp.autocast(enabled=True, dtype=torch.float16, cache_enabled=True) ``` 请参阅`torch.autocast`。 @@ -209,7 +209,7 @@ class torch.cuda.amp.autocast(enabled=True, dtype=torch.float16, cache_enabled=T `torch.cuda.amp.autocast(args...)`等同于`torch.autocast("cuda", args...)` ```py -torch.cuda.amp.custom_fwd(fwd=None, *, cast_inputs=None)¶ +torch.cuda.amp.custom_fwd(fwd=None, *, cast_inputs=None) ``` 为自定义自动求导函数的`forward`方法创建一个辅助装饰器。 @@ -225,7 +225,7 @@ torch.cuda.amp.custom_fwd(fwd=None, *, cast_inputs=None)¶ 如果装饰的`forward`在自动转换启用的区域之外被调用,则`custom_fwd`是一个空操作,`cast_inputs`没有效果。 ```py -torch.cuda.amp.custom_bwd(bwd)¶ +torch.cuda.amp.custom_bwd(bwd) ``` 为自定义自动求导函数的反向方法创建一个辅助装饰器。 @@ -233,7 +233,7 @@ torch.cuda.amp.custom_bwd(bwd)¶ 自动求导函数是`torch.autograd.Function`的子类。确保`backward`以与`forward`相同的自动转换状态执行。更多细节请参见示例页面。 ```py -class torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16, cache_enabled=True)¶ +class torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16, cache_enabled=True) ``` 请参见`torch.autocast`。`torch.cpu.amp.autocast(args...)`等同于`torch.autocast("cpu", args...)` ## 梯度缩放[](#gradient-scaling "跳转到此标题") @@ -249,7 +249,7 @@ class torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16, cache_enabled=T AMP/fp16 可能并不适用于每个模型!例如,大多数 bf16 预训练模型无法在最大 65504 的 fp16 数值范围内运行,会导致梯度溢出而不是下溢。在这种情况下,比例因子可能会减少到 1 以下,以尝试将梯度带到 fp16 动态范围内可表示的数字。虽然人们可能期望比例始终大于 1,但我们的 GradScaler 并不保证这一点以保持性能。如果在使用 AMP/fp16 时遇到损失或梯度中的 NaN,请验证您的模型是否兼容。 ```py -class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True)¶ +class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True) ``` `GradScaler`的一个实例`scaler`。 @@ -309,7 +309,7 @@ for epoch in epochs: + **enabled** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")*,* *可选*) – 如果为`False`,则禁用梯度缩放。`step()`只会调用底层的`optimizer.step()`,其他方法将变为无操作。默认值:`True` ```py -get_backoff_factor()¶ +get_backoff_factor() ``` 返回一个包含缩放退避因子的 Python 浮点数。 @@ -319,7 +319,7 @@ get_backoff_factor()¶ [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") ```py -get_growth_factor()¶ +get_growth_factor() ``` 返回一个包含增长因子的 Python 浮点数。 @@ -329,7 +329,7 @@ get_growth_factor()¶ [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") ```py -get_growth_interval()¶ +get_growth_interval() ``` 返回一个包含增长间隔的 Python 整数。 @@ -339,7 +339,7 @@ get_growth_interval()¶ [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)") ```py -get_scale()¶ +get_scale() ``` 返回一个包含当前比例的 Python 浮点数,如果禁用了缩放,则返回 1.0。 @@ -353,7 +353,7 @@ get_scale()¶ [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") ```py -is_enabled()¶ +is_enabled() ``` 返回一个指示此实例是否已启用的布尔值。 @@ -363,7 +363,7 @@ is_enabled()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -load_state_dict(state_dict)¶ +load_state_dict(state_dict) ``` 加载缩放器状态。 @@ -375,7 +375,7 @@ load_state_dict(state_dict)¶ **state_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(在 Python v3.12 中)")) – 缩放器状态。应该是从调用`state_dict()`返回的对象。 ```py -scale(outputs: Tensor) → Tensor¶ +scale(outputs: Tensor) → Tensor ``` ```py @@ -399,7 +399,7 @@ scale(outputs: Iterable[Tensor]) → Iterable[Tensor] **outputs** (*Tensor* *或* *可迭代* *的* *Tensors*) – 要缩放的输出。 ```py -set_backoff_factor(new_factor)¶ +set_backoff_factor(new_factor) ``` 设置一个新的退避因子。 @@ -409,7 +409,7 @@ set_backoff_factor(new_factor)¶ **new_scale** ([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)")) – 用作新的缩放退避因子的值。 ```py -set_growth_factor(new_factor)¶ +set_growth_factor(new_factor) ``` 设置一个新的增长因子。 @@ -419,7 +419,7 @@ set_growth_factor(new_factor)¶ **new_scale** ([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)")) – 用作新的增长因子的值。 ```py -set_growth_interval(new_interval)¶ +set_growth_interval(new_interval) ``` 设置一个新的增长间隔。 @@ -429,7 +429,7 @@ set_growth_interval(new_interval)¶ **new_interval** ([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) – 用作新增长间隔的值。 ```py -state_dict()¶ +state_dict() ``` 返回一个[`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(在 Python v3.12 中)")形式的缩放器状态。 @@ -457,7 +457,7 @@ state_dict()¶ [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")] ```py -step(optimizer, *args, **kwargs)¶ +step(optimizer, *args, **kwargs) ``` 如果梯度不是无穷大/NaN,则调用`unscale_(optimizer)`,然后进行参数更新。 @@ -489,7 +489,7 @@ step(optimizer, *args, **kwargs)¶ 目前不支持闭包使用。 ```py -unscale_(optimizer)¶ +unscale_(optimizer) ``` 通过比例因子除(“取消缩放”)优化器的梯度张量。 @@ -524,7 +524,7 @@ scaler.update() `unscale_()`可能会在原地取消缩放稀疏梯度,替换`.grad`属性。 ```py -update(new_scale=None)¶ +update(new_scale=None) ``` 更新比例因子。 diff --git a/totrans/doc22_038.md b/totrans/doc22_038.md index 1512ff320742bf79fd7bad61af95b4ca8cb6ba05..680487dae3c5b9c0a118713fcc71892257494b30 100644 --- a/totrans/doc22_038.md +++ b/totrans/doc22_038.md @@ -113,7 +113,7 @@ Variable API 已被弃用:不再需要使用 Variables 来使用带有 `requir ## Function ```py -class torch.autograd.Function(*args, **kwargs)¶ +class torch.autograd.Function(*args, **kwargs) ``` 用于创建自定义自动求导函数的基类。 @@ -170,7 +170,7 @@ class torch.autograd.Function(*args, **kwargs)¶ Autograd 包括一个性能分析器,让您可以检查模型内不同运算符的成本 - 包括在 CPU 和 GPU 上。目前实现了三种模式 - 仅 CPU 使用`profile`。基于 nvprof 的(同时注册 CPU 和 GPU 活动)使用`emit_nvtx`。基于 vtune 性能分析器的使用`emit_itt`。 ```py -class torch.autograd.profiler.profile(enabled=True, *, use_cuda=False, use_device=None, record_shapes=False, with_flops=False, profile_memory=False, with_stack=False, with_modules=False, use_kineto=False, use_cpu=True, use_mtia=False, experimental_config=None)¶ +class torch.autograd.profiler.profile(enabled=True, *, use_cuda=False, use_device=None, record_shapes=False, with_flops=False, profile_memory=False, with_stack=False, with_modules=False, use_kineto=False, use_cpu=True, use_mtia=False, experimental_config=None) ``` 上下文管理器,管理自动求导分析器状态并保存结果摘要。 @@ -227,7 +227,7 @@ torch::autograd::GraphRoot 691.816us 691.816us 100 | `profiler.profile.total_average` | 对所有事件进行平均。 | ```py -class torch.autograd.profiler.emit_nvtx(enabled=True, record_shapes=False)¶ +class torch.autograd.profiler.emit_nvtx(enabled=True, record_shapes=False) ``` 使每个自动求导操作发出一个 NVTX 范围的上下文管理器。 @@ -268,7 +268,7 @@ nvprof --profile-from-start off -o trace_name.prof -- 另一方面,如果正在进行带有`create_graph=True`的反向传递(换句话说,如果您正在为双向传递做准备),则在反向期间执行的每个函数都会获得一个非零、有用的`seq=`。这些函数本身可能会创建 Function 对象,以便稍后在双向传递期间执行,就像前向传递中的原始函数一样。反向和双向之间的关系在概念上与前向和反向之间的关系相同:函数仍然发出当前序列号标记的范围,它们创建的 Function 对象仍然存储这些序列号,并且在最终的双向传递期间,Function 对象的`apply()`范围仍然标记有`stashed seq`号,可以与反向传递中的 seq 号进行比较。 ```py -class torch.autograd.profiler.emit_itt(enabled=True, record_shapes=False)¶ +class torch.autograd.profiler.emit_itt(enabled=True, record_shapes=False) ``` 上下文管理器,使每个自动求导操作都发出一个 ITT 范围。 @@ -300,7 +300,7 @@ vtune <--vtune-flags> ## 异常检测 ```py -class torch.autograd.detect_anomaly(check_nan=True)¶ +class torch.autograd.detect_anomaly(check_nan=True) ``` 上下文管理器,用于启用自动求导引擎的异常检测。 @@ -367,7 +367,7 @@ class torch.autograd.detect_anomaly(check_nan=True)¶ ``` ```py -class torch.autograd.set_detect_anomaly(mode, check_nan=True)¶ +class torch.autograd.set_detect_anomaly(mode, check_nan=True) ``` 上下文管理器,用于设置自动求导引擎的异常检测开启或关闭。 @@ -411,7 +411,7 @@ True 您还可以使用钩子定义这些保存的张量应如何打包/解包。一个常见的应用是通过将这些中间结果保存到磁盘或 CPU 来交换计算和内存,而不是将它们留在 GPU 上。如果您注意到您的模型在评估期间适合 GPU,但在训练期间不适合,则这是非常有用的。另请参阅保存张量的钩子。 ```py -class torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook)¶ +class torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook) ``` 为保存的张量设置一对 pack / unpack 钩子的上下文管理器。 @@ -463,7 +463,7 @@ Unpacking tensor([2., 2., 2., 2., 2.], grad_fn=) 一次只允许一个钩子对。当递归嵌套这个上下文管理器时,只有最内层的一对钩子将被应用。 ```py -class torch.autograd.graph.save_on_cpu(pin_memory=False, device_type='cuda')¶ +class torch.autograd.graph.save_on_cpu(pin_memory=False, device_type='cuda') ``` 在前向传递期间保存的张量将存储在 CPU 上,然后在反向传递时检索。 @@ -499,7 +499,7 @@ class torch.autograd.graph.save_on_cpu(pin_memory=False, device_type='cuda')¶ ``` ```py -class torch.autograd.graph.disable_saved_tensors_hooks(error_message)¶ +class torch.autograd.graph.disable_saved_tensors_hooks(error_message) ``` 禁用保存的张量默认钩子功能的上下文管理器。 @@ -521,7 +521,7 @@ class torch.autograd.graph.disable_saved_tensors_hooks(error_message)¶ ``` ```py -class torch.autograd.graph.register_multi_grad_hook(tensors, fn)¶ +class torch.autograd.graph.register_multi_grad_hook(tensors, fn) ``` 注册一个多梯度反向钩子。 @@ -561,7 +561,7 @@ class torch.autograd.graph.register_multi_grad_hook(tensors, fn)¶ ``` ```py -class torch.autograd.graph.allow_mutation_on_saved_tensors¶ +class torch.autograd.graph.allow_mutation_on_saved_tensors ``` 允许变异保存用于反向传播的张量的上下文管理器。 @@ -592,13 +592,13 @@ tensor([[0.8415, 0.8415, 0.8415], ``` ```py -class torch.autograd.graph.GradientEdge(node, output_nr)¶ +class torch.autograd.graph.GradientEdge(node, output_nr) ``` 表示 autograd 图中给定梯度边缘的对象。要获取将计算给定张量梯度的梯度边缘,可以执行`edge = autograd.graph.get_gradient_edge(tensor)`。 ```py -torch.autograd.graph.get_gradient_edge(tensor)¶ +torch.autograd.graph.get_gradient_edge(tensor) ``` 获取给定张量的梯度的梯度边缘。 diff --git a/totrans/doc22_039.md b/totrans/doc22_039.md index a64a698a82e62776de95d6130b606ff986309c2c..683a928ca6a7783b12bb6a1424c63dc184638d44 100644 --- a/totrans/doc22_039.md +++ b/totrans/doc22_039.md @@ -9,7 +9,7 @@ torch.library 是一组用于扩展 PyTorch 核心运算符库的 API。它包 使用`torch.library.define()`来定义新的自定义运算符。使用 impl 方法,例如`torch.library.impl()`和 func:torch.library.impl_abstract,为任何运算符添加实现(它们可以使用`torch.library.define()`创建,或通过 PyTorch 的 C++运算符注册 API 创建)。 ```py -torch.library.define(qualname, schema, *, lib=None, tags=())¶ +torch.library.define(qualname, schema, *, lib=None, tags=()) ``` ```py @@ -53,7 +53,7 @@ torch.library.define(lib, schema, alias_analysis='') ``` ```py -torch.library.impl(qualname, types, func=None, *, lib=None)¶ +torch.library.impl(qualname, types, func=None, *, lib=None) ``` ```py @@ -94,7 +94,7 @@ torch.library.impl(lib, name, dispatch_key='') ``` ```py -torch.library.impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1)¶ +torch.library.impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1) ``` 为此运算符注册一个抽象实现。 @@ -153,7 +153,7 @@ torch.library.impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1)¶ ``` ```py -torch.library.get_ctx()¶ +torch.library.get_ctx() ``` get_ctx()返回当前的 AbstractImplCtx 对象。 @@ -175,7 +175,7 @@ get_ctx()返回当前的 AbstractImplCtx 对象。 有关如何使用此 API 的一些示例的教程可在[Google Colab](https://colab.research.google.com/drive/1RRhSfk7So3Cn02itzLWE9K4Fam-8U011?usp=sharing)上找到。 ```py -class torch.library.Library(ns, kind, dispatch_key='')¶ +class torch.library.Library(ns, kind, dispatch_key='') ``` 一个用于创建库的类,可以用于注册新操作符或从 Python 中覆盖现有库中的操作符。用户可以选择传递调度键名称,如果他们只想注册与特定调度键对应的内核。 @@ -191,7 +191,7 @@ class torch.library.Library(ns, kind, dispatch_key='')¶ + **dispatch_key** – PyTorch 调度键(默认:“”) ```py -define(schema, alias_analysis='', *, tags=())¶ +define(schema, alias_analysis='', *, tags=()) ``` 在 ns 命名空间中定义一个新操作符及其语义。 @@ -216,7 +216,7 @@ define(schema, alias_analysis='', *, tags=())¶ ``` ```py -impl(op_name, fn, dispatch_key='')¶ +impl(op_name, fn, dispatch_key='') ``` 为库中定义的操作符注册函数实现。 @@ -239,7 +239,7 @@ impl(op_name, fn, dispatch_key='')¶ ``` ```py -torch.library.fallthrough_kernel()¶ +torch.library.fallthrough_kernel() ``` 一个虚拟函数,传递给`Library.impl`以注册一个默认情况。 diff --git a/totrans/doc22_042.md b/totrans/doc22_042.md index f8a46ec9f026ab4f00c8a926d44e174c122e4d19..068ce8ed84e120c098589913f0c65239f8de2c83 100644 --- a/totrans/doc22_042.md +++ b/totrans/doc22_042.md @@ -40,7 +40,7 @@ torch.cuda.memory._dump_snapshot("my_snapshot.pickle") # 快照 API 参考 ```py -torch.cuda.memory._record_memory_history(enabled='all', context='all', stacks='all', max_entries=9223372036854775807, device=None)¶ +torch.cuda.memory._record_memory_history(enabled='all', context='all', stacks='all', max_entries=9223372036854775807, device=None) ``` 启用与内存分配相关的堆栈跟踪记录,这样您就可以知道`torch.cuda.memory._snapshot()`中分配了哪些内存片段。 @@ -64,7 +64,7 @@ C++跟踪收集也很快(~50ns/帧),对于许多典型程序来说,每 + **max_entries**([*int*](https://docs.python.org/3/library/functions.html#int),“可选”) - 在记录的历史记录中保留最多 max_entries 个分配/释放事件。 ```py -torch.cuda.memory._snapshot(device=None)¶ +torch.cuda.memory._snapshot(device=None) ``` 在调用时保存 CUDA 内存状态的快照。 @@ -142,7 +142,7 @@ class TraceEntry(TypedDict): 快照字典对象 ```py -torch.cuda.memory._dump_snapshot(filename='dump_snapshot.pickle')¶ +torch.cuda.memory._dump_snapshot(filename='dump_snapshot.pickle') ``` 将 torch.memory._snapshot()字典的 pickled 版本保存到文件中。 diff --git a/totrans/doc22_044.md b/totrans/doc22_044.md index 876d784bc2495caf5df35798ee4a880128d87899..6ffcc741235df50f645442e253d2a11fad8f06f4 100644 --- a/totrans/doc22_044.md +++ b/totrans/doc22_044.md @@ -27,7 +27,7 @@ torch.backends 控制 PyTorch 支持的各种后端的行为。 ## torch.backends.cpu ```py -torch.backends.cpu.get_cpu_capability()¶ +torch.backends.cpu.get_cpu_capability() ``` 返回 CPU 能力作为字符串值。 @@ -39,7 +39,7 @@ torch.backends.cpu.get_cpu_capability()¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") ## torch.backends.cuda ```py -torch.backends.cuda.is_built()¶ +torch.backends.cuda.is_built() ``` 返回 PyTorch 是否构建有 CUDA 支持。 @@ -47,49 +47,49 @@ torch.backends.cuda.is_built()¶ 请注意,这并不一定意味着 CUDA 可用;只是如果在具有工作 CUDA 驱动程序和设备的机器上运行此 PyTorch 二进制文件,我们将能够使用它。 ```py -torch.backends.cuda.matmul.allow_tf32¶ +torch.backends.cuda.matmul.allow_tf32 ``` 一个控制在安培或更新的 GPU 上是否可以使用 TensorFloat-32 张量核心进行矩阵乘法的布尔值。请参阅 Ampere(以及更高版本)设备上的 TensorFloat-32(TF32)。 ```py -torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction¶ +torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction ``` 一个控制是否允许使用减少精度的规约(例如,使用 fp16 累积类型)与 fp16 GEMM 一起使用的布尔值。 ```py -torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction¶ +torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction ``` 一个控制是否允许使用 bf16 GEMM 的减少精度规约的布尔值。 ```py -torch.backends.cuda.cufft_plan_cache¶ +torch.backends.cuda.cufft_plan_cache ``` `cufft_plan_cache`包含每个 CUDA 设备的 cuFFT 计划缓存。通过 torch.backends.cuda.cufft_plan_cache[i]查询特定设备 i 的缓存。 ```py -torch.backends.cuda.cufft_plan_cache.size¶ +torch.backends.cuda.cufft_plan_cache.size ``` 一个只读[`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"),显示 cuFFT 计划缓存中当前计划的数量。 ```py -torch.backends.cuda.cufft_plan_cache.max_size¶ +torch.backends.cuda.cufft_plan_cache.max_size ``` 一个[`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"),控制 cuFFT 计划缓存的容量。 ```py -torch.backends.cuda.cufft_plan_cache.clear()¶ +torch.backends.cuda.cufft_plan_cache.clear() ``` 清除 cuFFT 计划缓存。 ```py -torch.backends.cuda.preferred_linalg_library(backend=None)¶ +torch.backends.cuda.preferred_linalg_library(backend=None) ``` 覆盖 PyTorch 用于在 CUDA 线性代数操作中选择 cuSOLVER 和 MAGMA 之间的启发式。 @@ -147,19 +147,19 @@ torch.backends.cuda.preferred_linalg_library(backend=None)¶ *_LinalgBackend* ```py -torch.backends.cuda.SDPBackend¶ +torch.backends.cuda.SDPBackend ``` 别名为 `_SDPBackend` ```py -torch.backends.cuda.SDPAParams¶ +torch.backends.cuda.SDPAParams ``` 别名为 `_SDPAParams` ```py -torch.backends.cuda.flash_sdp_enabled()¶ +torch.backends.cuda.flash_sdp_enabled() ``` 警告 @@ -169,7 +169,7 @@ torch.backends.cuda.flash_sdp_enabled()¶ 返回 flash 缩放点积注意力是否已启用。 ```py -torch.backends.cuda.enable_mem_efficient_sdp(enabled)¶ +torch.backends.cuda.enable_mem_efficient_sdp(enabled) ``` 警告 @@ -179,7 +179,7 @@ torch.backends.cuda.enable_mem_efficient_sdp(enabled)¶ 启用或禁用内存高效的缩放点积注意力。 ```py -torch.backends.cuda.mem_efficient_sdp_enabled()¶ +torch.backends.cuda.mem_efficient_sdp_enabled() ``` 警告 @@ -189,7 +189,7 @@ torch.backends.cuda.mem_efficient_sdp_enabled()¶ 返回内存高效的缩放点积注意力是否已启用。 ```py -torch.backends.cuda.enable_flash_sdp(enabled)¶ +torch.backends.cuda.enable_flash_sdp(enabled) ``` 警告 @@ -199,7 +199,7 @@ torch.backends.cuda.enable_flash_sdp(enabled)¶ 启用或禁用 flash 缩放点积注意力。 ```py -torch.backends.cuda.math_sdp_enabled()¶ +torch.backends.cuda.math_sdp_enabled() ``` 警告 @@ -209,7 +209,7 @@ torch.backends.cuda.math_sdp_enabled()¶ 返回 math 缩放点积注意力是否已启用。 ```py -torch.backends.cuda.enable_math_sdp(enabled)¶ +torch.backends.cuda.enable_math_sdp(enabled) ``` 警告 @@ -219,7 +219,7 @@ torch.backends.cuda.enable_math_sdp(enabled)¶ 启用或禁用 math 缩放点积注意力。 ```py -torch.backends.cuda.can_use_flash_attention(params, debug=False)¶ +torch.backends.cuda.can_use_flash_attention(params, debug=False) ``` 检查是否可以在 scaled_dot_product_attention 中使用 FlashAttention。 @@ -243,7 +243,7 @@ torch.backends.cuda.can_use_flash_attention(params, debug=False)¶ 此函数依赖于 PyTorch 的 CUDA 版本。在非 CUDA 环境中将返回 False。 ```py -torch.backends.cuda.can_use_efficient_attention(params, debug=False)¶ +torch.backends.cuda.can_use_efficient_attention(params, debug=False) ``` 检查是否可以在 scaled_dot_product_attention 中使用 efficient_attention。 @@ -267,7 +267,7 @@ torch.backends.cuda.can_use_efficient_attention(params, debug=False)¶ 此函数依赖于 PyTorch 的 CUDA 版本。在非 CUDA 环境中将返回 False。 ```py -torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True)¶ +torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True) ``` 警告 @@ -277,49 +277,49 @@ torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_e 此上下文管理器可用于临时启用或禁用缩放点积注意力的三个后端之一。退出上下文管理器时,将恢复标志的先前状态。## torch.backends.cudnn[](#module-torch.backends.cudnn "Permalink to this heading") ```py -torch.backends.cudnn.version()¶ +torch.backends.cudnn.version() ``` 返回 cuDNN 的版本。 ```py -torch.backends.cudnn.is_available()¶ +torch.backends.cudnn.is_available() ``` 返回一个布尔值,指示当前是否可用 CUDNN。 ```py -torch.backends.cudnn.enabled¶ +torch.backends.cudnn.enabled ``` 一个控制 cuDNN 是否启用的 [`bool`](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")。 ```py -torch.backends.cudnn.allow_tf32¶ +torch.backends.cudnn.allow_tf32 ``` 一个[`bool`](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),控制在 Ampere 或更新的 GPU 上 cuDNN 卷积中是否可以使用 TensorFloat-32 张量核心。请参阅 Ampere(以及更高版本)设备上的 TensorFloat-32(TF32)。 ```py -torch.backends.cudnn.deterministic¶ +torch.backends.cudnn.deterministic ``` 一个[`bool`](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),如果为 True,则导致 cuDNN 仅使用确定性卷积算法。另请参阅`torch.are_deterministic_algorithms_enabled()`和`torch.use_deterministic_algorithms()`。 ```py -torch.backends.cudnn.benchmark¶ +torch.backends.cudnn.benchmark ``` 一个[`bool`](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),如果为 True,则导致 cuDNN 对多个卷积算法进行基准测试并选择最快的。 ```py -torch.backends.cudnn.benchmark_limit¶ +torch.backends.cudnn.benchmark_limit ``` 一个[`int`](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"),指定 torch.backends.cudnn.benchmark 为 True 时尝试的 cuDNN 卷积算法的最大数量。将 benchmark_limit 设置为零以尝试每个可用算法。请注意,此设置仅影响通过 cuDNN v8 API 分派的卷积。 ## torch.backends.mps[](#module-torch.backends.mps "跳转到此标题的永久链接") ```py -torch.backends.mps.is_available()¶ +torch.backends.mps.is_available() ``` 返回一个指示当前是否可用 MPS 的布尔值。 @@ -329,7 +329,7 @@ torch.backends.mps.is_available()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.backends.mps.is_built()¶ +torch.backends.mps.is_built() ``` 返回 PyTorch 是否构建有 MPS 支持。 @@ -341,13 +341,13 @@ torch.backends.mps.is_built()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ## torch.backends.mkl ```py -torch.backends.mkl.is_available()¶ +torch.backends.mkl.is_available() ``` 返回 PyTorch 是否构建有 MKL 支持。 ```py -class torch.backends.mkl.verbose(enable)¶ +class torch.backends.mkl.verbose(enable) ``` 按需 oneMKL 详细功能。 @@ -366,13 +366,13 @@ with torch.backends.mkl.verbose(torch.backends.mkl.VERBOSE_ON): **level** – 详细级别 - `VERBOSE_OFF`:禁用详细 - `VERBOSE_ON`:启用详细 ## torch.backends.mkldnn[](#module-torch.backends.mkldnn "跳转到此标题的永久链接") ```py -torch.backends.mkldnn.is_available()¶ +torch.backends.mkldnn.is_available() ``` 返回 PyTorch 是否构建有 MKL-DNN 支持。 ```py -class torch.backends.mkldnn.verbose(level)¶ +class torch.backends.mkldnn.verbose(level) ``` 按需 oneDNN(前 MKL-DNN)详细功能。 @@ -391,13 +391,13 @@ with torch.backends.mkldnn.verbose(torch.backends.mkldnn.VERBOSE_ON): **level** – 详细级别 - `VERBOSE_OFF`:禁用详细 - `VERBOSE_ON`:启用详细 - `VERBOSE_ON_CREATION`:启用详细,包括 oneDNN 内核创建 ## torch.backends.openmp[](#module-torch.backends.openmp "跳转到此标题的永久链接") ```py -torch.backends.openmp.is_available()¶ +torch.backends.openmp.is_available() ``` 返回 PyTorch 是否构建有 OpenMP 支持。 ## torch.backends.opt_einsum[](#module-torch.backends.opt_einsum "跳转到此标题") ```py -torch.backends.opt_einsum.is_available()¶ +torch.backends.opt_einsum.is_available() ``` 返回一个指示 opt_einsum 当前是否可用的 bool 值。 @@ -407,7 +407,7 @@ torch.backends.opt_einsum.is_available()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.backends.opt_einsum.get_opt_einsum()¶ +torch.backends.opt_einsum.get_opt_einsum() ``` 如果当前可用,则返回 opt_einsum 包,否则返回 None。 @@ -417,7 +417,7 @@ torch.backends.opt_einsum.get_opt_einsum()¶ [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(在 Python v3.12 中)") ```py -torch.backends.opt_einsum.enabled¶ +torch.backends.opt_einsum.enabled ``` 一个控制是否启用 opt_einsum 的`bool`(默认为`True`)。如果启用,torch.einsum 将使用 opt_einsum([`optimized-einsum.readthedocs.io/en/stable/path_finding.html`](https://optimized-einsum.readthedocs.io/en/stable/path_finding.html))来计算更快性能的最佳收缩路径。 @@ -425,7 +425,7 @@ torch.backends.opt_einsum.enabled¶ 如果 opt_einsum 不可用,torch.einsum 将退回到默认的从左到右的收缩路径。 ```py -torch.backends.opt_einsum.strategy¶ +torch.backends.opt_einsum.strategy ``` 一个指定当`torch.backends.opt_einsum.enabled`为`True`时要尝试哪些策略的`str`。默认情况下,torch.einsum 将尝试“auto”策略,但也支持“greedy”和“optimal”策略。请注意,“optimal”策略在尝试所有可能路径时与输入数量的阶乘成正比。在 opt_einsum 的文档中查看更多细节([`optimized-einsum.readthedocs.io/en/stable/path_finding.html`](https://optimized-einsum.readthedocs.io/en/stable/path_finding.html))。 ## torch.backends.xeon diff --git a/totrans/doc22_045.md b/totrans/doc22_045.md index b59c26feacf45ba5e18fec9a901aae4c0680915a..abc8dbdbda15bdf687facd5ef2a4b77083ca42aa 100644 --- a/totrans/doc22_045.md +++ b/totrans/doc22_045.md @@ -399,7 +399,7 @@ PyTorch 开发者深入了解 ## API 参考 ```py -torch.export.export(f, args, kwargs=None, *, constraints=None, dynamic_shapes=None, strict=True, preserve_module_call_signature=())¶ +torch.export.export(f, args, kwargs=None, *, constraints=None, dynamic_shapes=None, strict=True, preserve_module_call_signature=()) ``` `export()`接受任意的 Python 可调用对象(nn.Module、函数或方法)以及示例输入,并以 Ahead-of-Time(AOT)方式生成表示函数的张量计算的追踪图,随后可以使用不同的输入或序列化执行。追踪图(1)生成功能性 ATen 操作符集中的标准化操作符(以及任何用户指定的自定义操作符),(2)消除了所有 Python 控制流和数据结构(某些例外情况除外),(3)记录了为了证明这种标准化和控制流消除对未来输入是有效的所需的形状约束集。 @@ -459,7 +459,7 @@ dim = Dim("dim0_x", max=5) + 包含所有上述类型的`dict`、`list`、`tuple`、`namedtuple`和`OrderedDict`组成的(嵌套)数据结构。 ```py -torch.export.dynamic_dim(t, index)¶ +torch.export.dynamic_dim(t, index) ``` 警告 @@ -537,7 +537,7 @@ torch.export.dynamic_dim(t, index)¶ + 可以混合匹配上述所有类型,只要它们不表达冲突的要求 ```py -torch.export.save(ep, f, *, extra_files=None, opset_version=None)¶ +torch.export.save(ep, f, *, extra_files=None, opset_version=None) ``` 警告 @@ -581,7 +581,7 @@ torch.export.save(ep, 'exported_program.pt2', extra_files=extra_files) ``` ```py -torch.export.load(f, *, extra_files=None, expected_opset_version=None)¶ +torch.export.load(f, *, extra_files=None, expected_opset_version=None) ``` 警告 @@ -631,7 +631,7 @@ print(ep(torch.randn(5))) ``` ```py -torch.export.register_dataclass(cls)¶ +torch.export.register_dataclass(cls) ``` 将数据类注册为`torch.export.export()`的有效输入/输出类型。 @@ -663,7 +663,7 @@ print(ep) ``` ```py -torch.export.Dim(name, *, min=None, max=None)¶ +torch.export.Dim(name, *, min=None, max=None) ``` `Dim()`构造类似于具有范围的命名符号整数的类型。它可用于描述动态张量维度的多个可能值。请注意,同一张量的不同动态维度,或不同张量的动态维度,可以由相同类型描述。 @@ -681,13 +681,13 @@ torch.export.Dim(name, *, min=None, max=None)¶ 可以在张量的动态形状规范中使用的类型。 ```py -torch.export.dims(*names, min=None, max=None)¶ +torch.export.dims(*names, min=None, max=None) ``` 用于创建多个`Dim()`类型的工具。 ```py -class torch.export.Constraint(*args, **kwargs)¶ +class torch.export.Constraint(*args, **kwargs) ``` 警告 @@ -697,7 +697,7 @@ class torch.export.Constraint(*args, **kwargs)¶ 这代表了对输入张量维度的约束,例如,要求它们是完全多态的或在某个范围内。 ```py -class torch.export.ExportedProgram(root, graph, graph_signature, state_dict, range_constraints, equality_constraints, module_call_graph, example_inputs=None, verifier=None, tensor_constants=None)¶ +class torch.export.ExportedProgram(root, graph, graph_signature, state_dict, range_constraints, equality_constraints, module_call_graph, example_inputs=None, verifier=None, tensor_constants=None) ``` 从`export()`导出的程序的包。它包含一个表示张量计算的 torch.fx.Graph,一个包含所有提升参数和缓冲区的张量值的 state_dict,以及各种元数据。 @@ -707,7 +707,7 @@ class torch.export.ExportedProgram(root, graph, graph_signature, state_dict, ran 要对图进行转换,请使用`.module`属性来访问`torch.fx.GraphModule`。然后,您可以使用[FX 转换](https://pytorch.org/docs/stable/fx.html#writing-transformations)来重写图。之后,您可以简单地再次使用`export()`来构建一个正确的 ExportedProgram。 ```py -module(*, flat=True)¶ +module(*, flat=True) ``` 返回一个包含所有参数/缓冲区的自包含 GraphModule。 @@ -717,7 +717,7 @@ module(*, flat=True)¶ *模块* ```py -buffers()¶ +buffers() ``` 返回一个迭代器,遍历原始模块缓冲区。 @@ -731,7 +731,7 @@ buffers()¶ [*迭代器*](https://docs.python.org/3/library/typing.html#typing.Iterator "(在 Python v3.12 中)")[*张量*] ```py -named_buffers()¶ +named_buffers() ``` 返回一个迭代器,遍历原始模块缓冲区,同时产生缓冲区的名称和缓冲区本身。 @@ -745,7 +745,7 @@ named_buffers()¶ [*迭代器*](https://docs.python.org/3/library/typing.html#typing.Iterator "(在 Python v3.12 中)")[[*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), *张量*]] ```py -parameters()¶ +parameters() ``` 返回一个迭代器,遍历原始模块的参数。 @@ -759,7 +759,7 @@ parameters()¶ [*迭代器*](https://docs.python.org/3/library/typing.html#typing.Iterator "(在 Python v3.12 中)")[*参数*] ```py -named_parameters()¶ +named_parameters() ``` 返回一个迭代器,遍历原始模块参数,同时产生参数的名称和参数本身。 @@ -773,11 +773,11 @@ named_parameters()¶ [*迭代器*](https://docs.python.org/3/library/typing.html#typing.Iterator "(在 Python v3.12 中)")[[*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), *参数*]] ```py -class torch.export.ExportBackwardSignature(gradients_to_parameters: Dict[str, str], gradients_to_user_inputs: Dict[str, str], loss_output: str)¶ +class torch.export.ExportBackwardSignature(gradients_to_parameters: Dict[str, str], gradients_to_user_inputs: Dict[str, str], loss_output: str) ``` ```py -class torch.export.ExportGraphSignature(input_specs, output_specs)¶ +class torch.export.ExportGraphSignature(input_specs, output_specs) ``` `ExportGraphSignature` 模型化导出图的输入/输出签名,这是一个具有更强不变性保证的 fx.Graph。 @@ -851,35 +851,35 @@ ExportGraphSignature( ``` ```py -class torch.export.ModuleCallSignature(inputs: List[Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument]], outputs: List[Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument]], in_spec: torch.utils._pytree.TreeSpec, out_spec: torch.utils._pytree.TreeSpec)¶ +class torch.export.ModuleCallSignature(inputs: List[Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument]], outputs: List[Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument]], in_spec: torch.utils._pytree.TreeSpec, out_spec: torch.utils._pytree.TreeSpec) ``` ```py -class torch.export.ModuleCallEntry(fqn: str, signature: Union[torch.export.exported_program.ModuleCallSignature, NoneType] = None)¶ +class torch.export.ModuleCallEntry(fqn: str, signature: Union[torch.export.exported_program.ModuleCallSignature, NoneType] = None) ``` ```py -class torch.export.graph_signature.InputKind(value)¶ +class torch.export.graph_signature.InputKind(value) ``` 一个枚举。 ```py -class torch.export.graph_signature.InputSpec(kind: torch.export.graph_signature.InputKind, arg: Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument], target: Union[str, NoneType])¶ +class torch.export.graph_signature.InputSpec(kind: torch.export.graph_signature.InputKind, arg: Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument], target: Union[str, NoneType]) ``` ```py -class torch.export.graph_signature.OutputKind(value)¶ +class torch.export.graph_signature.OutputKind(value) ``` 一个枚举。 ```py -class torch.export.graph_signature.OutputSpec(kind: torch.export.graph_signature.OutputKind, arg: Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument], target: Union[str, NoneType])¶ +class torch.export.graph_signature.OutputSpec(kind: torch.export.graph_signature.OutputKind, arg: Union[torch.export.graph_signature.TensorArgument, torch.export.graph_signature.SymIntArgument, torch.export.graph_signature.ConstantArgument], target: Union[str, NoneType]) ``` ```py -class torch.export.graph_signature.ExportGraphSignature(input_specs, output_specs)¶ +class torch.export.graph_signature.ExportGraphSignature(input_specs, output_specs) ``` `ExportGraphSignature`模拟了导出图的输入/输出签名,这是一个具有更强不变性保证的 fx.Graph。 @@ -953,7 +953,7 @@ ExportGraphSignature( ``` ```py -replace_all_uses(old, new)¶ +replace_all_uses(old, new) ``` 在签名中用新名称替换所有旧名称的用法。 diff --git a/totrans/doc22_046.md b/totrans/doc22_046.md index 54a70b5979468594c1dac62084ac37698d786782..a141dbc3220cb0be585978f96a8cd5c42a87a14e 100644 --- a/totrans/doc22_046.md +++ b/totrans/doc22_046.md @@ -103,7 +103,7 @@ torch.distributed 包提供了 PyTorch 支持和通信原语,用于在一个 在调用任何其他方法之前,需要使用`torch.distributed.init_process_group()`或`torch.distributed.device_mesh.init_device_mesh()`函数初始化包。两者都会阻塞,直到所有进程都加入。 ```py -torch.distributed.is_available()¶ +torch.distributed.is_available() ``` 如果分布式包可用,则返回`True`。 @@ -115,7 +115,7 @@ torch.distributed.is_available()¶ [bool] ```py -torch.distributed.init_process_group(backend=None, init_method=None, timeout=None, world_size=-1, rank=-1, store=None, group_name='', pg_options=None)¶ +torch.distributed.init_process_group(backend=None, init_method=None, timeout=None, world_size=-1, rank=-1, store=None, group_name='', pg_options=None) ``` 初始化默认的分布式进程组。 @@ -157,7 +157,7 @@ torch.distributed.init_process_group(backend=None, init_method=None, timeout=Non 支持多个后端是实验性的。当前,当未指定后端时,将创建`gloo`和`nccl`后端。`gloo`后端将用于 CPU 张量的集合,`nccl`后端将用于 CUDA 张量的集合。可以通过传入格式为“:,:”的字符串来指定自定义后端,例如“cpu:gloo,cuda:custom_backend”。 ```py -torch.distributed.device_mesh.init_device_mesh(device_type, mesh_shape, *, mesh_dim_names=None)¶ +torch.distributed.device_mesh.init_device_mesh(device_type, mesh_shape, *, mesh_dim_names=None) ``` 根据 device_type、mesh_shape 和 mesh_dim_names 参数初始化一个 DeviceMesh。 @@ -198,7 +198,7 @@ DeviceMesh ``` ```py -torch.distributed.is_initialized()¶ +torch.distributed.is_initialized() ``` 检查默认进程组是否已初始化。 @@ -208,7 +208,7 @@ torch.distributed.is_initialized()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.distributed.is_mpi_available()¶ +torch.distributed.is_mpi_available() ``` 检查 MPI 后端是否可用。 @@ -218,7 +218,7 @@ torch.distributed.is_mpi_available()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.distributed.is_nccl_available()¶ +torch.distributed.is_nccl_available() ``` 检查 NCCL 后端是否可用。 @@ -228,7 +228,7 @@ torch.distributed.is_nccl_available()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.distributed.is_gloo_available()¶ +torch.distributed.is_gloo_available() ``` 检查 Gloo 后端是否可用。 @@ -238,7 +238,7 @@ torch.distributed.is_gloo_available()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.distributed.is_torchelastic_launched()¶ +torch.distributed.is_torchelastic_launched() ``` 检查此进程是否是使用`torch.distributed.elastic`(又名 torchelastic)启动的。 @@ -310,7 +310,7 @@ rank 0 的机器将用于建立所有连接。 一旦运行了`torch.distributed.init_process_group()`,就可以使用以下函数。要检查进程组是否已经初始化,请使用`torch.distributed.is_initialized()`。 ```py -class torch.distributed.Backend(name)¶ +class torch.distributed.Backend(name) ``` 用于后端的类似枚举的类。 @@ -326,7 +326,7 @@ class torch.distributed.Backend(name)¶ 条目`Backend.UNDEFINED`存在,但仅用作某些字段的初始值。用户既不应直接使用它,也不应假定其存在。 ```py -classmethod register_backend(name, func, extended_api=False, devices=None)¶ +classmethod register_backend(name, func, extended_api=False, devices=None) ``` 使用给定名称和实例化函数注册新后端。 @@ -348,7 +348,7 @@ classmethod register_backend(name, func, extended_api=False, devices=None)¶ 第三方后端支持是实验性的,可能会发生变化。 ```py -torch.distributed.get_backend(group=None)¶ +torch.distributed.get_backend(group=None) ``` 返回给定进程组的后端。 @@ -366,7 +366,7 @@ torch.distributed.get_backend(group=None)¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") ```py -torch.distributed.get_rank(group=None)¶ +torch.distributed.get_rank(group=None) ``` 返回提供的`group`中当前进程的等级,否则默认。 @@ -386,7 +386,7 @@ torch.distributed.get_rank(group=None)¶ [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") ```py -torch.distributed.get_world_size(group=None)¶ +torch.distributed.get_world_size(group=None) ``` 返回当前进程组中的进程数。 @@ -410,13 +410,13 @@ torch.distributed.get_world_size(group=None)¶ 分布式包带有一个分布式键值存储,可用于在组中的进程之间共享信息,以及在`torch.distributed.init_process_group()`中初始化分布式包(通过显式创建存储作为指定`init_method`的替代方法)。有 3 种键值存储选择:`TCPStore`,`FileStore`和`HashStore`。 ```py -class torch.distributed.Store¶ +class torch.distributed.Store ``` 所有存储实现的基类,例如 PyTorch 分布式提供的 3 个存储:(`TCPStore`,`FileStore`和`HashStore`)。 ```py -class torch.distributed.TCPStore¶ +class torch.distributed.TCPStore ``` 基于 TCP 的分布式键值存储实现。服务器存储保存数据,而客户端存储可以通过 TCP 连接到服务器存储并执行诸如`set()`(插入键值对)、`get()`(检索键值对)等操作。应始终初始化一个服务器存储,因为客户端存储将等待服务器建立连接。 @@ -454,7 +454,7 @@ class torch.distributed.TCPStore¶ ``` ```py -class torch.distributed.HashStore¶ +class torch.distributed.HashStore ``` 基于底层哈希映射的线程安全存储实现。此存储可以在同一进程中使用(例如,由其他线程),但不能跨进程使用。 @@ -470,7 +470,7 @@ class torch.distributed.HashStore¶ ``` ```py -class torch.distributed.FileStore¶ +class torch.distributed.FileStore ``` 使用文件存储底层键值对的存储实现。 @@ -493,7 +493,7 @@ class torch.distributed.FileStore¶ ``` ```py -class torch.distributed.PrefixStore¶ +class torch.distributed.PrefixStore ``` 对任何 3 个键值存储(`TCPStore`,`FileStore`和`HashStore`)的包装,将前缀添加到插入存储的每个键。 @@ -505,7 +505,7 @@ class torch.distributed.PrefixStore¶ + **store**(*torch.distributed.store*) - 形成底层键值存储的存储对象。 ```py -torch.distributed.Store.set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str) → None¶ +torch.distributed.Store.set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str) → None ``` 根据提供的`key`和`value`将键值对插入存储。如果`key`已经存在于存储中,则将旧值用新提供的`value`覆盖。 @@ -528,7 +528,7 @@ torch.distributed.Store.set(self: torch._C._distributed_c10d.Store, arg0: str, a ``` ```py -torch.distributed.Store.get(self: torch._C._distributed_c10d.Store, arg0: str) → bytes¶ +torch.distributed.Store.get(self: torch._C._distributed_c10d.Store, arg0: str) → bytes ``` 检索存储中与给定`key`关联的值。如果`key`不在存储中,则函数将等待`timeout`,在初始化存储时定义,然后抛出异常。 @@ -553,7 +553,7 @@ torch.distributed.Store.get(self: torch._C._distributed_c10d.Store, arg0: str) ``` ```py -torch.distributed.Store.add(self: torch._C._distributed_c10d.Store, arg0: str, arg1: int) → int¶ +torch.distributed.Store.add(self: torch._C._distributed_c10d.Store, arg0: str, arg1: int) → int ``` 对于给定的`key`,第一次调用`add`会在存储中创建与`key`关联的计数器,初始化为`amount`。后续使用相同`key`调用`add`会将计数器递增指定的`amount`。对已经通过`set()`在存储中设置的键调用`add()`将导致异常。 @@ -578,7 +578,7 @@ torch.distributed.Store.add(self: torch._C._distributed_c10d.Store, arg0: str, a ``` ```py -torch.distributed.Store.compare_set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str, arg2: str) → bytes¶ +torch.distributed.Store.compare_set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str, arg2: str) → bytes ``` 根据提供的`key`将键值对插入存储,并在插入之前执行`expected_value`和`desired_value`之间的比较。只有当存储中已经存在`key`的`expected_value`或`expected_value`为空字符串时,才会设置`desired_value`。 @@ -604,7 +604,7 @@ torch.distributed.Store.compare_set(self: torch._C._distributed_c10d.Store, arg0 ``` ```py -torch.distributed.Store.wait(*args, **kwargs)¶ +torch.distributed.Store.wait(*args, **kwargs) ``` 重载函数。 @@ -650,7 +650,7 @@ torch.distributed.Store.wait(*args, **kwargs)¶ ``` ```py -torch.distributed.Store.num_keys(self: torch._C._distributed_c10d.Store) → int¶ +torch.distributed.Store.num_keys(self: torch._C._distributed_c10d.Store) → int ``` 返回存储中设置的键数。请注意,此数字通常比`set()`和`add()`添加的键数多一个,因为一个键用于协调使用存储的所有工作进程。 @@ -676,7 +676,7 @@ torch.distributed.Store.num_keys(self: torch._C._distributed_c10d.Store) → int ``` ```py -torch.distributed.Store.delete_key(self: torch._C._distributed_c10d.Store, arg0: str) → bool¶ +torch.distributed.Store.delete_key(self: torch._C._distributed_c10d.Store, arg0: str) → bool ``` 从存储中删除与`key`关联的键值对。如果成功删除键,则返回 true,如果未成功删除,则返回 false。 @@ -708,7 +708,7 @@ torch.distributed.Store.delete_key(self: torch._C._distributed_c10d.Store, arg0: ``` ```py -torch.distributed.Store.set_timeout(self: torch._C._distributed_c10d.Store, arg0: datetime.timedelta) → None¶ +torch.distributed.Store.set_timeout(self: torch._C._distributed_c10d.Store, arg0: datetime.timedelta) → None ``` 设置存储的默认超时时间。此超时时间在初始化和`wait()`以及`get()`中使用。 @@ -734,7 +734,7 @@ torch.distributed.Store.set_timeout(self: torch._C._distributed_c10d.Store, arg0 默认情况下,集体操作在默认组(也称为全局组)上运行,并要求所有进程进入分布式函数调用。但是,某些工作负载可以从更精细的通信中受益。这就是分布式组发挥作用的地方。`new_group()`函数可用于创建新组,其中包含所有进程的任意子集。它返回一个不透明的组句柄,可以作为所有集体操作的`group`参数传递(集体操作是在某些众所周知的编程模式中交换信息的分布式函数)。 ```py -torch.distributed.new_group(ranks=None, timeout=None, backend=None, pg_options=None, use_local_synchronization=False)¶ +torch.distributed.new_group(ranks=None, timeout=None, backend=None, pg_options=None, use_local_synchronization=False) ``` 创建一个新的分布式组。 @@ -768,7 +768,7 @@ torch.distributed.new_group(ranks=None, timeout=None, backend=None, pg_options=N 注意:当每个排名创建多个重叠进程组时,`use_local_synchronization=True` 可能会导致死锁。为避免这种情况,请确保所有排名遵循相同的全局创建顺序。 ```py -torch.distributed.get_group_rank(group, global_rank)¶ +torch.distributed.get_group_rank(group, global_rank) ``` 将全局排名转换为组排名。 @@ -792,7 +792,7 @@ torch.distributed.get_group_rank(group, global_rank)¶ 注意:在默认进程组上调用此函数会返回身份 ```py -torch.distributed.get_global_rank(group, group_rank)¶ +torch.distributed.get_global_rank(group, group_rank) ``` 将组排名转换为全局排名。 @@ -816,7 +816,7 @@ torch.distributed.get_global_rank(group, group_rank)¶ 注意:在默认进程组上调用此函数会返回身份 ```py -torch.distributed.get_process_group_ranks(group)¶ +torch.distributed.get_process_group_ranks(group) ``` 获取与 `group` 关联的所有排名。 @@ -834,7 +834,7 @@ torch.distributed.get_process_group_ranks(group)¶ DeviceMesh 是一个更高级的抽象,管理进程组(或 NCCL 通信器)。它允许用户轻松创建节点间和节点内的进程组,而无需担心如何为不同的子进程组正确设置排名,并且它有助于轻松管理这些分布式进程组。`init_device_mesh()` 函数可用于创建新的 DeviceMesh,其中包含描述设备拓扑的网格形状。 ```py -class torch.distributed.device_mesh.DeviceMesh(device_type, mesh, *, mesh_dim_names=None, _init_process_groups=True)¶ +class torch.distributed.device_mesh.DeviceMesh(device_type, mesh, *, mesh_dim_names=None, _init_process_groups=True) ``` DeviceMesh 表示设备的网格,其中设备的布局可以表示为 n-d 维度数组,n-d 维度数组的每个值是默认进程组排名的全局 id。 @@ -876,7 +876,7 @@ DeviceMesh ## 点对点通信 ```py -torch.distributed.send(tensor, dst, group=None, tag=0)¶ +torch.distributed.send(tensor, dst, group=None, tag=0) ``` 同步发送张量。 @@ -892,7 +892,7 @@ torch.distributed.send(tensor, dst, group=None, tag=0)¶ + **tag**(*int*,可选)- 用于匹配发送和接收的标签 ```py -torch.distributed.recv(tensor, src=None, group=None, tag=0)¶ +torch.distributed.recv(tensor, src=None, group=None, tag=0) ``` 同步接收张量。 @@ -922,7 +922,7 @@ int + `wait()` - 将阻塞进程,直到操作完成。一旦返回,`is_completed()` 保证返回 True。 ```py -torch.distributed.isend(tensor, dst, group=None, tag=0)¶ +torch.distributed.isend(tensor, dst, group=None, tag=0) ``` 异步发送张量。 @@ -954,7 +954,7 @@ torch.distributed.isend(tensor, dst, group=None, tag=0)¶ 工作 ```py -torch.distributed.irecv(tensor, src=None, group=None, tag=0)¶ +torch.distributed.irecv(tensor, src=None, group=None, tag=0) ``` 异步接收张量。 @@ -982,7 +982,7 @@ torch.distributed.irecv(tensor, src=None, group=None, tag=0)¶ 工作 ```py -torch.distributed.batch_isend_irecv(p2p_op_list)¶ +torch.distributed.batch_isend_irecv(p2p_op_list) ``` 异步发送或接收一批张量,并返回请求列表。 @@ -1019,7 +1019,7 @@ tensor([0, 1]) # Rank 1 此外,如果此 API 是传递给`dist.P2POp`的`group`中的第一个集合调用,则`group`的所有等级必须参与此 API 调用;否则,行为是未定义的。如果此 API 调用不是`group`中的第一个集合调用,则允许涉及`group`的部分等级的批量 P2P 操作。 ```py -class torch.distributed.P2POp(op, tensor, peer, group=None, tag=0)¶ +class torch.distributed.P2POp(op, tensor, peer, group=None, tag=0) ``` 用于构建`batch_isend_irecv`的点对点操作的类。 @@ -1078,7 +1078,7 @@ if rank == 0: ## 集合函数 ```py -torch.distributed.broadcast(tensor, src, group=None, async_op=False)¶ +torch.distributed.broadcast(tensor, src, group=None, async_op=False) ``` 将张量广播到整个组。 @@ -1098,7 +1098,7 @@ torch.distributed.broadcast(tensor, src, group=None, async_op=False)¶ 异步工作句柄,如果 async_op 设置为 True。如果不是 async_op 或不是组的一部分,则为 None ```py -torch.distributed.broadcast_object_list(object_list, src=0, group=None, device=None)¶ +torch.distributed.broadcast_object_list(object_list, src=0, group=None, device=None) ``` 将`object_list`中的可 picklable 对象广播到整个组。 @@ -1153,7 +1153,7 @@ torch.distributed.broadcast_object_list(object_list, src=0, group=None, device=N ``` ```py -torch.distributed.all_reduce(tensor, op=, group=None, async_op=False)¶ +torch.distributed.all_reduce(tensor, op=, group=None, async_op=False) ``` 在所有机器上减少张量数据,以便所有人都获得最终结果。 @@ -1199,7 +1199,7 @@ tensor([4.+4.j, 6.+6.j]) # Rank 1 ``` ```py -torch.distributed.reduce(tensor, dst, op=, group=None, async_op=False)¶ +torch.distributed.reduce(tensor, dst, op=, group=None, async_op=False) ``` 在所有机器上减少张量数据。 @@ -1223,7 +1223,7 @@ torch.distributed.reduce(tensor, dst, op=, group=None, async_o 异步工作句柄,如果 async_op 设置为 True。如果不是 async_op 或不是组的一部分,则为 None ```py -torch.distributed.all_gather(tensor_list, tensor, group=None, async_op=False)¶ +torch.distributed.all_gather(tensor_list, tensor, group=None, async_op=False) ``` 从整个组中收集张量到列表中。 @@ -1279,7 +1279,7 @@ tensor([3.+3.j, 4.+4.j]) # Rank 1 ``` ```py -torch.distributed.all_gather_into_tensor(output_tensor, input_tensor, group=None, async_op=False)¶ +torch.distributed.all_gather_into_tensor(output_tensor, input_tensor, group=None, async_op=False) ``` 从所有等级中收集张量并将它们放入单个输出张量中。 @@ -1329,7 +1329,7 @@ tensor([[1, 2], Gloo 后端不支持此 API。 ```py -torch.distributed.all_gather_object(object_list, obj, group=None)¶ +torch.distributed.all_gather_object(object_list, obj, group=None) ``` 从整个组中收集可 picklable 对象到列表中。 @@ -1378,7 +1378,7 @@ torch.distributed.all_gather_object(object_list, obj, group=None)¶ ``` ```py -torch.distributed.gather(tensor, gather_list=None, dst=0, group=None, async_op=False)¶ +torch.distributed.gather(tensor, gather_list=None, dst=0, group=None, async_op=False) ``` 在单个进程中收集张量列表。 @@ -1400,7 +1400,7 @@ torch.distributed.gather(tensor, gather_list=None, dst=0, group=None, async_op=F 如果 async_op 设置为 True,则为异步工作句柄。如果不是 async_op 或不是组的一部分,则为 None ```py -torch.distributed.gather_object(obj, object_gather_list=None, dst=0, group=None)¶ +torch.distributed.gather_object(obj, object_gather_list=None, dst=0, group=None) ``` 在单个进程中从整个组中收集可 pickle 的对象。 @@ -1456,7 +1456,7 @@ None。在 `dst` 等级上,`object_gather_list` 将包含集合的输出。 ``` ```py -torch.distributed.scatter(tensor, scatter_list=None, src=0, group=None, async_op=False)¶ +torch.distributed.scatter(tensor, scatter_list=None, src=0, group=None, async_op=False) ``` 将张量列表分散到组中的所有进程。 @@ -1507,7 +1507,7 @@ tensor([5., 5.]) ``` ```py -torch.distributed.scatter_object_list(scatter_object_output_list, scatter_object_input_list, src=0, group=None)¶ +torch.distributed.scatter_object_list(scatter_object_output_list, scatter_object_input_list, src=0, group=None) ``` 将`scatter_object_input_list`中的可 picklable 对象分散到整个组中。 @@ -1559,7 +1559,7 @@ torch.distributed.scatter_object_list(scatter_object_output_list, scatter_object ``` ```py -torch.distributed.reduce_scatter(output, input_list, op=, group=None, async_op=False)¶ +torch.distributed.reduce_scatter(output, input_list, op=, group=None, async_op=False) ``` 将张量列表减少,然后分散到组中的所有进程。 @@ -1581,7 +1581,7 @@ torch.distributed.reduce_scatter(output, input_list, op=, grou 如果 async_op 设置为 True,则为异步工作句柄。如果不是 async_op 或不是组的一部分,则为 None。 ```py -torch.distributed.reduce_scatter_tensor(output, input, op=, group=None, async_op=False)¶ +torch.distributed.reduce_scatter_tensor(output, input, op=, group=None, async_op=False) ``` 将张量减少,然后分散到组中的所有秩。 @@ -1634,7 +1634,7 @@ tensor([4, 6], device='cuda:1') # Rank 1 Gloo 后端不支持此 API。 ```py -torch.distributed.all_to_all_single(output, input, output_split_sizes=None, input_split_sizes=None, group=None, async_op=False)¶ +torch.distributed.all_to_all_single(output, input, output_split_sizes=None, input_split_sizes=None, group=None, async_op=False) ``` 拆分输入张量,然后将拆分列表分散到组中的所有进程。 @@ -1735,7 +1735,7 @@ tensor([4+4j, 8+8j, 12+12j, 16+16j]) # Rank 3 ``` ```py -torch.distributed.all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False)¶ +torch.distributed.all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False) ``` 将输入张量列表分散到组中的所有进程,并返回输出列表中收集的张量列表。 @@ -1837,7 +1837,7 @@ tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3 ``` ```py -torch.distributed.barrier(group=None, async_op=False, device_ids=None)¶ +torch.distributed.barrier(group=None, async_op=False, device_ids=None) ``` 同步所有进程。 @@ -1857,7 +1857,7 @@ torch.distributed.barrier(group=None, async_op=False, device_ids=None)¶ 如果 async_op 设置为 True,则返回异步工作句柄。如果不是 async_op 或者不是组的一部分,则返回 None。 ```py -torch.distributed.monitored_barrier(group=None, timeout=None, wait_all_ranks=False)¶ +torch.distributed.monitored_barrier(group=None, timeout=None, wait_all_ranks=False) ``` 类似于`torch.distributed.barrier`的进程同步,但考虑可配置的超时时间。 @@ -1898,7 +1898,7 @@ torch.distributed.monitored_barrier(group=None, timeout=None, wait_all_ranks=Fal ``` ```py -class torch.distributed.ReduceOp¶ +class torch.distributed.ReduceOp ``` 可用规约操作的类似枚举类:`SUM`、`PRODUCT`、`MIN`、`MAX`、`BAND`、`BOR`、`BXOR`和`PREMUL_SUM`。 @@ -1916,7 +1916,7 @@ class torch.distributed.ReduceOp¶ 此类不支持`__members__`属性。 ```py -class torch.distributed.reduce_op¶ +class torch.distributed.reduce_op ``` 已弃用的类似枚举的规约操作类:`SUM`、`PRODUCT`、`MIN`和`MAX`。 @@ -2272,25 +2272,25 @@ RuntimeError: Error when verifying shape tensors for collective ALLREDUCE on ran + torch.distributed.DistStoreError: 当存储遇到错误(例如:TCPStore 超时)时抛出此异常 ```py -class torch.distributed.DistError¶ +class torch.distributed.DistError ``` 在分布式库中发生错误时引发异常 ```py -class torch.distributed.DistBackendError¶ +class torch.distributed.DistBackendError ``` 在分布式中发生后端错误时引发异常 ```py -class torch.distributed.DistNetworkError¶ +class torch.distributed.DistNetworkError ``` 在分布式网络发生错误时引发异常 ```py -class torch.distributed.DistStoreError¶ +class torch.distributed.DistStoreError ``` 在分布式存储中发生错误时引发异常 @@ -2298,7 +2298,7 @@ class torch.distributed.DistStoreError¶ 如果您正在运行单节点训练,可能会方便地在脚本中交互式设置断点。我们提供了一种方便地在单个 rank 上设置断点的方法: ```py -torch.distributed.breakpoint(rank=0)¶ +torch.distributed.breakpoint(rank=0) ``` 设置断点,但仅在单个 rank 上。所有其他 rank 将等待您完成断点后继续。这在底层调用了`breakpoint()`,因此您可以使用正常的工具进行自定义,例如,`PYTHONBREAKPOINT`环境变量。 diff --git a/totrans/doc22_047.md b/totrans/doc22_047.md index 1564669791271092fc3ba156e0f4c82f3e414a9d..8704f1d0ef0de77eb4db1982664dccb0a157fa50 100644 --- a/totrans/doc22_047.md +++ b/totrans/doc22_047.md @@ -5,7 +5,7 @@ 通用加入上下文管理器促进了不均匀输入的分布式训练。本页概述了相关类的 API:`Join`、`Joinable`和`JoinHook`。有关教程,请参阅[使用加入上下文管理器进行不均匀输入的分布式训练](https://pytorch.org/tutorials/advanced/generic_join.html)。 ```py -class torch.distributed.algorithms.Join(joinables, enable=True, throw_on_early_termination=False, **kwargs)¶ +class torch.distributed.algorithms.Join(joinables, enable=True, throw_on_early_termination=False, **kwargs) ``` 此类定义了通用加入上下文管理器,允许在进程加入后调用自定义钩子。 @@ -55,7 +55,7 @@ class torch.distributed.algorithms.Join(joinables, enable=True, throw_on_early_t ``` ```py -static notify_join_context(joinable)¶ +static notify_join_context(joinable) ``` 通知加入上下文管理器,调用进程尚未加入。 @@ -75,7 +75,7 @@ static notify_join_context(joinable)¶ 一个用于全局归约的异步工作句柄,用于通知上下文管理器进程尚未加入,如果`joinable`是传递到上下文管理器的第一个;否则为`None`。 ```py -class torch.distributed.algorithms.Joinable¶ +class torch.distributed.algorithms.Joinable ``` 这为可加入类定义了一个抽象基类。 @@ -83,13 +83,13 @@ class torch.distributed.algorithms.Joinable¶ 一个可加入的类(从`Joinable`继承)应该实现`join_hook()`,它返回一个`JoinHook`实例,另外还应该实现`join_device()`和`join_process_group()`来分别返回设备和进程组信息。 ```py -abstract property join_device: device¶ +abstract property join_device: device ``` 返回执行加入上下文管理器所需的集体通信的设备。 ```py -abstract join_hook(**kwargs)¶ +abstract join_hook(**kwargs) ``` 为给定的`Joinable`返回一个`JoinHook`实例。 @@ -103,13 +103,13 @@ abstract join_hook(**kwargs)¶ *JoinHook* ```py -abstract property join_process_group: Any¶ +abstract property join_process_group: Any ``` 返回加入上下文管理器本身所需的集体通信的进程组。 ```py -class torch.distributed.algorithms.JoinHook¶ +class torch.distributed.algorithms.JoinHook ``` 这定义了一个加入钩子,在加入上下文管理器中提供了两个入口点。 @@ -119,7 +119,7 @@ class torch.distributed.algorithms.JoinHook¶ 要为通用加入上下文管理器实现一个加入钩子,需要定义一个从`JoinHook`继承的类,并适当地重写`main_hook()`和`post_hook()`。 ```py -main_hook()¶ +main_hook() ``` 在训练迭代中,当存在一个未加入的进程时调用此钩子以隐藏集体通信。 @@ -127,7 +127,7 @@ main_hook()¶ 训练迭代,即在一个前向传播、反向传播和优化器步骤中。 ```py -post_hook(is_last_joiner)¶ +post_hook(is_last_joiner) ``` 在所有进程都已加入后调用钩子。 diff --git a/totrans/doc22_049.md b/totrans/doc22_049.md index 9ac081c62b1f0384ebfeb3289164731406e2937e..2fb0fd52a5b699bf1b5a391535a3d7fc3dc8bab7 100644 --- a/totrans/doc22_049.md +++ b/totrans/doc22_049.md @@ -3,7 +3,7 @@ > 原文:[`pytorch.org/docs/stable/fsdp.html`](https://pytorch.org/docs/stable/fsdp.html) ```py -class torch.distributed.fsdp.FullyShardedDataParallel(module, process_group=None, sharding_strategy=None, cpu_offload=None, auto_wrap_policy=None, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, mixed_precision=None, ignored_modules=None, param_init_fn=None, device_id=None, sync_module_states=False, forward_prefetch=False, limit_all_gathers=True, use_orig_params=False, ignored_states=None, device_mesh=None)¶ +class torch.distributed.fsdp.FullyShardedDataParallel(module, process_group=None, sharding_strategy=None, cpu_offload=None, auto_wrap_policy=None, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, mixed_precision=None, ignored_modules=None, param_init_fn=None, device_id=None, sync_module_states=False, forward_prefetch=False, limit_all_gathers=True, use_orig_params=False, ignored_states=None, device_mesh=None) ``` 用于在数据并行工作者之间分片模块参数的包装器。 @@ -147,7 +147,7 @@ FSDP 在前向和后向计算期间用`torch.Tensor`视图替换托管模块的 + **ignored_states**(*可选**[**Iterable**[**torch.nn.Parameter**]**]**,* *可选****Iterable**[*[*torch.nn.Module**]**]*)- 不受此 FSDP 实例管理的被忽略的参数或模块,这意味着参数未分片,它们的梯度未在等级之间减少。此参数与现有的`ignored_modules`参数统一,我们可能很快会弃用`ignored_modules`。为了向后兼容,我们保留`ignored_states`和`ignored_modules`,但是 FSDP 只允许其中一个被指定为非`None`。 ```py -apply(fn)¶ +apply(fn) ``` 递归地将`fn`应用于每个子模块(由`.children()`返回)以及自身。 @@ -169,7 +169,7 @@ self Module ```py -check_is_root()¶ +check_is_root() ``` 检查此实例是否为根 FSDP 模块。 @@ -179,7 +179,7 @@ check_is_root()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") ```py -clip_grad_norm_(max_norm, norm_type=2.0)¶ +clip_grad_norm_(max_norm, norm_type=2.0) ``` 裁剪所有参数的梯度规范。 @@ -217,7 +217,7 @@ clip_grad_norm_(max_norm, norm_type=2.0)¶ 由于使用集体通信,因此需要在所有秩上调用此函数。 ```py -static flatten_sharded_optim_state_dict(sharded_optim_state_dict, model, optim)¶ +static flatten_sharded_optim_state_dict(sharded_optim_state_dict, model, optim) ``` 展平分片的优化器状态字典。 @@ -241,7 +241,7 @@ API 类似于`shard_full_optim_state_dict()`。唯一的区别是输入的`shard [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")] ```py -forward(*args, **kwargs)¶ +forward(*args, **kwargs) ``` 运行包装模块的前向传递,插入 FSDP 特定的前向和后向分片逻辑。 @@ -251,7 +251,7 @@ forward(*args, **kwargs)¶ [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)") ```py -static fsdp_modules(module, root_only=False)¶ +static fsdp_modules(module, root_only=False) ``` 返回所有嵌套的 FSDP 实例。 @@ -273,7 +273,7 @@ static fsdp_modules(module, root_only=False)¶ List[FullyShardedDataParallel] ```py -static full_optim_state_dict(model, optim, optim_input=None, rank0_only=True, group=None)¶ +static full_optim_state_dict(model, optim, optim_input=None, rank0_only=True, group=None) ``` 返回完整的优化器状态字典。 @@ -313,7 +313,7 @@ static full_optim_state_dict(model, optim, optim_input=None, rank0_only=True, gr Dict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), Any] ```py -static get_state_dict_type(module)¶ +static get_state_dict_type(module) ``` 获取根据`module`根模块的 FSDP 模块的 state_dict_type 和相应的配置。 @@ -335,13 +335,13 @@ static get_state_dict_type(module)¶ *StateDictSettings* ```py -property module: Module¶ +property module: Module ``` 返回包装的模块。 ```py -named_buffers(*args, **kwargs)¶ +named_buffers(*args, **kwargs) ``` 返回一个模块缓冲区的迭代器,同时产生缓冲区的名称和缓冲区本身。 @@ -353,7 +353,7 @@ named_buffers(*args, **kwargs)¶ [*Iterator*](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.12)")[[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), *Tensor*]] ```py -named_parameters(*args, **kwargs)¶ +named_parameters(*args, **kwargs) ``` 返回一个模块参数的迭代器,同时产生参数的名称和参数本身。 @@ -365,7 +365,7 @@ named_parameters(*args, **kwargs)¶ [*Iterator*](https://docs.python.org/3/library/typing.html#typing.Iterator "(在 Python v3.12 中)")[[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), *Parameter*]] ```py -no_sync()¶ +no_sync() ``` 禁用 FSDP 实例之间的梯度同步。 @@ -385,7 +385,7 @@ no_sync()¶ [*Generator*](https://docs.python.org/3/library/typing.html#typing.Generator "(在 Python v3.12 中)") ```py -static optim_state_dict(model, optim, optim_state_dict=None, group=None)¶ +static optim_state_dict(model, optim, optim_state_dict=None, group=None) ``` 转换与分片模型对应的优化器的状态字典。 @@ -451,7 +451,7 @@ static optim_state_dict(model, optim, optim_state_dict=None, group=None)¶ Dict[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), Any] ```py -static optim_state_dict_to_load(model, optim, optim_state_dict, is_named_optimizer=False, load_directly=False, group=None)¶ +static optim_state_dict_to_load(model, optim, optim_state_dict, is_named_optimizer=False, load_directly=False, group=None) ``` 将优化器状态字典转换为可以加载到与 FSDP 模型关联的优化器中的格式。 @@ -514,7 +514,7 @@ static optim_state_dict_to_load(model, optim, optim_state_dict, is_named_optimiz [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")] ```py -register_comm_hook(state, hook)¶ +register_comm_hook(state, hook) ``` 注册通信钩子。 @@ -534,7 +534,7 @@ register_comm_hook(state, hook)¶ + **hook** (*Callable*) – 可调用函数,具有以下签名之一:1) `hook: Callable[torch.Tensor] -> None`:此函数接受一个 Python 张量,表示与此 FSDP 单元包装的模型对应的所有变量的全面、扁平化、未分片梯度(未被其他 FSDP 子单元包装)。然后执行所有必要的处理并返回`None`;2) `hook: Callable[torch.Tensor, torch.Tensor] -> None`:此函数接受两个 Python 张量,第一个表示与此 FSDP 单元包装的模型对应的所有变量的全面、扁平化、未分片梯度(未被其他 FSDP 子单元包装)。后者表示一个预先大小的张量,用于存储分片梯度的一部分。在这两种情况下,可调用函数执行所有必要的处理并返回`None`。具有签名 1 的可调用函数应处理 NO_SHARD 情况的梯度通信。具有签名 2 的可调用函数应处理分片情况的梯度通信。 ```py -static rekey_optim_state_dict(optim_state_dict, optim_state_key_type, model, optim_input=None, optim=None)¶ +static rekey_optim_state_dict(optim_state_dict, optim_state_key_type, model, optim_input=None, optim=None) ``` 重新调整优化器状态字典`optim_state_dict`以使用键类型`optim_state_key_type`。 @@ -571,7 +571,7 @@ static rekey_optim_state_dict(optim_state_dict, optim_state_key_type, model, opt 字典[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), Any] ```py -static scatter_full_optim_state_dict(full_optim_state_dict, model, optim_input=None, optim=None, group=None)¶ +static scatter_full_optim_state_dict(full_optim_state_dict, model, optim_input=None, optim=None, group=None) ``` 将来自排名 0 的完整优化器状态字典分散到所有其他排名。 @@ -615,7 +615,7 @@ static scatter_full_optim_state_dict(full_optim_state_dict, model, optim_input=N Dict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), Any] ```py -static set_state_dict_type(module, state_dict_type, state_dict_config=None, optim_state_dict_config=None)¶ +static set_state_dict_type(module, state_dict_type, state_dict_config=None, optim_state_dict_config=None) ``` 设置目标模块的所有后代 FSDP 模块的`state_dict_type`。 @@ -663,7 +663,7 @@ static set_state_dict_type(module, state_dict_type, state_dict_config=None, opti *StateDictSettings* ```py -static shard_full_optim_state_dict(full_optim_state_dict, model, optim_input=None, optim=None)¶ +static shard_full_optim_state_dict(full_optim_state_dict, model, optim_input=None, optim=None) ``` 分片完整的优化器状态字典。 @@ -707,7 +707,7 @@ static shard_full_optim_state_dict(full_optim_state_dict, model, optim_input=Non 字典[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), Any] ```py -static sharded_optim_state_dict(model, optim, group=None)¶ +static sharded_optim_state_dict(model, optim, group=None) ``` 以其分片形式返回优化器状态字典。 @@ -725,7 +725,7 @@ API 类似于`full_optim_state_dict()`,但此 API 将所有非零维状态分 [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")] ```py -static state_dict_type(module, state_dict_type, state_dict_config=None, optim_state_dict_config=None)¶ +static state_dict_type(module, state_dict_type, state_dict_config=None, optim_state_dict_config=None) ``` 设置目标模块的所有后代 FSDP 模块的`state_dict_type`。 @@ -754,7 +754,7 @@ static state_dict_type(module, state_dict_type, state_dict_config=None, optim_st [*生成器*](https://docs.python.org/3/library/typing.html#typing.Generator "(在 Python v3.12 中)") ```py -static summon_full_params(module, recurse=True, writeback=True, rank0_only=False, offload_to_cpu=False, with_grads=False)¶ +static summon_full_params(module, recurse=True, writeback=True, rank0_only=False, offload_to_cpu=False, with_grads=False) ``` 使用此上下文管理器为 FSDP 实例公开完整参数。 @@ -806,7 +806,7 @@ static summon_full_params(module, recurse=True, writeback=True, rank0_only=False [*生成器*](https://docs.python.org/3/library/typing.html#typing.Generator "(在 Python v3.12 版本)") ```py -class torch.distributed.fsdp.BackwardPrefetch(value)¶ +class torch.distributed.fsdp.BackwardPrefetch(value) ``` 这配置了显式的向后预取,通过在向后传递中启用通信和计算重叠来提高吞吐量,但会略微增加内存使用量。 @@ -820,7 +820,7 @@ class torch.distributed.fsdp.BackwardPrefetch(value)¶ 更多技术背景:对于使用 NCCL 后端的单个进程组,任何集合,即使从不同流发出,也会争夺相同的每个设备 NCCL 流,这意味着发出集合的相对顺序对于重叠很重要。两个向后预取值对应不同的发出顺序。 ```py -class torch.distributed.fsdp.ShardingStrategy(value)¶ +class torch.distributed.fsdp.ShardingStrategy(value) ``` 这指定了由`FullyShardedDataParallel`用于分布式训练的分片策略。 @@ -836,7 +836,7 @@ class torch.distributed.fsdp.ShardingStrategy(value)¶ + `_HYBRID_SHARD_ZERO2`:在节点内应用`SHARD_GRAD_OP`,并在节点之间复制参数。这类似于`HYBRID_SHARD`,不同之处在于在前向传递后不释放未分片参数,从而节省了前向传递中的所有收集操作。 ```py -class torch.distributed.fsdp.MixedPrecision(param_dtype=None, reduce_dtype=None, buffer_dtype=None, keep_low_precision_grads=False, cast_forward_inputs=False, cast_root_forward_inputs=True, _module_classes_to_ignore=(, ))¶ +class torch.distributed.fsdp.MixedPrecision(param_dtype=None, reduce_dtype=None, buffer_dtype=None, keep_low_precision_grads=False, cast_forward_inputs=False, cast_root_forward_inputs=True, _module_classes_to_ignore=(, )) ``` 这配置了 FSDP 本机混合精度训练。 @@ -902,7 +902,7 @@ class torch.distributed.fsdp.MixedPrecision(param_dtype=None, reduce_dtype=None, 上面展示了一个工作示例。另一方面,如果 `model[1]` 被替换为 `model[0]`,意味着使用不同 `MixedPrecision` 的子模块先运行其前向传播,那么 `model[1]` 将错误地看到 `float16` 激活而不是 `bfloat16` 的激活。 ```py -class torch.distributed.fsdp.CPUOffload(offload_params=False)¶ +class torch.distributed.fsdp.CPUOffload(offload_params=False) ``` 这配置了 CPU 卸载。 @@ -912,7 +912,7 @@ class torch.distributed.fsdp.CPUOffload(offload_params=False)¶ **offload_params** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – 这指定是否在计算中未涉及时将参数卸载到 CPU。如果为 `True`,则梯度也会被卸载到 CPU,这意味着优化器步骤在 CPU 上运行。 ```py -class torch.distributed.fsdp.StateDictConfig(offload_to_cpu=False)¶ +class torch.distributed.fsdp.StateDictConfig(offload_to_cpu=False) ``` `StateDictConfig` 是所有 `state_dict` 配置类的基类。用户应该实例化一个子类(例如 `FullStateDictConfig`)以配置由 FSDP 支持的相应 `state_dict` 类型的设置。 @@ -922,7 +922,7 @@ class torch.distributed.fsdp.StateDictConfig(offload_to_cpu=False)¶ **offload_to_cpu** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – 如果为 `True`,则 FSDP 将状态字典值卸载到 CPU,如果为 `False`,则 FSDP 保留在 GPU 上。(默认值:`False`) ```py -class torch.distributed.fsdp.FullStateDictConfig(offload_to_cpu=False, rank0_only=False)¶ +class torch.distributed.fsdp.FullStateDictConfig(offload_to_cpu=False, rank0_only=False) ``` `FullStateDictConfig` 是一个配置类,用于与 `StateDictType.FULL_STATE_DICT` 一起使用。我们建议在保存完整状态字典时分别启用 `offload_to_cpu=True` 和 `rank0_only=True`,以节省 GPU 内存和 CPU 内存。这个配置类应该通过 `state_dict_type()` 上下文管理器来使用,如下所示: @@ -951,7 +951,7 @@ class torch.distributed.fsdp.FullStateDictConfig(offload_to_cpu=False, rank0_onl **rank0_only** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – 如果为 `True`,则只有排名为 0 的进程保存完整状态字典,非零排名的进程保存一个空字典。如果为 `False`,则所有排名都保存完整状态字典。(默认值:`False`) ```py -class torch.distributed.fsdp.ShardedStateDictConfig(offload_to_cpu=False, _use_dtensor=False)¶ +class torch.distributed.fsdp.ShardedStateDictConfig(offload_to_cpu=False, _use_dtensor=False) ``` `ShardedStateDictConfig` 是一个配置类,用于与 `StateDictType.SHARDED_STATE_DICT` 一起使用。 @@ -965,11 +965,11 @@ class torch.distributed.fsdp.ShardedStateDictConfig(offload_to_cpu=False, _use_d `_use_dtensor`是`ShardedStateDictConfig`的私有字段,由 FSDP 用于确定状态字典值的类型。用户不应手动修改`_use_dtensor`。 ```py -class torch.distributed.fsdp.LocalStateDictConfig(offload_to_cpu: bool = False)¶ +class torch.distributed.fsdp.LocalStateDictConfig(offload_to_cpu: bool = False) ``` ```py -class torch.distributed.fsdp.OptimStateDictConfig(offload_to_cpu=True)¶ +class torch.distributed.fsdp.OptimStateDictConfig(offload_to_cpu=True) ``` `OptimStateDictConfig`是所有`optim_state_dict`配置类的基类。用户应该实例化一个子类(例如`FullOptimStateDictConfig`)以配置由 FSDP 支持的相应`optim_state_dict`类型的设置。 @@ -979,7 +979,7 @@ class torch.distributed.fsdp.OptimStateDictConfig(offload_to_cpu=True)¶ **offload_to_cpu**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")) - 如果为`True`,则 FSDP 将状态字典的张量值转移到 CPU,如果为`False`,则 FSDP 将其保留在原始设备上(即 GPU,除非启用了 CPU 卸载参数)。 (默认值:`True`) ```py -class torch.distributed.fsdp.FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=False)¶ +class torch.distributed.fsdp.FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=False) ``` 变量 @@ -987,7 +987,7 @@ class torch.distributed.fsdp.FullOptimStateDictConfig(offload_to_cpu=True, rank0 **rank0_only**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")) - 如果为`True`,则只有排名为 0 的进程保存完整的状态字典,非零排名的进程保存空字典。如果为`False`,则所有进程都保存完整的状态字典。(默认值:`False`) ```py -class torch.distributed.fsdp.ShardedOptimStateDictConfig(offload_to_cpu=True, _use_dtensor=False)¶ +class torch.distributed.fsdp.ShardedOptimStateDictConfig(offload_to_cpu=True, _use_dtensor=False) ``` `ShardedOptimStateDictConfig`是一个配置类,用于与`StateDictType.SHARDED_STATE_DICT`一起使用。 @@ -1001,9 +1001,9 @@ class torch.distributed.fsdp.ShardedOptimStateDictConfig(offload_to_cpu=True, _u `_use_dtensor`是`ShardedOptimStateDictConfig`的私有字段,由 FSDP 用于确定状态字典值的类型。用户不应手动修改`_use_dtensor`。 ```py -class torch.distributed.fsdp.LocalOptimStateDictConfig(offload_to_cpu: bool = False)¶ +class torch.distributed.fsdp.LocalOptimStateDictConfig(offload_to_cpu: bool = False) ``` ```py -class torch.distributed.fsdp.StateDictSettings(state_dict_type: torch.distributed.fsdp.api.StateDictType, state_dict_config: torch.distributed.fsdp.api.StateDictConfig, optim_state_dict_config: torch.distributed.fsdp.api.OptimStateDictConfig)¶ +class torch.distributed.fsdp.StateDictSettings(state_dict_type: torch.distributed.fsdp.api.StateDictType, state_dict_config: torch.distributed.fsdp.api.StateDictConfig, optim_state_dict_config: torch.distributed.fsdp.api.OptimStateDictConfig) ``` diff --git a/totrans/doc22_050.md b/totrans/doc22_050.md index 4ee542f8b53482daa5563ceeb74714bedc4a0f6f..6d06b9b43d40b8712d72ba5ad1ca054b1662c6e1 100644 --- a/totrans/doc22_050.md +++ b/totrans/doc22_050.md @@ -9,7 +9,7 @@ `torch.distributed.optim` 暴露了 DistributedOptimizer,它接受一个远程参数(`RRef`)的列表,并在参数所在的工作节点上本地运行优化器。分布式优化器可以使用任何本地优化器基类来在每个工作节点上应用梯度。 ```py -class torch.distributed.optim.DistributedOptimizer(optimizer_class, params_rref, *args, **kwargs)¶ +class torch.distributed.optim.DistributedOptimizer(optimizer_class, params_rref, *args, **kwargs) ``` DistributedOptimizer 接受分布在工作节点上的参数的远程引用,并为每个参数本地应用给定的优化器。 @@ -57,7 +57,7 @@ DistributedOptimizer 默认启用了启用了 TorchScript 的本地优化器, ``` ```py -step(context_id)¶ +step(context_id) ``` 执行单个优化步骤。 @@ -69,7 +69,7 @@ step(context_id)¶ **context_id** – 我们应该运行优化器步骤的自动求导上下文 id。 ```py -class torch.distributed.optim.PostLocalSGDOptimizer(optim, averager)¶ +class torch.distributed.optim.PostLocalSGDOptimizer(optim, averager) ``` 包装任意`torch.optim.Optimizer`并运行[后局部 SGD](https://arxiv.org/abs/1808.07217),此优化器在每一步都运行本地优化器。在热身阶段之后,它会定期平均参数,然后应用本地优化器。 @@ -121,7 +121,7 @@ class torch.distributed.optim.PostLocalSGDOptimizer(optim, averager)¶ ``` ```py -load_state_dict(state_dict)¶ +load_state_dict(state_dict) ``` 这与`torch.optim.Optimizer` `load_state_dict()`相同,但还将模型平均器的步骤值恢复为提供的`state_dict`中保存的值。 @@ -129,19 +129,19 @@ load_state_dict(state_dict)¶ 如果`state_dict`中没有`"step"`条目,它将引发警告并将模型平均器的步骤初始化为 0。 ```py -state_dict()¶ +state_dict() ``` 这与`torch.optim.Optimizer` `state_dict()`相同,但添加了一个额外的条目来记录模型平均器的步骤到检查点,以确保重新加载不会导致不必要的再次热身。 ```py -step()¶ +step() ``` 执行单个优化步骤(参数更新)。 ```py -class torch.distributed.optim.ZeroRedundancyOptimizer(params, optimizer_class, process_group=None, parameters_as_bucket_view=False, overlap_with_ddp=False, **defaults)¶ +class torch.distributed.optim.ZeroRedundancyOptimizer(params, optimizer_class, process_group=None, parameters_as_bucket_view=False, overlap_with_ddp=False, **defaults) ``` 将任意的`optim.Optimizer`包装起来,并将其状态在组中分片。 @@ -198,7 +198,7 @@ class torch.distributed.optim.ZeroRedundancyOptimizer(params, optimizer_class, p ZeroRedundancyOptimizer 是实验性的,可能会发生变化。 ```py -add_param_group(param_group)¶ +add_param_group(param_group) ``` 向`Optimizer`的`param_groups`添加一个参数组。 @@ -214,7 +214,7 @@ add_param_group(param_group)¶ 此方法处理所有分区上的碎片更新,但需要在所有等级上调用。在部分等级上调用此方法将导致训练挂起,因为通信原语是根据受管理的参数调用的,并且期望所有等级参与相同的参数集。 ```py -consolidate_state_dict(to=0)¶ +consolidate_state_dict(to=0) ``` 在目标等级上合并`state_dict`列表(每个等级一个)。 @@ -232,13 +232,13 @@ consolidate_state_dict(to=0)¶ 这需要在所有等级上调用。 ```py -property join_device: device¶ +property join_device: device ``` 返回默认设备。 ```py -join_hook(**kwargs)¶ +join_hook(**kwargs) ``` 返回 ZeRO 连接钩子。 @@ -254,13 +254,13 @@ join_hook(**kwargs)¶ 此钩子不支持任何关键字参数;即`kwargs`未使用。 ```py -property join_process_group: Any¶ +property join_process_group: Any ``` 返回进程组。 ```py -load_state_dict(state_dict)¶ +load_state_dict(state_dict) ``` 从输入`state_dict`中加载与给定等级相关的状态,根据需要更新本地优化器。 @@ -274,7 +274,7 @@ load_state_dict(state_dict)¶ [**RuntimeError**](https://docs.python.org/3/library/exceptions.html#RuntimeError) - 如果`overlap_with_ddp=True`,并且在此`ZeroRedundancyOptimizer`实例完全初始化之前调用此方法,这会在`DistributedDataParallel`梯度桶被重建后发生。 ```py -state_dict()¶ +state_dict() ``` 返回此等级已知的最后一个全局优化器状态。 @@ -288,7 +288,7 @@ state_dict()¶ [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*任意*](https://docs.python.org/3/library/typing.html#typing.Any "(在 Python v3.12 中)")] ```py -step(closure=None, **kwargs)¶ +step(closure=None, **kwargs) ``` 执行单个优化器步骤并同步所有排名的参数。 diff --git a/totrans/doc22_051.md b/totrans/doc22_051.md index b5130e8e411377baae7bb355ecc8000c0639f022..d30b2c5a3a609b9213bbc4c0b3635c4009f9691b 100644 --- a/totrans/doc22_051.md +++ b/totrans/doc22_051.md @@ -11,7 +11,7 @@ 使用张量并行并行化您的`nn.Module`的入口点是: ```py -torch.distributed.tensor.parallel.parallelize_module(module, device_mesh, parallelize_plan, tp_mesh_dim=0)¶ +torch.distributed.tensor.parallel.parallelize_module(module, device_mesh, parallelize_plan, tp_mesh_dim=0) ``` 通过根据用户指定的计划并行化模块或子模块来应用 PyTorch 中的张量并行。 @@ -60,7 +60,7 @@ torch.distributed.tensor.parallel.parallelize_module(module, device_mesh, parall 张量并行支持以下并行样式: ```py -class torch.distributed.tensor.parallel.ColwiseParallel(*, input_layouts=None, output_layouts=None, use_local_output=True)¶ +class torch.distributed.tensor.parallel.ColwiseParallel(*, input_layouts=None, output_layouts=None, use_local_output=True) ``` 以行方式对兼容的 nn.Module 进行分区。目前支持 nn.Linear 和 nn.Embedding。用户可以将其与 RowwiseParallel 组合在一起,以实现更复杂模块的分片(即 MLP、Attention) @@ -98,7 +98,7 @@ class torch.distributed.tensor.parallel.ColwiseParallel(*, input_layouts=None, o 默认情况下,如果未指定`output_layouts`,则`ColwiseParallel`输出在最后一个维度上进行分片,如果有需要特定张量形状的运算符(即在配对的`RowwiseParallel`之前),请记住,如果输出被分片,运算符可能需要调整为分片大小。 ```py -class torch.distributed.tensor.parallel.RowwiseParallel(*, input_layouts=None, output_layouts=None, use_local_output=True)¶ +class torch.distributed.tensor.parallel.RowwiseParallel(*, input_layouts=None, output_layouts=None, use_local_output=True) ``` 将兼容的 nn.Module 按行划分。目前仅支持 nn.Linear。用户可以将其与 ColwiseParallel 组合,以实现更复杂模块的分片(即 MLP,Attention) @@ -134,7 +134,7 @@ class torch.distributed.tensor.parallel.RowwiseParallel(*, input_layouts=None, o 要简单配置 nn.Module 的输入和输出以及执行必要的布局重分配,而不将模块参数分发到 DTensors,可以在`parallelize_module`的`parallelize_plan`中使用以下类: ```py -class torch.distributed.tensor.parallel.PrepareModuleInput(*, input_layouts, desired_input_layouts, use_local_output=False)¶ +class torch.distributed.tensor.parallel.PrepareModuleInput(*, input_layouts, desired_input_layouts, use_local_output=False) ``` 根据`input_layouts`配置 nn.Module 的输入,根据`desired_input_layouts`执行布局重分配,将 nn.Module 的输入张量转换为 DTensors。 @@ -171,7 +171,7 @@ class torch.distributed.tensor.parallel.PrepareModuleInput(*, input_layouts, des ``` ```py -class torch.distributed.tensor.parallel.PrepareModuleOutput(*, output_layouts, desired_output_layouts, use_local_output=True)¶ +class torch.distributed.tensor.parallel.PrepareModuleOutput(*, output_layouts, desired_output_layouts, use_local_output=True) ``` 根据`output_layouts`配置 nn.Module 的输出,根据`desired_output_layouts`执行布局重分配,将 nn.Module 的输出张量转换为 DTensors。 diff --git a/totrans/doc22_052.md b/totrans/doc22_052.md index e127978ac182ff39586c842c3456203b98b6da46..8442789679bb1ae94e52c78dbd8c7d2d2c7a5af7 100644 --- a/totrans/doc22_052.md +++ b/totrans/doc22_052.md @@ -13,7 +13,7 @@ DCP 与 torch.save 和 torch.load 在几个重要方面有所不同: 加载和保存检查点的入口点如下: ```py -torch.distributed.checkpoint.load(state_dict, storage_reader, *, process_group=None, coordinator_rank=0, no_dist=False, planner=None)¶ +torch.distributed.checkpoint.load(state_dict, storage_reader, *, process_group=None, coordinator_rank=0, no_dist=False, planner=None) ``` 以 SPMD 风格加载分布式`state_dict`。 @@ -80,7 +80,7 @@ torch.distributed.checkpoint.load(state_dict, storage_reader, *, process_group=N load_state_dict 使用集合来协调跨排读取。对于基于 NCCL 的进程组,对象的内部张量表示必须在通信发生之前移动到 GPU 设备。在这种情况下,使用的设备由`torch.cuda.current_device()`给出,用户有责任确保设置了这一点,以便每个排名都有一个独立的 GPU,通过`torch.cuda.set_device()`。 ```py -torch.distributed.checkpoint.save(state_dict, storage_writer, *, process_group=None, coordinator_rank=0, no_dist=False, planner=None)¶ +torch.distributed.checkpoint.save(state_dict, storage_writer, *, process_group=None, coordinator_rank=0, no_dist=False, planner=None) ``` 以 SPMD 风格保存分布式模型。 @@ -148,13 +148,13 @@ torch.distributed.checkpoint.save(state_dict, storage_writer, *, process_group=N save_state_dict 使用集合来协调跨等级的写入。对于基于 NCCL 的进程组,对象的内部张量表示必须在通信发生之前移动到 GPU 设备。在这种情况下,使用的设备由`torch.cuda.current_device()`给出,用户有责任确保设置正确,以便每个等级都有独立的 GPU,通过`torch.cuda.set_device()`。 ```py -torch.distributed.checkpoint.load_state_dict(state_dict, storage_reader, process_group=None, coordinator_rank=0, no_dist=False, planner=None)¶ +torch.distributed.checkpoint.load_state_dict(state_dict, storage_reader, process_group=None, coordinator_rank=0, no_dist=False, planner=None) ``` 此方法已弃用。请切换到“load”。 ```py -torch.distributed.checkpoint.save_state_dict(state_dict, storage_writer, process_group=None, coordinator_rank=0, no_dist=False, planner=None)¶ +torch.distributed.checkpoint.save_state_dict(state_dict, storage_writer, process_group=None, coordinator_rank=0, no_dist=False, planner=None) ``` 此方法已弃用。请切换到“save”。 @@ -166,13 +166,13 @@ torch.distributed.checkpoint.save_state_dict(state_dict, storage_writer, process 除了上述入口点外,如下所述的 Stateful 对象在保存/加载期间提供额外的定制化.. automodule:: torch.distributed.checkpoint.stateful ```py -class torch.distributed.checkpoint.stateful.Stateful(*args, **kwargs)¶ +class torch.distributed.checkpoint.stateful.Stateful(*args, **kwargs) ``` 可以进行检查点和恢复的具有状态的对象的 Stateful 协议。 ```py -load_state_dict(state_dict)¶ +load_state_dict(state_dict) ``` 从提供的 state_dict 中恢复对象的状态。 @@ -182,7 +182,7 @@ load_state_dict(state_dict)¶ **state_dict**([*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(在 Python v3.12 中)")*]*) - 要从中恢复的状态字典 ```py -state_dict()¶ +state_dict() ``` 对象应该将它们的 state_dict 表示作为字典返回。此函数的输出将被检查点,并稍后在 load_state_dict()中恢复。 @@ -204,7 +204,7 @@ state_dict()¶ 以下类型定义了检查点期间使用的 IO 接口: ```py -class torch.distributed.checkpoint.StorageReader¶ +class torch.distributed.checkpoint.StorageReader ``` `load_state_dict`用于从存储中读取的接口。 @@ -224,7 +224,7 @@ class torch.distributed.checkpoint.StorageReader¶ 1. (所有等级)read_data() ```py -abstract prepare_global_plan(plans)¶ +abstract prepare_global_plan(plans) ``` 执行存储加载的集中规划。 @@ -246,7 +246,7 @@ abstract prepare_global_plan(plans)¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[*LoadPlan*] ```py -abstract prepare_local_plan(plan)¶ +abstract prepare_local_plan(plan) ``` 执行特定于存储的本地规划。 @@ -266,7 +266,7 @@ abstract prepare_local_plan(plan)¶ *LoadPlan* ```py -abstract read_data(plan, planner)¶ +abstract read_data(plan, planner) ``` 使用`planner`从`plan`中读取所有项目以解析数据。 @@ -292,7 +292,7 @@ StorageLayer 有责任正确安排所需的任何跨设备复制。 *Future*[无] ```py -abstract read_metadata()¶ +abstract read_metadata() ``` 读取检查点元数据。 @@ -306,7 +306,7 @@ abstract read_metadata()¶ *元数据* ```py -abstract set_up_storage_reader(metadata, is_coordinator)¶ +abstract set_up_storage_reader(metadata, is_coordinator) ``` 初始化此实例。 @@ -318,7 +318,7 @@ abstract set_up_storage_reader(metadata, is_coordinator)¶ + **is_coordinator**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")) - 此实例是否负责协调检查点。 ```py -class torch.distributed.checkpoint.StorageWriter¶ +class torch.distributed.checkpoint.StorageWriter ``` `save_state_dict`用于写入存储的接口。 @@ -338,7 +338,7 @@ class torch.distributed.checkpoint.StorageWriter¶ 1. (协调器)完成() ```py -abstract finish(metadata, results)¶ +abstract finish(metadata, results) ``` 写入元数据并将当前检查点标记为成功。 @@ -360,7 +360,7 @@ abstract finish(metadata, results)¶ 无 ```py -abstract prepare_global_plan(plans)¶ +abstract prepare_global_plan(plans) ``` 执行存储的集中规划。 @@ -382,7 +382,7 @@ abstract prepare_global_plan(plans)¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[*SavePlan*] ```py -abstract prepare_local_plan(plan)¶ +abstract prepare_local_plan(plan) ``` 执行特定于存储的本地规划。 @@ -402,7 +402,7 @@ abstract prepare_local_plan(plan)¶ *SavePlan* ```py -abstract set_up_storage_writer(is_coordinator)¶ +abstract set_up_storage_writer(is_coordinator) ``` 初始化此实例。 @@ -412,7 +412,7 @@ abstract set_up_storage_writer(is_coordinator)¶ **is_coordinator**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")) - 此实例是否负责协调检查点。 ```py -abstract write_data(plan, planner)¶ +abstract write_data(plan, planner) ``` 使用`planner`解析数据,从`plan`中写入所有项目。 @@ -442,7 +442,7 @@ abstract write_data(plan, planner)¶ 以下类型定义了检查点期间使用的规划器接口: ```py -class torch.distributed.checkpoint.LoadPlanner¶ +class torch.distributed.checkpoint.LoadPlanner ``` 定义 load_state_dict 用于规划加载过程的协议的抽象类。 @@ -513,7 +513,7 @@ LoadPlanner 充当对 state_dict 的访问代理,因此对其进行的任何 ``` ```py -abstract commit_tensor(read_item, tensor)¶ +abstract commit_tensor(read_item, tensor) ``` 在 StorageReader 完成将数据加载到`tensor`后调用一次。 @@ -523,7 +523,7 @@ abstract commit_tensor(read_item, tensor)¶ 张量的内容将遵循其设备同步模型。 ```py -abstract create_global_plan(global_plan)¶ +abstract create_global_plan(global_plan) ``` 计算全局加载计划并返回每个等级的计划。 @@ -535,7 +535,7 @@ abstract create_global_plan(global_plan)¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[*LoadPlan*] ```py -abstract create_local_plan()¶ +abstract create_local_plan() ``` 根据 set_up_planner 提供的 state_dict 和元数据创建一个 LoadPlan。 @@ -547,7 +547,7 @@ abstract create_local_plan()¶ *LoadPlan* ```py -abstract finish_plan(central_plan)¶ +abstract finish_plan(central_plan) ``` 接受来自协调员的计划并返回最终的 LoadPlan。 @@ -557,7 +557,7 @@ abstract finish_plan(central_plan)¶ *LoadPlan* ```py -abstract load_bytes(read_item, value)¶ +abstract load_bytes(read_item, value) ``` 加载由`read_item``和``value`描述的项目。 @@ -567,7 +567,7 @@ abstract load_bytes(read_item, value)¶ `value`的内容由用于生成正在加载的检查点的 SavePlanner 定义。 ```py -abstract resolve_tensor(read_item)¶ +abstract resolve_tensor(read_item) ``` 返回由`read_item`描述的张量,以供 StorageReader 加载 read_item 使用。 @@ -579,7 +579,7 @@ abstract resolve_tensor(read_item)¶ *Tensor* ```py -abstract set_up_planner(state_dict, metadata, is_coordinator)¶ +abstract set_up_planner(state_dict, metadata, is_coordinator) ``` 初始化此实例以将数据加载到`state_dict`中。 @@ -587,15 +587,15 @@ abstract set_up_planner(state_dict, metadata, is_coordinator)¶ . 注意。这在每个等级上都会被调用。 ```py -class torch.distributed.checkpoint.LoadPlan(items: List[torch.distributed.checkpoint.planner.ReadItem], storage_data: Any = None, planner_data: Any = None)¶ +class torch.distributed.checkpoint.LoadPlan(items: List[torch.distributed.checkpoint.planner.ReadItem], storage_data: Any = None, planner_data: Any = None) ``` ```py -class torch.distributed.checkpoint.ReadItem(type: torch.distributed.checkpoint.planner.LoadItemType, dest_index: torch.distributed.checkpoint.metadata.MetadataIndex, dest_offsets: torch.Size, storage_index: torch.distributed.checkpoint.metadata.MetadataIndex, storage_offsets: torch.Size, lengths: torch.Size)¶ +class torch.distributed.checkpoint.ReadItem(type: torch.distributed.checkpoint.planner.LoadItemType, dest_index: torch.distributed.checkpoint.metadata.MetadataIndex, dest_offsets: torch.Size, storage_index: torch.distributed.checkpoint.metadata.MetadataIndex, storage_offsets: torch.Size, lengths: torch.Size) ``` ```py -class torch.distributed.checkpoint.SavePlanner¶ +class torch.distributed.checkpoint.SavePlanner ``` 定义由 save_state_dict 用于规划保存过程的协议的抽象类。 @@ -690,7 +690,7 @@ SavePlanner 充当对 state_dict 的访问代理,因此对其进行的任何 ``` ```py -abstract create_global_plan(all_plans)¶ +abstract create_global_plan(all_plans) ``` 计算全局检查点计划并返回每个等级的本地计划。 @@ -702,7 +702,7 @@ abstract create_global_plan(all_plans)¶ [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[*SavePlan*], *Metadata*] ```py -abstract create_local_plan()¶ +abstract create_local_plan() ``` 计算当前等级的保存计划。 @@ -716,7 +716,7 @@ abstract create_local_plan()¶ *SavePlan* ```py -abstract finish_plan(new_plan)¶ +abstract finish_plan(new_plan) ``` 合并由 create_local_plan 创建的计划和 create_global_plan 的结果。 @@ -728,7 +728,7 @@ abstract finish_plan(new_plan)¶ *SavePlan* ```py -abstract resolve_data(write_item)¶ +abstract resolve_data(write_item) ``` 转换和准备`state_dict`中的`write_item`以供存储,确保幂等性和线程安全。 @@ -748,7 +748,7 @@ abstract resolve_data(write_item)¶ [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")[*Tensor*, *BytesIO*] ```py -abstract set_up_planner(state_dict, is_coordinator)¶ +abstract set_up_planner(state_dict, is_coordinator) ``` 初始化此规划者以保存 `state_dict`。 @@ -758,21 +758,21 @@ abstract set_up_planner(state_dict, is_coordinator)¶ 这在所有秩上都被调用。 ```py -class torch.distributed.checkpoint.SavePlan(items: List[torch.distributed.checkpoint.planner.WriteItem], storage_data: Any = None, planner_data: Any = None)¶ +class torch.distributed.checkpoint.SavePlan(items: List[torch.distributed.checkpoint.planner.WriteItem], storage_data: Any = None, planner_data: Any = None) ``` ```py -class torch.distributed.checkpoint.WriteItem(index: torch.distributed.checkpoint.metadata.MetadataIndex, type: torch.distributed.checkpoint.planner.WriteItemType, tensor_data: Union[torch.distributed.checkpoint.planner.TensorWriteData, NoneType] = None)¶ +class torch.distributed.checkpoint.WriteItem(index: torch.distributed.checkpoint.metadata.MetadataIndex, type: torch.distributed.checkpoint.planner.WriteItemType, tensor_data: Union[torch.distributed.checkpoint.planner.TensorWriteData, NoneType] = None) ``` 我们提供了基于文件系统的存储层: ```py -class torch.distributed.checkpoint.FileSystemReader(path)¶ +class torch.distributed.checkpoint.FileSystemReader(path) ``` ```py -class torch.distributed.checkpoint.FileSystemWriter(path, single_file_per_rank=True, sync_files=True, thread_count=1, per_thread_copy_ahead=10000000)¶ +class torch.distributed.checkpoint.FileSystemWriter(path, single_file_per_rank=True, sync_files=True, thread_count=1, per_thread_copy_ahead=10000000) ``` 使用文件 IO 的 StorageWriter 的基本实现。 @@ -788,11 +788,11 @@ class torch.distributed.checkpoint.FileSystemWriter(path, single_file_per_rank=T 我们提供了默认的 LoadPlanner 和 SavePlanner 实现,可以处理所有 torch.distributed 构造,如 FSDP、DDP、ShardedTensor 和 DistributedTensor。 ```py -class torch.distributed.checkpoint.DefaultSavePlanner(flatten_state_dict=True, flatten_sharded_tensors=True, dedup_replicated_tensors=True)¶ +class torch.distributed.checkpoint.DefaultSavePlanner(flatten_state_dict=True, flatten_sharded_tensors=True, dedup_replicated_tensors=True) ``` ```py -lookup_object(index)¶ +lookup_object(index) ``` 从规划者接口扩展以便于扩展默认规划者。 @@ -802,13 +802,13 @@ lookup_object(index)¶ [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)") ```py -transform_object(write_item, object)¶ +transform_object(write_item, object) ``` 从规划者接口扩展以便于扩展默认规划者。 ```py -class torch.distributed.checkpoint.DefaultLoadPlanner(flatten_state_dict=True, flatten_sharded_tensors=True)¶ +class torch.distributed.checkpoint.DefaultLoadPlanner(flatten_state_dict=True, flatten_sharded_tensors=True) ``` DefaultLoadPlanner 在 LoadPlanner 的基础上添加了多个功能。 @@ -818,7 +818,7 @@ DefaultLoadPlanner 在 LoadPlanner 的基础上添加了多个功能。 flatten_state_dict: 处理具有嵌套字典的 state_dict flatten_sharded_tensors: 用于 FSDP 的 2D 并行模式 ```py -lookup_tensor(index)¶ +lookup_tensor(index) ``` 从规划者接口扩展以便于扩展默认规划者。 @@ -828,7 +828,7 @@ lookup_tensor(index)¶ *Tensor* ```py -transform_tensor(read_item, tensor)¶ +transform_tensor(read_item, tensor) ``` 从规划者接口扩展以便于扩展默认规划者。 @@ -836,7 +836,7 @@ transform_tensor(read_item, tensor)¶ 我们提供了一组 API 来帮助用户轻松获取和设置 state_dict。这是一个实验性功能,可能会发生变化。 ```py -torch.distributed.checkpoint.state_dict.get_state_dict(model, optimizers, *, submodules=None, options=None)¶ +torch.distributed.checkpoint.state_dict.get_state_dict(model, optimizers, *, submodules=None, options=None) ``` 返回模型 state_dict 和优化器 state_dict。 @@ -866,7 +866,7 @@ ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim) fsdp + **选项**(*StateDictOptions*")[[*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*列表*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*列表*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), ValueType]]]]], [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")[[*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*列表*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), [*列表*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[*联合*](https://docs.python.org/3/library/typing.html#typing.Union "(在 Python v3.12 中)")*DTensor*, *ShardedTensor*, [*张量*, [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), [float](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")]], [*字典*](https://docs.python.org/3/library/typing.html#typing.Dict "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"), ValueType]]]]]]]]] ```py -torch.distributed.checkpoint.state_dict.get_model_state_dict(model, *, submodules=None, options=None)¶ +torch.distributed.checkpoint.state_dict.get_model_state_dict(model, *, submodules=None, options=None) ``` 返回`model`的模型 state_dict。 @@ -882,7 +882,7 @@ torch.distributed.checkpoint.state_dict.get_model_state_dict(model, *, submodule + **选项**(*StateDictOptions*")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), ValueType]]]]] ```py -torch.distributed.checkpoint.state_dict.get_optimizer_state_dict(model, optimizers, *, submodules=None, options=None)¶ +torch.distributed.checkpoint.state_dict.get_optimizer_state_dict(model, optimizers, *, submodules=None, options=None) ``` 返回优化器的组合 state_dict。 @@ -908,7 +908,7 @@ torch.distributed.checkpoint.state_dict.get_optimizer_state_dict(model, optimize [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")[[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), ValueType]]]]], [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")[[*Union*](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.12)")*DTensor*, *ShardedTensor*, [*Tensor*, [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")]], [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), ValueType]]]]]]]] ```py -torch.distributed.checkpoint.state_dict.set_state_dict(model, optimizers, *, model_state_dict, optim_state_dict, options=None)¶ +torch.distributed.checkpoint.state_dict.set_state_dict(model, optimizers, *, model_state_dict, optim_state_dict, options=None) ``` 加载模型的 state_dict 和优化器的 state_dict。 @@ -936,7 +936,7 @@ torch.distributed.checkpoint.state_dict.set_state_dict(model, optimizers, *, mod 带有`missing_keys`和`unexpected_keys`字段的`NamedTuple` ```py -torch.distributed.checkpoint.state_dict.set_model_state_dict(model, model_state_dict, *, options=None)¶ +torch.distributed.checkpoint.state_dict.set_model_state_dict(model, model_state_dict, *, options=None) ``` 加载模型的 state_dict。 @@ -962,7 +962,7 @@ torch.distributed.checkpoint.state_dict.set_model_state_dict(model, model_state_ 带有`missing_keys`和`unexpected_keys`字段的`NamedTuple` ```py -torch.distributed.checkpoint.state_dict.set_optimizer_state_dict(model, optimizers, *, optim_state_dict, options=None)¶ +torch.distributed.checkpoint.state_dict.set_optimizer_state_dict(model, optimizers, *, optim_state_dict, options=None) ``` 加载优化器的状态字典。 @@ -988,7 +988,7 @@ None None ```py -class torch.distributed.checkpoint.state_dict.StateDictOptions(full_state_dict=False, cpu_offload=False, ignore_frozen_params=False, keep_submodule_prefixes=True, strict=True)¶ +class torch.distributed.checkpoint.state_dict.StateDictOptions(full_state_dict=False, cpu_offload=False, ignore_frozen_params=False, keep_submodule_prefixes=True, strict=True) ``` 此数据类指定了 get_state_dict/set_state_dict 的工作方式。 diff --git a/totrans/doc22_053.md b/totrans/doc22_053.md index e79dbba6760a30a37b4a627a10c2496c94dc5fd1..bac2028dcbe2f9f2109ab04768b30a9b67872d60 100644 --- a/totrans/doc22_053.md +++ b/totrans/doc22_053.md @@ -43,7 +43,7 @@ loss.backward() ## 分布 ```py -class torch.distributions.distribution.Distribution(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)¶ +class torch.distributions.distribution.Distribution(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None) ``` 基类:[`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)") @@ -51,19 +51,19 @@ class torch.distributions.distribution.Distribution(batch_shape=torch.Size([]), Distribution 是概率分布的抽象基类。 ```py -property arg_constraints: Dict[str, Constraint]¶ +property arg_constraints: Dict[str, Constraint] ``` 返回一个从参数名到应满足该分布每个参数的`Constraint`对象的字典。不需要出现在此字典中的非张量参数。 ```py -property batch_shape: Size¶ +property batch_shape: Size ``` 返回参数批处理的形状。 ```py -cdf(value)¶ +cdf(value) ``` 返回在值处评估的累积密度/质量函数。 @@ -77,7 +77,7 @@ cdf(value)¶ *张量* ```py -entropy()¶ +entropy() ``` 返回分布的熵,批处理在批形状上。 @@ -91,7 +91,7 @@ entropy()¶ *张量* ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` 返回包含离散分布支持的所有值的张量。结果将枚举维度 0,因此结果的形状将是(基数,)+批形状+事件形状(其中事件形状=()表示单变量分布)。 @@ -113,13 +113,13 @@ enumerate_support(expand=True)¶ *Tensor* ```py -property event_shape: Size¶ +property event_shape: Size ``` 返回单个样本的形状(不包含批处理)。 ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` 返回一个新的分布实例(或填充由派生类提供的现有实例),其批量维度扩展到 batch_shape。此方法在分布的参数上调用`expand`。因此,这不会为扩展的分布实例分配新内存。此外,在首次创建实例时,这不会重复任何 args 检查或参数广播在 __init__.py 中。 @@ -135,7 +135,7 @@ expand(batch_shape, _instance=None)¶ 具有批量维度扩展到 batch_size 的新分布实例。 ```py -icdf(value)¶ +icdf(value) ``` 返回在值处评估的累积密度/质量函数的逆函数。 @@ -149,7 +149,7 @@ icdf(value)¶ *Tensor* ```py -log_prob(value)¶ +log_prob(value) ``` 返回在值处评估的概率密度/质量函数的对数。 @@ -163,19 +163,19 @@ log_prob(value)¶ *Tensor* ```py -property mean: Tensor¶ +property mean: Tensor ``` 返回分布的均值。 ```py -property mode: Tensor¶ +property mode: Tensor ``` 返回分布的模式。 ```py -perplexity()¶ +perplexity() ``` 返回分布的困惑度,批量化到批量形状。 @@ -189,7 +189,7 @@ perplexity()¶ *Tensor* ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` 生成一个 sample_shape 形状的重参数化样本或者如果分布参数是批量的,则生成一个 sample_shape 形状的重参数化样本批次。 @@ -199,7 +199,7 @@ rsample(sample_shape=torch.Size([]))¶ *Tensor* ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` 生成一个 sample_shape 形状的样本或者如果分布参数是批量的,则生成一个 sample_shape 形状的样本批次。 @@ -209,7 +209,7 @@ sample(sample_shape=torch.Size([]))¶ *Tensor* ```py -sample_n(n)¶ +sample_n(n) ``` 生成 n 个样本或者如果分布参数是批量的,则生成 n 个样本批次。 @@ -219,7 +219,7 @@ sample_n(n)¶ *Tensor* ```py -static set_default_validate_args(value)¶ +static set_default_validate_args(value) ``` 设置验证是否启用或禁用。 @@ -231,19 +231,19 @@ static set_default_validate_args(value)¶ **value**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"))- 是否启用验证。 ```py -property stddev: Tensor¶ +property stddev: Tensor ``` 返回分布的标准差。 ```py -property support: Optional[Any]¶ +property support: Optional[Any] ``` 返回表示此分布支持的`Constraint`对象。 ```py -property variance: Tensor¶ +property variance: Tensor ``` 返回分布的方差。 @@ -251,7 +251,7 @@ property variance: Tensor¶ ## 指数族 ```py -class torch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None)¶ +class torch.distributions.exp_family.ExponentialFamily(batch_shape=torch.Size([]), event_shape=torch.Size([]), validate_args=None) ``` 基类:`Distribution` @@ -267,7 +267,7 @@ $p_{F}(x; \theta) = \exp(\langle t(x), \theta\rangle - F(\theta) + k(x))$pF​(x 这个类是 Distribution 类和属于指数族的分布之间的中介,主要用于检查.entropy()和解析 KL 散度方法的正确性。我们使用这个类来使用 AD 框架和 Bregman 散度计算熵和 KL 散度(感谢:Frank Nielsen 和 Richard Nock,指数族的熵和交叉熵)。 ```py -entropy()¶ +entropy() ``` 使用 Bregman 散度计算熵的方法。 @@ -275,7 +275,7 @@ entropy()¶ ## 伯努利 ```py -class torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None)¶ +class torch.distributions.bernoulli.Bernoulli(probs=None, logits=None, validate_args=None) ``` 基类:`ExponentialFamily` @@ -299,65 +299,65 @@ tensor([ 0.]) + **logits**(*Number**,* *Tensor*) - 采样 1 的对数几率 ```py -arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶ +arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_enumerate_support = True¶ +has_enumerate_support = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = Boolean()¶ +support = Boolean() ``` ```py -property variance¶ +property variance ``` ## Beta ```py -class torch.distributions.beta.Beta(concentration1, concentration0, validate_args=None)¶ +class torch.distributions.beta.Beta(concentration1, concentration0, validate_args=None) ``` 基类:`ExponentialFamily` @@ -379,57 +379,57 @@ tensor([ 0.1046]) + **concentration0**([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *or* *Tensor*) - 分布的第二个集中参数(通常称为 beta) ```py -arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)} ``` ```py -property concentration0¶ +property concentration0 ``` ```py -property concentration1¶ +property concentration1 ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=())¶ +rsample(sample_shape=()) ``` ```py -support = Interval(lower_bound=0.0, upper_bound=1.0)¶ +support = Interval(lower_bound=0.0, upper_bound=1.0) ``` ```py -property variance¶ +property variance ``` ## 二项式 ```py -class torch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.binomial.Binomial(total_count=1, probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -458,65 +458,65 @@ tensor([[ 4., 5.], + **logits**(*Tensor*) - 事件对数几率 ```py -arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0), 'total_count': IntegerGreaterThan(lower_bound=0)}¶ +arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0), 'total_count': IntegerGreaterThan(lower_bound=0)} ``` ```py -entropy()¶ +entropy() ``` ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_enumerate_support = True¶ +has_enumerate_support = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## 分类 ```py -class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)¶ +class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -554,65 +554,65 @@ tensor(3) + **logits**(*张量*) - 事件对数概率(未归一化) ```py -arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶ +arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()} ``` ```py -entropy()¶ +entropy() ``` ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_enumerate_support = True¶ +has_enumerate_support = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## 柯西 ```py -class torch.distributions.cauchy.Cauchy(loc, scale, validate_args=None)¶ +class torch.distributions.cauchy.Cauchy(loc, scale, validate_args=None) ``` 基类:`Distribution` @@ -634,57 +634,57 @@ tensor([ 2.3214]) + **scale**([*浮点数*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *张量*) - 半峰宽。 ```py -arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` ## 卡方 ```py -class torch.distributions.chi2.Chi2(df, validate_args=None)¶ +class torch.distributions.chi2.Chi2(df, validate_args=None) ``` 基类:`Gamma` @@ -704,21 +704,21 @@ tensor([ 0.1046]) **df**([*浮点数*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *张量*) - 分布的形状参数 ```py -arg_constraints = {'df': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'df': GreaterThan(lower_bound=0.0)} ``` ```py -property df¶ +property df ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ## 连续伯努利 ```py -class torch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None)¶ +class torch.distributions.continuous_bernoulli.ContinuousBernoulli(probs=None, logits=None, lims=(0.499, 0.501), validate_args=None) ``` 基类:`ExponentialFamily` @@ -744,73 +744,73 @@ tensor([ 0.2538]) [1] 连续伯努利:修复变分自动编码器中的普遍错误,Loaiza-Ganem G 和 Cunningham JP,NeurIPS 2019。[`arxiv.org/abs/1907.06845`](https://arxiv.org/abs/1907.06845) ```py -arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶ +arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property stddev¶ +property stddev ``` ```py -support = Interval(lower_bound=0.0, upper_bound=1.0)¶ +support = Interval(lower_bound=0.0, upper_bound=1.0) ``` ```py -property variance¶ +property variance ``` ## 狄利克雷 ```py -class torch.distributions.dirichlet.Dirichlet(concentration, validate_args=None)¶ +class torch.distributions.dirichlet.Dirichlet(concentration, validate_args=None) ``` 基类:`ExponentialFamily` @@ -830,49 +830,49 @@ tensor([ 0.1046, 0.8954]) **concentration**(*Tensor*)– 分布的集中参数(通常称为 alpha) ```py -arg_constraints = {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1)}¶ +arg_constraints = {'concentration': IndependentConstraint(GreaterThan(lower_bound=0.0), 1)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=())¶ +rsample(sample_shape=()) ``` ```py -support = Simplex()¶ +support = Simplex() ``` ```py -property variance¶ +property variance ``` ## 指数 ```py -class torch.distributions.exponential.Exponential(rate, validate_args=None)¶ +class torch.distributions.exponential.Exponential(rate, validate_args=None) ``` 基类:`ExponentialFamily` @@ -892,61 +892,61 @@ tensor([ 0.1046]) **rate**([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *Tensor*)– rate = 1 / 分布的比例 ```py -arg_constraints = {'rate': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'rate': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -property stddev¶ +property stddev ``` ```py -support = GreaterThanEq(lower_bound=0.0)¶ +support = GreaterThanEq(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## FisherSnedecor ```py -class torch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None)¶ +class torch.distributions.fishersnedecor.FisherSnedecor(df1, df2, validate_args=None) ``` 基类:`Distribution` @@ -968,45 +968,45 @@ tensor([ 0.2453]) + **df2**([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *Tensor*)– 自由度参数 2 ```py -arg_constraints = {'df1': GreaterThan(lower_bound=0.0), 'df2': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'df1': GreaterThan(lower_bound=0.0), 'df2': GreaterThan(lower_bound=0.0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -support = GreaterThan(lower_bound=0.0)¶ +support = GreaterThan(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## Gamma ```py -class torch.distributions.gamma.Gamma(concentration, rate, validate_args=None)¶ +class torch.distributions.gamma.Gamma(concentration, rate, validate_args=None) ``` 基类:`ExponentialFamily` @@ -1028,53 +1028,53 @@ tensor([ 0.1046]) + **rate**([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *Tensor*)– rate = 1 / 分布的比例(通常称为 beta) ```py -arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -support = GreaterThanEq(lower_bound=0.0)¶ +support = GreaterThanEq(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## 几何 ```py -class torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None)¶ +class torch.distributions.geometric.Geometric(probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -1102,53 +1102,53 @@ tensor([ 2.]) + **logits**(*数字**,* *Tensor*)– 抽样 1 的对数几率。 ```py -arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶ +arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = IntegerGreaterThan(lower_bound=0)¶ +support = IntegerGreaterThan(lower_bound=0) ``` ```py -property variance¶ +property variance ``` ## Gumbel ```py -class torch.distributions.gumbel.Gumbel(loc, scale, validate_args=None)¶ +class torch.distributions.gumbel.Gumbel(loc, scale, validate_args=None) ``` 基类:`TransformedDistribution` @@ -1170,45 +1170,45 @@ tensor([ 1.0124]) + **scale**([*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *Tensor*)– 分布的比例参数 ```py -arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property stddev¶ +property stddev ``` ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` ## HalfCauchy ```py -class torch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None)¶ +class torch.distributions.half_cauchy.HalfCauchy(scale, validate_args=None) ``` 基类:`TransformedDistribution` @@ -1233,57 +1233,57 @@ tensor([ 2.3214]) **scale**(*浮点数*或*张量*)- 完整柯西分布的比例 ```py -arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(prob)¶ +icdf(prob) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property scale¶ +property scale ``` ```py -support = GreaterThanEq(lower_bound=0.0)¶ +support = GreaterThanEq(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## HalfNormal ```py -class torch.distributions.half_normal.HalfNormal(scale, validate_args=None)¶ +class torch.distributions.half_normal.HalfNormal(scale, validate_args=None) ``` 基类:`TransformedDistribution` @@ -1308,57 +1308,57 @@ tensor([ 0.1046]) **scale**(*浮点数*或*张量*)- 完整正态分布的比例 ```py -arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'scale': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(prob)¶ +icdf(prob) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property scale¶ +property scale ``` ```py -support = GreaterThanEq(lower_bound=0.0)¶ +support = GreaterThanEq(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## 独立 ```py -class torch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None)¶ +class torch.distributions.independent.Independent(base_distribution, reinterpreted_batch_ndims, validate_args=None) ``` 基类:`Distribution` @@ -1390,61 +1390,61 @@ class torch.distributions.independent.Independent(base_distribution, reinterpret + **reinterpreted_batch_ndims**(*整数*)- 要重新解释为事件维度的批次维度数 ```py -arg_constraints: Dict[str, Constraint] = {}¶ +arg_constraints: Dict[str, Constraint] = {} ``` ```py -entropy()¶ +entropy() ``` ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -property has_enumerate_support¶ +property has_enumerate_support ``` ```py -property has_rsample¶ +property has_rsample ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## InverseGamma ```py -class torch.distributions.inverse_gamma.InverseGamma(concentration, rate, validate_args=None)¶ +class torch.distributions.inverse_gamma.InverseGamma(concentration, rate, validate_args=None) ``` 基类:`TransformedDistribution` @@ -1471,49 +1471,49 @@ tensor([ 1.2953]) + **rate**(*浮点数*或*张量*)- 分布的比例尺率(通常称为 beta 的倒数) ```py -arg_constraints: Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'concentration': GreaterThan(lower_bound=0.0), 'rate': GreaterThan(lower_bound=0.0)} ``` ```py -property concentration¶ +property concentration ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property rate¶ +property rate ``` ```py -support = GreaterThan(lower_bound=0.0)¶ +support = GreaterThan(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## Kumaraswamy ```py -class torch.distributions.kumaraswamy.Kumaraswamy(concentration1, concentration0, validate_args=None)¶ +class torch.distributions.kumaraswamy.Kumaraswamy(concentration1, concentration0, validate_args=None) ``` 基类:`TransformedDistribution` @@ -1535,41 +1535,41 @@ tensor([ 0.1729]) + **concentration0**(*浮点数*或*张量*)- 分布的第二个浓度参数(通常称为 beta) ```py -arg_constraints: Dict[str, Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'concentration0': GreaterThan(lower_bound=0.0), 'concentration1': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -support = Interval(lower_bound=0.0, upper_bound=1.0)¶ +support = Interval(lower_bound=0.0, upper_bound=1.0) ``` ```py -property variance¶ +property variance ``` ## LKJCholesky ```py -class torch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None)¶ +class torch.distributions.lkj_cholesky.LKJCholesky(dim, concentration=1.0, validate_args=None) ``` 基类:`Distribution` @@ -1604,29 +1604,29 @@ tensor([[ 1.0000, 0.0000, 0.0000], [1] 基于藤和扩展洋葱方法生成随机相关矩阵(2009 年),Daniel Lewandowski,Dorota Kurowicka,Harry Joe。多元分析杂志。100. 10.1016/j.jmva.2009.04.008 ```py -arg_constraints = {'concentration': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'concentration': GreaterThan(lower_bound=0.0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = CorrCholesky()¶ +support = CorrCholesky() ``` ## 拉普拉斯 ```py -class torch.distributions.laplace.Laplace(loc, scale, validate_args=None)¶ +class torch.distributions.laplace.Laplace(loc, scale, validate_args=None) ``` 基础:`Distribution` @@ -1648,61 +1648,61 @@ tensor([ 0.1046]) + **scale**([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *或* *Tensor*) - 分布的尺度 ```py -arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -property stddev¶ +property stddev ``` ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` ## 对数正态 ```py -class torch.distributions.log_normal.LogNormal(loc, scale, validate_args=None)¶ +class torch.distributions.log_normal.LogNormal(loc, scale, validate_args=None) ``` 基础:`TransformedDistribution` @@ -1729,49 +1729,49 @@ tensor([ 0.1046]) + **scale**([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *或* *Tensor*) - 对数分布的标准差 ```py -arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -property loc¶ +property loc ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property scale¶ +property scale ``` ```py -support = GreaterThan(lower_bound=0.0)¶ +support = GreaterThan(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## 低秩多元正态分布 ```py -class torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None)¶ +class torch.distributions.lowrank_multivariate_normal.LowRankMultivariateNormal(loc, cov_factor, cov_diag, validate_args=None) ``` 基础:`Distribution` @@ -1807,61 +1807,61 @@ capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor ``` ```py -arg_constraints = {'cov_diag': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'cov_factor': IndependentConstraint(Real(), 2), 'loc': IndependentConstraint(Real(), 1)}¶ +arg_constraints = {'cov_diag': IndependentConstraint(GreaterThan(lower_bound=0.0), 1), 'cov_factor': IndependentConstraint(Real(), 2), 'loc': IndependentConstraint(Real(), 1)} ``` ```py -property covariance_matrix¶ +property covariance_matrix ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property precision_matrix¶ +property precision_matrix ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -property scale_tril¶ +property scale_tril ``` ```py -support = IndependentConstraint(Real(), 1)¶ +support = IndependentConstraint(Real(), 1) ``` ```py -property variance¶ +property variance ``` ## MixtureSameFamily ```py -class torch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None)¶ +class torch.distributions.mixture_same_family.MixtureSameFamily(mixture_distribution, component_distribution, validate_args=None) ``` 基础:`Distribution` @@ -1899,53 +1899,53 @@ MixtureSameFamily 分布实现了一个(批量的)混合分布,其中所 + **component_distribution** - torch.distributions.Distribution-like 实例。最右边的批次维度索引组件。 ```py -arg_constraints: Dict[str, Constraint] = {}¶ +arg_constraints: Dict[str, Constraint] = {} ``` ```py -cdf(x)¶ +cdf(x) ``` ```py -property component_distribution¶ +property component_distribution ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = False¶ +has_rsample = False ``` ```py -log_prob(x)¶ +log_prob(x) ``` ```py -property mean¶ +property mean ``` ```py -property mixture_distribution¶ +property mixture_distribution ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## 多项式 ```py -class torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.multinomial.Multinomial(total_count=1, probs=None, logits=None, validate_args=None) ``` 基类:`分布` @@ -1977,57 +1977,57 @@ tensor([-4.1338]) + **total_count**([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) - 试验次数 -+ **probs**(*张量*, 1), 'probs': Simplex()}¶ ++ **probs**(*张量*, 1), 'probs': Simplex()} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property support¶ +property support ``` ```py -total_count: int¶ +total_count: int ``` ```py -property variance¶ +property variance ``` ## 多元正态分布 ```py -class torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)¶ +class torch.distributions.multivariate_normal.MultivariateNormal(loc, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None) ``` 基类:`分布` @@ -2055,61 +2055,61 @@ tensor([-0.2102, -0.5429]) 使用`scale_tril`将更有效:所有计算内部都基于`scale_tril`。如果传递的是`covariance_matrix`或`precision_matrix`,则仅用于使用 Cholesky 分解计算相应的下三角矩阵。 ```py -arg_constraints = {'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶ +arg_constraints = {'covariance_matrix': PositiveDefinite(), 'loc': IndependentConstraint(Real(), 1), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()} ``` ```py -property covariance_matrix¶ +property covariance_matrix ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property precision_matrix¶ +property precision_matrix ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -property scale_tril¶ +property scale_tril ``` ```py -support = IndependentConstraint(Real(), 1)¶ +support = IndependentConstraint(Real(), 1) ``` ```py -property variance¶ +property variance ``` ## 负二项分布 ```py -class torch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.negative_binomial.NegativeBinomial(total_count, probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -2125,53 +2125,53 @@ class torch.distributions.negative_binomial.NegativeBinomial(total_count, probs= + **logits**(*Tensor*) - 成功概率的事件对数几率 ```py -arg_constraints = {'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)}¶ +arg_constraints = {'logits': Real(), 'probs': HalfOpenInterval(lower_bound=0.0, upper_bound=1.0), 'total_count': GreaterThanEq(lower_bound=0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = IntegerGreaterThan(lower_bound=0)¶ +support = IntegerGreaterThan(lower_bound=0) ``` ```py -property variance¶ +property variance ``` ## 正态分布 ```py -class torch.distributions.normal.Normal(loc, scale, validate_args=None)¶ +class torch.distributions.normal.Normal(loc, scale, validate_args=None) ``` 基类:`ExponentialFamily` @@ -2193,65 +2193,65 @@ tensor([ 0.1046]) + **scale**([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *或* *Tensor*) - 分布的标准差(通常称为 sigma) ```py -arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -property stddev¶ +property stddev ``` ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` ## OneHotCategorical ```py -class torch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None)¶ +class torch.distributions.one_hot_categorical.OneHotCategorical(probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -2281,65 +2281,65 @@ tensor([ 0., 0., 0., 1.]) + **logits**(*Tensor*) - 事件对数概率(未归一化) ```py -arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶ +arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()} ``` ```py -entropy()¶ +entropy() ``` ```py -enumerate_support(expand=True)¶ +enumerate_support(expand=True) ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_enumerate_support = True¶ +has_enumerate_support = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = OneHot()¶ +support = OneHot() ``` ```py -property variance¶ +property variance ``` ## Pareto ```py -class torch.distributions.pareto.Pareto(scale, alpha, validate_args=None)¶ +class torch.distributions.pareto.Pareto(scale, alpha, validate_args=None) ``` 基类:`TransformedDistribution` @@ -2361,37 +2361,37 @@ tensor([ 1.5623]) + **alpha**([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *或* *Tensor*) - 分布的形状参数 ```py -arg_constraints: Dict[str, Constraint] = {'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints: Dict[str, Constraint] = {'alpha': GreaterThan(lower_bound=0.0), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## 泊松 ```py -class torch.distributions.poisson.Poisson(rate, validate_args=None)¶ +class torch.distributions.poisson.Poisson(rate, validate_args=None) ``` 基类:`ExponentialFamily` @@ -2415,41 +2415,41 @@ tensor([ 3.]) **rate**(*Number**,* *Tensor*) - 速率参数 ```py -arg_constraints = {'rate': GreaterThanEq(lower_bound=0.0)}¶ +arg_constraints = {'rate': GreaterThanEq(lower_bound=0.0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` ```py -support = IntegerGreaterThan(lower_bound=0)¶ +support = IntegerGreaterThan(lower_bound=0) ``` ```py -property variance¶ +property variance ``` ## RelaxedBernoulli ```py -class torch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.relaxed_bernoulli.RelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None) ``` 基类:`TransformedDistribution` @@ -2474,37 +2474,37 @@ tensor([ 0.2951, 0.3442, 0.8918, 0.9021]) + **logits**(*Number**,* *Tensor*) - 采样 1 的对数几率 ```py -arg_constraints: Dict[str, Constraint] = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶ +arg_constraints: Dict[str, Constraint] = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -property logits¶ +property logits ``` ```py -property probs¶ +property probs ``` ```py -support = Interval(lower_bound=0.0, upper_bound=1.0)¶ +support = Interval(lower_bound=0.0, upper_bound=1.0) ``` ```py -property temperature¶ +property temperature ``` ## LogitRelaxedBernoulli ```py -class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, probs=None, logits=None, validate_args=None) ``` 基类:`Distribution` @@ -2526,41 +2526,41 @@ class torch.distributions.relaxed_bernoulli.LogitRelaxedBernoulli(temperature, p [2] 使用 Gumbel-Softmax 的分类重参数化(Jang 等人,2017) ```py -arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)}¶ +arg_constraints = {'logits': Real(), 'probs': Interval(lower_bound=0.0, upper_bound=1.0)} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property logits¶ +property logits ``` ```py -property param_shape¶ +property param_shape ``` ```py -property probs¶ +property probs ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -support = Real()¶ +support = Real() ``` ## RelaxedOneHotCategorical ```py -class torch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None)¶ +class torch.distributions.relaxed_categorical.RelaxedOneHotCategorical(temperature, probs=None, logits=None, validate_args=None) ``` 基类:`TransformedDistribution` @@ -2585,37 +2585,37 @@ tensor([ 0.1294, 0.2324, 0.3859, 0.2523]) + **logits** (*Tensor*) – 每个事件的未归一化对数概率 ```py -arg_constraints: Dict[str, Constraint] = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()}¶ +arg_constraints: Dict[str, Constraint] = {'logits': IndependentConstraint(Real(), 1), 'probs': Simplex()} ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -property logits¶ +property logits ``` ```py -property probs¶ +property probs ``` ```py -support = Simplex()¶ +support = Simplex() ``` ```py -property temperature¶ +property temperature ``` ## StudentT ```py -class torch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None)¶ +class torch.distributions.studentT.StudentT(df, loc=0.0, scale=1.0, validate_args=None) ``` 基类:`Distribution` @@ -2639,49 +2639,49 @@ tensor([ 0.1046]) + **scale** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *or* *Tensor*) – 分布的标度 ```py -arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)}¶ +arg_constraints = {'df': GreaterThan(lower_bound=0.0), 'loc': Real(), 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` ## TransformedDistribution ```py -class torch.distributions.transformed_distribution.TransformedDistribution(base_distribution, transforms, validate_args=None)¶ +class torch.distributions.transformed_distribution.TransformedDistribution(base_distribution, transforms, validate_args=None) ``` 基类:`Distribution` @@ -2711,55 +2711,55 @@ logistic = TransformedDistribution(base_distribution, transforms) 更多示例,请查看`Gumbel`,`HalfCauchy`,`HalfNormal`,`LogNormal`,`Pareto`,`Weibull`,`RelaxedBernoulli`和`RelaxedOneHotCategorical`的实现。 ```py -arg_constraints: Dict[str, Constraint] = {}¶ +arg_constraints: Dict[str, Constraint] = {} ``` ```py -cdf(value)¶ +cdf(value) ``` 通过反转变换(s)并计算基本分布的得分来计算累积分布函数。 ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -property has_rsample¶ +property has_rsample ``` ```py -icdf(value)¶ +icdf(value) ``` 使用 transform(s)计算逆累积分布函数,并计算基本分布的得分。 ```py -log_prob(value)¶ +log_prob(value) ``` 通过反转变换(s)并使用基本分布的得分和对数绝对值行列式雅可比矩阵的得分来对样本进行评分。 ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` 生成一个形状为 sample_shape 的重参数化样本或者如果分布参数是批处理的,则生成一个形状为 sample_shape 的重参数化样本批次。首先从基本分布中抽样,然后对列表中的每个变换应用 transform()。 ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` 如果分布参数是批处理的,则生成一个形状为 sample_shape 的样本或者形状为 sample_shape 的样本批次。首先从基本分布中抽样,然后对列表中的每个变换应用 transform()。 ```py -property support¶ +property support ``` ## 均匀分布 ```py -class torch.distributions.uniform.Uniform(low, high, validate_args=None)¶ +class torch.distributions.uniform.Uniform(low, high, validate_args=None) ``` 基类:`Distribution` @@ -2781,61 +2781,61 @@ tensor([ 2.3418]) + **high**(*float*或*Tensor*) - 上限范围(不包括)。 ```py -arg_constraints = {'high': Dependent(), 'low': Dependent()}¶ +arg_constraints = {'high': Dependent(), 'low': Dependent()} ``` ```py -cdf(value)¶ +cdf(value) ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -icdf(value)¶ +icdf(value) ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -rsample(sample_shape=torch.Size([]))¶ +rsample(sample_shape=torch.Size([])) ``` ```py -property stddev¶ +property stddev ``` ```py -property support¶ +property support ``` ```py -property variance¶ +property variance ``` ## VonMises ```py -class torch.distributions.von_mises.VonMises(loc, concentration, validate_args=None)¶ +class torch.distributions.von_mises.VonMises(loc, concentration, validate_args=None) ``` 基类:`Distribution` @@ -2859,33 +2859,33 @@ tensor([1.9777]) + **concentration**(*torch.Tensor*) - 集中参数 ```py -arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'loc': Real()}¶ +arg_constraints = {'concentration': GreaterThan(lower_bound=0.0), 'loc': Real()} ``` ```py -expand(batch_shape)¶ +expand(batch_shape) ``` ```py -has_rsample = False¶ +has_rsample = False ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` 提供的均值是圆形的。 ```py -property mode¶ +property mode ``` ```py -sample(sample_shape=torch.Size([]))¶ +sample(sample_shape=torch.Size([])) ``` von Mises 分布的抽样算法基于以下论文:D.J. Best 和 N.I. Fisher,“von Mises 分布的高效模拟。”应用统计(1979 年):152-157。 @@ -2893,11 +2893,11 @@ von Mises 分布的抽样算法基于以下论文:D.J. Best 和 N.I. Fisher, 采样始终在内部以双精度进行,以避免在集中值较小时(在单精度约为 1e-4 时)在 _rejection_sample()中出现挂起(请参见问题#88443)。 ```py -support = Real()¶ +support = Real() ``` ```py -property variance¶ +property variance ``` 提供的方差是圆形的。 @@ -2905,7 +2905,7 @@ property variance¶ ## 威布尔 ```py -class torch.distributions.weibull.Weibull(scale, concentration, validate_args=None)¶ +class torch.distributions.weibull.Weibull(scale, concentration, validate_args=None) ``` 基类:`TransformedDistribution` @@ -2924,37 +2924,37 @@ tensor([ 0.4784]) + **scale**(*float*或*Tensor*) - 分布的比例参数(lambda)。 -+ **浓度**([*浮点数*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *张量*, 'scale': GreaterThan(lower_bound=0.0)}¶ ++ **浓度**([*浮点数*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)") *或* *张量*, 'scale': GreaterThan(lower_bound=0.0)} ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -support = GreaterThan(lower_bound=0.0)¶ +support = GreaterThan(lower_bound=0.0) ``` ```py -property variance¶ +property variance ``` ## Wishart ```py -class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None)¶ +class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_matrix=None, scale_tril=None, validate_args=None) ``` 基类:`指数族` @@ -2978,43 +2978,43 @@ class torch.distributions.wishart.Wishart(df, covariance_matrix=None, precision_ [1] 王,Z.,吴,Y.和楚,H.,2018。LKJ 分布和受限制的 Wishart 分布的等价性。[2] 索耶,S.,2007。Wishart 分布和逆 Wishart 抽样。[3] 安德森,T. W.,2003。多元统计分析导论(第 3 版)。[4] 奥德尔,P. L. & 费夫森,A. H.,1966。生成样本协方差矩阵的数值过程。JASA,61(313):199-203。[5] 顾,Y.-C. & 布鲁姆菲尔德,P.,2010。在 OX 中生成具有分数自由度的随机 Wishart 矩阵。 ```py -arg_constraints = {'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()}¶ +arg_constraints = {'covariance_matrix': PositiveDefinite(), 'df': GreaterThan(lower_bound=0), 'precision_matrix': PositiveDefinite(), 'scale_tril': LowerCholesky()} ``` ```py -property covariance_matrix¶ +property covariance_matrix ``` ```py -entropy()¶ +entropy() ``` ```py -expand(batch_shape, _instance=None)¶ +expand(batch_shape, _instance=None) ``` ```py -has_rsample = True¶ +has_rsample = True ``` ```py -log_prob(value)¶ +log_prob(value) ``` ```py -property mean¶ +property mean ``` ```py -property mode¶ +property mode ``` ```py -property precision_matrix¶ +property precision_matrix ``` ```py -rsample(sample_shape=torch.Size([]), max_try_correction=None)¶ +rsample(sample_shape=torch.Size([]), max_try_correction=None) ``` 警告 @@ -3022,21 +3022,21 @@ rsample(sample_shape=torch.Size([]), max_try_correction=None)¶ 在某些情况下,基于 Bartlett 分解的采样算法可能返回奇异矩阵样本。默认情况下会尝试多次纠正奇异样本,但最终可能会返回奇异矩阵样本。奇异样本可能会在.log_prob()中返回-inf 值。在这种情况下,用户应验证样本,并修复 df 的值或根据需要调整.rsample 中 max_try_correction 参数的值。 ```py -property scale_tril¶ +property scale_tril ``` ```py -support = PositiveDefinite()¶ +support = PositiveDefinite() ``` ```py -property variance¶ +property variance ``` ## KL 散度 ```py -torch.distributions.kl.kl_divergence(p, q)¶ +torch.distributions.kl.kl_divergence(p, q) ``` 计算两个分布之间的 Kullback-Leibler 散度$KL(p \| q)$KL(p∥q)。 @@ -3224,7 +3224,7 @@ KL 散度目前针对以下分布对实现: + `均匀` 和 `均匀` ```py -torch.distributions.kl.register_kl(type_p, type_q)¶ +torch.distributions.kl.register_kl(type_p, type_q) ``` 装饰器用于使用`kl_divergence()`注册成对函数。用法: @@ -3257,13 +3257,13 @@ register_kl(DerivedP, DerivedQ)(kl_version1) # Break the tie. + **type_q**([*type*](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)")) - `Distribution` 的子类。## 转换[](#module-torch.distributions.transforms "Permalink to this heading") ```py -class torch.distributions.transforms.AbsTransform(cache_size=0)¶ +class torch.distributions.transforms.AbsTransform(cache_size=0) ``` 通过映射 $y = |x|$ 进行变换。 ```py -class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0)¶ +class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, cache_size=0) ``` 通过逐点仿射映射变换 $y = \text{loc} + \text{scale} \times x$。 @@ -3277,7 +3277,7 @@ class torch.distributions.transforms.AffineTransform(loc, scale, event_dim=0, ca + **event_dim**([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) - 事件形状的可选大小。对于一元随机变量,应为零;对于向量分布,应为 1;对于矩阵分布,应为 2,依此类推。 ```py -class torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0)¶ +class torch.distributions.transforms.CatTransform(tseq, dim=0, lengths=None, cache_size=0) ``` 应用一系列变换 tseq,逐个组件地将每个子矩阵在维度 dim 处的长度为 lengths[dim]的变换,以与`torch.cat()`兼容的方式。 @@ -3293,7 +3293,7 @@ y = t(x) ``` ```py -class torch.distributions.transforms.ComposeTransform(parts, cache_size=0)¶ +class torch.distributions.transforms.ComposeTransform(parts, cache_size=0) ``` 在链中组合多个变换。被组合的变换负责缓存。 @@ -3305,7 +3305,7 @@ class torch.distributions.transforms.ComposeTransform(parts, cache_size=0)¶ + **cache_size**([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) - 缓存大小。如果为零,则不进行缓存。如果为一,则缓存最新的单个值。仅支持 0 和 1。 ```py -class torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)¶ +class torch.distributions.transforms.CorrCholeskyTransform(cache_size=0) ``` 将长度为$D*(D-1)/2$的无约束实向量$x$转换为 D 维相关矩阵的 Cholesky 因子。这个 Cholesky 因子是一个下三角矩阵,对角线为正,每行的欧几里得范数为单位。变换如下进行: @@ -3315,7 +3315,7 @@ class torch.distributions.transforms.CorrCholeskyTransform(cache_size=0)¶ > 1. 对于下三角部分的每一行$X_i$,我们应用类`StickBreakingTransform`的*有符号*版本,将$X_i$转换为单位欧几里得长度向量,步骤如下: - 缩放到区间$(-1, 1)$:$r_i = \tanh(X_i)$。 - 转换为无符号域:$z_i = r_i²$。 - 应用$si = StickBreakingTransform(z_i)$。 - 转换回有符号域:$y_i = sign(r_i) * \sqrt{s_i}$。 ```py -class torch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0)¶ +class torch.distributions.transforms.CumulativeDistributionTransform(distribution, cache_size=0) ``` 通过概率分布的累积分布函数进行变换。 @@ -3337,13 +3337,13 @@ copula = TransformedDistribution(base_dist, [transform]) ``` ```py -class torch.distributions.transforms.ExpTransform(cache_size=0)¶ +class torch.distributions.transforms.ExpTransform(cache_size=0) ``` 通过映射$y = \exp(x)$进行变换。 ```py -class torch.distributions.transforms.IndependentTransform(base_transform, reinterpreted_batch_ndims, cache_size=0)¶ +class torch.distributions.transforms.IndependentTransform(base_transform, reinterpreted_batch_ndims, cache_size=0) ``` 封装另一个变换,以将`reinterpreted_batch_ndims`-许多右侧维度视为相关。这对前向或后向变换没有影响,但在`log_abs_det_jacobian()`中会对右侧维度进行`reinterpreted_batch_ndims`求和。 @@ -3355,7 +3355,7 @@ class torch.distributions.transforms.IndependentTransform(base_transform, reinte + **reinterpreted_batch_ndims**([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) - 要视为相关的额外右侧维度的数量。 ```py -class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)¶ +class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0) ``` 从无约束矩阵转换为具有非负对角元的下三角矩阵。 @@ -3363,19 +3363,19 @@ class torch.distributions.transforms.LowerCholeskyTransform(cache_size=0)¶ 这对于用 Cholesky 分解参数化正定矩阵非常有用。 ```py -class torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0)¶ +class torch.distributions.transforms.PositiveDefiniteTransform(cache_size=0) ``` 从无约束矩阵转换为正定矩阵。 ```py -class torch.distributions.transforms.PowerTransform(exponent, cache_size=0)¶ +class torch.distributions.transforms.PowerTransform(exponent, cache_size=0) ``` 通过映射$y = x^{\text{exponent}}$进行变换。 ```py -class torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache_size=0)¶ +class torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache_size=0) ``` 单位雅可比变换,用于重塑张量的最右侧部分。 @@ -3389,19 +3389,19 @@ class torch.distributions.transforms.ReshapeTransform(in_shape, out_shape, cache + **out_shape**(*torch.Size*) - 输出事件形状。 ```py -class torch.distributions.transforms.SigmoidTransform(cache_size=0)¶ +class torch.distributions.transforms.SigmoidTransform(cache_size=0) ``` 通过映射$y = \frac{1}{1 + \exp(-x)}$和$x = \text{logit}(y)$进行变换。 ```py -class torch.distributions.transforms.SoftplusTransform(cache_size=0)¶ +class torch.distributions.transforms.SoftplusTransform(cache_size=0) ``` 通过映射$\text{Softplus}(x) = \log(1 + \exp(x))$Softplus(x)=log(1+exp(x))进行变换。当$x > 20$时,实现会恢复为线性函数。 ```py -class torch.distributions.transforms.TanhTransform(cache_size=0)¶ +class torch.distributions.transforms.TanhTransform(cache_size=0) ``` 通过映射$y = \tanh(x)$y=tanh(x)进行变换。 @@ -3411,7 +3411,7 @@ class torch.distributions.transforms.TanhTransform(cache_size=0)¶ 请注意,当涉及 NaN/Inf 值时,应使用 cache_size=1。 ```py -class torch.distributions.transforms.SoftmaxTransform(cache_size=0)¶ +class torch.distributions.transforms.SoftmaxTransform(cache_size=0) ``` 从非约束空间到单纯形的变换,通过$y = \exp(x)$y=exp(x)然后归一化。 @@ -3419,7 +3419,7 @@ class torch.distributions.transforms.SoftmaxTransform(cache_size=0)¶ 这不是双射的,不能用于 HMC。但是这主要是按坐标进行的(除了最终的归一化),因此适用于按坐标优化算法。 ```py -class torch.distributions.transforms.StackTransform(tseq, dim=0, cache_size=0)¶ +class torch.distributions.transforms.StackTransform(tseq, dim=0, cache_size=0) ``` 将变换序列 tseq 逐个组件地应用于维度 dim 中的每个子矩阵的变换函数,以与`torch.stack()`兼容的方式。 @@ -3433,7 +3433,7 @@ y = t(x) ``` ```py -class torch.distributions.transforms.StickBreakingTransform(cache_size=0)¶ +class torch.distributions.transforms.StickBreakingTransform(cache_size=0) ``` 通过一个破棍过程,将非约束空间转换为一个额外维度的单纯形。 @@ -3443,7 +3443,7 @@ class torch.distributions.transforms.StickBreakingTransform(cache_size=0)¶ 这是双射的,适用于在 HMC 中使用;但是它将坐标混合在一起,不太适合优化。 ```py -class torch.distributions.transforms.Transform(cache_size=0)¶ +class torch.distributions.transforms.Transform(cache_size=0) ``` 可计算对数行列式雅可比的可逆变换的抽象类。它们主要用于`torch.distributions.TransformedDistribution`中。 @@ -3480,31 +3480,31 @@ grad(z.sum(), [y]) # error because z is x + **符号**([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *或* *Tensor*) - 对于双射单变量变换,这应该是+1 或-1,取决于变换是单调递增还是递减。 ```py -property inv¶ +property inv ``` 返回此变换的逆`Transform`。这应该满足`t.inv.inv is t`。 ```py -property sign¶ +property sign ``` 返回雅可比行列式的符号,如果适用的话。一般来说,这只对双射变换有意义。 ```py -log_abs_det_jacobian(x, y)¶ +log_abs_det_jacobian(x, y) ``` 计算给定输入和输出的对数行列式雅可比行列式 log |dy/dx|。 ```py -forward_shape(shape)¶ +forward_shape(shape) ``` 推断前向计算的形状,给定输入形状。默认保留形状。 ```py -inverse_shape(shape)¶ +inverse_shape(shape) ``` 推断逆计算的形状,给定输出形状。默认保留形状。 ## 约束[](#module-torch.distributions.constraints "Permalink to this heading") @@ -3568,7 +3568,7 @@ inverse_shape(shape)¶ + `constraints.unit_interval` ```py -class torch.distributions.constraints.Constraint¶ +class torch.distributions.constraints.Constraint ``` 约束的抽象基类。 @@ -3582,73 +3582,73 @@ class torch.distributions.constraints.Constraint¶ + **event_dim** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – 定义事件的最右边维度的数量。`check()`方法在计算有效性时将删除这么多维度。 ```py -check(value)¶ +check(value) ``` 返回一个`sample_shape + batch_shape`的字节张量,指示值中的每个事件是否满足此约束。 ```py -torch.distributions.constraints.cat¶ +torch.distributions.constraints.cat ``` 别名为`_Cat` ```py -torch.distributions.constraints.dependent_property¶ +torch.distributions.constraints.dependent_property ``` 别名为`_DependentProperty` ```py -torch.distributions.constraints.greater_than¶ +torch.distributions.constraints.greater_than ``` 别名为`_GreaterThan` ```py -torch.distributions.constraints.greater_than_eq¶ +torch.distributions.constraints.greater_than_eq ``` 别名为`_GreaterThanEq` ```py -torch.distributions.constraints.independent¶ +torch.distributions.constraints.independent ``` 别名为`_IndependentConstraint` ```py -torch.distributions.constraints.integer_interval¶ +torch.distributions.constraints.integer_interval ``` 别名为`_IntegerInterval` ```py -torch.distributions.constraints.interval¶ +torch.distributions.constraints.interval ``` 别名为`_Interval` ```py -torch.distributions.constraints.half_open_interval¶ +torch.distributions.constraints.half_open_interval ``` 别名为`_HalfOpenInterval` ```py -torch.distributions.constraints.less_than¶ +torch.distributions.constraints.less_than ``` 别名为`_LessThan` ```py -torch.distributions.constraints.multinomial¶ +torch.distributions.constraints.multinomial ``` 别名为`_Multinomial` ```py -torch.distributions.constraints.stack¶ +torch.distributions.constraints.stack ``` 别名为`_Stack` ## 约束注册[](#module-torch.distributions.constraint_registry "Permalink to this heading") @@ -3699,13 +3699,13 @@ def my_factory(constraint): 您可以通过创建一个新的`ConstraintRegistry`对象来创建自己的注册表。 ```py -class torch.distributions.constraint_registry.ConstraintRegistry¶ +class torch.distributions.constraint_registry.ConstraintRegistry ``` 将约束链接到变换的注册表。 ```py -register(constraint, factory=None)¶ +register(constraint, factory=None) ``` 在此注册表中注册一个`Constraint`子类。用法: diff --git a/totrans/doc22_057.md b/totrans/doc22_057.md index e89ea43fa50929623f5c3c3b3fe417c5d8c17bf8..611013f802a73bc23207148141cecd6d1a3cec01 100644 --- a/totrans/doc22_057.md +++ b/totrans/doc22_057.md @@ -5,7 +5,7 @@ 此软件包提供了一个`Future`类型,封装了异步执行和一组实用函数,以简化对`Future`对象的操作。目前,`Future`类型主要由分布式 RPC 框架使用。 ```py -class torch.futures.Future(*, devices=None)¶ +class torch.futures.Future(*, devices=None) ``` 封装了对可调用对象的异步执行的`torch._C.Future`的包装器,例如`rpc_async()`。它还公开了一组 API 来添加回调函数和设置结果。 @@ -15,7 +15,7 @@ class torch.futures.Future(*, devices=None)¶ GPU 支持是一个测试功能,可能会发生变化。 ```py -add_done_callback(callback)¶ +add_done_callback(callback) ``` 将给定的回调函数附加到此`Future`,当`Future`完成时将运行该回调。可以向同一个`Future`添加多个回调,但不能保证它们将以何种顺序执行。回调必须接受一个参数,即对此`Future`的引用。回调函数可以使用`value()`方法获取值。请注意,如果此`Future`已经完成,给定的回调将内联运行。 @@ -46,7 +46,7 @@ This will run after the future has finished. ``` ```py -done()¶ +done() ``` 如果此`Future`已完成,则返回`True`。如果`Future`有结果或异常,则已完成。 @@ -58,7 +58,7 @@ done()¶ [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") ```py -set_exception(result)¶ +set_exception(result) ``` 为此`Future`设置异常,这将标记此`Future`为已完成并触发所有附加的回调。请注意,当在此`Future`上调用 wait()/value()时,此处设置的异常将内联引发。 @@ -79,7 +79,7 @@ ValueError: foo ``` ```py -set_result(result)¶ +set_result(result) ``` 设置此`Future`的结果,这将标记此`Future`为已完成并触发所有附加的回调。请注意,`Future`不能被标记为已完成两次。 @@ -110,7 +110,7 @@ tensor([3., 3.]) ``` ```py -then(callback)¶ +then(callback) ``` 将给定的回调函数附加到此`Future`,当`Future`完成时将运行该回调函数。可以向同一个`Future`添加多个回调,但不能保证它们将按照特定顺序执行(要强制执行特定顺序,请考虑链接:`fut.then(cb1).then(cb2)`)。回调函数必须接受一个参数,即对此`Future`的引用。回调函数可以使用`value()`方法获取值。请注意,如果此`Future`已经完成,给定的回调将立即内联运行。 @@ -153,7 +153,7 @@ Chained cb done. None ``` ```py -value()¶ +value() ``` 获取已完成 future 的值。 @@ -171,7 +171,7 @@ value()¶ *T* ```py -wait()¶ +wait() ``` 阻塞,直到此`Future`的值准备就绪。 @@ -187,7 +187,7 @@ wait()¶ *T* ```py -torch.futures.collect_all(futures)¶ +torch.futures.collect_all(futures) ``` 将提供的`Future`对象收集到一个单独的组合`Future`中,当所有子 Future 完成时,该组合 Future 完成。 @@ -220,7 +220,7 @@ fut1 result = 1 ``` ```py -torch.futures.wait_all(futures)¶ +torch.futures.wait_all(futures) ``` 等待所有提供的 Futures 完成,并返回已完成值的列表。如果任何 Future 遇到错误,该方法将提前退出并报告错误,不等待其他 Futures 完成。 diff --git a/totrans/doc22_058.md b/totrans/doc22_058.md index 5821482844590699d62dab19d484b61ab81df10d..50b1c6875b1f04a264631de3855942c06ef227f1 100644 --- a/totrans/doc22_058.md +++ b/totrans/doc22_058.md @@ -871,7 +871,7 @@ def forward(self, x): ## API 参考 ```py -torch.fx.symbolic_trace(root, concrete_args=None)¶ +torch.fx.symbolic_trace(root, concrete_args=None) ``` 符号追踪 API @@ -930,7 +930,7 @@ GraphModule 此 API 的向后兼容性已得到保证。 ```py -torch.fx.wrap(fn_or_name)¶ +torch.fx.wrap(fn_or_name) ``` 这个函数可以在模块级别范围内调用,将 fn_or_name 注册为“叶函数”。 “叶函数”将作为 CallFunction 节点保留在 FX 跟踪中,而不是被跟踪通过: @@ -968,7 +968,7 @@ def my_custom_function(x, y): 此 API 的向后兼容性已得到保证。 ```py -class torch.fx.GraphModule(*args, **kwargs)¶ +class torch.fx.GraphModule(*args, **kwargs) ``` GraphModule 是从 fx.Graph 生成的 nn.Module。Graphmodule 具有`graph`属性,以及从该`graph`生成的`code`和`forward`属性。 @@ -982,7 +982,7 @@ GraphModule 是从 fx.Graph 生成的 nn.Module。Graphmodule 具有`graph`属 此 API 的向后兼容性已得到保证。 ```py -__init__(root, graph, class_name='GraphModule')¶ +__init__(root, graph, class_name='GraphModule') ``` 构建一个 GraphModule。 @@ -1000,7 +1000,7 @@ __init__(root, graph, class_name='GraphModule')¶ 此 API 的向后兼容性已得到保证。 ```py -add_submodule(target, m)¶ +add_submodule(target, m) ``` 将给定的子模块添加到`self`。 @@ -1028,13 +1028,13 @@ add_submodule(target, m)¶ 此 API 的向后兼容性是有保证的。 ```py -property code: str¶ +property code: str ``` 返回从支持此`GraphModule`的`Graph`生成的 Python 代码。 ```py -delete_all_unused_submodules()¶ +delete_all_unused_submodules() ``` 从`self`中删除所有未使用的子模块。 @@ -1048,7 +1048,7 @@ delete_all_unused_submodules()¶ 此 API 的向后兼容性是有保证的。 ```py -delete_submodule(target)¶ +delete_submodule(target) ``` 从`self`中删除给定的子模块。 @@ -1074,13 +1074,13 @@ delete_submodule(target)¶ 此 API 的向后兼容性是有保证的。 ```py -property graph: Graph¶ +property graph: Graph ``` 返回此`GraphModule`的基础`Graph` ```py -print_readable(print_output=True)¶ +print_readable(print_output=True) ``` 返回为当前`GraphModule`及其子`GraphModule`生成的 Python 代码 @@ -1090,7 +1090,7 @@ print_readable(print_output=True)¶ 此 API 是实验性的,*不*向后兼容。 ```py -recompile()¶ +recompile() ``` 重新编译此`GraphModule`从其`graph`属性。在编辑包含的`graph`后应调用此方法,否则此`GraphModule`的生成代码将过时。 @@ -1104,7 +1104,7 @@ recompile()¶ *PythonCode* ```py -to_folder(folder, module_name='FxModule')¶ +to_folder(folder, module_name='FxModule') ``` 将模块转储到带有`module_name`的`folder`中,以便可以 @@ -1124,7 +1124,7 @@ to_folder(folder, module_name='FxModule')¶ 此 API 是实验性的,*不*向后兼容。 ```py -class torch.fx.Graph(owning_module=None, tracer_cls=None, tracer_extras=None)¶ +class torch.fx.Graph(owning_module=None, tracer_cls=None, tracer_extras=None) ``` `Graph`是 FX 中间表示中使用的主要数据结构。它由一系列`Node`组成,每个`Node`代表调用点(或其他语法结构)。一起取出的`Node`列表构成一个有效的 Python 函数。 @@ -1172,7 +1172,7 @@ graph(x): 此 API 的向后兼容性是有保证的。 ```py -__init__(owning_module=None, tracer_cls=None, tracer_extras=None)¶ +__init__(owning_module=None, tracer_cls=None, tracer_extras=None) ``` 构建一个空的图表。 @@ -1182,7 +1182,7 @@ __init__(owning_module=None, tracer_cls=None, tracer_extras=None)¶ 此 API 的向后兼容性是有保证的。 ```py -call_function(the_function, args=None, kwargs=None, type_expr=None)¶ +call_function(the_function, args=None, kwargs=None, type_expr=None) ``` 将`call_function` `Node`插入`Graph`。`call_function`节点表示对由`the_function`指定的 Python 可调用对象的调用。 @@ -1214,7 +1214,7 @@ call_function(the_function, args=None, kwargs=None, type_expr=None)¶ 此 API 的向后兼容性得到保证。 ```py -call_method(method_name, args=None, kwargs=None, type_expr=None)¶ +call_method(method_name, args=None, kwargs=None, type_expr=None) ``` 将`call_method` `Node`插入`Graph`中。`call_method`节点表示在`args`的第 0 个元素上调用给定方法。 @@ -1246,7 +1246,7 @@ call_method(method_name, args=None, kwargs=None, type_expr=None)¶ 此 API 的向后兼容性得到保证。 ```py -call_module(module_name, args=None, kwargs=None, type_expr=None)¶ +call_module(module_name, args=None, kwargs=None, type_expr=None) ``` 将`call_module` `Node`插入`Graph`中。`call_module`节点表示在`Module`层次结构中的`Module`的 forward()函数的调用。 @@ -1278,7 +1278,7 @@ call_module(module_name, args=None, kwargs=None, type_expr=None)¶ 此 API 的向后兼容性得到保证。 ```py -create_node(op, target, args=None, kwargs=None, name=None, type_expr=None)¶ +create_node(op, target, args=None, kwargs=None, name=None, type_expr=None) ``` 创建一个`Node`并将其添加到当前插入点的`Graph`。请注意,当前插入点可以通过`Graph.inserting_before()`和`Graph.inserting_after()`进行设置。 @@ -1308,7 +1308,7 @@ create_node(op, target, args=None, kwargs=None, name=None, type_expr=None)¶ 此 API 的向后兼容性已得到保证。 ```py -eliminate_dead_code()¶ +eliminate_dead_code() ``` 从图中删除所有死代码,基于每个节点的用户数量以及节点是否具有任何副作用。在调用之前,图必须进行拓扑排序。 @@ -1347,7 +1347,7 @@ def forward(self, x): 此 API 的向后兼容性已得到保证。 ```py -erase_node(to_erase)¶ +erase_node(to_erase) ``` 从`Graph`中擦除`Node`。如果在`Graph`中仍然有该节点的用户,则会引发异常。 @@ -1361,7 +1361,7 @@ erase_node(to_erase)¶ 此 API 的向后兼容性已得到保证。 ```py -get_attr(qualified_name, type_expr=None)¶ +get_attr(qualified_name, type_expr=None) ``` 将`get_attr`节点插入图中。`get_attr` `Node`表示从`Module`层次结构中获取属性。 @@ -1389,7 +1389,7 @@ get_attr(qualified_name, type_expr=None)¶ 此 API 的向后兼容性已得到保证。 ```py -graph_copy(g, val_map, return_output_node=False)¶ +graph_copy(g, val_map, return_output_node=False) ``` 将给定图中的所有节点复制到`self`中。 @@ -1413,7 +1413,7 @@ graph_copy(g, val_map, return_output_node=False)¶ 此 API 的向后兼容性已得到保证。 ```py -inserting_after(n=None)¶ +inserting_after(n=None) ``` 设置 create_node 和 companion 方法将插入到图中的位置。 @@ -1442,7 +1442,7 @@ g.inserting_after(n) # set the insert point permanently 此 API 的向后兼容性已得到保证。 ```py -inserting_before(n=None)¶ +inserting_before(n=None) ``` 设置 create_node 和 companion 方法将插入到图中的位置。 @@ -1471,7 +1471,7 @@ g.inserting_before(n) # set the insert point permanently 此 API 的向后兼容性已得到保证。 ```py -lint()¶ +lint() ``` 对此图运行各种检查,以确保其形式良好。特别是:-检查节点具有正确的所有权(由此图拥有)-检查节点按拓扑顺序出现-如果此图具有拥有的 GraphModule,则检查目标是否存在于该 GraphModule 中 @@ -1481,7 +1481,7 @@ lint()¶ 此 API 的向后兼容性已得到保证。 ```py -node_copy(node, arg_transform=>)¶ +node_copy(node, arg_transform=>) ``` 将一个图中的节点复制到另一个图中。`arg_transform`需要将节点图中的参数转换为 self 图中的参数。例如: @@ -1510,7 +1510,7 @@ for node in g.nodes: 此 API 的向后兼容性已得到保证。 ```py -property nodes: _node_list¶ +property nodes: _node_list ``` 获取构成此图的节点列表。 @@ -1522,7 +1522,7 @@ property nodes: _node_list¶ 节点的双向链表。请注意,可以在此列表上调用`reversed`以切换迭代顺序。 ```py -on_generate_code(make_transformer)¶ +on_generate_code(make_transformer) ``` 在生成 Python 代码时注册一个转换器函数 @@ -1593,7 +1593,7 @@ on_generate_code(make_transformer)¶ 此 API 是实验性的,*不*向后兼容。 ```py -output(result, type_expr=None)¶ +output(result, type_expr=None) ``` 将`output` `Node`插入`Graph`。`output`节点表示 Python 代码中的`return`语句。`result`是应该返回的值。 @@ -1613,7 +1613,7 @@ output(result, type_expr=None)¶ 此 API 的向后兼容性得到保证。 ```py -placeholder(name, type_expr=None, default_value)¶ +placeholder(name, type_expr=None, default_value) ``` 将`placeholder`节点插入 Graph。`placeholder`表示函数输入。 @@ -1639,7 +1639,7 @@ placeholder(name, type_expr=None, default_value)¶ 此 API 的向后兼容性得到保证。 ```py -print_tabular()¶ +print_tabular() ``` 以表格形式打印图的中间表示。请注意,此 API 需要安装`tabulate`模块。 @@ -1649,7 +1649,7 @@ print_tabular()¶ 此 API 的向后兼容性得到保证。 ```py -process_inputs(*args)¶ +process_inputs(*args) ``` 处理参数,以便它们可以传递给 FX 图。 @@ -1659,7 +1659,7 @@ process_inputs(*args)¶ 此 API 是实验性的,*不*向后兼容。 ```py -process_outputs(out)¶ +process_outputs(out) ``` 警告 @@ -1667,7 +1667,7 @@ process_outputs(out)¶ 此 API 是实验性的,*不*向后兼容。 ```py -python_code(root_module, *, verbose=False)¶ +python_code(root_module, *, verbose=False) ``` 将此`Graph`转换为有效的 Python 代码。 @@ -1689,7 +1689,7 @@ src:表示对象全局名称的 Python 源代码 globals:src 中的全局名 此 API 的向后兼容性得到保证。 ```py -set_codegen(codegen)¶ +set_codegen(codegen) ``` 警告 @@ -1697,7 +1697,7 @@ set_codegen(codegen)¶ 此 API 是实验性的,*不*向后兼容。 ```py -class torch.fx.Node(graph, name, op, target, args, kwargs, return_type=None)¶ +class torch.fx.Node(graph, name, op, target, args, kwargs, return_type=None) ``` `Node`是表示`Graph`中各个操作的数据结构。在大多数情况下,节点表示对各种实体的调用点,例如运算符、方法和模块(一些例外包括指定函数输入和输出的节点)。每个`Node`都有一个由其`op`属性指定的函数。对于`op`的每个值,`Node`的语义如下: @@ -1719,7 +1719,7 @@ class torch.fx.Node(graph, name, op, target, args, kwargs, return_type=None)¶ 此 API 的向后兼容性是有保证的。 ```py -property all_input_nodes: List[Node]¶ +property all_input_nodes: List[Node] ``` 返回是此节点的输入的所有节点。这相当于迭代 `args` 和 `kwargs` 并仅收集是节点的值。 @@ -1729,7 +1729,7 @@ property all_input_nodes: List[Node]¶ 在这个 `Node` 的 `args` 和 `kwargs` 中出现的 `Nodes` 列表,按顺序排列。 ```py -append(x)¶ +append(x) ``` 在此节点后插入 `x` 到图中的节点列表中。等同于 `self.next.prepend(x)` @@ -1743,7 +1743,7 @@ append(x)¶ 此 API 的向后兼容性是有保证的。 ```py -property args: Tuple[Optional[Union[Tuple[Any, ...], List[Any], Dict[str, Any], slice, range, Node, str, int, float, bool, complex, dtype, Tensor, device, memory_format, layout, OpOverload]], ...]¶ +property args: Tuple[Optional[Union[Tuple[Any, ...], List[Any], Dict[str, Any], slice, range, Node, str, int, float, bool, complex, dtype, Tensor, device, memory_format, layout, OpOverload]], ...] ``` 这个 `Node` 的参数元组。参数的解释取决于节点的操作码。查看 `Node` 文档字符串以获取更多信息。 @@ -1751,7 +1751,7 @@ property args: Tuple[Optional[Union[Tuple[Any, ...], List[Any], Dict[str, Any], 允许对此属性进行赋值。在赋值时,所有使用和用户的计数都会自动更新。 ```py -format_node(placeholder_names=None, maybe_return_typename=None)¶ +format_node(placeholder_names=None, maybe_return_typename=None) ``` 返回 `self` 的描述性字符串表示。 @@ -1781,7 +1781,7 @@ format_node(placeholder_names=None, maybe_return_typename=None)¶ 此 API 的向后兼容性得到保证。 ```py -insert_arg(idx, arg)¶ +insert_arg(idx, arg) ``` 在给定索引处向参数列表中插入一个位置参数。 @@ -1797,7 +1797,7 @@ insert_arg(idx, arg)¶ 此 API 的向后兼容性得到保证。 ```py -is_impure()¶ +is_impure() ``` 返回此操作是否不纯净,即其操作是占位符或输出,或者是不纯净的 call_function 或 call_module。 @@ -1815,7 +1815,7 @@ is_impure()¶ 此 API 是实验性的,*不*向后兼容。 ```py -property kwargs: Dict[str, Optional[Union[Tuple[Any, ...], List[Any], Dict[str, Any], slice, range, Node, str, int, float, bool, complex, dtype, Tensor, device, memory_format, layout, OpOverload]]]¶ +property kwargs: Dict[str, Optional[Union[Tuple[Any, ...], List[Any], Dict[str, Any], slice, range, Node, str, int, float, bool, complex, dtype, Tensor, device, memory_format, layout, OpOverload]]] ``` 关键字参数的字典到此`Node`。参数的解释取决于节点的操作码。有关更多信息,请参阅`Node`文档字符串。 @@ -1823,7 +1823,7 @@ property kwargs: Dict[str, Optional[Union[Tuple[Any, ...], List[Any], Dict[str, 允许对此属性进行赋值。所有使用和用户的计算都会在分配时自动更新。 ```py -property next: Node¶ +property next: Node ``` 返回链接列表中的下一个`Node`。 @@ -1833,7 +1833,7 @@ property next: Node¶ 链接列表中的下一个`Node`。 ```py -normalized_arguments(root, arg_types=None, kwarg_types=None, normalize_to_only_use_kwargs=False)¶ +normalized_arguments(root, arg_types=None, kwarg_types=None, normalize_to_only_use_kwargs=False) ``` 将参数标准化为 Python 目标的参数。这意味着 args/kwargs 将与模块/功能的签名匹配,并且如果 normalize_to_only_use_kwargs 为 true,则仅以位置顺序返回 kwargs。还填充默认值。不支持仅位置参数或可变参数。 @@ -1865,7 +1865,7 @@ normalized_arguments(root, arg_types=None, kwarg_types=None, normalize_to_only_u 此 API 是实验性的,*不*向后兼容。 ```py -prepend(x)¶ +prepend(x) ``` 在图中的节点列表中的此节点之前插入 x。示例: @@ -1886,7 +1886,7 @@ After: p -> x -> self 此 API 的向后兼容性得到保证。 ```py -property prev: Node¶ +property prev: Node ``` 返回链接列表中的上一个`Node`。 @@ -1896,7 +1896,7 @@ property prev: Node¶ 链接列表中的上一个`Node`。 ```py -replace_all_uses_with(replace_with, delete_user_cb=>, *, propagate_meta=False)¶ +replace_all_uses_with(replace_with, delete_user_cb=>, *, propagate_meta=False) ``` 用 Node`replace_with`替换图中所有`self`的使用。 @@ -1922,7 +1922,7 @@ replace_all_uses_with(replace_with, delete_user_cb=>, *, 此 API 的向后兼容性得到保证。 ```py -replace_input_with(old_input, new_input)¶ +replace_input_with(old_input, new_input) ``` 循环遍历`self`的输入节点,并用`new_input`替换所有`old_input`的实例。 @@ -1938,7 +1938,7 @@ replace_input_with(old_input, new_input)¶ 此 API 的向后兼容性已得到保证。 ```py -property stack_trace: Optional[str]¶ +property stack_trace: Optional[str] ``` 返回在跟踪期间记录的 Python 堆栈跟踪,如果有的话。使用 fx.Tracer 跟踪时,此属性通常由 Tracer.create_proxy 填充。为了记录跟踪期间的堆栈跟踪以进行调试,可以在 Tracer 实例上设置 record_stack_traces = True。使用 dynamo 跟踪时,此属性将默认由 OutputGraph.create_proxy 填充。 @@ -1946,7 +1946,7 @@ property stack_trace: Optional[str]¶ stack_trace 将在字符串末尾具有最内部的帧。 ```py -update_arg(idx, arg)¶ +update_arg(idx, arg) ``` 更新现有的位置参数以包含新值`arg`。调用后,`self.args[idx] == arg`。 @@ -1962,7 +1962,7 @@ update_arg(idx, arg)¶ 此 API 的向后兼容性已得到保证。 ```py -update_kwarg(key, arg)¶ +update_kwarg(key, arg) ``` 更新现有的关键字参数以包含新值`arg`。调用后,`self.kwargs[key] == arg`。 @@ -1978,7 +1978,7 @@ update_kwarg(key, arg)¶ 此 API 的向后兼容性已得到保证。 ```py -class torch.fx.Tracer(autowrap_modules=(math,), autowrap_functions=())¶ +class torch.fx.Tracer(autowrap_modules=(math,), autowrap_functions=()) ``` > `Tracer`是实现`torch.fx.symbolic_trace`的符号跟踪功能的类。对`symbolic_trace(m)`的调用等效于`Tracer().trace(m)`。 @@ -1990,7 +1990,7 @@ class torch.fx.Tracer(autowrap_modules=(math,), autowrap_functions=())¶ 此 API 的向后兼容性已得到保证。 ```py -call_module(m, forward, args, kwargs)¶ +call_module(m, forward, args, kwargs) ``` 指定此`Tracer`在遇到对`nn.Module`实例的调用时的行为的方法。 @@ -2022,7 +2022,7 @@ call_module(m, forward, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -create_arg(a)¶ +create_arg(a) ``` 一种方法,用于指定在准备将值用作图中节点的参数时跟踪的行为。 @@ -2058,7 +2058,7 @@ create_arg(a)¶ 此 API 的向后兼容性已经得到保证。 ```py -create_args_for_root(root_fn, is_module, concrete_args=None)¶ +create_args_for_root(root_fn, is_module, concrete_args=None) ``` 创建与`root`模块的签名对应的`placeholder`节点。此方法审查 root 的签名并相应地发出这些节点,还支持`*args`和`**kwargs`。 @@ -2068,7 +2068,7 @@ create_args_for_root(root_fn, is_module, concrete_args=None)¶ 此 API 是实验性的,*不*向后兼容。 ```py -create_node(kind, target, args, kwargs, name=None, type_expr=None)¶ +create_node(kind, target, args, kwargs, name=None, type_expr=None) ``` 插入一个给定目标、args、kwargs 和名称的图节点。 @@ -2084,7 +2084,7 @@ create_node(kind, target, args, kwargs, name=None, type_expr=None)¶ *Node* ```py -create_proxy(kind, target, args, kwargs, name=None, type_expr=None, proxy_factory_fn=None)¶ +create_proxy(kind, target, args, kwargs, name=None, type_expr=None, proxy_factory_fn=None) ``` 从给定的参数创建一个节点,然后返回包装在代理对象中的节点。 @@ -2096,7 +2096,7 @@ create_proxy(kind, target, args, kwargs, name=None, type_expr=None, proxy_factor 此 API 的向后兼容性已经得到保证。 ```py -getattr(attr, attr_val, parameter_proxy_cache)¶ +getattr(attr, attr_val, parameter_proxy_cache) ``` 指定当我们在调用`nn.Module`实例的`getattr`时,此`Tracer`的行为的方法。 @@ -2122,7 +2122,7 @@ getattr(attr, attr_val, parameter_proxy_cache)¶ 此 API 是实验性的,*不*向后兼容。 ```py -is_leaf_module(m, module_qualified_name)¶ +is_leaf_module(m, module_qualified_name) ``` 指定给定的`nn.Module`是否是“叶子”模块的方法。 @@ -2144,7 +2144,7 @@ is_leaf_module(m, module_qualified_name)¶ 此 API 的向后兼容性得到保证。 ```py -iter(obj)¶ +iter(obj) ``` 当代理对象被迭代时调用,例如 @@ -2160,7 +2160,7 @@ iter(obj)¶ [*Iterator*](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.12)") ```py -keys(obj)¶ +keys(obj) ``` 当代理对象调用 keys()方法时调用。 @@ -2176,7 +2176,7 @@ keys(obj)¶ [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)") ```py -path_of_module(mod)¶ +path_of_module(mod) ``` 在`root`的模块层次结构中查找`mod`的限定名称的辅助方法。例如,如果`root`有一个名为`foo`的子模块,其中有一个名为`bar`的子模块,将`bar`传递给此函数将返回字符串“foo.bar”。 @@ -2194,7 +2194,7 @@ path_of_module(mod)¶ 此 API 的向后兼容性得到保证。 ```py -proxy(node)¶ +proxy(node) ``` 注意 @@ -2206,7 +2206,7 @@ proxy(node)¶ *Proxy* ```py -to_bool(obj)¶ +to_bool(obj) ``` 当代理对象被转换为布尔值时调用,例如 @@ -2222,7 +2222,7 @@ to_bool(obj)¶ [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") ```py -trace(root, concrete_args=None)¶ +trace(root, concrete_args=None) ``` 跟踪`root`并返回相应的 FX`Graph`表示。`root`可以是`nn.Module`实例或 Python 可调用对象。 @@ -2248,7 +2248,7 @@ trace(root, concrete_args=None)¶ 此 API 的向后兼容性得到保证。 ```py -class torch.fx.Proxy(node, tracer=None)¶ +class torch.fx.Proxy(node, tracer=None) ``` `Proxy`对象是`Node`包装器,它们在符号跟踪期间流经程序,并记录它们触及的所有操作(`torch`函数调用,方法调用,运算符)到不断增长的 FX 图中。 @@ -2271,7 +2271,7 @@ for i in range(self.some_hyperparameter): 此 API 的向后兼容性是有保证的。 ```py -class torch.fx.Interpreter(module, garbage_collect_values=True)¶ +class torch.fx.Interpreter(module, garbage_collect_values=True) ``` Interpreter 逐节点执行 FX 图。这种模式对于许多事情都很有用,包括编写代码转换以及分析传递。 @@ -2328,7 +2328,7 @@ torch.testing.assert_close(result, torch.neg(input).sigmoid()) 此 API 的向后兼容性是有保证的。 ```py -boxed_run(args_list)¶ +boxed_run(args_list) ``` 通过解释运行模块并返回结果。这使用“封装”调用约定,您传递一个参数列表,该列表将被解释器清除。这确保输入张量会被及时释放。 @@ -2338,7 +2338,7 @@ boxed_run(args_list)¶ 此 API 的向后兼容性是有保证的。 ```py -call_function(target, args, kwargs)¶ +call_function(target, args, kwargs) ``` 执行`call_function`节点并返回结果。 @@ -2364,7 +2364,7 @@ call_function(target, args, kwargs)¶ 此 API 的向后兼容性是有保证的。 ```py -call_method(target, args, kwargs)¶ +call_method(target, args, kwargs) ``` 执行`call_method`节点并返回结果。 @@ -2390,7 +2390,7 @@ call_method(target, args, kwargs)¶ 此 API 的向后兼容性是有保证的。 ```py -call_module(target, args, kwargs)¶ +call_module(target, args, kwargs) ``` 执行`call_module`节点并返回结果。 @@ -2416,7 +2416,7 @@ call_module(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -fetch_args_kwargs_from_env(n)¶ +fetch_args_kwargs_from_env(n) ``` 从当前执行环境中获取节点`n`的`args`和`kwargs`的具体值。 @@ -2438,7 +2438,7 @@ Tuple[Tuple, Dict] 此 API 的向后兼容性已得到保证。 ```py -fetch_attr(target)¶ +fetch_attr(target) ``` 从`self.module`的`Module`层次结构中提取属性。 @@ -2460,7 +2460,7 @@ fetch_attr(target)¶ 此 API 的向后兼容性已得到保证。 ```py -get_attr(target, args, kwargs)¶ +get_attr(target, args, kwargs) ``` 执行一个`get_attr`节点。将从`self.module`的`Module`层次结构中检索属性值。 @@ -2486,7 +2486,7 @@ get_attr(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -map_nodes_to_values(args, n)¶ +map_nodes_to_values(args, n) ``` 递归地遍历`args`并查找当前执行环境中每个`Node`的具体值。 @@ -2506,7 +2506,7 @@ map_nodes_to_values(args, n)¶ 此 API 的向后兼容性已得到保证。 ```py -output(target, args, kwargs)¶ +output(target, args, kwargs) ``` 执行一个`output`节点。这只是检索由`output`节点引用的值并返回它。 @@ -2532,7 +2532,7 @@ output(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -placeholder(target, args, kwargs)¶ +placeholder(target, args, kwargs) ``` 执行`placeholder`节点。请注意,这是有状态的:`Interpreter`在传递给`run`的参数上维护一个内部迭代器,此方法在该迭代器上返回 next()。 @@ -2558,7 +2558,7 @@ placeholder(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -run(*args, initial_env=None, enable_io_processing=True)¶ +run(*args, initial_env=None, enable_io_processing=True) ``` 通过解释运行模块并返回结果。 @@ -2584,7 +2584,7 @@ run(*args, initial_env=None, enable_io_processing=True)¶ 此 API 的向后兼容性已得到保证。 ```py -run_node(n)¶ +run_node(n) ``` 运行特定节点`n`并返回结果。根据`node.op`调用占位符、get_attr、call_function、call_method、call_module 或输出 @@ -2606,7 +2606,7 @@ run_node(n)¶ 此 API 的向后兼容性已得到保证。 ```py -class torch.fx.Transformer(module)¶ +class torch.fx.Transformer(module) ``` `Transformer`是一种特殊类型的解释器,它生成一个新的`Module`。它公开了一个返回转换后`Module`的`transform()`方法。`Transformer`不需要参数来运行,而`Interpreter`需要。`Transformer`完全以符号方式工作。 @@ -2647,7 +2647,7 @@ torch.testing.assert_close(transformed(input), torch.neg(input).sigmoid()) 此 API 的向后兼容性已得到保证。 ```py -call_function(target, args, kwargs)¶ +call_function(target, args, kwargs) ``` 注意 @@ -2659,7 +2659,7 @@ call_function(target, args, kwargs)¶ [*任何*](https://docs.python.org/3/library/typing.html#typing.Any "(在 Python v3.12 中)") ```py -call_module(target, args, kwargs)¶ +call_module(target, args, kwargs) ``` 注意 @@ -2671,7 +2671,7 @@ call_module(target, args, kwargs)¶ [*任何*](https://docs.python.org/3/library/typing.html#typing.Any "(在 Python v3.12 中)") ```py -get_attr(target, args, kwargs)¶ +get_attr(target, args, kwargs) ``` 执行`get_attr`节点。在`Transformer`中,这被重写为将一个新的`get_attr`节点插入输出图中。 @@ -2693,7 +2693,7 @@ get_attr(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -placeholder(target, args, kwargs)¶ +placeholder(target, args, kwargs) ``` 执行`placeholder`节点。在`Transformer`中,这被重写为将一个新的`placeholder`插入输出图中。 @@ -2715,7 +2715,7 @@ placeholder(target, args, kwargs)¶ 此 API 的向后兼容性已得到保证。 ```py -transform()¶ +transform() ``` 转换`self.module`并返回转换后的`GraphModule`。 @@ -2729,7 +2729,7 @@ transform()¶ *GraphModule* ```py -torch.fx.replace_pattern(gm, pattern, replacement)¶ +torch.fx.replace_pattern(gm, pattern, replacement) ``` 在 GraphModule(`gm`)的图中匹配所有可能的非重叠运算符及其数据依赖关系(`pattern`),然后用另一个子图(`replacement`)替换这些匹配的子图。 diff --git a/totrans/doc22_059.md b/totrans/doc22_059.md index ff679b03c54b5a7e2fa6da0f9a3ffd37cee4e9e9..f5934c9bf660f1c2b006227b625332381078b49e 100644 --- a/totrans/doc22_059.md +++ b/totrans/doc22_059.md @@ -69,7 +69,7 @@ if pretrained: Pytorch Hub 提供了方便的 API,通过`torch.hub.list()`来探索 hub 中所有可用的模型,通过`torch.hub.help()`显示文档字符串和示例,以及使用`torch.hub.load()`加载预训练模型。 ```py -torch.hub.list(github, force_reload=False, skip_validation=False, trust_repo=None)¶ +torch.hub.list(github, force_reload=False, skip_validation=False, trust_repo=None) ``` 列出由`github`指定的存储库中可调用的所有入口点。 @@ -111,7 +111,7 @@ torch.hub.list(github, force_reload=False, skip_validation=False, trust_repo=Non ``` ```py -torch.hub.help(github, model, force_reload=False, skip_validation=False, trust_repo=None)¶ +torch.hub.help(github, model, force_reload=False, skip_validation=False, trust_repo=None) ``` 显示入口点`model`的文档字符串。 @@ -147,7 +147,7 @@ torch.hub.help(github, model, force_reload=False, skip_validation=False, trust_r ``` ```py -torch.hub.load(repo_or_dir, model, *args, source='github', trust_repo=None, force_reload=False, verbose=True, skip_validation=False, **kwargs)¶ +torch.hub.load(repo_or_dir, model, *args, source='github', trust_repo=None, force_reload=False, verbose=True, skip_validation=False, **kwargs) ``` 从 github 存储库或本地目录加载模型。 @@ -206,7 +206,7 @@ torch.hub.load(repo_or_dir, model, *args, source='github', trust_repo=None, forc ``` ```py -torch.hub.download_url_to_file(url, dst, hash_prefix=None, progress=True)¶ +torch.hub.download_url_to_file(url, dst, hash_prefix=None, progress=True) ``` - 将给定 URL 处的对象下载到本地路径。 @@ -228,7 +228,7 @@ torch.hub.download_url_to_file(url, dst, hash_prefix=None, progress=True)¶ ``` ```py -torch.hub.load_state_dict_from_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None, weights_only=False)¶ +torch.hub.load_state_dict_from_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None, weights_only=False) ``` - 加载给定 URL 处的 Torch 序列化对象。 @@ -286,7 +286,7 @@ torch.hub.load_state_dict_from_url(url, model_dir=None, map_location=None, progr + `~/.cache/torch/hub` ```py -torch.hub.get_dir()¶ +torch.hub.get_dir() ``` 获取用于存储下载模型和权重的 Torch Hub 缓存目录。 @@ -294,7 +294,7 @@ torch.hub.get_dir()¶ 如果未调用`set_dir()`,默认路径为`$TORCH_HOME/hub`,其中环境变量`$TORCH_HOME`默认为`$XDG_CACHE_HOME/torch`。`$XDG_CACHE_HOME`遵循 Linux 文件系统布局的 X Design Group 规范,如果未设置环境变量,则默认值为`~/.cache`。 ```py -torch.hub.set_dir(d)¶ +torch.hub.set_dir(d) ``` 可选设置用于保存下载模型和权重的 Torch Hub 目录。 diff --git a/totrans/doc22_060.md b/totrans/doc22_060.md index 1e27953d3d8790be5772370154a2ad6075b108a0..cb74cf97be2f7372ea0da1e36654085ac8689db9 100644 --- a/totrans/doc22_060.md +++ b/totrans/doc22_060.md @@ -569,7 +569,7 @@ my_scripted_model = torch.jit.script(my_model) 当传递给`torch.jit.script`函数时,`torch.nn.Module`的数据会被复制到一个`ScriptModule`中,TorchScript 编译器会编译该模块。模块的`forward`默认被编译。从`forward`调用的方法会按照它们在`forward`中被使用的顺序进行延迟编译,以及任何`@torch.jit.export`方法。 ```py -torch.jit.export(fn)¶ +torch.jit.export(fn) ``` 这个装饰器表示`nn.Module`上的一个方法被用作进入`ScriptModule`的入口点,并且应该被编译。 diff --git a/totrans/doc22_062.md b/totrans/doc22_062.md index 685b14be4a290cce66234f0a318efc662f383178..5506d95b6a5423e4ccde1bbf642c1d6dde2f4fa0 100644 --- a/totrans/doc22_062.md +++ b/totrans/doc22_062.md @@ -17,7 +17,7 @@ ## API 参考 ```py -class torch.monitor.Aggregation¶ +class torch.monitor.Aggregation ``` > 这些是可用于累积统计数据的聚合类型。 @@ -49,11 +49,11 @@ class torch.monitor.Aggregation¶ > MIN 返回添加值的最小值。 ```py -property name¶ +property name ``` ```py -class torch.monitor.Stat¶ +class torch.monitor.Stat ``` Stat 用于以高效的方式在固定间隔内计算摘要统计信息。Stat 每隔`window_size`持续时间记录一次统计信息作为事件。当窗口关闭时,统计信息将通过事件处理程序作为`torch.monitor.Stat`事件记录。 @@ -65,43 +65,43 @@ Stat 用于以高效的方式在固定间隔内计算摘要统计信息。Stat 当 Stat 被销毁时,即使窗口尚未过去,也会记录任何剩余数据。 ```py -__init__(self: torch._C._monitor.Stat, name: str, aggregations: List[torch._C._monitor.Aggregation], window_size: datetime.timedelta, max_samples: int = 9223372036854775807) → None¶ +__init__(self: torch._C._monitor.Stat, name: str, aggregations: List[torch._C._monitor.Aggregation], window_size: datetime.timedelta, max_samples: int = 9223372036854775807) → None ``` 构造`Stat`。 ```py -add(self: torch._C._monitor.Stat, v: float) → None¶ +add(self: torch._C._monitor.Stat, v: float) → None ``` 将一个值添加到要根据配置的统计类型和聚合进行聚合的统计数据中。 ```py -property count¶ +property count ``` 当前已收集的数据点数量。一旦事件已记录,将重置。 ```py -get(self: torch._C._monitor.Stat) → Dict[torch._C._monitor.Aggregation, float]¶ +get(self: torch._C._monitor.Stat) → Dict[torch._C._monitor.Aggregation, float] ``` 返回统计数据的当前值,主要用于测试目的。如果统计数据已记录且未添加任何额外值,则该值将为零。 ```py -property name¶ +property name ``` 在创建时设置的统计名称。 ```py -class torch.monitor.data_value_t¶ +class torch.monitor.data_value_t ``` data_value_t 是`str`、`float`、`int`、`bool`之一。 ```py -class torch.monitor.Event¶ +class torch.monitor.Event ``` Event 表示要记录的特定类型事件。这可以表示每个时代的损失或准确性等高级数据点,或者通过此库提供的统计数据进行更低级别的聚合。 @@ -109,37 +109,37 @@ Event 表示要记录的特定类型事件。这可以表示每个时代的损 所有相同类型的事件应具有相同的名称,以便下游处理程序可以正确处理它们。 ```py -__init__(self: torch._C._monitor.Event, name: str, timestamp: datetime.datetime, data: Dict[str, data_value_t]) → None¶ +__init__(self: torch._C._monitor.Event, name: str, timestamp: datetime.datetime, data: Dict[str, data_value_t]) → None ``` 构造`Event`。 ```py -property data¶ +property data ``` 包含在`Event`中的结构化数据。 ```py -property name¶ +property name ``` `Event`的名称。 ```py -property timestamp¶ +property timestamp ``` 事件发生时的时间戳。 ```py -class torch.monitor.EventHandlerHandle¶ +class torch.monitor.EventHandlerHandle ``` EventHandlerHandle 是由`register_event_handler`返回的包装类型,用于通过`unregister_event_handler`取消注册处理程序。不能直接初始化。 ```py -torch.monitor.log_event(event: torch._C._monitor.Event) → None¶ +torch.monitor.log_event(event: torch._C._monitor.Event) → None ``` log_event 将指定的事件记录到所有已注册的事件处理程序中。由事件处理程序负责将事件记录到相应的事件接收器。 @@ -147,19 +147,19 @@ log_event 将指定的事件记录到所有已注册的事件处理程序中。 如果没有注册事件处理程序,则此方法不执行任何操作。 ```py -torch.monitor.register_event_handler(callback: Callable[[torch._C._monitor.Event], None]) → torch._C._monitor.EventHandlerHandle¶ +torch.monitor.register_event_handler(callback: Callable[[torch._C._monitor.Event], None]) → torch._C._monitor.EventHandlerHandle ``` register_event_handler 注册一个回调,每当通过`log_event`记录事件时都会调用该回调。这些处理程序应避免阻塞主线程,因为这可能会干扰训练,因为它们在`log_event`调用期间运行。 ```py -torch.monitor.unregister_event_handler(handler: torch._C._monitor.EventHandlerHandle) → None¶ +torch.monitor.unregister_event_handler(handler: torch._C._monitor.EventHandlerHandle) → None ``` unregister_event_handler 取消注册在调用`register_event_handler`后返回的`EventHandlerHandle`。完成后,事件处理程序将不再接收事件。 ```py -class torch.monitor.TensorboardEventHandler(writer)¶ +class torch.monitor.TensorboardEventHandler(writer) ``` TensorboardEventHandler 是一个事件处理程序,将已知事件写入提供的 SummaryWriter。 @@ -176,7 +176,7 @@ TensorboardEventHandler 是一个事件处理程序,将已知事件写入提 ``` ```py -__init__(writer)¶ +__init__(writer) ``` 构造`TensorboardEventHandler`。 diff --git a/totrans/doc22_064.md b/totrans/doc22_064.md index 2a373917cfa7db2892f07ba40a191aa197317ac3..6eb9c69933c62a097c888fb3db8dd4262d5484a4 100644 --- a/totrans/doc22_064.md +++ b/totrans/doc22_064.md @@ -7,7 +7,7 @@ torch.special 模块,模仿 SciPy 的[special](https://docs.scipy.org/doc/scip ## 函数 ```py -torch.special.airy_ai(input, *, out=None) → Tensor¶ +torch.special.airy_ai(input, *, out=None) → Tensor ``` Airy 函数$\text{Ai}\left(\text{input}\right)$。 @@ -21,7 +21,7 @@ Airy 函数$\text{Ai}\left(\text{input}\right)$。 - 输出张量(可选)- 输出张量。 ```py -torch.special.bessel_j0(input, *, out=None) → Tensor¶ +torch.special.bessel_j0(input, *, out=None) → Tensor ``` 第一类贝塞尔函数的阶数为$0$。 @@ -35,7 +35,7 @@ torch.special.bessel_j0(input, *, out=None) → Tensor¶ - 输出张量(可选)- 输出张量。 ```py -torch.special.bessel_j1(input, *, out=None) → Tensor¶ +torch.special.bessel_j1(input, *, out=None) → Tensor ``` 第一类贝塞尔函数的阶数为$1$。 @@ -49,7 +49,7 @@ torch.special.bessel_j1(input, *, out=None) → Tensor¶ - 输出张量(可选)- 输出张量。 ```py -torch.special.digamma(input, *, out=None) → Tensor¶ +torch.special.digamma(input, *, out=None) → Tensor ``` 计算输入上的伽玛函数的对数导数。 @@ -81,7 +81,7 @@ tensor([-0.5772, -1.9635]) ``` ```py -torch.special.entr(input, *, out=None) → Tensor¶ +torch.special.entr(input, *, out=None) → Tensor ``` 计算输入上的熵(如下所定义),逐元素。 @@ -107,7 +107,7 @@ tensor([ -inf, 0.0000, 0.3466]) ``` ```py -torch.special.erf(input, *, out=None) → Tensor¶ +torch.special.erf(input, *, out=None) → Tensor ``` 计算输入的误差函数。误差函数定义如下: @@ -130,7 +130,7 @@ tensor([ 0.0000, -0.8427, 1.0000]) ``` ```py -torch.special.erfc(input, *, out=None) → Tensor¶ +torch.special.erfc(input, *, out=None) → Tensor ``` 计算输入的互补误差函数。互补误差函数定义如下: @@ -153,7 +153,7 @@ tensor([ 1.0000, 1.8427, 0.0000]) ``` ```py -torch.special.erfcx(input, *, out=None) → Tensor¶ +torch.special.erfcx(input, *, out=None) → Tensor ``` 计算输入的每个元素的缩放互补误差函数。缩放互补误差函数定义如下: @@ -176,7 +176,7 @@ tensor([ 1.0000, 5.0090, 0.0561]) ``` ```py -torch.special.erfinv(input, *, out=None) → Tensor¶ +torch.special.erfinv(input, *, out=None) → Tensor ``` 计算输入的逆误差函数。逆误差函数在范围$(-1, 1)$内定义如下: @@ -199,7 +199,7 @@ tensor([ 0.0000, 0.4769, -inf]) ``` ```py -torch.special.exp2(input, *, out=None) → Tensor¶ +torch.special.exp2(input, *, out=None) → Tensor ``` 计算输入的以 2 为底的指数函数。 @@ -222,7 +222,7 @@ tensor([ 1., 2., 8., 16.]) ``` ```py -torch.special.expit(input, *, out=None) → Tensor¶ +torch.special.expit(input, *, out=None) → Tensor ``` 计算`input`元素的 expit(也称为逻辑 Sigmoid 函数)。 @@ -248,7 +248,7 @@ tensor([ 0.7153, 0.7481, 0.2920, 0.1458]) ``` ```py -torch.special.expm1(input, *, out=None) → Tensor¶ +torch.special.expm1(input, *, out=None) → Tensor ``` 计算`input`元素减 1 的指数。 @@ -275,7 +275,7 @@ tensor([ 0., 1.]) ``` ```py -torch.special.gammainc(input, other, *, out=None) → Tensor¶ +torch.special.gammainc(input, other, *, out=None) → Tensor ``` 计算正则化的下不完全伽玛函数: @@ -317,7 +317,7 @@ tensor([1., 1., 1.]) ``` ```py -torch.special.gammaincc(input, other, *, out=None) → Tensor¶ +torch.special.gammaincc(input, other, *, out=None) → Tensor ``` 计算正则化的上不完全伽玛函数: @@ -358,7 +358,7 @@ tensor([1., 1., 1.]) ``` ```py -torch.special.gammaln(input, *, out=None) → Tensor¶ +torch.special.gammaln(input, *, out=None) → Tensor ``` 计算`input`上伽玛函数绝对值的自然对数。 @@ -382,7 +382,7 @@ tensor([ 0.5724, 0.0000, -0.1208]) ``` ```py -torch.special.i0(input, *, out=None) → Tensor¶ +torch.special.i0(input, *, out=None) → Tensor ``` 计算每个`input`元素的第零阶修正贝塞尔函数(如下所定义)。 @@ -405,7 +405,7 @@ tensor([ 1.0000, 1.2661, 2.2796, 4.8808, 11.3019]) ``` ```py -torch.special.i0e(input, *, out=None) → Tensor¶ +torch.special.i0e(input, *, out=None) → Tensor ``` 计算每个`input`元素的指数缩放的第零阶修正贝塞尔函数(如下所定义)。 @@ -428,7 +428,7 @@ tensor([1.0000, 0.4658, 0.3085, 0.2430, 0.2070]) ``` ```py -torch.special.i1(input, *, out=None) → Tensor¶ +torch.special.i1(input, *, out=None) → Tensor ``` 计算每个`input`元素的第一类修正贝塞尔函数(如下所定义)。 @@ -451,7 +451,7 @@ tensor([0.0000, 0.5652, 1.5906, 3.9534, 9.7595]) ``` ```py -torch.special.i1e(input, *, out=None) → Tensor¶ +torch.special.i1e(input, *, out=None) → Tensor ``` 计算每个`input`元素的指数缩放的第一类修正贝塞尔函数(如下所定义)。 @@ -474,13 +474,13 @@ tensor([0.0000, 0.2079, 0.2153, 0.1968, 0.1788]) ``` ```py -torch.special.log1p(input, *, out=None) → Tensor¶ +torch.special.log1p(input, *, out=None) → Tensor ``` `torch.log1p()`的别名。 ```py -torch.special.log_ndtr(input, *, out=None) → Tensor¶ +torch.special.log_ndtr(input, *, out=None) → Tensor ``` 计算标准高斯概率密度函数下面积的对数,从负无穷到`input`,逐元素。 @@ -503,7 +503,7 @@ tensor([-6.6077 -3.7832 -1.841 -0.6931 -0.1728 -0.023 -0.0014]) ``` ```py -torch.special.log_softmax(input, dim, *, dtype=None) → Tensor¶ +torch.special.log_softmax(input, dim, *, dtype=None) → Tensor ``` 计算 softmax 后跟对数。 @@ -530,7 +530,7 @@ tensor([[-0.6931, -0.6931], ``` ```py -torch.special.logit(input, eps=None, *, out=None) → Tensor¶ +torch.special.logit(input, eps=None, *, out=None) → Tensor ``` 返回一个新张量,其中包含`input`元素的 logit。当 eps 不为 None 时,`input`被夹在[eps, 1 - eps]之间。当 eps 为 None 且`input` < 0 或`input` > 1 时,函数将产生 NaN。 @@ -556,13 +556,13 @@ tensor([-0.9466, 2.6352, 0.6131, -1.7169, 0.6261]) ``` ```py -torch.special.logsumexp(input, dim, keepdim=False, *, out=None)¶ +torch.special.logsumexp(input, dim, keepdim=False, *, out=None) ``` `torch.logsumexp()`的别名。 ```py -torch.special.multigammaln(input, p, *, out=None) → Tensor¶ +torch.special.multigammaln(input, p, *, out=None) → Tensor ``` 计算多元对数伽玛函数,维度为$p$,逐元素给出 @@ -594,7 +594,7 @@ tensor([[0.3928, 0.4007, 0.7586], ``` ```py -torch.special.ndtr(input, *, out=None) → Tensor¶ +torch.special.ndtr(input, *, out=None) → Tensor ``` 计算标准高斯概率密度函数下的面积,从负无穷积分到`输入`,逐元素计算。 @@ -613,7 +613,7 @@ tensor([0.0013, 0.0228, 0.1587, 0.5000, 0.8413, 0.9772, 0.9987]) ``` ```py -torch.special.ndtri(input, *, out=None) → Tensor¶ +torch.special.ndtri(input, *, out=None) → Tensor ``` 计算参数$x$,使得高斯概率密度函数下的面积(从负无穷积分到 x)等于`输入`,逐元素计算。 @@ -636,7 +636,7 @@ tensor([ -inf, -0.6745, 0.0000, 0.6745, inf]) ``` ```py -torch.special.polygamma(n, input, *, out=None) → Tensor¶ +torch.special.polygamma(n, input, *, out=None) → Tensor ``` 计算`输入`上的第$n$阶 digamma 函数的导数。$n \geq 0$ @@ -668,19 +668,19 @@ tensor([ -24.8863, -771.4742]) ``` ```py -torch.special.psi(input, *, out=None) → Tensor¶ +torch.special.psi(input, *, out=None) → Tensor ``` `torch.special.digamma()`的别名。 ```py -torch.special.round(input, *, out=None) → Tensor¶ +torch.special.round(input, *, out=None) → Tensor ``` `torch.round()`的别名。 ```py -torch.special.scaled_modified_bessel_k0(input, *, out=None) → Tensor¶ +torch.special.scaled_modified_bessel_k0(input, *, out=None) → Tensor ``` 第二类修正贝塞尔函数的缩放形式,阶数为$0$。 @@ -690,7 +690,7 @@ torch.special.scaled_modified_bessel_k0(input, *, out=None) → Tensor¶ **输入**(*张量**,* *可选*)- 输出张量。 ```py -torch.special.scaled_modified_bessel_k1(input, *, out=None) → Tensor¶ +torch.special.scaled_modified_bessel_k1(input, *, out=None) → Tensor ``` 第二类修正贝塞尔函数的缩放形式,阶数为$1$。 @@ -700,7 +700,7 @@ torch.special.scaled_modified_bessel_k1(input, *, out=None) → Tensor¶ **输入**(*张量**,* *可选*) - 输出张量。 ```py -torch.special.sinc(input, *, out=None) → Tensor¶ +torch.special.sinc(input, *, out=None) → Tensor ``` 计算`input`的归一化 sinc。 @@ -726,7 +726,7 @@ tensor([ 0.9186, 0.8631, -0.0259, -0.1300]) ``` ```py -torch.special.softmax(input, dim, *, dtype=None) → Tensor¶ +torch.special.softmax(input, dim, *, dtype=None) → Tensor ``` 计算 softmax 函数。 @@ -755,7 +755,7 @@ tensor([[0.5000, 0.5000], ``` ```py -torch.special.spherical_bessel_j0(input, *, out=None) → Tensor¶ +torch.special.spherical_bessel_j0(input, *, out=None) → Tensor ``` 第一类零阶球贝塞尔函数。 @@ -769,7 +769,7 @@ torch.special.spherical_bessel_j0(input, *, out=None) → Tensor¶ **out**(*Tensor**,* *可选*) - 输出张量。 ```py -torch.special.xlog1py(input, other, *, out=None) → Tensor¶ +torch.special.xlog1py(input, other, *, out=None) → Tensor ``` 使用以下情况计算`input * log1p(other)`。 @@ -810,7 +810,7 @@ tensor([2.7726, 2.1972, 1.3863]) ``` ```py -torch.special.xlogy(input, other, *, out=None) → Tensor¶ +torch.special.xlogy(input, other, *, out=None) → Tensor ``` 使用以下情况计算`input * log(other)`。 @@ -851,7 +851,7 @@ tensor([2.1972, 1.3863, 0.0000]) ``` ```py -torch.special.zeta(input, other, *, out=None) → Tensor¶ +torch.special.zeta(input, other, *, out=None) → Tensor ``` 逐元素计算 Hurwitz zeta 函数。 diff --git a/totrans/doc22_065.md b/totrans/doc22_065.md index 51f5b6b57ef5e48862e115078b83f8caec69942e..d747635bc345d330348a7b8dd70262c126011e8d 100644 --- a/totrans/doc22_065.md +++ b/totrans/doc22_065.md @@ -7,7 +7,7 @@ ## 函数 ```py -torch.overrides.get_ignored_functions()¶ +torch.overrides.get_ignored_functions() ``` 返回不能通过`__torch_function__`覆盖的公共函数。 @@ -30,7 +30,7 @@ False ``` ```py -torch.overrides.get_overridable_functions()¶ +torch.overrides.get_overridable_functions() ``` 列出可以通过 __torch_function__ 覆盖的函数 @@ -44,7 +44,7 @@ torch.overrides.get_overridable_functions()¶ Dict[Any, List[Callable]] ```py -torch.overrides.resolve_name(f)¶ +torch.overrides.resolve_name(f) ``` 获取传递给 __torch_function__ 的函数的人类可读字符串名称 @@ -62,7 +62,7 @@ torch.overrides.resolve_name(f)¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)") ```py -torch.overrides.get_testing_overrides()¶ +torch.overrides.get_testing_overrides() ``` 返回一个包含所有可重写函数的虚拟覆盖的字典 @@ -85,7 +85,7 @@ Dict[Callable, Callable] ``` ```py -torch.overrides.handle_torch_function(public_api, relevant_args, *args, **kwargs)¶ +torch.overrides.handle_torch_function(public_api, relevant_args, *args, **kwargs) ``` 实现带有`__torch_function__`覆盖的函数。 @@ -122,7 +122,7 @@ torch.overrides.handle_torch_function(public_api, relevant_args, *args, **kwargs ``` ```py -torch.overrides.has_torch_function()¶ +torch.overrides.has_torch_function() ``` 检查可迭代对象中元素的 __torch_function__ 实现,或者是否启用了 __torch_function__ 模式。将确切的`Tensor`和`Parameter`视为不可分派。使用此功能来保护对`handle_torch_function()`的调用;不要用它来测试某物是否类似于 Tensor,而是使用`is_tensor_like()`。:param relevant_args: 要检查 __torch_function__ 方法的可迭代对象或参数。:type relevant_args: iterable @@ -142,7 +142,7 @@ torch.overrides.has_torch_function()¶ 检查某物是否类似于 Tensor,包括确切的`Tensor`。 ```py -torch.overrides.is_tensor_like(inp)¶ +torch.overrides.is_tensor_like(inp) ``` 如果传入的输入是类似于 Tensor 的,则返回`True`。 @@ -183,7 +183,7 @@ True ``` ```py -torch.overrides.is_tensor_method_or_property(func)¶ +torch.overrides.is_tensor_method_or_property(func) ``` 如果传入的函数是`torch.Tensor`的方法或属性的处理程序,则返回 True,如传入`__torch_function__`。 @@ -212,7 +212,7 @@ False [bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)") ```py -torch.overrides.wrap_torch_function(dispatcher)¶ +torch.overrides.wrap_torch_function(dispatcher) ``` 使用与`__torch_function__`相关的功能包装给定的函数。 diff --git a/totrans/doc22_066.md b/totrans/doc22_066.md index be34027cf863a5eeb06d4464ea6741a133d86e24..f50c29221ec623c47ce82d971643de17d23e45b6 100644 --- a/totrans/doc22_066.md +++ b/totrans/doc22_066.md @@ -697,19 +697,19 @@ print(imported_MyClass.__name__) # prints .foo.MyClass ## API 参考 ```py -class torch.package.PackagingError(dependency_graph, debug=False)¶ +class torch.package.PackagingError(dependency_graph, debug=False) ``` 在导出包时出现问题时会引发此异常。`PackageExporter`将尝试收集所有错误并一次性呈现给您。 ```py -class torch.package.EmptyMatchError¶ +class torch.package.EmptyMatchError ``` 当在打包过程中遇到将 mock 或 extern 标记为`allow_empty=False`,并且在打包期间未匹配到任何模块时,将引发此异常。 ```py -class torch.package.PackageExporter(f, importer=, debug=False)¶ +class torch.package.PackageExporter(f, importer=, debug=False) ``` 导出器允许您将代码包、Python 数据、以及任意二进制和文本资源写入一个独立的包中。 @@ -723,7 +723,7 @@ class torch.package.PackageExporter(f, importer=, debug=False)¶ +__init__(f, importer=, debug=False) ``` 创建一个导出器。 @@ -737,13 +737,13 @@ __init__(f, importer=, debug=False) + **debug** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – 如果设置为 True,则将损坏模块的路径添加到 PackagingErrors 中。 ```py -add_dependency(module_name, dependencies=True)¶ +add_dependency(module_name, dependencies=True) ``` 给定一个模块,根据用户指定的模式将其添加到依赖图中。 ```py -all_paths(src, dst)¶ +all_paths(src, dst) ``` 返回子图的点表示 @@ -759,7 +759,7 @@ all_paths(src, dst)¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") ```py -close()¶ +close() ``` 将包写入文件系统。`close()`之后的任何调用现在都是无效的。最好使用资源保护语法: @@ -770,7 +770,7 @@ with PackageExporter("file.zip") as e: ``` ```py -denied_modules()¶ +denied_modules() ``` 返回当前被拒绝的所有模块。 @@ -784,7 +784,7 @@ denied_modules()¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")] ```py -deny(include, *, exclude=())¶ +deny(include, *, exclude=()) ``` 从包可以导入的模块列表中阻止与给定 glob 模式匹配的模块名称。如果找到任何匹配的包的依赖项,将引发`PackagingError`。 @@ -796,7 +796,7 @@ deny(include, *, exclude=())¶ + **exclude** (*Union**[**List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]**,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) – 一个可选模式,用于排除与包含字符串匹配的某些模式。 ```py -dependency_graph_string()¶ +dependency_graph_string() ``` 返回包中依赖项的双字母字符串表示。 @@ -810,7 +810,7 @@ dependency_graph_string()¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") ```py -extern(include, *, exclude=(), allow_empty=True)¶ +extern(include, *, exclude=(), allow_empty=True) ``` 将`module`包含在包可以导入的外部模块列表中。这将阻止依赖项发现将其保存在包中。导入程序将直接从标准导入系统加载外部模块。外部模块的代码也必须存在于加载包的进程中。 @@ -824,7 +824,7 @@ extern(include, *, exclude=(), allow_empty=True)¶ + **allow_empty**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"))- 一个可选标志,指定此调用`extern`方法指定的外部模块是否必须在打包过程中与某个模块匹配。如果添加了一个`allow_empty=False`的外部模块 glob 模式,并且在任何模块匹配该模式之前调用了`close()`(显式调用或通过`__exit__`),则会抛出异常。如果`allow_empty=True`,则不会抛出此类异常。 ```py -externed_modules()¶ +externed_modules() ``` 返回当前所有已经 externed 的模块。 @@ -838,7 +838,7 @@ externed_modules()¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")] ```py -get_rdeps(module_name)¶ +get_rdeps(module_name) ``` 返回一个依赖于模块`module_name`的所有模块的列表。 @@ -852,7 +852,7 @@ get_rdeps(module_name)¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")] ```py -get_unique_id()¶ +get_unique_id() ``` 获取一个 id。此 id 保证仅在此包中分配一次。 @@ -862,7 +862,7 @@ get_unique_id()¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)") ```py -intern(include, *, exclude=(), allow_empty=True)¶ +intern(include, *, exclude=(), allow_empty=True) ``` 指定应该打包的模块。模块必须匹配一些`intern`模式才能包含在包中,并且其依赖项会被递归处理。 @@ -876,7 +876,7 @@ intern(include, *, exclude=(), allow_empty=True)¶ + **allow_empty**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"))- 一个可选标志,指定此调用`intern`方法指定的 intern 模块是否必须在打包过程中与某个模块匹配。如果添加了一个`allow_empty=False`的`intern`模块 glob 模式,并且在任何模块匹配该模式之前调用了`close()`(显式调用或通过`__exit__`),则会抛出异常。如果`allow_empty=True`,则不会抛出此类异常。 ```py -interned_modules()¶ +interned_modules() ``` 返回当前所有已经 interned 的模块。 @@ -890,7 +890,7 @@ interned_modules()¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")] ```py -mock(include, *, exclude=(), allow_empty=True)¶ +mock(include, *, exclude=(), allow_empty=True) ``` 用模拟实现替换一些必需的模块。模拟的模块将为从中访问的任何属性返回一个虚假对象。因为我们是逐个文件复制的,所以依赖关系解析有时会找到由模型文件导入但其功能从未被使用的文件(例如自定义序列化代码或训练助手)。使用此函数可以模拟此功能,而无需修改原始代码。 @@ -912,7 +912,7 @@ mock(include, *, exclude=(), allow_empty=True)¶ + **allow_empty**(*bool*)- 一个可选标志,指定此调用`mock()`方法指定的模拟实现是否在打包期间必须与某个模块匹配。如果使用`allow_empty=False`添加了一个模拟,并且调用了`close()`(显式调用或通过`__exit__`),并且该模拟未与要导出的包使用的模块匹配,则会抛出异常。如果`allow_empty=True`,则不会抛出此类异常。 ```py -mocked_modules()¶ +mocked_modules() ``` 返回当前模拟的所有模块。 @@ -926,7 +926,7 @@ mocked_modules()¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")] ```py -register_extern_hook(hook)¶ +register_extern_hook(hook) ``` 在导出器上注册一个 extern 钩子。 @@ -948,7 +948,7 @@ hook(exporter: PackageExporter, module_name: str) -> None `torch.utils.hooks.RemovableHandle` ```py -register_intern_hook(hook)¶ +register_intern_hook(hook) ``` 在导出器上注册一个 intern 钩子。 @@ -970,7 +970,7 @@ hook(exporter: PackageExporter, module_name: str) -> None `torch.utils.hooks.RemovableHandle` ```py -register_mock_hook(hook)¶ +register_mock_hook(hook) ``` 在导出器上注册一个模拟钩子。 @@ -992,7 +992,7 @@ hook(exporter: PackageExporter, module_name: str) -> None `torch.utils.hooks.RemovableHandle` ```py -save_binary(package, resource, binary)¶ +save_binary(package, resource, binary) ``` 将原始字节保存到包中。 @@ -1006,7 +1006,7 @@ save_binary(package, resource, binary)¶ + **二进制**([*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")) - 要保存的数据。 ```py -save_module(module_name, dependencies=True)¶ +save_module(module_name, dependencies=True) ``` 将`module`的代码保存到包中。使用`importers`路径解析模块对象的代码,然后使用其`__file__`属性查找源代码。 @@ -1018,7 +1018,7 @@ save_module(module_name, dependencies=True)¶ + **依赖项**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),可选) - 如果为`True`,我们会扫描源代码以查找依赖项。 ```py -save_pickle(package, resource, obj, dependencies=True, pickle_protocol=3)¶ +save_pickle(package, resource, obj, dependencies=True, pickle_protocol=3) ``` 使用 pickle 将 Python 对象保存到存档中。相当于`torch.save()`,但保存到存档而不是独立文件。标准 pickle 不保存代码,只保存对象。如果`dependencies`为 true,则此方法还将扫描 pickled 对象以确定重建它们所需的模块,并保存相关代码。 @@ -1036,7 +1036,7 @@ save_pickle(package, resource, obj, dependencies=True, pickle_protocol=3)¶ + **依赖项**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),可选) - 如果为`True`,我们会扫描源代码以查找依赖项。 ```py -save_source_file(module_name, file_or_directory, dependencies=True)¶ +save_source_file(module_name, file_or_directory, dependencies=True) ``` 将本地文件系统中的`file_or_directory`添加到源包中,以提供`module_name`的代码。 @@ -1050,7 +1050,7 @@ save_source_file(module_name, file_or_directory, dependencies=True)¶ + **依赖项**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),可选) - 如果为`True`,我们会扫描源代码以查找依赖项。 ```py -save_source_string(module_name, src, is_package=False, dependencies=True)¶ +save_source_string(module_name, src, is_package=False, dependencies=True) ``` 在导出的包中将`src`作为`module_name`的源代码添加。 @@ -1066,7 +1066,7 @@ save_source_string(module_name, src, is_package=False, dependencies=True)¶ + **依赖**(*bool*,可选)- 如果为`True`,我们会扫描源代码以获取依赖项。 ```py -save_text(package, resource, text)¶ +save_text(package, resource, text) ``` 将文本数据保存到包中。 @@ -1080,7 +1080,7 @@ save_text(package, resource, text)¶ + **text**(*str*)- 要保存的内容。 ```py -class torch.package.PackageImporter(file_or_buffer, module_allowed=>)¶ +class torch.package.PackageImporter(file_or_buffer, module_allowed=>) ``` 导入器允许您加载由`PackageExporter`编写的包中的代码。代码以封闭方式加载,使用包中的文件而不是正常的 python 导入系统。这允许将 PyTorch 模型代码和数据打包,以便在服务器上运行或在将来用于迁移学习。 @@ -1088,7 +1088,7 @@ class torch.package.PackageImporter(file_or_buffer, module_allowed=>)¶ +__init__(file_or_buffer, module_allowed=>) ``` 打开`file_or_buffer`以进行导入。这将检查导入的包是否仅需要`module_allowed`允许的模块。 @@ -1104,7 +1104,7 @@ __init__(file_or_buffer, module_allowed=>)¶ [**ImportError**](https://docs.python.org/3/library/exceptions.html#ImportError "(in Python v3.12)")- 如果包将使用不允许的模块。 ```py -file_structure(*, include='**', exclude=())¶ +file_structure(*, include='**', exclude=()) ``` 返回包的 zip 文件结构表示。 @@ -1124,7 +1124,7 @@ file_structure(*, include='**', exclude=())¶ *Directory* ```py -id()¶ +id() ``` 返回内部标识符,torch.package 用于区分 `PackageImporter` 实例。看起来像: @@ -1134,7 +1134,7 @@ id()¶ ``` ```py -import_module(name, package=None)¶ +import_module(name, package=None) ``` 如果尚未加载包中的模块,则加载该模块,然后返回模块。模块在导入程序本地加载,并将出现在 `self.modules` 而不是 `sys.modules` 中。 @@ -1154,7 +1154,7 @@ import_module(name, package=None)¶ [types.ModuleType](https://docs.python.org/3/library/types.html#types.ModuleType "(in Python v3.12)") ```py -load_binary(package, resource)¶ +load_binary(package, resource) ``` 加载原始字节。 @@ -1174,7 +1174,7 @@ load_binary(package, resource)¶ [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.12)") ```py -load_pickle(package, resource, map_location=None)¶ +load_pickle(package, resource, map_location=None) ``` 从包中反序列化资源,加载任何需要构造对象的模块,使用 `import_module()`。 @@ -1196,7 +1196,7 @@ load_pickle(package, resource, map_location=None)¶ 任何 ```py -load_text(package, resource, encoding='utf-8', errors='strict')¶ +load_text(package, resource, encoding='utf-8', errors='strict') ``` 加载字符串。 @@ -1220,7 +1220,7 @@ load_text(package, resource, encoding='utf-8', errors='strict')¶ [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") ```py -python_version()¶ +python_version() ``` 返回用于创建此包的 python 版本。 @@ -1232,13 +1232,13 @@ python_version()¶ `Optional[str]` 一个 python 版本,例如 3.8.9,如果没有存储与此包相关的版本,则为 None ```py -class torch.package.Directory(name, is_dir)¶ +class torch.package.Directory(name, is_dir) ``` 文件结构表示。组织为具有其 Directory 子节点列表的 Directory 节点。通过调用 `PackageImporter.file_structure()` 来创建包的目录。 ```py -has_file(filename)¶ +has_file(filename) ``` 检查文件是否存在于 `Directory` 中。 diff --git a/totrans/doc22_067.md b/totrans/doc22_067.md index a335e0913a557db820645704f115bfa08a3aa8ce..8d789fa85e55f5849d462190b04646139587655c 100644 --- a/totrans/doc22_067.md +++ b/totrans/doc22_067.md @@ -13,7 +13,7 @@ PyTorch Profiler 是一个工具,允许在训练和推断过程中收集性能 ## API 参考 ```py -class torch.profiler._KinetoProfile(*, activities=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None)¶ +class torch.profiler._KinetoProfile(*, activities=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None) ``` 低级别分析器包装自动梯度分析 @@ -41,31 +41,31 @@ class torch.profiler._KinetoProfile(*, activities=None, record_shapes=False, pro 启用形状和堆栈跟踪会导致额外的开销。当指定 record_shapes=True 时,分析器将暂时保留对张量的引用;这可能进一步阻止依赖引用计数的某些优化,并引入额外的张量副本。 ```py -add_metadata(key, value)¶ +add_metadata(key, value) ``` 向跟踪文件中添加具有字符串键和字符串值的用户定义的元数据 ```py -add_metadata_json(key, value)¶ +add_metadata_json(key, value) ``` 向跟踪文件中添加具有字符串键和有效 json 值的用户定义的元数据 ```py -events()¶ +events() ``` 返回未聚合的分析器事件列表,用于在跟踪回调中使用或在分析完成后使用 ```py -export_chrome_trace(path)¶ +export_chrome_trace(path) ``` 以 Chrome JSON 格式导出收集的跟踪信息。 ```py -export_memory_timeline(path, device=None)¶ +export_memory_timeline(path, device=None) ``` 从收集的树中导出分析器的内存事件信息,用于给定设备,并导出时间线图。使用`export_memory_timeline`有 3 个可导出的文件,每个文件由`path`的后缀控制。 @@ -79,7 +79,7 @@ export_memory_timeline(path, device=None)¶ 输出:内存时间线以 gzipped JSON、JSON 或 HTML 形式编写。 ```py -export_stacks(path, metric='self_cpu_time_total')¶ +export_stacks(path, metric='self_cpu_time_total') ``` 将堆栈跟踪保存在适合可视化的文件中。 @@ -101,7 +101,7 @@ export_stacks(path, metric='self_cpu_time_total')¶ + ./flamegraph.pl –title “CPU time” –countname “us.” profiler.stacks > perf_viz.svg ```py -key_averages(group_by_input_shape=False, group_by_stack_n=0)¶ +key_averages(group_by_input_shape=False, group_by_stack_n=0) ``` 通过运算符名称和(可选)输入形状和堆栈对事件进行平均分组。 @@ -111,7 +111,7 @@ key_averages(group_by_input_shape=False, group_by_stack_n=0)¶ 要使用形状/堆栈功能,请确保在创建分析器上下文管理器时设置 record_shapes/with_stack。 ```py -class torch.profiler.profile(*, activities=None, schedule=None, on_trace_ready=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None, use_cuda=None)¶ +class torch.profiler.profile(*, activities=None, schedule=None, on_trace_ready=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None, use_cuda=None) ``` 分析器上下文管理器。 @@ -215,19 +215,19 @@ with torch.profiler.profile( ``` ```py -step()¶ +step() ``` 信号分析器下一个分析步骤已经开始。 ```py -class torch.profiler.ProfilerAction(value)¶ +class torch.profiler.ProfilerAction(value) ``` 在指定间隔可以执行的分析器操作 ```py -class torch.profiler.ProfilerActivity¶ +class torch.profiler.ProfilerActivity ``` 成员: @@ -241,11 +241,11 @@ MTIA CUDA ```py -property name¶ +property name ``` ```py -torch.profiler.schedule(*, wait, warmup, active, repeat=0, skip_first=0)¶ +torch.profiler.schedule(*, wait, warmup, active, repeat=0, skip_first=0) ``` 返回一个可用作分析器`schedule`参数的可调用对象。分析器将跳过前`skip_first`步,然后等待`wait`步,然后为接下来的`warmup`步进行预热,然后为接下来的`active`步进行活动记录,然后重复以`wait`步开始的循环。循环的可选次数由`repeat`参数指定,零值表示循环将持续直到分析完成。 @@ -255,7 +255,7 @@ torch.profiler.schedule(*, wait, warmup, active, repeat=0, skip_first=0)¶ [*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(在 Python v3.12 中)") ```py -torch.profiler.tensorboard_trace_handler(dir_name, worker_name=None, use_gzip=False)¶ +torch.profiler.tensorboard_trace_handler(dir_name, worker_name=None, use_gzip=False) ``` 将跟踪文件输出到`dir_name`目录,然后该目录可以直接作为 logdir 传递给 tensorboard。在分布式场景中,`worker_name`应该对每个 worker 是唯一的,默认情况下将设置为‘[hostname]_[pid]’。 @@ -263,13 +263,13 @@ torch.profiler.tensorboard_trace_handler(dir_name, worker_name=None, use_gzip=Fa ## 英特尔仪器和跟踪技术 APIs[](#intel-instrumentation-and-tracing-technology-apis "跳转到此标题") ```py -torch.profiler.itt.is_available()¶ +torch.profiler.itt.is_available() ``` 检查 ITT 功能是否可用 ```py -torch.profiler.itt.mark(msg)¶ +torch.profiler.itt.mark(msg) ``` 描述在某个时间点发生的瞬时事件。 @@ -279,7 +279,7 @@ torch.profiler.itt.mark(msg)¶ **msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")) – 与事件关联的 ASCII 消息。 ```py -torch.profiler.itt.range_push(msg)¶ +torch.profiler.itt.range_push(msg) ``` 将范围推送到嵌套范围堆栈上。返回开始的范围的从零开始的深度。 @@ -289,7 +289,7 @@ torch.profiler.itt.range_push(msg)¶ **msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")) – 与范围关联的 ASCII 消息 ```py -torch.profiler.itt.range_pop()¶ +torch.profiler.itt.range_pop() ``` 从嵌套范围跨度堆栈中弹出一个范围。返回结束的范围的从零开始的深度。 diff --git a/totrans/doc22_068.md b/totrans/doc22_068.md index e54b6bc46ab21eaf0cfc9aa4bce080b749ff1103..94047447dfe9f0fba100aee13d3ad2395bb22e66 100644 --- a/totrans/doc22_068.md +++ b/totrans/doc22_068.md @@ -7,7 +7,7 @@ 该模块中的所有函数都旨在用于初始化神经网络参数,因此它们都在`torch.no_grad()`模式下运行,并且不会被 autograd 考虑。 ```py -torch.nn.init.calculate_gain(nonlinearity, param=None)¶ +torch.nn.init.calculate_gain(nonlinearity, param=None) ``` 返回给定非线性函数的推荐增益值。 @@ -41,7 +41,7 @@ torch.nn.init.calculate_gain(nonlinearity, param=None)¶ ``` ```py -torch.nn.init.uniform_(tensor, a=0.0, b=1.0, generator=None)¶ +torch.nn.init.uniform_(tensor, a=0.0, b=1.0, generator=None) ``` 用从均匀分布中抽取的值填充输入张量。 @@ -70,7 +70,7 @@ $\mathcal{U}(a, b)$U(a,b). ``` ```py -torch.nn.init.normal_(tensor, mean=0.0, std=1.0, generator=None)¶ +torch.nn.init.normal_(tensor, mean=0.0, std=1.0, generator=None) ``` 用从正态分布中抽取的值填充输入张量。 @@ -99,7 +99,7 @@ $\mathcal{N}(\text{mean}, \text{std}²)$N(mean,std2). ``` ```py -torch.nn.init.constant_(tensor, val)¶ +torch.nn.init.constant_(tensor, val) ``` 用值$\text{val}$填充输入张量。 @@ -122,7 +122,7 @@ torch.nn.init.constant_(tensor, val)¶ ``` ```py -torch.nn.init.ones_(tensor)¶ +torch.nn.init.ones_(tensor) ``` 用标量值 1 填充输入张量。 @@ -143,7 +143,7 @@ torch.nn.init.ones_(tensor)¶ ``` ```py -torch.nn.init.zeros_(tensor)¶ +torch.nn.init.zeros_(tensor) ``` 用标量值 0 填充输入张量。 @@ -164,7 +164,7 @@ torch.nn.init.zeros_(tensor)¶ ``` ```py -torch.nn.init.eye_(tensor)¶ +torch.nn.init.eye_(tensor) ``` 用单位矩阵填充 2 维输入张量。 @@ -183,7 +183,7 @@ torch.nn.init.eye_(tensor)¶ ``` ```py -torch.nn.init.dirac_(tensor, groups=1)¶ +torch.nn.init.dirac_(tensor, groups=1) ``` 使用 Dirac delta 函数填充{3, 4, 5}维度的输入张量。 @@ -206,7 +206,7 @@ torch.nn.init.dirac_(tensor, groups=1)¶ ``` ```py -torch.nn.init.xavier_uniform_(tensor, gain=1.0, generator=None)¶ +torch.nn.init.xavier_uniform_(tensor, gain=1.0, generator=None) ``` 使用 Xavier 均匀分布填充输入张量的值。 @@ -237,7 +237,7 @@ $a = \text{gain} \times \sqrt{\frac{6}{\text{fan\_in} + \text{fan\_out}}}$ ``` ```py -torch.nn.init.xavier_normal_(tensor, gain=1.0, generator=None)¶ +torch.nn.init.xavier_normal_(tensor, gain=1.0, generator=None) ``` 使用 Xavier 正态分布填充输入张量的值。 @@ -268,7 +268,7 @@ $\text{std} = \text{gain} \times \sqrt{\frac{2}{\text{fan\_in} + \text{fan\_out} ``` ```py -torch.nn.init.kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)¶ +torch.nn.init.kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None) ``` 使用 Kaiming 均匀分布填充输入张量的值。 @@ -299,7 +299,7 @@ $\text{bound} = \text{gain} \times \sqrt{\frac{3}{\text{fan\_mode}}}$ ``` ```py -torch.nn.init.kaiming_normal_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None)¶ +torch.nn.init.kaiming_normal_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu', generator=None) ``` 用 Kaiming 正态分布填充输入张量的值。 @@ -330,7 +330,7 @@ $\text{std} = \frac{\text{gain}}{\sqrt{\text{fan\_mode}}}$ std=fan_mode​gain ``` ```py -torch.nn.init.trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0, generator=None)¶ +torch.nn.init.trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0, generator=None) ``` 用截断正态分布中抽取的值填充输入张量。 @@ -363,7 +363,7 @@ torch.nn.init.trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0, generator= ``` ```py -torch.nn.init.orthogonal_(tensor, gain=1, generator=None)¶ +torch.nn.init.orthogonal_(tensor, gain=1, generator=None) ``` 用(半)正交矩阵填充输入张量。 @@ -386,7 +386,7 @@ torch.nn.init.orthogonal_(tensor, gain=1, generator=None)¶ ``` ```py -torch.nn.init.sparse_(tensor, sparsity, std=0.01, generator=None)¶ +torch.nn.init.sparse_(tensor, sparsity, std=0.01, generator=None) ``` 将 2D 输入张量填充为稀疏矩阵。 diff --git a/totrans/doc22_070.md b/totrans/doc22_070.md index 7cbc3a15a0e07e03aa6ce40e42a9ed08e601c620..422d3f1cc1defae8adf5fa94febbda61f5e2286f 100644 --- a/totrans/doc22_070.md +++ b/totrans/doc22_070.md @@ -79,7 +79,7 @@ for input, target in dataset: ## 基类 ```py -class torch.optim.Optimizer(params, defaults)¶ +class torch.optim.Optimizer(params, defaults) ``` 所有优化器的基类。 diff --git a/totrans/doc22_072.md b/totrans/doc22_072.md index f48123a0442b6aa6fbd2094e9007eaf4c340f96b..0d98866b1fb2687d1a98221d3914f27a6c7d0984 100644 --- a/totrans/doc22_072.md +++ b/totrans/doc22_072.md @@ -15,13 +15,13 @@ DDP 通信钩子是一个通用接口,通过覆盖[DistributedDataParallel](ht 通信钩子提供了一种灵活的方式来 allreduce 梯度。因此,它主要在每个副本上的梯度上操作,然后进行 allreduce,这些梯度被分桶以增加通信和计算之间的重叠。特别地,`torch.distributed.GradBucket`表示要进行 allreduce 的梯度张量的一个桶。 ```py -class torch.distributed.GradBucket¶ +class torch.distributed.GradBucket ``` 这个类主要将一个扁平化的梯度张量(由`buffer()`返回)传递给 DDP 通信钩子。这个张量可以进一步分解为此桶中每个参数张量的列表(由`get_per_parameter_tensors()`返回),以应用逐层操作。 ```py -torch.distributed.GradBucket.index(self: torch._C._distributed_c10d.GradBucket) → int¶ +torch.distributed.GradBucket.index(self: torch._C._distributed_c10d.GradBucket) → int ``` 警告 @@ -33,7 +33,7 @@ torch.distributed.GradBucket.index(self: torch._C._distributed_c10d.GradBucket) 存储少数连续层梯度的桶的索引。所有梯度都被分桶。 ```py -torch.distributed.GradBucket.buffer(self: torch._C._distributed_c10d.GradBucket) → torch.Tensor¶ +torch.distributed.GradBucket.buffer(self: torch._C._distributed_c10d.GradBucket) → torch.Tensor ``` 返回值 @@ -41,7 +41,7 @@ torch.distributed.GradBucket.buffer(self: torch._C._distributed_c10d.GradBucket) 一个扁平化的 1D `torch.Tensor` 缓冲区,可以进一步分解为此桶中每个参数张量的列表。 ```py -torch.distributed.GradBucket.gradients(self: torch._C._distributed_c10d.GradBucket) → List[torch.Tensor]¶ +torch.distributed.GradBucket.gradients(self: torch._C._distributed_c10d.GradBucket) → List[torch.Tensor] ``` 返回值 @@ -49,7 +49,7 @@ torch.distributed.GradBucket.gradients(self: torch._C._distributed_c10d.GradBuck 一个`torch.Tensor`列表。列表中的每个张量对应一个梯度。 ```py -torch.distributed.GradBucket.is_last(self: torch._C._distributed_c10d.GradBucket) → bool¶ +torch.distributed.GradBucket.is_last(self: torch._C._distributed_c10d.GradBucket) → bool ``` 返回值 @@ -57,13 +57,13 @@ torch.distributed.GradBucket.is_last(self: torch._C._distributed_c10d.GradBucket 这个桶是否是迭代中最后一个要进行 allreduce 的桶。这也意味着这个桶对应于前向传播中的前几层。 ```py -torch.distributed.GradBucket.set_buffer(self: torch._C._distributed_c10d.GradBucket, buffer: torch.Tensor) → None¶ +torch.distributed.GradBucket.set_buffer(self: torch._C._distributed_c10d.GradBucket, buffer: torch.Tensor) → None ``` 用输入张量缓冲区替换桶中的张量。 ```py -torch.distributed.GradBucket.parameters(self: torch._C._distributed_c10d.GradBucket) → List[torch.Tensor]¶ +torch.distributed.GradBucket.parameters(self: torch._C._distributed_c10d.GradBucket) → List[torch.Tensor] ``` 返回值 @@ -75,7 +75,7 @@ torch.distributed.GradBucket.parameters(self: torch._C._distributed_c10d.GradBuc 默认通信钩子是简单的**无状态**钩子,因此`register_comm_hook`中的输入状态要么是一个进程组,要么是`None`。输入`bucket`是一个`torch.distributed.GradBucket`对象。 ```py -torch.distributed.algorithms.ddp_comm_hooks.default_hooks.allreduce_hook(process_group, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.default_hooks.allreduce_hook(process_group, bucket) ``` 这个 DDP 通信钩子只是使用`GradBucket`张量调用`allreduce`。一旦梯度张量在所有工作进程中聚合,它的`then`回调会取平均值并返回结果。如果用户注册了这个钩子,DDP 的结果预计与未注册钩子的情况相同。因此,这不会改变 DDP 的行为,用户可以将其用作参考或修改此钩子以记录有用信息或其他目的,同时不影响 DDP 的行为。 @@ -91,7 +91,7 @@ torch.distributed.algorithms.ddp_comm_hooks.default_hooks.allreduce_hook(process *Future*[*Tensor*] ```py -torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook(process_group, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook(process_group, bucket) ``` 这个 DDP 通信钩子实现了一种简单的梯度压缩方法,将`GradBucket`张量转换为半精度浮点格式(`torch.float16`),然后将其除以进程组大小。它对这些`float16`梯度张量进行全局归约。一旦压缩的梯度张量全部归约,链式回调`decompress`将其转换回输入数据类型(如`float32`)。 @@ -107,7 +107,7 @@ torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook(pro *Future*[*Tensor*] ```py -torch.distributed.algorithms.ddp_comm_hooks.default_hooks.bf16_compress_hook(process_group, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.default_hooks.bf16_compress_hook(process_group, bucket) ``` 警告:此 API 是实验性的,需要 NCCL 版本高于 2.9.6。 @@ -127,7 +127,7 @@ torch.distributed.algorithms.ddp_comm_hooks.default_hooks.bf16_compress_hook(pro 此外,提供了一个通信钩子包装器,支持`fp16_compress_hook()`或`bf16_compress_hook()`作为一个包装器,可以与其他通信钩子组合使用。 ```py -torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_wrapper(hook)¶ +torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_wrapper(hook) ``` 这个包装器将给定 DDP 通信钩子的输入梯度张量转换为半精度浮点格式(`torch.float16`),并将给定钩子的结果张量转换回输入数据类型,如`float32`。 @@ -146,7 +146,7 @@ torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_wrapper( [*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")[[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)"), *GradBucket*], *Future*[*Tensor*]] ```py -torch.distributed.algorithms.ddp_comm_hooks.default_hooks.bf16_compress_wrapper(hook)¶ +torch.distributed.algorithms.ddp_comm_hooks.default_hooks.bf16_compress_wrapper(hook) ``` 警告:此 API 是实验性的,需要 NCCL 版本高于 2.9.6。 @@ -173,7 +173,7 @@ PowerSGD([Vogels 等人,NeurIPS 2019](https://arxiv.org/abs/1905.13727)) ### PowerSGD 状态 ```py -class torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.PowerSGDState(process_group, matrix_approximation_rank=1, start_powerSGD_iter=1000, min_compression_rate=2, use_error_feedback=True, warm_start=True, orthogonalization_epsilon=0, random_seed=0, compression_stats_logging_frequency=10000, batch_tensors_with_same_shape=False)¶ +class torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.PowerSGDState(process_group, matrix_approximation_rank=1, start_powerSGD_iter=1000, min_compression_rate=2, use_error_feedback=True, warm_start=True, orthogonalization_epsilon=0, random_seed=0, compression_stats_logging_frequency=10000, batch_tensors_with_same_shape=False) ``` 在训练期间存储算法的超参数和所有梯度的内部状态。特别是,`matrix_approximation_rank` 和 `start_powerSGD_iter` 是用户应该调整的主要超参数。为了性能,建议保持二进制超参数 `use_error_feedback` 和 `warm_start` 打开。 @@ -213,7 +213,7 @@ PowerSGD 通常需要额外的内存,大小与模型梯度相同,以启用 PowerSGD 钩子可能与[Apex 自动混合精度包](https://github.com/NVIDIA/apex)冲突。请改用 PyTorch 的[本机自动混合精度包](https://pytorch.org/docs/stable/amp.html)。 ```py -torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.powerSGD_hook(state, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.powerSGD_hook(state, bucket) ``` 这个 DDP 通信钩子实现了[论文](https://arxiv.org/abs/1905.13727)中描述的 PowerSGD 梯度压缩算法。一旦梯度张量在所有工作节点上聚合,此钩子将按以下方式应用压缩: @@ -271,7 +271,7 @@ torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.powerSGD_hook(state, b ``` ```py -torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.batched_powerSGD_hook(state, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.batched_powerSGD_hook(state, bucket) ``` 这个 DDP 通信钩子实现了一个简化的 PowerSGD 梯度压缩算法,描述在[论文](https://arxiv.org/abs/1905.13727)中。这个变体不是逐层压缩梯度,而是压缩批处理所有梯度的扁平输入张量。因此,它比`powerSGD_hook()`**更快**,但通常会导致**更低的准确性**,除非`matrix_approximation_rank`为 1。 @@ -332,7 +332,7 @@ torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.batched_powerSGD_hook( 调试通信挂钩不一定会输出正确的结果。 ```py -torch.distributed.algorithms.ddp_comm_hooks.debugging_hooks.noop_hook(_, bucket)¶ +torch.distributed.algorithms.ddp_comm_hooks.debugging_hooks.noop_hook(_, bucket) ``` 此 DDP 通信挂钩返回一个包装输入的未来,因此它是一个不会产生任何通信开销的空操作。 @@ -368,13 +368,13 @@ class torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook.PowerSGDState ``` ```py -__getstate__()¶ +__getstate__() ``` 返回一个`Dict[str, Any]`,将被 pickle 化并保存。`process_group`不可序列化并从返回的状态中排除。 ```py -__setstate__(state)¶ +__setstate__(state) ``` 接受一个提供的`state`并检索`PowerSGDState`。`process_group`设置为默认值。 diff --git a/totrans/doc22_073.md b/totrans/doc22_073.md index 50833d24a34e8809e3a1ee01cf66829e10ea4e70..88b37576b877b35fb86eaa09b8f51eec2f76384b 100644 --- a/totrans/doc22_073.md +++ b/totrans/doc22_073.md @@ -27,7 +27,7 @@ ## PyTorch 中的 Pipe API ```py -class torch.distributed.pipeline.sync.Pipe(module, chunks=1, checkpoint='except_last', deferred_batch_norm=False)¶ +class torch.distributed.pipeline.sync.Pipe(module, chunks=1, checkpoint='except_last', deferred_batch_norm=False) ``` 将任意`nn.Sequential`模块包装起来,以便使用同步管道并行训练。如果模块需要大量内存且无法放入单个 GPU 中,则管道并行是一种有用的训练技术。 @@ -86,7 +86,7 @@ Pipe 将管道并行与检查点结合起来,以减少训练所需的峰值内 `Pipe`是实验性的,可能会发生变化。 ```py -forward(*inputs)¶ +forward(*inputs) ``` 通过管道处理单个输入小批次并返回指向输出的`RRef`。`Pipe`是一个相当透明的模块包装器。它不修改底层模块的输入和输出签名。但有类型限制。输入和输出必须至少包含一个张量。此限制也适用于分区边界。 @@ -122,7 +122,7 @@ forward(*inputs)¶ 像[ResNeXt](https://pytorch.org/hub/pytorch_vision_resnext/)这样的某些模型并不完全是顺序的,它们在层之间有跳过连接。简单地作为管道并行的一部分实现会意味着我们需要通过多个 GPU 复制某些层的输出,直到最终到达包含跳过连接层的 GPU。为了避免这种复制开销,我们提供以下 API 来在模型的不同层中存储和弹出张量。 ```py -torch.distributed.pipeline.sync.skip.skippable.skippable(stash=(), pop=())¶ +torch.distributed.pipeline.sync.skip.skippable.skippable(stash=(), pop=()) ``` 定义一个装饰器来创建带有跳过连接的`nn.Module`。 @@ -172,7 +172,7 @@ class StashStashPop(nn.Module): [*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(在 Python v3.12 中)")[[[*Type*](https://docs.python.org/3/library/typing.html#typing.Type "(在 Python v3.12 中)")[*Module*]], [*Type*](https://docs.python.org/3/library/typing.html#typing.Type "(在 Python v3.12 中)")[*Skippable*]] ```py -class torch.distributed.pipeline.sync.skip.skippable.stash(name, tensor)¶ +class torch.distributed.pipeline.sync.skip.skippable.stash(name, tensor) ``` 存储跳过张量的命令。 @@ -190,7 +190,7 @@ def forward(self, input): + **input** (*torch.Tensor* *或* *None*) – 传递给跳过连接的张量 ```py -class torch.distributed.pipeline.sync.skip.skippable.pop(name)¶ +class torch.distributed.pipeline.sync.skip.skippable.pop(name) ``` 弹出跳过张量的命令。 @@ -214,7 +214,7 @@ def forward(self, input): 无 ```py -torch.distributed.pipeline.sync.skip.skippable.verify_skippables(module)¶ +torch.distributed.pipeline.sync.skip.skippable.verify_skippables(module) ``` 验证底层可跳过模块是否满足完整性。 diff --git a/totrans/doc22_075.md b/totrans/doc22_075.md index 974222b42810bfbcb996116674a455d6a5afd18c..c75eda899bc0595325a46c178e0942b922cd4df7 100644 --- a/totrans/doc22_075.md +++ b/totrans/doc22_075.md @@ -33,7 +33,7 @@ CUDA 支持在 PyTorch 1.9 中引入,仍然是一个**beta**功能。RPC 包 在使用 RPC 和分布式自动微分原语之前,必须进行初始化。要初始化 RPC 框架,我们需要使用`init_rpc()`,这将初始化 RPC 框架、RRef 框架和分布式自动微分。 ```py -torch.distributed.rpc.init_rpc(name, backend=None, rank=-1, world_size=None, rpc_backend_options=None)¶ +torch.distributed.rpc.init_rpc(name, backend=None, rank=-1, world_size=None, rpc_backend_options=None) ``` 初始化 RPC 原语,如本地 RPC 代理和分布式自动微分,这将立即使当前进程准备好发送和接收 RPC。 @@ -57,7 +57,7 @@ torch.distributed.rpc.init_rpc(name, backend=None, rank=-1, world_size=None, rpc RPC 中的 TorchScript 支持是一个原型功能,可能会发生变化。自 v1.5.0 以来,`torch.distributed.rpc`支持将 TorchScript 函数作为 RPC 目标函数调用,这将有助于提高被调用者端的并行性,因为执行 TorchScript 函数不需要 GIL。 ```py -torch.distributed.rpc.rpc_sync(to, func, args=None, kwargs=None, timeout=-1.0)¶ +torch.distributed.rpc.rpc_sync(to, func, args=None, kwargs=None, timeout=-1.0) ``` 在工作节点`to`上运行函数`func`的阻塞 RPC 调用。RPC 消息在执行 Python 代码的同时并行发送和接收。此方法是线程安全的。 @@ -127,7 +127,7 @@ export MASTER_ADDR=localhost export MASTER_PORT=5678 ``` ```py -torch.distributed.rpc.rpc_async(to, func, args=None, kwargs=None, timeout=-1.0)¶ +torch.distributed.rpc.rpc_async(to, func, args=None, kwargs=None, timeout=-1.0) ``` 在工作节点`to`上运行函数`func`的非阻塞 RPC 调用。RPC 消息在执行 Python 代码的同时并行发送和接收。此方法是线程安全的。此方法将立即返回一个可以等待的`Future`。 @@ -208,7 +208,7 @@ torch.distributed.rpc.rpc_async(to, func, args=None, kwargs=None, timeout=-1.0) ``` ```py -torch.distributed.rpc.remote(to, func, args=None, kwargs=None, timeout=-1.0)¶ +torch.distributed.rpc.remote(to, func, args=None, kwargs=None, timeout=-1.0) ``` 在工作节点 `to` 上运行 `func` 并立即返回结果值的 `RRef`。工作节点 `to` 将是返回的 `RRef` 的所有者,调用 `remote` 的工作节点是用户。所有者管理其 `RRef` 的全局引用计数,只有当全局没有对其的活动引用时,所有者的 `RRef` 才会被销毁。 @@ -284,7 +284,7 @@ Below is an example of running a TorchScript function using RPC. ``` ```py -torch.distributed.rpc.get_worker_info(worker_name=None)¶ +torch.distributed.rpc.get_worker_info(worker_name=None) ``` 获取给定工作进程名称的`WorkerInfo`。使用此`WorkerInfo`以避免在每次调用时传递昂贵的字符串。 @@ -298,7 +298,7 @@ torch.distributed.rpc.get_worker_info(worker_name=None)¶ 给定`worker_name`的`WorkerInfo`实例或当前工作进程的`WorkerInfo`如果`worker_name`为`None`。 ```py -torch.distributed.rpc.shutdown(graceful=True, timeout=0)¶ +torch.distributed.rpc.shutdown(graceful=True, timeout=0) ``` 执行 RPC 代理的关闭,然后销毁 RPC 代理。这将停止本地代理接受未完成的请求,并通过终止所有 RPC 线程关闭 RPC 框架。如果`graceful=True`,这将阻塞,直到所有本地和远程 RPC 进程到达此方法并等待所有未完成的工作完成。否则,如果`graceful=False`,这是一个本地关闭,不会等待其他 RPC 进程到达此方法。 @@ -339,19 +339,19 @@ export MASTER_ADDR=localhost export MASTER_PORT=5678 ``` ```py -class torch.distributed.rpc.WorkerInfo¶ +class torch.distributed.rpc.WorkerInfo ``` 封装系统中工作进程信息的结构。包含工作进程的名称和 ID。此类不应直接构造,而是可以通过`get_worker_info()`检索实例,并将结果传递给函数,如`rpc_sync()`、`rpc_async()`、`remote()`以避免在每次调用时复制字符串。 ```py -property id¶ +property id ``` 用于标识工作进程的全局唯一 ID。 ```py -property name¶ +property name ``` 工作进程的名称。 @@ -359,7 +359,7 @@ property name¶ RPC 包还提供了装饰器,允许应用程序指定在被调用方如何处理给定函数。 ```py -torch.distributed.rpc.functions.async_execution(fn)¶ +torch.distributed.rpc.functions.async_execution(fn) ``` 一个函数的装饰器,指示函数的返回值保证是一个`Future`对象,并且此函数可以在 RPC 被调用方异步运行。更具体地说,被调用方提取由包装函数返回的`Future`并将后续处理步骤安装为该`Future`的回调。安装的回调将在完成时从`Future`中读取值并将该值作为 RPC 响应发送回去。这也意味着返回的`Future`仅存在于被调用方,并且永远不会通过 RPC 发送。当包装函数的执行需要暂停和恢复时,例如包含`rpc_async()`或等待其他信号时,此装饰器非常有用。 @@ -500,7 +500,7 @@ torch.distributed.rpc.functions.async_execution(fn)¶ RPC 模块可以利用不同的后端来执行节点之间的通信。要使用的后端可以在`init_rpc()`函数中指定,通过传递`BackendType`枚举的某个值。无论使用什么后端,RPC API 的其余部分都不会改变。每个后端还定义了自己的`RpcBackendOptions`类的子类,该类的实例也可以传递给`init_rpc()`以配置后端的行为。 ```py -class torch.distributed.rpc.BackendType(value)¶ +class torch.distributed.rpc.BackendType(value) ``` 可用后端的枚举类。 @@ -508,19 +508,19 @@ class torch.distributed.rpc.BackendType(value)¶ PyTorch 内置了`BackendType.TENSORPIPE`后端。可以使用`register_backend()`函数注册其他后端。 ```py -class torch.distributed.rpc.RpcBackendOptions¶ +class torch.distributed.rpc.RpcBackendOptions ``` 封装传递给 RPC 后端的选项的抽象结构。可以将此类的实例传递给`init_rpc()`以使用特定配置初始化 RPC,例如 RPC 超时和要使用的`init_method`。 ```py -property init_method¶ +property init_method ``` 指定如何初始化进程组的 URL。默认为`env://`。 ```py -property rpc_timeout¶ +property rpc_timeout ``` 一个浮点数,表示用于所有 RPC 的超时时间。如果一个 RPC 在这个时间段内没有完成,它将以超时的异常完成。 @@ -553,7 +553,7 @@ TensorPipe 后端已经在 PyTorch v1.6 中引入,并正在积极开发中。 ``` ```py -class torch.distributed.rpc.TensorPipeRpcBackendOptions(*, num_worker_threads=16, rpc_timeout=60.0, init_method='env://', device_maps=None, devices=None, _transports=None, _channels=None)¶ +class torch.distributed.rpc.TensorPipeRpcBackendOptions(*, num_worker_threads=16, rpc_timeout=60.0, init_method='env://', device_maps=None, devices=None, _transports=None, _channels=None) ``` `TensorPipeAgent`的后端选项,派生自`RpcBackendOptions`。 @@ -571,37 +571,37 @@ class torch.distributed.rpc.TensorPipeRpcBackendOptions(*, num_worker_threads=16 + **devices**(List[int, str, or `torch.device`],可选)– RPC 代理使用的所有本地 CUDA 设备。默认情况下,它将被初始化为来自其自身`device_maps`和对等方`device_maps`的所有本地设备。在处理 CUDA RPC 请求时,代理将为此`List`中的所有设备正确同步 CUDA 流。 ```py -property device_maps¶ +property device_maps ``` 设备映射位置。 ```py -property devices¶ +property devices ``` 本地代理使用的所有设备。 ```py -property init_method¶ +property init_method ``` 指定如何初始化进程组的 URL。默认为`env://` ```py -property num_worker_threads¶ +property num_worker_threads ``` `TensorPipeAgent`用于执行请求的线程池中的线程数。 ```py -property rpc_timeout¶ +property rpc_timeout ``` 指示用于所有 RPC 的超时的浮点数。如果 RPC 在此时间段内未完成,它将以超时的异常完成。 ```py -set_device_map(to, device_map)¶ +set_device_map(to, device_map) ``` 设置每个 RPC 调用者和被调用者对之间的设备映射。此函数可以多次调用以逐步添加设备放置配置。 @@ -648,7 +648,7 @@ set_device_map(to, device_map)¶ ``` ```py -set_devices(devices)¶ +set_devices(devices) ``` 设置 TensorPipe RPC 代理使用的本地设备。在处理 CUDA RPC 请求时,TensorPipe RPC 代理将为此`List`中所有设备适当同步 CUDA 流。 @@ -668,7 +668,7 @@ RPC 框架不会自动重试任何`rpc_sync()`、`rpc_async()`和`remote()`调 `RRef`(远程引用)是对远程工作器上某种类型`T`(例如`Tensor`)的值的引用。此句柄在所有者上保持引用的远程值保持活动状态,但并不意味着该值将来会传输到本地工作器。RRefs 可以通过持有对其他工作器上存在的[nn.Modules](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)的引用,在多机训练中使用,并调用适当的函数在训练期间检索或修改它们的参数。有关更多详细信息,请参见远程引用协议。 ```py -class torch.distributed.rpc.PyRRef(RRef)¶ +class torch.distributed.rpc.PyRRef(RRef) ``` 封装对远程工作器上某种类型值的引用的类。此句柄将保持工作器上引用的远程值保持活动状态。当`UserRRef`被删除时,1)在应用程序代码和本地 RRef 上没有对它的引用,或 2)应用程序已调用了优雅关闭时,`UserRRef`将被删除。在已删除的 RRef 上调用方法会导致未定义的行为。RRef 实现仅提供尽力检测错误,应用程序不应在`rpc.shutdown()`之后使用`UserRRefs`。 @@ -726,7 +726,7 @@ RRefs 只能由 RPC 模块序列化和反序列化。在没有 RPC 的情况下 ``` ```py -backward(self: torch._C._distributed_rpc.PyRRef, dist_autograd_ctx_id: int = -1, retain_graph: bool = False) → None¶ +backward(self: torch._C._distributed_rpc.PyRRef, dist_autograd_ctx_id: int = -1, retain_graph: bool = False) → None ``` > 使用 RRef 作为反向传递的根运行反向传递。如果提供了`dist_autograd_ctx_id`,我们将使用提供的 ctx_id 从 RRef 的所有者开始执行分布式反向传递。在这种情况下,应使用`get_gradients()`来检索梯度。如果`dist_autograd_ctx_id`为`None`,则假定这是一个本地自动梯度图,我们只执行本地反向传递。在本地情况下,调用此 API 的节点必须是 RRef 的所有者。预期 RRef 的值是标量张量。 @@ -746,37 +746,37 @@ backward(self: torch._C._distributed_rpc.PyRRef, dist_autograd_ctx_id: int = -1, ``` ```py -confirmed_by_owner(self: torch._C._distributed_rpc.PyRRef) → bool¶ +confirmed_by_owner(self: torch._C._distributed_rpc.PyRRef) → bool ``` 返回此`RRef`是否已被所有者确认。`OwnerRRef`始终返回 true,而`UserRRef`仅在所有者知道此`UserRRef`时返回 true。 ```py -is_owner(self: torch._C._distributed_rpc.PyRRef) → bool¶ +is_owner(self: torch._C._distributed_rpc.PyRRef) → bool ``` 返回当前节点是否是此`RRef`的所有者。 ```py -local_value(self: torch._C._distributed_rpc.PyRRef) → object¶ +local_value(self: torch._C._distributed_rpc.PyRRef) → object ``` 如果当前节点是所有者,则返回对本地值的引用。否则,抛出异常。 ```py -owner(self: torch._C._distributed_rpc.PyRRef) → torch._C._distributed_rpc.WorkerInfo¶ +owner(self: torch._C._distributed_rpc.PyRRef) → torch._C._distributed_rpc.WorkerInfo ``` 返回拥有此`RRef`的节点的工作人员信息。 ```py -owner_name(self: torch._C._distributed_rpc.PyRRef) → str¶ +owner_name(self: torch._C._distributed_rpc.PyRRef) → str ``` 返回拥有此`RRef`的节点的工作人员名称。 ```py -remote(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object¶ +remote(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object ``` 创建一个辅助代理,以便使用拥有 RRef 的所有者作为目标轻松启动`remote`,以在此 RRef 引用的对象上运行函数。更具体地说,`rref.remote().func_name(*args, **kwargs)`等同于以下内容: @@ -802,7 +802,7 @@ remote(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object ``` ```py -rpc_async(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object¶ +rpc_async(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object ``` 创建一个辅助代理,以便使用拥有 RRef 的所有者作为目标轻松启动`rpc_async`,以在此 RRef 引用的对象上运行函数。更具体地说,`rref.rpc_async().func_name(*args, **kwargs)`等同于以下内容: @@ -828,7 +828,7 @@ rpc_async(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → obj ``` ```py -rpc_sync(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object¶ +rpc_sync(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object ``` 创建一个辅助代理,以便使用 RRef 的所有者轻松启动`rpc_sync`,以运行此 RRef 引用的对象上的函数。更具体地说,`rref.rpc_sync().func_name(*args, **kwargs)`等同于以下内容: @@ -854,7 +854,7 @@ rpc_sync(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → obje ``` ```py -to_here(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object¶ +to_here(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → object ``` 阻塞调用,将 RRef 的值从所有者复制到本地节点并返回。如果当前节点是所有者,则返回对本地值的引用。 @@ -894,7 +894,7 @@ to_here(self: torch._C._distributed_rpc.PyRRef, timeout: float = -1.0) → objec `RemoteModule`是在不同进程上轻松创建 nn.Module 的一种方式。实际模块驻留在远程主机上,但本地主机具有对此模块的句柄,并且可以像常规的 nn.Module 一样调用此模块。但是,调用会导致 RPC 调用到远程端,并且如果需要,可以通过 RemoteModule 支持的其他 API 以异步方式执行。 ```py -class torch.distributed.nn.api.remote_module.RemoteModule(*args, **kwargs)¶ +class torch.distributed.nn.api.remote_module.RemoteModule(*args, **kwargs) ``` > 只有在 RPC 初始化后才能创建 RemoteModule 实例。 @@ -964,7 +964,7 @@ class torch.distributed.nn.api.remote_module.RemoteModule(*args, **kwargs)¶ 此外,可以在[分布式数据并行](https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel)(DDP)中结合更实际的示例,详见此[教程](https://pytorch.org/tutorials/advanced/rpc_ddp_tutorial.html)。 ```py -get_module_rref()¶ +get_module_rref() ``` 返回一个指向远程模块的 `RRef`(`RRef[nn.Module]`)。 @@ -974,7 +974,7 @@ get_module_rref()¶ *RRef*[*Module*] ```py -remote_parameters(recurse=True)¶ +remote_parameters(recurse=True) ``` 返回一个指向远程模块参数的 `RRef` 列表。 @@ -1002,7 +1002,7 @@ remote_parameters(recurse=True)¶ 这个模块提供了一个基于 RPC 的分布式自动求导框架,可用于诸如模型并行训练等应用。简而言之,应用程序可以通过 RPC 发送和接收梯度记录张量。在前向传播中,当梯度记录张量通过 RPC 发送时,我们记录下来;在反向传播过程中,我们使用这些信息来使用 RPC 执行分布式反向传播。更多细节请参见分布式自动求导设计。 ```py -torch.distributed.autograd.backward(context_id: int, roots: List[Tensor], retain_graph=False) → None¶ +torch.distributed.autograd.backward(context_id: int, roots: List[Tensor], retain_graph=False) → None ``` 使用提供的根启动分布式反向传播。目前实现了 FAST mode 算法,该算法假定在同一分布式自动求导上下文中的所有 RPC 消息在反向传播过程中都将成为自动求导图的一部分。 @@ -1030,7 +1030,7 @@ torch.distributed.autograd.backward(context_id: int, roots: List[Tensor], retain ``` ```py -class torch.distributed.autograd.context¶ +class torch.distributed.autograd.context ``` 在使用分布式自动求导时,用于包装前向和后向传递的上下文对象。在`with`语句中生成的`context_id`用于唯一标识所有工作进程上的分布式后向传递。每个工作进程存储与此`context_id`相关的元数据,这是正确执行分布式自动求导传递所必需的。 @@ -1047,7 +1047,7 @@ class torch.distributed.autograd.context¶ ``` ```py -torch.distributed.autograd.get_gradients(context_id: int) → Dict[Tensor, Tensor]¶ +torch.distributed.autograd.get_gradients(context_id: int) → Dict[Tensor, Tensor] ``` 从张量到在分布式自动求导后向传递的提供的上下文中累积的该张量的适当梯度的映射中检索映射,对应于给定的`context_id`。 diff --git a/totrans/doc22_076.md b/totrans/doc22_076.md index 6ada1c264c499230147a570a1d5a654814a43d62..8db98382c292f6582a77846218c136bb16aed032 100644 --- a/totrans/doc22_076.md +++ b/totrans/doc22_076.md @@ -3,7 +3,7 @@ > 原文:[`pytorch.org/docs/stable/random.html`](https://pytorch.org/docs/stable/random.html) ```py -torch.random.fork_rng(devices=None, enabled=True, _caller='fork_rng', _devices_kw='devices', device_type='cuda')¶ +torch.random.fork_rng(devices=None, enabled=True, _caller='fork_rng', _devices_kw='devices', device_type='cuda') ``` 分叉 RNG,以便在返回时,RNG 被重置为先前的状态。 @@ -21,7 +21,7 @@ torch.random.fork_rng(devices=None, enabled=True, _caller='fork_rng', _devices_k [*生成器*](https://docs.python.org/3/library/typing.html#typing.Generator "(在 Python v3.12 中)") ```py -torch.random.get_rng_state()¶ +torch.random.get_rng_state() ``` 将随机数生成器状态返回为 torch.ByteTensor。 @@ -31,7 +31,7 @@ torch.random.get_rng_state()¶ *张量* ```py -torch.random.initial_seed()¶ +torch.random.initial_seed() ``` 返回生成随机数的初始种子作为 Python 长整型。 @@ -41,7 +41,7 @@ torch.random.initial_seed()¶ [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)") ```py -torch.random.manual_seed(seed)¶ +torch.random.manual_seed(seed) ``` 设置生成随机数的种子。返回一个 torch.Generator 对象。 @@ -55,7 +55,7 @@ torch.random.manual_seed(seed)¶ *生成器* ```py -torch.random.seed()¶ +torch.random.seed() ``` 将生成随机数的种子设置为非确定性随机数。返回用于种子 RNG 的 64 位数字。 @@ -65,7 +65,7 @@ torch.random.seed()¶ [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)") ```py -torch.random.set_rng_state(new_state)¶ +torch.random.set_rng_state(new_state) ``` 设置随机数生成器状态。 diff --git a/totrans/doc22_078.md b/totrans/doc22_078.md index c1f0b1911b665fdb3addee9e6897c18dde8fe3b0..c6616c121fe0fdbd8b178ef720230d93808a7d1d 100644 --- a/totrans/doc22_078.md +++ b/totrans/doc22_078.md @@ -159,7 +159,7 @@ nested_tensor([ 以下函数与嵌套张量相关: ```py -torch.nested.nested_tensor(tensor_list, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False)¶ +torch.nested.nested_tensor(tensor_list, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) ``` 从`tensor_list`(张量列表)构造一个没有自动求导历史(也称为“叶张量”,参见自动求导机制)的嵌套张量。 @@ -197,7 +197,7 @@ True ``` ```py -torch.nested.as_nested_tensor(tensor_list, dtype=None, device=None, layout=None)¶ +torch.nested.as_nested_tensor(tensor_list, dtype=None, device=None, layout=None) ``` 从`tensor_list`张量列表构造一个保留自动求导历史的嵌套张量。 @@ -239,7 +239,7 @@ tensor([0., 0., 0., 0., 0.]) ``` ```py -torch.nested.to_padded_tensor(input, padding, output_size=None, out=None) → Tensor¶ +torch.nested.to_padded_tensor(input, padding, output_size=None, out=None) → Tensor ``` 通过填充`input`嵌套张量,返回一个新的(非嵌套)张量。前导条目将填充嵌套数据,而尾随条目将被填充。 diff --git a/totrans/doc22_080.md b/totrans/doc22_080.md index 57ce4522facb8dfce9198086859368896600435c..322531d4e43a34392d6e364defe89729dec19ec3 100644 --- a/totrans/doc22_080.md +++ b/totrans/doc22_080.md @@ -15,63 +15,63 @@ 除了 `torch.UntypedStorage` 外,所有存储类将来将被移除,而 `torch.UntypedStorage` 将在所有情况下使用。 ```py -class torch.TypedStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.TypedStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -bfloat16()¶ +bfloat16() ``` 将此存储转换为 bfloat16 类型。 ```py -bool()¶ +bool() ``` 将此存储转换为布尔类型。 ```py -byte()¶ +byte() ``` 将此存储转换为字节类型。 ```py -char()¶ +char() ``` 将此存储转换为字符类型。 ```py -clone()¶ +clone() ``` 返回此存储的副本。 ```py -complex_double()¶ +complex_double() ``` 将此存储转换为复数双精度类型。 ```py -complex_float()¶ +complex_float() ``` 将此存储转换为复数浮点类型。 ```py -copy_(source, non_blocking=None)¶ +copy_(source, non_blocking=None) ``` ```py -cpu()¶ +cpu() ``` 如果尚未在 CPU 上,则返回此存储的 CPU 副本。 ```py -cuda(device=None, non_blocking=False, **kwargs)¶ +cuda(device=None, non_blocking=False, **kwargs) ``` 返回此对象在 CUDA 内存中的副本。 @@ -91,61 +91,61 @@ cuda(device=None, non_blocking=False, **kwargs)¶ *T* ```py -data_ptr()¶ +data_ptr() ``` ```py -property device¶ +property device ``` ```py -double()¶ +double() ``` 将此存储转换为双精度类型。 ```py -dtype: dtype¶ +dtype: dtype ``` ```py -element_size()¶ +element_size() ``` ```py -property filename: Optional[str]¶ +property filename: Optional[str] ``` 如果存储是从文件内存映射而来,则返回与此存储关联的文件名。如果存储不是通过内存映射文件创建的,则返回 `None`。 ```py -fill_(value)¶ +fill_(value) ``` ```py -float()¶ +float() ``` 将此存储转换为浮点类型。 ```py -float8_e4m3fn()¶ +float8_e4m3fn() ``` 将此存储转换为 float8_e4m3fn 类型 ```py -float8_e5m2()¶ +float8_e5m2() ``` 将此存储转换为 float8_e5m2 类型 ```py -classmethod from_buffer(*args, **kwargs)¶ +classmethod from_buffer(*args, **kwargs) ``` ```py -classmethod from_file(filename, shared=False, size=0) → Storage¶ +classmethod from_file(filename, shared=False, size=0) → Storage ``` 创建由内存映射文件支持的 CPU 存储。 @@ -163,7 +163,7 @@ classmethod from_file(filename, shared=False, size=0) → Storage¶ + **size**([*int*](https://docs.python.org/3/library/functions.html#int))- 存储中的元素数 ```py -get_device()¶ +get_device() ``` 返回类型 @@ -171,13 +171,13 @@ get_device()¶ [*int*](https://docs.python.org/3/library/functions.html#int) ```py -half()¶ +half() ``` 将此存储转换为半精度类型。 ```py -hpu(device=None, non_blocking=False, **kwargs)¶ +hpu(device=None, non_blocking=False, **kwargs) ``` 在 HPU 内存中返回此对象的副本。 @@ -197,21 +197,21 @@ hpu(device=None, non_blocking=False, **kwargs)¶ *T* ```py -int()¶ +int() ``` 将此存储转换为整型。 ```py -property is_cuda¶ +property is_cuda ``` ```py -property is_hpu¶ +property is_hpu ``` ```py -is_pinned(device='cuda')¶ +is_pinned(device='cuda') ``` 确定 CPU TypedStorage 是否已经固定在设备上。 @@ -225,29 +225,29 @@ is_pinned(device='cuda')¶ 一个布尔变量。 ```py -is_shared()¶ +is_shared() ``` ```py -is_sparse = False¶ +is_sparse = False ``` ```py -long()¶ +long() ``` 将此存储转换为长整型。 ```py -nbytes()¶ +nbytes() ``` ```py -pickle_storage_type()¶ +pickle_storage_type() ``` ```py -pin_memory(device='cuda')¶ +pin_memory(device='cuda') ``` 将 CPU TypedStorage 复制到固定内存,如果尚未固定。 @@ -261,33 +261,33 @@ pin_memory(device='cuda')¶ 固定的 CPU 存储。 ```py -resize_(size)¶ +resize_(size) ``` ```py -share_memory_()¶ +share_memory_() ``` 参见`torch.UntypedStorage.share_memory_()`。 ```py -short()¶ +short() ``` 将此存储转换为短整型。 ```py -size()¶ +size() ``` ```py -tolist()¶ +tolist() ``` 返回包含此存储元素的列表。 ```py -type(dtype=None, non_blocking=False)¶ +type(dtype=None, non_blocking=False) ``` 如果未提供 dtype,则返回类型,否则将此对象转换为指定类型。 @@ -307,75 +307,75 @@ type(dtype=None, non_blocking=False)¶ [*Union*](https://docs.python.org/3/library/typing.html#typing.Union)[*T*, [*str*](https://docs.python.org/3/library/stdtypes.html#str)] ```py -untyped()¶ +untyped() ``` 返回内部`torch.UntypedStorage`。 ```py -class torch.UntypedStorage(*args, **kwargs)¶ +class torch.UntypedStorage(*args, **kwargs) ``` ```py -bfloat16()¶ +bfloat16() ``` 将此存储转换为 bfloat16 类型。 ```py -bool()¶ +bool() ``` 将此存储转换为布尔类型。 ```py -byte()¶ +byte() ``` 将此存储转换为字节类型。 ```py -byteswap(dtype)¶ +byteswap(dtype) ``` 交换底层数据中的字节。 ```py -char()¶ +char() ``` 将此存储转换为字符类型。 ```py -clone()¶ +clone() ``` 返回此存储的副本。 ```py -complex_double()¶ +complex_double() ``` 将此存储转换为复数双精度类型。 ```py -complex_float()¶ +complex_float() ``` 将此存储转换为复数浮点类型。 ```py -copy_()¶ +copy_() ``` ```py -cpu()¶ +cpu() ``` 如果尚未在 CPU 上,则返回此存储的 CPU 副本。 ```py -cuda(device=None, non_blocking=False, **kwargs)¶ +cuda(device=None, non_blocking=False, **kwargs) ``` 在 CUDA 内存中返回此对象的副本。 @@ -391,57 +391,57 @@ cuda(device=None, non_blocking=False, **kwargs)¶ + ****kwargs** - 为了兼容性,可能包含`async`键,而不是`non_blocking`参数。 ```py -data_ptr()¶ +data_ptr() ``` ```py -device: device¶ +device: device ``` ```py -double()¶ +double() ``` 将此存储转换为 double 类型。 ```py -element_size()¶ +element_size() ``` ```py -property filename: Optional[str]¶ +property filename: Optional[str] ``` 如果存储是从文件内存映射而来,则返回与此存储关联的文件名。如果存储不是通过内存映射文件创建的,则返回`None`。 ```py -fill_()¶ +fill_() ``` ```py -float()¶ +float() ``` 将此存储转换为 float 类型。 ```py -float8_e4m3fn()¶ +float8_e4m3fn() ``` 将此存储转换为 float8_e4m3fn 类型 ```py -float8_e5m2()¶ +float8_e5m2() ``` 将此存储转换为 float8_e5m2 类型 ```py -static from_buffer()¶ +static from_buffer() ``` ```py -static from_file(filename, shared=False, size=0) → Storage¶ +static from_file(filename, shared=False, size=0) → Storage ``` 创建由内存映射文件支持的 CPU 存储。 @@ -461,7 +461,7 @@ static from_file(filename, shared=False, size=0) → Storage¶ + **size**([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) - 存储中的元素数量 ```py -get_device()¶ +get_device() ``` 返回类型 @@ -469,13 +469,13 @@ get_device()¶ [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") ```py -half()¶ +half() ``` 将此存储转换为 half 类型。 ```py -hpu(device=None, non_blocking=False, **kwargs)¶ +hpu(device=None, non_blocking=False, **kwargs) ``` 在 HPU 内存中返回此对象的副本。 @@ -491,21 +491,21 @@ hpu(device=None, non_blocking=False, **kwargs)¶ + ****kwargs** - 为了兼容性,可能包含`async`键,而不是`non_blocking`参数。 ```py -int()¶ +int() ``` 将此存储转换为 int 类型。 ```py -property is_cuda¶ +property is_cuda ``` ```py -property is_hpu¶ +property is_hpu ``` ```py -is_pinned(device='cuda')¶ +is_pinned(device='cuda') ``` 确定 CPU 存储是否已固定在设备上。 @@ -519,39 +519,39 @@ is_pinned(device='cuda')¶ 一个布尔变量。 ```py -is_shared()¶ +is_shared() ``` ```py -is_sparse: bool = False¶ +is_sparse: bool = False ``` ```py -is_sparse_csr: bool = False¶ +is_sparse_csr: bool = False ``` ```py -long()¶ +long() ``` 将此存储转换为 long 类型。 ```py -mps()¶ +mps() ``` 如果尚未在 MPS 上,则返回此存储的 MPS 副本。 ```py -nbytes()¶ +nbytes() ``` ```py -new()¶ +new() ``` ```py -pin_memory(device='cuda')¶ +pin_memory(device='cuda') ``` 将 CPU 存储复制到固定内存,如果尚未固定。 @@ -565,11 +565,11 @@ pin_memory(device='cuda')¶ 一个固定的 CPU 存储。 ```py -resize_()¶ +resize_() ``` ```py -share_memory_(*args, **kwargs)¶ +share_memory_(*args, **kwargs) ``` 将存储移动到共享内存。 @@ -595,13 +595,13 @@ share_memory_(*args, **kwargs)¶ `self` ```py -short()¶ +short() ``` 将此存储转换为 short 类型。 ```py -size()¶ +size() ``` 返回类型 @@ -609,13 +609,13 @@ size()¶ [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") ```py -tolist()¶ +tolist() ``` 返回包含此存储元素的列表。 ```py -type(dtype=None, non_blocking=False, **kwargs)¶ +type(dtype=None, non_blocking=False, **kwargs) ``` 如果未提供 dtype,则返回类型,否则将此对象转换为指定类型。 @@ -631,141 +631,141 @@ type(dtype=None, non_blocking=False, **kwargs)¶ + ****kwargs** - 为了兼容性,可能包含`async`键代替`non_blocking`参数。`async`参数已被弃用。 ```py -untyped()¶ +untyped() ``` ```py -class torch.DoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.DoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.float64¶ +dtype: dtype = torch.float64 ``` ```py -class torch.FloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.FloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.float32¶ +dtype: dtype = torch.float32 ``` ```py -class torch.HalfStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.HalfStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.float16¶ +dtype: dtype = torch.float16 ``` ```py -class torch.LongStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.LongStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.int64¶ +dtype: dtype = torch.int64 ``` ```py -class torch.IntStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.IntStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.int32¶ +dtype: dtype = torch.int32 ``` ```py -class torch.ShortStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.ShortStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.int16¶ +dtype: dtype = torch.int16 ``` ```py -class torch.CharStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.CharStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.int8¶ +dtype: dtype = torch.int8 ``` ```py -class torch.ByteStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.ByteStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.uint8¶ +dtype: dtype = torch.uint8 ``` ```py -class torch.BoolStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.BoolStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.bool¶ +dtype: dtype = torch.bool ``` ```py -class torch.BFloat16Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.BFloat16Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.bfloat16¶ +dtype: dtype = torch.bfloat16 ``` ```py -class torch.ComplexDoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.ComplexDoubleStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.complex128¶ +dtype: dtype = torch.complex128 ``` ```py -class torch.ComplexFloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.ComplexFloatStorage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.complex64¶ +dtype: dtype = torch.complex64 ``` ```py -class torch.QUInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.QUInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.quint8¶ +dtype: dtype = torch.quint8 ``` ```py -class torch.QInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.QInt8Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.qint8¶ +dtype: dtype = torch.qint8 ``` ```py -class torch.QInt32Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.QInt32Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.qint32¶ +dtype: dtype = torch.qint32 ``` ```py -class torch.QUInt4x2Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.QUInt4x2Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.quint4x2¶ +dtype: dtype = torch.quint4x2 ``` ```py -class torch.QUInt2x4Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False)¶ +class torch.QUInt2x4Storage(*args, wrap_storage=None, dtype=None, device=None, _internal=False) ``` ```py -dtype: dtype = torch.quint2x4¶ +dtype: dtype = torch.quint2x4 ``` diff --git a/totrans/doc22_081.md b/totrans/doc22_081.md index 9bd9d7db9a66c8f7de3d8a25176929948952369e..8e1f765f78119cb5d324e958ec9a5f4e9cad7042 100644 --- a/totrans/doc22_081.md +++ b/totrans/doc22_081.md @@ -3,7 +3,7 @@ > [`pytorch.org/docs/stable/testing.html`](https://pytorch.org/docs/stable/testing.html) ```py -torch.testing.assert_close(actual, expected, *, allow_subclasses=True, rtol=None, atol=None, equal_nan=False, check_device=True, check_dtype=True, check_layout=True, check_stride=False, msg=None)¶ +torch.testing.assert_close(actual, expected, *, allow_subclasses=True, rtol=None, atol=None, equal_nan=False, check_device=True, check_dtype=True, check_layout=True, check_stride=False, msg=None) ``` 断言`actual`和`expected`是接近的。 @@ -240,7 +240,7 @@ Footer ``` ```py -torch.testing.make_tensor(*shape, dtype, device, low=None, high=None, requires_grad=False, noncontiguous=False, exclude_zero=False, memory_format=None)¶ +torch.testing.make_tensor(*shape, dtype, device, low=None, high=None, requires_grad=False, noncontiguous=False, exclude_zero=False, memory_format=None) ``` 创建具有给定`shape`、`device`和`dtype`的张量,并用从`[low, high)`均匀抽取的值填充。 @@ -309,7 +309,7 @@ tensor([[False, False], ``` ```py -torch.testing.assert_allclose(actual, expected, rtol=None, atol=None, equal_nan=True, msg='')¶ +torch.testing.assert_allclose(actual, expected, rtol=None, atol=None, equal_nan=True, msg='') ``` 警告 diff --git a/totrans/doc22_083.md b/totrans/doc22_083.md index 7f31c3d8f2cd2ba26ecfc9f92d42edc40f615f31..d59d0c02a58e948e078caceed964490ba9e1f58d 100644 --- a/totrans/doc22_083.md +++ b/totrans/doc22_083.md @@ -3,7 +3,7 @@ > [`pytorch.org/docs/stable/benchmark_utils.html`](https://pytorch.org/docs/stable/benchmark_utils.html) ```py -class torch.utils.benchmark.Timer(stmt='pass', setup='pass', global_setup='', timer=, globals=None, label=None, sub_label=None, description=None, env=None, num_threads=1, language=Language.PYTHON)¶ +class torch.utils.benchmark.Timer(stmt='pass', setup='pass', global_setup='', timer=, globals=None, label=None, sub_label=None, description=None, env=None, num_threads=1, language=Language.PYTHON) ``` 用于测量 PyTorch 语句执行时间的辅助类。 @@ -74,7 +74,7 @@ PyTorch 计时器特定的构造函数参数: + **num_threads**([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12)")) - 在执行 stmt 时 PyTorch 线程池的大小。单线程性能很重要,既是关键的推理工作负载,也是内在算法效率的良好指标,因此默认设置为 1。这与默认的 PyTorch 线程池大小相反,后者尝试利用所有核心。 ```py -adaptive_autorange(threshold=0.1, *, min_run_time=0.01, max_run_time=10.0, callback=None)¶ +adaptive_autorange(threshold=0.1, *, min_run_time=0.01, max_run_time=10.0, callback=None) ``` 类似于 blocked_autorange,但还检查测量中的变异性,并重复直到 iqr/median 小于阈值或达到 max_run_time。 @@ -115,7 +115,7 @@ while times.sum < max_run_time *Measurement* ```py -blocked_autorange(callback=None, min_run_time=0.2)¶ +blocked_autorange(callback=None, min_run_time=0.2) ``` 在保持计时器开销最低的情况下测量许多复制品。 @@ -150,7 +150,7 @@ blocked_autorange 通过运行预热期来设置块大小,增加块大小直 *Measurement* ```py -collect_callgrind(number: int, *, repeats: None, collect_baseline: bool, retain_out_file: bool) → CallgrindStats¶ +collect_callgrind(number: int, *, repeats: None, collect_baseline: bool, retain_out_file: bool) → CallgrindStats ``` ```py @@ -172,7 +172,7 @@ collect_callgrind(number: int, *, repeats: int, collect_baseline: bool, retain_o 一个 CallgrindStats 对象,提供指令计数和一些基本设施用于分析和操作结果。 ```py -timeit(number=1000000)¶ +timeit(number=1000000) ``` 反映了 timeit.Timer.timeit()的语义。 @@ -184,7 +184,7 @@ timeit(number=1000000)¶ *Measurement* ```py -class torch.utils.benchmark.Measurement(number_per_run, raw_times, task_spec, metadata=None)¶ +class torch.utils.benchmark.Measurement(number_per_run, raw_times, task_spec, metadata=None) ``` 计时器测量的结果。 @@ -192,7 +192,7 @@ class torch.utils.benchmark.Measurement(number_per_run, raw_times, task_spec, me 这个类存储给定语句的一个或多个测量。它是可序列化的,并为下游消费者提供几种便利方法(包括详细的 __repr__)。 ```py -static merge(measurements)¶ +static merge(measurements) ``` 用于合并重复实验的便利方法。 @@ -204,7 +204,7 @@ static merge(measurements)¶ [*List*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[*Measurement*] ```py -property significant_figures: int¶ +property significant_figures: int ``` 近似的显著数字估计。 @@ -214,7 +214,7 @@ property significant_figures: int¶ 与 trim_sigfig 方法一起使用的显著数字估计,以提供更易于人类理解的数据摘要。__repr__ 不使用此方法;它只显示原始值。显著数字估计用于 Compare。 ```py -class torch.utils.benchmark.CallgrindStats(task_spec, number_per_run, built_with_debug_symbols, baseline_inclusive_stats, baseline_exclusive_stats, stmt_inclusive_stats, stmt_exclusive_stats, stmt_callgrind_out)¶ +class torch.utils.benchmark.CallgrindStats(task_spec, number_per_run, built_with_debug_symbols, baseline_inclusive_stats, baseline_exclusive_stats, stmt_inclusive_stats, stmt_exclusive_stats, stmt_callgrind_out) ``` 由计时器收集的 Callgrind 结果的顶层容器。 @@ -222,7 +222,7 @@ class torch.utils.benchmark.CallgrindStats(task_spec, number_per_run, built_with 通常使用 FunctionCounts 类进行操作,该类通过调用 CallgrindStats.stats(…)获得。还提供了几种便利方法;最重要的是 CallgrindStats.as_standardized()。 ```py -as_standardized()¶ +as_standardized() ``` 从函数字符串中删除库名称和一些前缀。 @@ -246,7 +246,7 @@ as_standardized()¶ *CallgrindStats* ```py -counts(*, denoise=False)¶ +counts(*, denoise=False) ``` 返回执行的指令总数。 @@ -258,7 +258,7 @@ counts(*, denoise=False)¶ [int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)") ```py -delta(other, inclusive=False)¶ +delta(other, inclusive=False) ``` 比较两组计数。 @@ -270,7 +270,7 @@ delta(other, inclusive=False)¶ *FunctionCounts* ```py -stats(inclusive=False)¶ +stats(inclusive=False) ``` 返回详细的函数计数。 @@ -284,7 +284,7 @@ inclusive 匹配 callgrind 的语义。如果为 True,则计数包括子级执 *FunctionCounts* ```py -class torch.utils.benchmark.FunctionCounts(_data, inclusive, truncate_rows=True, _linewidth=None)¶ +class torch.utils.benchmark.FunctionCounts(_data, inclusive, truncate_rows=True, _linewidth=None) ``` 用于操作 Callgrind 结果的容器。 @@ -300,7 +300,7 @@ class torch.utils.benchmark.FunctionCounts(_data, inclusive, truncate_rows=True, 1. 两个高阶方法(filter 和 transform)用于自定义操作。 ```py -denoise()¶ +denoise() ``` 删除已知的嘈杂指令。 @@ -312,7 +312,7 @@ CPython 解释器中的几条指令相当嘈杂。这些指令涉及 Python 用 *FunctionCounts* ```py -filter(filter_fn)¶ +filter(filter_fn) ``` 仅保留 filter_fn 应用于函数名称返回 True 的元素。 @@ -322,7 +322,7 @@ filter(filter_fn)¶ *FunctionCounts* ```py -transform(map_fn)¶ +transform(map_fn) ``` 将 map_fn 应用于所有函数名称。 diff --git a/totrans/doc22_085.md b/totrans/doc22_085.md index 6ba4a6bcc3f79eda0dfe5f28382eb022432fbf41..2c973bc6c620850ef6860ddf8db65e7e799ac1f2 100644 --- a/totrans/doc22_085.md +++ b/totrans/doc22_085.md @@ -9,7 +9,7 @@ 存储逻辑会保存并恢复 CPU 和另一设备类型(通过`_infer_device_type`从张量参数中排除 CPU 张量推断设备类型)的 RNG 状态到`run_fn`。如果有多个设备,设备状态只会为单个设备类型的设备保存,其余设备将被忽略。因此,如果任何检查点函数涉及随机性,可能会导致梯度不正确。(请注意,如果检测到 CUDA 设备,则会优先考虑;否则,将选择遇到的第一个设备。)如果没有 CPU 张量,则将保存和恢复默认设备类型状态(默认值为 cuda,可以通过`DefaultDeviceType`设置为其他设备)。然而,该逻辑无法预测用户是否会在`run_fn`内将张量移动到新设备。因此,如果您在`run_fn`内将张量移动到新设备(“新”意味着不属于[当前设备+张量参数的设备]集合),则与未检查点的通过相比,确定性输出永远无法保证。 ```py -torch.utils.checkpoint.checkpoint(function, *args, use_reentrant=None, context_fn=, determinism_check='default', debug=False, **kwargs)¶ +torch.utils.checkpoint.checkpoint(function, *args, use_reentrant=None, context_fn=, determinism_check='default', debug=False, **kwargs) ``` 检查点一个模型或模型的一部分。 @@ -63,7 +63,7 @@ torch.utils.checkpoint.checkpoint(function, *args, use_reentrant=None, context_f 在`*args`上运行`function`的输出 ```py -torch.utils.checkpoint.checkpoint_sequential(functions, segments, input, use_reentrant=None, **kwargs)¶ +torch.utils.checkpoint.checkpoint_sequential(functions, segments, input, use_reentrant=None, **kwargs) ``` 检查点一个顺序模型以节省内存。 @@ -98,7 +98,7 @@ torch.utils.checkpoint.checkpoint_sequential(functions, segments, input, use_ree ``` ```py -torch.utils.checkpoint.set_checkpoint_debug_enabled(enabled)¶ +torch.utils.checkpoint.set_checkpoint_debug_enabled(enabled) ``` 上下文管理器,设置检查点在运行时是否应该打印额外的调试信息。有关更多信息,请参阅`checkpoint()`中的`debug`标志。请注意,当设置时,此上下文管理器会覆盖传递给检查点的`debug`值。要推迟到本地设置,请将`None`传递给此上下文。 diff --git a/totrans/doc22_086.md b/totrans/doc22_086.md index 5b45bcc30f740e1688078f5866229613e552dc81..2a100430858706a43a136c897a087f76f1c2d94e 100644 --- a/totrans/doc22_086.md +++ b/totrans/doc22_086.md @@ -3,7 +3,7 @@ > 原文:[`pytorch.org/docs/stable/cpp_extension.html`](https://pytorch.org/docs/stable/cpp_extension.html) ```py -torch.utils.cpp_extension.CppExtension(name, sources, *args, **kwargs)¶ +torch.utils.cpp_extension.CppExtension(name, sources, *args, **kwargs) ``` 为 C++创建一个`setuptools.Extension`。 @@ -31,7 +31,7 @@ torch.utils.cpp_extension.CppExtension(name, sources, *args, **kwargs)¶ ``` ```py -torch.utils.cpp_extension.CUDAExtension(name, sources, *args, **kwargs)¶ +torch.utils.cpp_extension.CUDAExtension(name, sources, *args, **kwargs) ``` 为 CUDA/C++创建一个`setuptools.Extension`。 @@ -104,7 +104,7 @@ torch.utils.cpp_extension.CUDAExtension(name, sources, *args, **kwargs)¶ ``` ```py -torch.utils.cpp_extension.BuildExtension(*args, **kwargs)¶ +torch.utils.cpp_extension.BuildExtension(*args, **kwargs) ``` 一个自定义的`setuptools`构建扩展。 @@ -120,7 +120,7 @@ torch.utils.cpp_extension.BuildExtension(*args, **kwargs)¶ 默认情况下,Ninja 后端使用#CPUS + 2 个工作进程来构建扩展。这可能会在某些系统上使用过多资源。可以通过将 MAX_JOBS 环境变量设置为非负数来控制工作进程的数量。 ```py -torch.utils.cpp_extension.load(name, sources, extra_cflags=None, extra_cuda_cflags=None, extra_ldflags=None, extra_include_paths=None, build_directory=None, verbose=False, with_cuda=None, is_python_module=True, is_standalone=False, keep_intermediates=True)¶ +torch.utils.cpp_extension.load(name, sources, extra_cflags=None, extra_cuda_cflags=None, extra_ldflags=None, extra_include_paths=None, build_directory=None, verbose=False, with_cuda=None, is_python_module=True, is_standalone=False, keep_intermediates=True) ``` 即时加载 PyTorch C++扩展(JIT)。 @@ -185,7 +185,7 @@ torch.utils.cpp_extension.load(name, sources, extra_cflags=None, extra_cuda_cfla ``` ```py -torch.utils.cpp_extension.load_inline(name, cpp_sources, cuda_sources=None, functions=None, extra_cflags=None, extra_cuda_cflags=None, extra_ldflags=None, extra_include_paths=None, build_directory=None, verbose=False, with_cuda=None, is_python_module=True, with_pytorch_error_handling=True, keep_intermediates=True, use_pch=False)¶ +torch.utils.cpp_extension.load_inline(name, cpp_sources, cuda_sources=None, functions=None, extra_cflags=None, extra_cuda_cflags=None, extra_ldflags=None, extra_include_paths=None, build_directory=None, verbose=False, with_cuda=None, is_python_module=True, with_pytorch_error_handling=True, keep_intermediates=True, use_pch=False) ``` 从字符串源加载 PyTorch C++扩展程序。 @@ -233,7 +233,7 @@ at::Tensor sin_add(at::Tensor x, at::Tensor y) { 默认情况下,Ninja 后端使用#CPUS + 2 个工作进程来构建扩展。这可能会在某些系统上使用过多资源。可以通过将 MAX_JOBS 环境变量设置为非负数来控制工作进程的数量。 ```py -torch.utils.cpp_extension.include_paths(cuda=False)¶ +torch.utils.cpp_extension.include_paths(cuda=False) ``` 获取构建 C++或 CUDA 扩展所需的包含路径。 @@ -251,7 +251,7 @@ torch.utils.cpp_extension.include_paths(cuda=False)¶ [*列表*](https://docs.python.org/3/library/typing.html#typing.List "(在 Python v3.12 中)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")] ```py -torch.utils.cpp_extension.get_compiler_abi_compatibility_and_version(compiler)¶ +torch.utils.cpp_extension.get_compiler_abi_compatibility_and_version(compiler) ``` 确定给定编译器是否与 PyTorch ABI 兼容以及其版本。 @@ -269,13 +269,13 @@ torch.utils.cpp_extension.get_compiler_abi_compatibility_and_version(compiler)¶ [*元组*](https://docs.python.org/3/library/typing.html#typing.Tuple "(在 Python v3.12 中)")[[bool](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"), *TorchVersion*] ```py -torch.utils.cpp_extension.verify_ninja_availability()¶ +torch.utils.cpp_extension.verify_ninja_availability() ``` 如果系统上没有[ninja](https://ninja-build.org/)构建系统,则引发`RuntimeError`,否则不执行任何操作。 ```py -torch.utils.cpp_extension.is_ninja_available()¶ +torch.utils.cpp_extension.is_ninja_available() ``` 如果系统上可用[ninja](https://ninja-build.org/)构建系统,则返回`True`,否则返回`False`。 diff --git a/totrans/doc22_087.md b/totrans/doc22_087.md index d7657dd0717a421209148eb2d6cce09c3f5b87a9..fa84d40026378c6921de5366f575b4ab00a2890d 100644 --- a/totrans/doc22_087.md +++ b/totrans/doc22_087.md @@ -242,7 +242,7 @@ for batch_ndx, sample in enumerate(loader): ``` ```py -class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None, *, prefetch_factor=None, persistent_workers=False, pin_memory_device='')¶ +class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None, *, prefetch_factor=None, persistent_workers=False, pin_memory_device='') ``` 数据加载器结合了数据集和采样器,并提供了对给定数据集的可迭代对象。 @@ -302,7 +302,7 @@ class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, sampler=N 有关随机种子相关问题,请参见可重现性,以及我的数据加载器工作进程返回相同的随机数,以及多进程数据加载中的随机性注释。 ```py -class torch.utils.data.Dataset(*args, **kwds)¶ +class torch.utils.data.Dataset(*args, **kwds) ``` 表示`Dataset`的抽象类。 @@ -314,7 +314,7 @@ class torch.utils.data.Dataset(*args, **kwds)¶ `DataLoader` 默认构造一个产生整数索引的索引采样器。要使其与具有非整数索引/键的映射样式数据集一起工作,必须提供自定义采样器。 ```py -class torch.utils.data.IterableDataset(*args, **kwds)¶ +class torch.utils.data.IterableDataset(*args, **kwds) ``` 一个可迭代的数据集。 @@ -413,7 +413,7 @@ class torch.utils.data.IterableDataset(*args, **kwds)¶ ``` ```py -class torch.utils.data.TensorDataset(*tensors)¶ +class torch.utils.data.TensorDataset(*tensors) ``` 包装张量的数据集。 @@ -425,7 +425,7 @@ class torch.utils.data.TensorDataset(*tensors)¶ ***tensors** (*Tensor*) - 具有相同第一维度大小的张量。 ```py -class torch.utils.data.StackDataset(*args, **kwargs)¶ +class torch.utils.data.StackDataset(*args, **kwargs) ``` 数据集作为多个数据集的堆叠。 @@ -450,7 +450,7 @@ class torch.utils.data.StackDataset(*args, **kwargs)¶ + ****kwargs** (*Dataset*) - 作为字典返回的堆叠数据集。 ```py -class torch.utils.data.ConcatDataset(datasets)¶ +class torch.utils.data.ConcatDataset(datasets) ``` 数据集作为多个数据集的串联。 @@ -462,7 +462,7 @@ class torch.utils.data.ConcatDataset(datasets)¶ **datasets** (*序列*) - 要连接的数据集列表 ```py -class torch.utils.data.ChainDataset(datasets)¶ +class torch.utils.data.ChainDataset(datasets) ``` 用于链接多个`IterableDataset`的数据集。 @@ -474,7 +474,7 @@ class torch.utils.data.ChainDataset(datasets)¶ **datasets** (*可迭代的* *IterableDataset*) - 要链接在一起的数据集 ```py -class torch.utils.data.Subset(dataset, indices)¶ +class torch.utils.data.Subset(dataset, indices) ``` 指定索引处数据集的子集。 @@ -486,7 +486,7 @@ class torch.utils.data.Subset(dataset, indices)¶ + **indices** (*序列*) - 选择子集的整个集合中的索引 ```py -torch.utils.data._utils.collate.collate(batch, *, collate_fn_map=None)¶ +torch.utils.data._utils.collate.collate(batch, *, collate_fn_map=None) ``` 处理每个批次中元素的集合类型的一般整理函数。 @@ -517,7 +517,7 @@ torch.utils.data._utils.collate.collate(batch, *, collate_fn_map=None)¶ 每个聚合函数都需要一个用于批处理的位置参数和一个用于聚合函数字典的关键字参数作为 collate_fn_map。 ```py -torch.utils.data.default_collate(batch)¶ +torch.utils.data.default_collate(batch) ``` 接收一批数据并将批次内的元素放入一个具有额外外部维度(批量大小)的张量中。 @@ -586,7 +586,7 @@ Point(x=tensor([0, 1]), y=tensor([0, 1])) ``` ```py -torch.utils.data.default_convert(data)¶ +torch.utils.data.default_convert(data) ``` 将每个 NumPy 数组元素转换为 `torch.Tensor`。 @@ -620,7 +620,7 @@ Point(x=tensor(0), y=tensor(0)) ``` ```py -torch.utils.data.get_worker_info()¶ +torch.utils.data.get_worker_info() ``` 返回有关当前 `DataLoader` 迭代器工作进程的信息。 @@ -646,7 +646,7 @@ torch.utils.data.get_worker_info()¶ [*可选*](https://docs.python.org/3/library/typing.html#typing.Optional "(在 Python v3.12 中)")[*WorkerInfo*] ```py -torch.utils.data.random_split(dataset, lengths, generator=)¶ +torch.utils.data.random_split(dataset, lengths, generator=) ``` 将数据集随机拆分为给定长度的不重叠新数据集。 @@ -679,7 +679,7 @@ torch.utils.data.random_split(dataset, lengths, generator= [`pytorch.org/docs/stable/deterministic.html`](https://pytorch.org/docs/stable/deterministic.html) ```py -torch.utils.deterministic.fill_uninitialized_memory¶ +torch.utils.deterministic.fill_uninitialized_memory ``` 一个[`bool`](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)"),如果为 True,则在将`torch.use_deterministic_algorithms()`设置为`True`时,未初始化的内存将被填充为已知值。浮点数和复数值设置为 NaN,整数值设置为最大值。 diff --git a/totrans/doc22_090.md b/totrans/doc22_090.md index 46374f47b210a7ddf018ceb82b36de0f1438edd3..47a4657284a7ea89e17c50c6165a99edabc53404 100644 --- a/totrans/doc22_090.md +++ b/totrans/doc22_090.md @@ -3,7 +3,7 @@ > 原文:[`pytorch.org/docs/stable/dlpack.html`](https://pytorch.org/docs/stable/dlpack.html) ```py -torch.utils.dlpack.from_dlpack(ext_tensor) → Tensor¶ +torch.utils.dlpack.from_dlpack(ext_tensor) → Tensor ``` 将来自外部库的张量转换为`torch.Tensor`。 @@ -53,7 +53,7 @@ tensor([-9, -1, 2, 3]) ``` ```py -torch.utils.dlpack.to_dlpack(tensor) → PyCapsule¶ +torch.utils.dlpack.to_dlpack(tensor) → PyCapsule ``` 返回表示张量的不透明对象(“DLPack 胶囊”)。 diff --git a/totrans/doc22_091.md b/totrans/doc22_091.md index 86cda09bbee3722ac981cb701bc43ab089c8ebaa..19fbfc32337b569e99aeff2a8f8a4305b4608d7b 100644 --- a/totrans/doc22_091.md +++ b/totrans/doc22_091.md @@ -29,7 +29,7 @@ Torch 移动支持 `torch.utils.mobile_optimizer.optimize_for_mobile` 实用程 `optimize_for_mobile` 还会调用 `freeze_module` pass,该 pass 仅保留 `forward` 方法。如果您有其他需要保留的方法,请将它们添加到保留方法列表中并传递给该方法。 ```py -torch.utils.mobile_optimizer.optimize_for_mobile(script_module, optimization_blocklist=None, preserved_methods=None, backend='CPU')¶ +torch.utils.mobile_optimizer.optimize_for_mobile(script_module, optimization_blocklist=None, preserved_methods=None, backend='CPU') ``` 为移动部署优化 torch 脚本模块。 diff --git a/totrans/doc22_092.md b/totrans/doc22_092.md index b3da68084fd4b02d38f938945ab6c98ef2af914e..a56c4f8022f71fc21730e21f9491af6c0af27e81 100644 --- a/totrans/doc22_092.md +++ b/totrans/doc22_092.md @@ -5,7 +5,7 @@ 移至 torch.hub。 ```py -torch.utils.model_zoo.load_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None, weights_only=False)¶ +torch.utils.model_zoo.load_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None, weights_only=False) ``` 加载给定 URL 处的 Torch 序列化对象。 diff --git a/totrans/doc22_093.md b/totrans/doc22_093.md index 5f418bcd56048090f35b2656b2743b5d374faf5d..043c2e6b10bea9dedb4f11ab657be9d0e773519f 100644 --- a/totrans/doc22_093.md +++ b/totrans/doc22_093.md @@ -58,7 +58,7 @@ for n_iter in range(100): ![_images/hier_tags.png](img/hier_tags.png) ```py -class torch.utils.tensorboard.writer.SummaryWriter(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='')¶ +class torch.utils.tensorboard.writer.SummaryWriter(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='') ``` 直接将条目写入 log_dir 中的事件文件,以供 TensorBoard 消费。 @@ -66,7 +66,7 @@ class torch.utils.tensorboard.writer.SummaryWriter(log_dir=None, comment='', pur SummaryWriter 类提供了一个高级 API,用于在给定目录中创建事件文件并向其中添加摘要和事件。该类异步更新文件内容。这允许训练程序从训练循环中直接调用方法将数据添加到文件中,而不会减慢训练速度。 ```py -__init__(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='')¶ +__init__(log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix='') ``` 创建一个 SummaryWriter,将事件和摘要写入事件文件。 @@ -104,7 +104,7 @@ writer = SummaryWriter(comment="LR_0.1_BATCH_16") ``` ```py -add_scalar(tag, scalar_value, global_step=None, walltime=None, new_style=False, double_precision=False)¶ +add_scalar(tag, scalar_value, global_step=None, walltime=None, new_style=False, double_precision=False) ``` 将标量数据添加到摘要。 @@ -137,7 +137,7 @@ writer.close() ![_images/add_scalar.png](img/add_scalar.png) ```py -add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None)¶ +add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None) ``` 将许多标量数据添加到摘要中。 @@ -172,7 +172,7 @@ writer.close() ![_images/add_scalars.png](img/add_scalars.png) ```py -add_histogram(tag, values, global_step=None, bins='tensorflow', walltime=None, max_bins=None)¶ +add_histogram(tag, values, global_step=None, bins='tensorflow', walltime=None, max_bins=None) ``` 将直方图添加到摘要中。 @@ -206,7 +206,7 @@ writer.close() ![_images/add_histogram.png](img/add_histogram.png) ```py -add_image(tag, img_tensor, global_step=None, walltime=None, dataformats='CHW')¶ +add_image(tag, img_tensor, global_step=None, walltime=None, dataformats='CHW') ``` 将图像数据添加到摘要中。 @@ -255,7 +255,7 @@ writer.close() ![_images/add_image.png](img/add_image.png) ```py -add_images(tag, img_tensor, global_step=None, walltime=None, dataformats='NCHW')¶ +add_images(tag, img_tensor, global_step=None, walltime=None, dataformats='NCHW') ``` 将批量图像数据添加到摘要中。 @@ -299,7 +299,7 @@ writer.close() ![_images/add_images.png](img/add_images.png) ```py -add_figure(tag, figure, global_step=None, close=True, walltime=None)¶ +add_figure(tag, figure, global_step=None, close=True, walltime=None) ``` 将 matplotlib 图形渲染为图像并将其添加到摘要中。 @@ -319,7 +319,7 @@ add_figure(tag, figure, global_step=None, close=True, walltime=None)¶ + **walltime** ([*可选*](https://docs.python.org/3/library/typing.html#typing.Optional "(在 Python v3.12 中)")*[*[*float*](https://docs.python.org/3/library/functions.html#float "(在 Python v3.12 中)")*]*) – 可选,覆盖默认的事件发生时的墙上时间(time.time())秒数 ```py -add_video(tag, vid_tensor, global_step=None, fps=4, walltime=None)¶ +add_video(tag, vid_tensor, global_step=None, fps=4, walltime=None) ``` 向摘要中添加视频数据。 @@ -343,7 +343,7 @@ add_video(tag, vid_tensor, global_step=None, fps=4, walltime=None)¶ vid_tensor: $(N, T, C, H, W)$(N,T,C,H,W)。值应在[0, 255]之间,对于 uint8 类型为[0, 255],对于 float 类型为[0, 1]。 ```py -add_audio(tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None)¶ +add_audio(tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None) ``` 向摘要中添加音频数据。 @@ -365,7 +365,7 @@ add_audio(tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None)¶ snd_tensor: $(1, L)$(1,L)。值应在[-1, 1]之间。 ```py -add_text(tag, text_string, global_step=None, walltime=None)¶ +add_text(tag, text_string, global_step=None, walltime=None) ``` 向摘要中添加文本数据。 @@ -388,7 +388,7 @@ writer.add_text('rnn', 'This is an rnn', 10) ``` ```py -add_graph(model, input_to_model=None, verbose=False, use_strict_trace=True)¶ +add_graph(model, input_to_model=None, verbose=False, use_strict_trace=True) ``` 将图形数据添加到摘要。 @@ -404,7 +404,7 @@ add_graph(model, input_to_model=None, verbose=False, use_strict_trace=True)¶ + **use_strict_trace**([*bool*](https://docs.python.org/3/library/functions.html#bool "(在 Python v3.12 中)")) - 是否将关键字参数 strict 传递给 torch.jit.trace。当您希望跟踪器记录您的可变容器类型(列表、字典)时,请传递 False ```py -add_embedding(mat, metadata=None, label_img=None, global_step=None, tag='default', metadata_header=None)¶ +add_embedding(mat, metadata=None, label_img=None, global_step=None, tag='default', metadata_header=None) ``` 将嵌入式投影仪数据添加到摘要。 @@ -450,7 +450,7 @@ writer.add_embedding(torch.randn(100, 5), metadata=meta) ``` ```py -add_pr_curve(tag, labels, predictions, global_step=None, num_thresholds=127, weights=None, walltime=None)¶ +add_pr_curve(tag, labels, predictions, global_step=None, num_thresholds=127, weights=None, walltime=None) ``` 添加精度召回曲线。 @@ -484,7 +484,7 @@ writer.close() ``` ```py -add_custom_scalars(layout)¶ +add_custom_scalars(layout) ``` 通过在“标量”中收集图表标签创建特殊图表。 @@ -508,7 +508,7 @@ writer.add_custom_scalars(layout) ``` ```py -add_mesh(tag, vertices, colors=None, faces=None, config_dict=None, global_step=None, walltime=None)¶ +add_mesh(tag, vertices, colors=None, faces=None, config_dict=None, global_step=None, walltime=None) ``` 将网格或 3D 点云添加到 TensorBoard。 @@ -569,7 +569,7 @@ writer.close() ``` ```py -add_hparams(hparam_dict, metric_dict, hparam_domain_discrete=None, run_name=None, global_step=None)¶ +add_hparams(hparam_dict, metric_dict, hparam_domain_discrete=None, run_name=None, global_step=None) ``` 添加一组要在 TensorBoard 中进行比较的超参数。 @@ -601,7 +601,7 @@ with SummaryWriter() as w: ![_images/add_hparam.png](img/add_hparam.png) ```py -flush()¶ +flush() ``` 将事件文件刷新到磁盘。 @@ -609,5 +609,5 @@ flush()¶ 调用此方法以确保所有待处理事件都已写入磁盘。 ```py -close()¶ +close() ``` diff --git a/totrans/doc22_094.md b/totrans/doc22_094.md index bf69f1f837f93911368eab31151e46f8ef11b1c3..7eebdb3e379beac8e2a28e322e93b18f7ab7e1af 100644 --- a/totrans/doc22_094.md +++ b/totrans/doc22_094.md @@ -7,7 +7,7 @@ ## torch.finfo ```py -class torch.finfo¶ +class torch.finfo ``` `torch.finfo`是一个表示浮点数`torch.dtype`(即`torch.float32`、`torch.float64`、`torch.float16`和`torch.bfloat16`)的数字属性的对象。这类似于[numpy.finfo](https://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html)。 @@ -33,7 +33,7 @@ class torch.finfo¶ smallest_normal 返回最小的*正常*数,但存在更小的次正常数。有关更多信息,请参阅[`en.wikipedia.org/wiki/Denormal_number`](https://en.wikipedia.org/wiki/Denormal_number)。## torch.iinfo ```py -class torch.iinfo¶ +class torch.iinfo ``` `torch.iinfo`是一个表示整数`torch.dtype`(即`torch.uint8`、`torch.int8`、`torch.int16`、`torch.int32`和`torch.int64`)的数字属性的对象。这类似于[numpy.iinfo](https://docs.scipy.org/doc/numpy/reference/generated/numpy.iinfo.html)。 diff --git a/totrans/doc22_095.md b/totrans/doc22_095.md index a2a64bada9373e3507f32a0b6b970df3bd8750df..805c31e76775d06a1b82558850c4797a69c706c8 100644 --- a/totrans/doc22_095.md +++ b/totrans/doc22_095.md @@ -253,7 +253,7 @@ class torch.Tensor ``` ```py -names¶ +names ``` 为该张量的每个维度存储名称。 @@ -269,7 +269,7 @@ names¶ 命名张量 API 是实验性的,可能会发生变化。 ```py -rename(*names, **rename_map)¶ +rename(*names, **rename_map) ``` 重命名`self`的维度名称。 @@ -304,13 +304,13 @@ rename(*names, **rename_map)¶ 命名张量 API 是实验性的,可能会发生变化。 ```py -rename_(*names, **rename_map)¶ +rename_(*names, **rename_map) ``` `rename()`的原地版本。 ```py -refine_names(*names)¶ +refine_names(*names) ``` 根据`names`细化`self`的维度名称。 @@ -346,7 +346,7 @@ Python 2 不支持省略号,但可以使用字符串文字代替(`'...'`) 命名张量 API 是实验性的,可能会发生变化。 ```py -align_as(other) → Tensor¶ +align_as(other) → Tensor ``` 将`self`张量的维度重新排列以匹配`other`张量中的维度顺序,在任何新名称中添加大小为一的维度。 @@ -389,7 +389,7 @@ align_as(other) → Tensor¶ 命名张量 API 是实验性的,可能会发生变化。 ```py -align_to(*names)¶ +align_to(*names) ``` 重新排列`self`张量的维度,以匹配`names`中指定的顺序,在任何新名称中添加大小为一的维度。 diff --git a/totrans/doc22_097.md b/totrans/doc22_097.md index cb0235c1131e1cdeac01e67e5cb06cb497acef84..81bca4903df5305dacdca1fa43f29b93beed49ff 100644 --- a/totrans/doc22_097.md +++ b/totrans/doc22_097.md @@ -3,13 +3,13 @@ > 原文:[`pytorch.org/docs/stable/config_mod.html`](https://pytorch.org/docs/stable/config_mod.html) ```py -torch.__config__.show()¶ +torch.__config__.show() ``` 返回一个包含 PyTorch 配置描述的易读字符串。 ```py -torch.__config__.parallel_info()¶ +torch.__config__.parallel_info() ``` 返回带有并行设置的详细字符串