Pytorch torch
对照 PyTorch 2.10.0+cpu 实际命名空间核对 16 类 420 项 torch API,标注 4 处顶层不存在名称与弃用接口迁移。
学完这一章,你能够
- 对照 PyTorch 2.10.0+cpu 实际命名空间核对 16 类 420 项 torch API,标注 4 处顶层不存在名称与弃用接口迁移。
torch 核心包定位与版本边界
torch 是 PyTorch 的核心命名空间,提供多维张量数据结构、数学与线性代数算子、自动求导控制以及序列化工具。需要按当前版本核对硬件支持:早期文档常提及“计算能力 >= 3.0 的 NVIDIA GPU”,但 PyTorch 2.10 CUDA 预编译包要求更新一代 GPU 架构,而本站 Windows CPU 构建下 torch.cuda.is_available() 返回 False。
下文按 16 个功能分组完整保留 420 项 API 条目,并在 PyTorch 2.10.0+cpu 中逐项核对命名空间存在性:共 416 项可直接解析、4 项顶层名称不存在——torch.expand 与 torch.expand_as 实际为张量方法 Tensor.expand / Tensor.expand_as;torch.linalg.matrix_transpose 不存在,应改用 Tensor.mT 或 torch.transpose(x, -2, -1);torch.cuda.device_context 不存在,CUDA 上下文管理器即为 torch.cuda.device。

同时需注意两类常见细节:一是 torch.set_default_tensor_type、torch.range 及部分旧顶层线代函数(如 torch.inverse / torch.svd / torch.trapz)在 2.x 中已弃用,推荐迁移至 set_default_dtype、torch.arange、torch.linalg.* 与 torch.trapezoid;二是 torch.softmax 属于沿维度归一化而非独立逐元素算子,torch.load 在 2.6+ 默认启用 weights_only=True 以防范不可信 pickle 风险。
核心张量、索引与自动求导综合示例
本站实测脚本在 CPU 上串联验证了张量创建、逐元素加法([1,2,3]+1 -> [2,3,4])、布尔掩码提取(x>1 -> [2,3])、矩阵乘法([3,4]@[4,5] -> [3,5])、标量求导(grad=[1,1,1])、STFT/ISTFT 重建、weights_only=True 读写往返以及上述 4 处缺失接口与 2 处弃用警告。完整参数规格以 PyTorch 2.10 官方文档为准。
Tensors 类型判断与默认配置
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.is_tensor(obj) | 判断对象是否为 PyTorch Tensor 实例。 | 2.10 已存在(本例已实测) |
| torch.is_storage(obj) | 判断对象是否为 PyTorch 底层 Storage 实例。 | 2.10 已存在(本例已实测) |
| torch.is_complex(input) | 判断张量元素类型是否为复数(如 complex64/complex128)。 | 2.10 已存在(本例已实测) |
| torch.is_conj(input) | 判断张量是否带有延迟共轭位标记。 | 2.10 已存在(本例已实测) |
| torch.is_floating_point(input) | 判断张量元素类型是否为浮点数(如 float32/float64/bfloat16)。 | 2.10 已存在(本例已实测) |
| torch.is_nonzero(input) | 判断单元素张量值是否非零;多元素张量将抛出 RuntimeError。 | 2.10 已存在(本例已实测) |
| torch.set_default_dtype(d) | 设置全局默认浮点 dtype,影响后续未显式指定类型的浮点张量创建。 | 2.10 已存在(本例已实测) |
| torch.get_default_dtype() | 返回当前全局默认浮点 dtype(初始为 torch.float32)。 | 2.10 已存在(本例已实测) |
| torch.set_default_device(device) | 设置全局默认设备(如 cpu/cuda),作用于后续张量与模块分配。 | 2.10 已存在(本例已实测) |
| torch.get_default_device() | 返回当前全局默认分配设备(CPU 环境默认 cpu)。 | 2.10 已存在(本例已实测) |
| torch.set_default_tensor_type(tensor_type) | 旧版默认张量类型接口(2.10 已弃用并触发警告),应改用 set_default_dtype 与 set_default_device。 | 2.10 仍保留(已弃用/旧别名) |
| torch.numel(input) | 返回张量包含的元素总个数(各维长度之积)。 | 2.10 已存在(本例已实测) |
| torch.set_printoptions(...) | 配置张量打印精度、阈值、换行宽度与科学计数法显示。 | 2.10 已存在(本例已实测) |
Tensor 创建
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.tensor(data, dtype, device, requires_grad) | 复制输入数据构造新张量,默认不继承来源计算图。 | 2.10 已存在(本例已实测) |
| torch.as_tensor(data, dtype, device) | 尽量避免拷贝地转换数据;仅当输入本为同类型同设备张量时保留梯度历史,NumPy 仅在内存兼容时共享。 | 2.10 已存在(本例已实测) |
| torch.asarray(data, dtype, device) | 按 NumPy asarray 风格转换输入,可选 copy 参数控制是否共享存储。 | 2.10 已存在(本例已实测) |
| torch.from_numpy(ndarray) | 将 CPU NumPy 数组包装为共享底层内存的张量,任一方原地修改彼此可见。 | 2.10 已存在(本例已实测) |
| torch.from_dlpack(ext_tensor) | 通过 DLPack 零拷贝协议将外部框架张量导入 PyTorch。 | 2.10 命名空间已核对(未逐项调用) |
| torch.frombuffer(buffer, dtype, count, offset) | 从 Python 缓冲区对象构造共享内存的一维张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.zeros(*size, dtype, device, requires_grad) | 按指定形状分配全 0 张量。 | 2.10 已存在(本例已实测) |
| torch.zeros_like(input, dtype, device, requires_grad) | 按参考张量形状(默认同 dtype/device)创建全 0 张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ones(*size, dtype, device, requires_grad) | 按指定形状分配全 1 张量。 | 2.10 已存在(本例已实测) |
| torch.ones_like(input, dtype, device, requires_grad) | 按参考张量形状创建全 1 张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.empty(*size, dtype, device, requires_grad) | 分配未初始化内存的张量,读取前应先写入有效数值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.empty_like(input, dtype, device, requires_grad) | 按参考张量形状分配未初始化内存张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.empty_strided(size, stride, dtype, device) | 按显式形状与内存步幅分配未初始化张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arange(start, end, step, dtype, device, requires_grad) | 生成半开区间 [start, end) 步长为 step 的一维等差序列。 | 2.10 已存在(本例已实测) |
| torch.range(start, end, step, dtype, device, requires_grad) | 生成闭区间 [start, end] 等差序列(2.10 已弃用并触发警告),请改用 torch.arange。 | 2.10 仍保留(已弃用/旧别名) |
| torch.linspace(start, end, steps, dtype, device, requires_grad) | 在闭区间 [start, end] 上均匀采样 steps 个点。 | 2.10 已存在(本例已实测) |
| torch.logspace(start, end, steps, base, dtype, device, requires_grad) | 以 base 为底,在指数区间 [start, end] 上生成 steps 个对数间隔点。 | 2.10 命名空间已核对(未逐项调用) |
| torch.eye(n, m, dtype, device, requires_grad) | 构造主对角线为 1、其余为 0 的二维单位矩阵(默认方阵 n×n)。 | 2.10 已存在(本例已实测) |
| torch.full(size, fill_value, dtype, device, requires_grad) | 按指定形状创建并全部填充 fill_value。 | 2.10 已存在(本例已实测) |
| torch.full_like(input, fill_value, dtype, device, requires_grad) | 按参考张量形状创建并填充指定标量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.rand(*size, dtype, device, requires_grad) | 生成 [0, 1) 区间连续均匀分布随机张量。 | 2.10 已存在(本例已实测) |
| torch.rand_like(input, dtype, device, requires_grad) | 按参考张量形状生成 [0, 1) 均匀分布随机数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randn(*size, dtype, device, requires_grad) | 生成均值为 0、方差为 1 的标准正态分布张量。 | 2.10 已存在(本例已实测) |
| torch.randn_like(input, dtype, device, requires_grad) | 按参考张量形状生成标准正态分布随机数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randint(low, high, size, dtype, device, requires_grad) | 生成半开区间 [low, high) 内均匀分布的随机整数张量。 | 2.10 已存在(本例已实测) |
| torch.randint_like(input, low, high, dtype, device, requires_grad) | 按参考张量形状生成 [low, high) 随机整数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randperm(n, dtype, device, requires_grad) | 返回 0 到 n-1 的随机置换一维整数张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sparse_coo_tensor(indices, values, size, dtype, device, requires_grad) | 按坐标格式(COO)非零索引与对应值构造稀疏张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sparse_csr_tensor(crow_indices, col_indices, values, size, dtype, device) | 按压缩稀疏行格式(CSR)构造二维稀疏张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sparse_csc_tensor(ccol_indices, row_indices, values, size, dtype, device) | 按压缩稀疏列格式(CSC)构造二维稀疏张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantize_per_tensor(input, scale, zero_point, dtype) | 按整张量统一缩放因子与零点将浮点张量线性量化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantize_per_channel(input, scales, zero_points, axis, dtype) | 沿指定通道轴分别应用缩放因子与零点进行线性量化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.dequantize(input) | 将量化张量反量化还原为浮点张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.complex(real, imag) | 由等形状浮点实部与虚部张量合成复数张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.polar(abs, angle) | 由模长 abs 与辐角 angle 构造复数张量 abs·(cos+i·sin)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.heaviside(input, values) | 计算单位阶跃函数:负值取 0、正值取 1、0 处取 values 对应值。 | 2.10 已存在(本例已实测) |
索引、切片、连接与形状变换
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.cat(tensors, dim, out) | 沿已有维度拼接多个除拼接轴外同形的张量。 | 2.10 已存在(本例已实测) |
| torch.concat(tensors, dim, out) | torch.cat 的别名,语义与参数一致。 | 2.10 命名空间已核对(未逐项调用) |
| torch.concatenate(tensors, dim, out) | torch.cat 的 NumPy 风格别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.stack(tensors, dim, out) | 新增一个维度并沿该新维堆叠等形状张量。 | 2.10 已存在(本例已实测) |
| torch.split(tensor, split_size, dim) | 按固定块大小或各段长度列表沿 dim 拆分张量。 | 2.10 已存在(本例已实测) |
| torch.chunk(tensor, chunks, dim) | 沿指定维度尽量均匀切分为最多 chunks 块视图。 | 2.10 已存在(本例已实测) |
| torch.reshape(input, shape) | 在元素总数不变前提下返回目标形状(可能返回视图或拷贝)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.transpose(input, dim0, dim1) | 交换两个指定维度,返回共享存储的非连续视图。 | 2.10 已存在(本例已实测) |
| torch.t(input) | 对不超过二维的张量转置 0 维与 1 维。 | 2.10 命名空间已核对(未逐项调用) |
| torch.squeeze(input, dim) | 移除长度为 1 的维度;生产代码建议显式传 dim 避免误删批次轴。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unsqueeze(input, dim) | 在指定轴位置插入长度为 1 的新维度。 | 2.10 命名空间已核对(未逐项调用) |
| torch.permute(input, dims) | 按新轴序列 dims 重排张量全部维度。 | 2.10 命名空间已核对(未逐项调用) |
| torch.movedim(input, source, destination) | 将一个或多个维度从 source 位置移动到 destination。 | 2.10 命名空间已核对(未逐项调用) |
| torch.moveaxis(input, source, destination) | torch.movedim 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.narrow(input, dim, start, length) | 沿 dim 从 start 起截取长度 length 的连续视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.narrow_copy(input, dim, start, length) | 与 narrow 类似但返回独立拷贝而非共享视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.select(input, dim, index) | 沿指定维度按单个整数索引降维切片。 | 2.10 命名空间已核对(未逐项调用) |
| torch.slice_scatter(input, src, dim, start, end) | 将 src 写入 input 切片区间并返回新张量(非原地)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.select_scatter(input, src, dim, index) | 将 src 写入指定单索引切片并返回新张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diagonal_scatter(input, src, offset, dim1, dim2) | 将 src 写入指定对角线并返回新张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.expand(input, size) | 【2.10 纠偏】顶层 torch.expand 不存在;请调用张量方法 Tensor.expand(*sizes) 创建步幅为 0 的广播视图。 | 2.10 顶层不存在(已实测缺失并给出替代) |
| torch.expand_as(input, other) | 【2.10 纠偏】顶层 torch.expand_as 不存在;请调用张量方法 Tensor.expand_as(other)。 | 2.10 顶层不存在(已实测缺失并给出替代) |
| torch.masked_select(input, mask) | 按布尔掩码提取 True 位置元素并展平为一维新张量。 | 2.10 已存在(本例已实测) |
| torch.index_select(input, dim, index) | 沿指定维度按一维整型索引张量抽取子集。 | 2.10 命名空间已核对(未逐项调用) |
| torch.gather(input, dim, index, sparse_grad) | 沿指定维度按与输出同形的索引张量收集元素。 | 2.10 已存在(本例已实测) |
| torch.scatter(input, dim, index, src, reduce) | 沿指定维度将 src 值按 index 散射写入新张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.scatter_add(input, dim, index, src) | 将 src 按索引累加散射至新张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.scatter_reduce(input, dim, index, src, reduce, include_self) | 按 sum/prod/mean/amax/amin 规约方式散射聚合。 | 2.10 命名空间已核对(未逐项调用) |
| torch.index_add(input, dim, index, source, alpha) | 沿 dim 将 alpha * source 累加到 index 对应切片。 | 2.10 命名空间已核对(未逐项调用) |
| torch.index_copy(input, dim, index, source) | 沿 dim 将 source 复制覆盖到 index 对应切片。 | 2.10 命名空间已核对(未逐项调用) |
| torch.index_reduce(input, dim, index, source, reduce, include_self) | 沿 dim 按指定规约操作把 source 聚合到 index 对应切片。 | 2.10 命名空间已核对(未逐项调用) |
| torch.take(input, index) | 把输入视为一维展平序列按 index 抽取元素。 | 2.10 命名空间已核对(未逐项调用) |
| torch.take_along_dim(input, indices, dim) | 沿指定轴按广播兼容的索引张量收集元素。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nonzero(input) | 返回所有非零元素的多维坐标索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.argwhere(input) | 返回所有非零元素的二维坐标矩阵(与 nonzero(as_tuple=False) 一致)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.where(condition, input, other) | 按布尔条件逐元素从 input 或 other 选值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unbind(tensor, dim) | 沿 dim 拆解为多个降一维的张量元组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.split_with_sizes(tensor, split_sizes, dim) | 按显式各段尺寸序列沿 dim 拆分张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tensor_split(tensor, indices_or_sections, dim) | 按切分点或段数拆分,支持无法整除时的近均匀分配。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hsplit(tensor, indices_or_sections) | 按水平方向(1D 沿轴 0,>=2D 沿轴 1)拆分张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.vsplit(tensor, indices_or_sections) | 沿垂直方向(轴 0)拆分至少二维张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.dsplit(tensor, indices_or_sections) | 沿深度方向(轴 2)拆分至少三维张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hstack(tensors, dim, out) | 水平拼接张量(1D 沿轴 0,>=2D 沿轴 1)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.vstack(tensors, out) | 垂直沿轴 0 拼接(1D 先升维为行向量)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.dstack(tensors, out) | 沿深度轴 2 拼接(不足三维时自动补维)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.column_stack(tensors, out) | 将一维或二维张量按列水平堆叠为二维矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.row_stack(tensors, out) | torch.vstack 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tile(input, dims) | 按各轴重复次数复制数据构造更大张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.repeat_interleave(input, repeats, dim) | 将每个元素或切片连续重复指定次数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.flip(input, dims) | 沿给定维度列表反转元素顺序。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fliplr(input) | 沿左右方向(轴 1)翻转至少二维张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.flipud(input) | 沿上下方向(轴 0)翻转张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.rot90(input, k, dims) | 在 dims 指定的平面内将张量逆时针旋转 k×90 度。 | 2.10 命名空间已核对(未逐项调用) |
| torch.linalg.matrix_transpose(input) | 【2.10 纠偏】torch.linalg.matrix_transpose 与 torch.matrix_transpose 均不存在;请改用 Tensor.mT 或 torch.transpose(input, -2, -1)。 | 2.10 顶层不存在(已实测缺失并给出替代) |
| torch.adjoint(input) | 返回最后两维共轭转置视图(等价于 Tensor.mH)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.resolve_conj(input) | 若带有延迟共轭位则物化为实际共轭张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.resolve_neg(input) | 若带有延迟取负位则物化为实际取负张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.view_as_real(input) | 将复数张量以末维长度 2 的实数视图呈现。 | 2.10 命名空间已核对(未逐项调用) |
| torch.view_as_complex(input) | 将末维长度为 2 的连续实数张量视为复数视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unravel_index(indices, shape) | 将扁平下标还原为对应目标 shape 的各维坐标元组。 | 2.10 已存在(本例已实测) |
随机数生成
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.manual_seed(seed) | 设置 CPU(及可用 CUDA 设备)的默认随机数种子。 | 2.10 已存在(本例已实测) |
| torch.seed() | 使用非确定性熵重置随机种子并返回该新种子。 | 2.10 命名空间已核对(未逐项调用) |
| torch.initial_seed() | 返回当前 CPU 默认随机生成器的初始种子。 | 2.10 命名空间已核对(未逐项调用) |
| torch.get_rng_state() | 导出当前 CPU 随机数生成器内部状态字节张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.set_rng_state(state) | 恢复先前保存的 CPU 随机数生成器状态。 | 2.10 命名空间已核对(未逐项调用) |
| torch.rand(*size, dtype, device, requires_grad) | 采样 [0, 1) 均匀分布随机张量。 | 2.10 已存在(本例已实测) |
| torch.rand_like(input, dtype, device, requires_grad) | 按参考张量形状采样 [0, 1) 均匀分布。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randn(*size, dtype, device, requires_grad) | 采样均值为 0、标准差为 1 的标准正态分布。 | 2.10 已存在(本例已实测) |
| torch.randn_like(input, dtype, device, requires_grad) | 按参考张量形状采样标准正态分布。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randint(low, high, size, dtype, device, requires_grad) | 采样 [low, high) 均匀随机整数。 | 2.10 已存在(本例已实测) |
| torch.randint_like(input, low, high, dtype, device, requires_grad) | 按参考张量形状采样 [low, high) 随机整数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.randperm(n, dtype, device, requires_grad) | 返回 0..n-1 的随机排列。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bernoulli(input, *, generator) | 以 input 中各元素为概率逐项抽取 0/1 伯努利样本。 | 2.10 命名空间已核对(未逐项调用) |
| torch.multinomial(input, num_samples, replacement, generator) | 按行非负权重做多项式有放回/无放回抽样。 | 2.10 命名空间已核对(未逐项调用) |
| torch.normal(mean, std, out) | 按给定均值与标准差采样正态分布随机数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.poisson(input, generator) | 以 input 各元素为速率参数采样泊松分布随机数。 | 2.10 已存在(本例已实测) |
序列化
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.save(obj, f, pickle_module, pickle_protocol) | 将张量或状态字典序列化保存至文件或二进制流。 | 2.10 已存在(本例已实测) |
| torch.load(f, map_location, pickle_module, weights_only) | 加载序列化文件;PyTorch 2.6+ 默认 weights_only=True 以避免任意 pickle 执行风险,切勿对不可信文件关闭。 | 2.10 已存在(本例已实测) |
梯度控制
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.no_grad() | 上下文管理器/装饰器,在作用域内关闭梯度图记录,常用于评估与参数手动更新。 | 2.10 已存在(本例已实测) |
| torch.enable_grad() | 在外部已禁梯度的作用域内局部恢复梯度记录。 | 2.10 已存在(本例已实测) |
| torch.set_grad_enabled(grad) | 按布尔值动态切换梯度记录开关(可作上下文管理器或全局调用)。 | 2.10 已存在(本例已实测) |
| torch.is_grad_enabled() | 查询当前线程是否开启梯度计算。 | 2.10 已存在(本例已实测) |
| torch.inference_mode() | 比 no_grad 更严格的推理上下文,同时跳过视图版本追踪以降低推理开销。 | 2.10 已存在(本例已实测) |
| torch.is_inference_mode_enabled() | 查询当前线程是否处于推理模式上下文中。 | 2.10 已存在(本例已实测) |
数学运算 - 点操作(含 softmax 纠偏)
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.abs(input, out) | 计算各元素绝对值(复数取模长)。 | 2.10 已存在(本例已实测) |
| torch.absolute(input, out) | torch.abs 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.acos(input, out) | 逐元素反余弦,定义域实数 [-1, 1]。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arccos(input, out) | torch.acos 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.acosh(input, out) | 逐元素反双曲余弦,实数输入需 >= 1。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arccosh(input, out) | torch.acosh 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.add(input, other, alpha, out) | 计算 input + alpha * other,支持广播。 | 2.10 已存在(本例已实测) |
| torch.addcdiv(input, tensor1, tensor2, value, out) | 融合计算 input + value * (tensor1 / tensor2)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.addcmul(input, tensor1, tensor2, value, out) | 融合计算 input + value * tensor1 * tensor2。 | 2.10 命名空间已核对(未逐项调用) |
| torch.angle(input, out) | 返回各元素的辐角(弧度制)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.asin(input, out) | 逐元素反正弦。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arcsin(input, out) | torch.asin 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.asinh(input, out) | 逐元素反双曲正弦。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arcsinh(input, out) | torch.asinh 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.atan(input, out) | 逐元素反正切。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arctan(input, out) | torch.atan 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.atan2(input, other, out) | 按象限计算逐元素二元反正切 atan2(input, other)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arctan2(input, other, out) | torch.atan2 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.atanh(input, out) | 逐元素反双曲正切,实数输入需在 (-1, 1)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.arctanh(input, out) | torch.atanh 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_not(input, out) | 整型/布尔张量逐元素按位取反。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_and(input, other, out) | 整型/布尔张量逐元素按位与。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_or(input, other, out) | 整型/布尔张量逐元素按位或。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_xor(input, other, out) | 整型/布尔张量逐元素按位异或。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_left_shift(input, other, out) | 整型张量逐元素按位左移。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bitwise_right_shift(input, other, out) | 整型张量逐元素按位右移。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ceil(input, out) | 逐元素向上取整。 | 2.10 命名空间已核对(未逐项调用) |
| torch.clamp(input, min, max, out) | 将元素截断到 [min, max] 区间内。 | 2.10 命名空间已核对(未逐项调用) |
| torch.clip(input, min, max, out) | torch.clamp 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.conj_physical(input, out) | 直接计算并返回物理共轭张量而非延迟标记。 | 2.10 命名空间已核对(未逐项调用) |
| torch.copysign(input, other, out) | 取 input 幅值并采用 other 的正负号。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cos(input, out) | 逐元素余弦(弧度)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cosh(input, out) | 逐元素双曲余弦。 | 2.10 命名空间已核对(未逐项调用) |
| torch.deg2rad(input, out) | 将角度值转换为弧度值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.div(input, other, rounding_mode, out) | 逐元素除法;rounding_mode 可选 None/trunc/floor。 | 2.10 命名空间已核对(未逐项调用) |
| torch.divide(input, other, rounding_mode, out) | torch.div 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.digamma(input, out) | 计算伽马函数对数的导数(psi 函数)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.erf(input, out) | 计算高斯误差函数 erf(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.erfc(input, out) | 计算互补误差函数 1 - erf(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.erfinv(input, out) | 计算误差函数的反函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.exp(input, out) | 计算逐元素自然指数 e^x。 | 2.10 命名空间已核对(未逐项调用) |
| torch.exp2(input, out) | 计算逐元素以 2 为底的指数 2^x。 | 2.10 命名空间已核对(未逐项调用) |
| torch.expm1(input, out) | 高精度计算 e^x - 1,x 接近 0 时更稳定。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) | 在量化感知训练(QAT)中模拟按通道仿射量化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) | 在量化感知训练(QAT)中模拟按张量仿射量化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fix(input, out) | 向零方向截断取整(同 torch.trunc)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.float_power(input, exponent, out) | 以双精度浮点执行幂运算,避免整数溢出。 | 2.10 命名空间已核对(未逐项调用) |
| torch.floor(input, out) | 逐元素向下取整。 | 2.10 命名空间已核对(未逐项调用) |
| torch.floor_divide(input, other, out) | 逐元素向下取整除法(旧接口,建议改用 div(..., rounding_mode='floor'))。 | 2.10 仍保留(已弃用/旧别名) |
| torch.fmod(input, other, out) | C 风格浮点/整数取余,余数符号与被除数一致。 | 2.10 命名空间已核对(未逐项调用) |
| torch.frac(input, out) | 提取各元素小数部分 x - trunc(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.frexp(input, out) | 将浮点数分解为尾数 mantissa 与 2 的整数幂 exponent。 | 2.10 命名空间已核对(未逐项调用) |
| torch.gradient(input, dim, spacing, edge_order) | 用二阶中心差分估计张量沿指定维度的数值导数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.imag(input, out) | 提取复数张量的虚部视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ldexp(input, other, out) | 计算 input * 2^other(frexp 的逆过程)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lerp(input, end, weight, out) | 按 weight 在 input 与 end 之间做线性插值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lgamma(input, out) | 计算 ln(|Gamma(x)|)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.log(input, out) | 逐元素自然对数 ln(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.log10(input, out) | 逐元素常用对数 log10(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.log1p(input, out) | 高精度计算 ln(1 + x),x 接近 0 时减少精度损失。 | 2.10 命名空间已核对(未逐项调用) |
| torch.log2(input, out) | 逐元素以 2 为底的对数 log2(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logaddexp(input, other, out) | 数值稳定地计算 ln(e^input + e^other)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logaddexp2(input, other, out) | 数值稳定地计算 log2(2^input + 2^other)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logical_and(input, other, out) | 逐元素布尔逻辑与。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logical_not(input, out) | 逐元素布尔逻辑非。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logical_or(input, other, out) | 逐元素布尔逻辑或。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logical_xor(input, other, out) | 逐元素布尔逻辑异或。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logit(input, eps, out) | 计算 Sigmoid 反函数 ln(p/(1-p)),可选 eps 裁剪端点。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hypot(input, other, out) | 数值稳定地计算直角三角形斜边 sqrt(x^2 + y^2)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.i0(input, out) | 计算零阶第一类修正贝塞尔函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.igamma(input, other, out) | 计算正则化下不完全伽马函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.igammac(input, other, out) | 计算正则化上不完全伽马函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mul(input, other, out) | 逐元素乘法(Hadamard 积),支持广播。 | 2.10 命名空间已核对(未逐项调用) |
| torch.multiply(input, other, out) | torch.mul 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mvlgamma(input, p, out) | 计算 p 维多元伽马函数的自然对数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nan_to_num(input, nan, posinf, neginf, out) | 将 NaN 与正负无穷替换为指定有限数值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.neg(input, out) | 逐元素取相反数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.negative(input, out) | torch.neg 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nextafter(input, other, out) | 返回从 input 朝 other 方向的下一个可表示浮点数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.polygamma(input, n, out) | 计算 n 阶多伽马函数(参数顺序实际为 polygamma(n, input))。 | 2.10 命名空间已核对(未逐项调用) |
| torch.positive(input, out) | 返回输入张量自身(一元正号语义)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.pow(input, exponent, out) | 逐元素幂运算 input^exponent。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantized_batch_norm(input, weight, bias, mean, var, eps, output_scale, output_zero_point) | 对量化张量执行批归一化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantized_max_pool1d(input, kernel_size, stride, padding, dilation, ceil_mode) | 对量化张量执行一维最大池化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantized_max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode) | 对量化张量执行二维最大池化。 | 2.10 命名空间已核对(未逐项调用) |
| torch.rad2deg(input, out) | 将弧度值转换为角度值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.real(input, out) | 提取复数张量的实部视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.reciprocal(input, out) | 逐元素求倒数 1/x。 | 2.10 命名空间已核对(未逐项调用) |
| torch.remainder(input, other, out) | Python 风格取余,余数符号与除数 other 一致。 | 2.10 命名空间已核对(未逐项调用) |
| torch.round(input, decimals, out) | 按偶舍入(banker's rounding)四舍五入,可选小数位数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.rsqrt(input, out) | 逐元素计算平方根倒数 1/sqrt(x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sigmoid(input, out) | 逐元素逻辑 Sigmoid 映射 1/(1+e^-x)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sign(input, out) | 返回实数元素符号 {-1, 0, 1}。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sgn(input, out) | 返回单位符号值,支持复数 x/|x|。 | 2.10 命名空间已核对(未逐项调用) |
| torch.signbit(input, out) | 逐元素判断浮点符号位是否为负(区分 -0.0 与 +0.0)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sin(input, out) | 逐元素正弦(弧度)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sinc(input, out) | 计算归一化 sinc 函数 sin(pi*x)/(pi*x)(x=0 处为 1)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sinh(input, out) | 逐元素双曲正弦。 | 2.10 命名空间已核对(未逐项调用) |
| torch.softmax(input, dim, dtype) | 【纠偏】沿指定维度 dim 做指数归一化(总和为 1),属于维度规约归一化而非独立逐元素函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sqrt(input, out) | 逐元素平方根。 | 2.10 命名空间已核对(未逐项调用) |
| torch.square(input, out) | 逐元素平方 x^2。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sub(input, other, alpha, out) | 计算 input - alpha * other。 | 2.10 命名空间已核对(未逐项调用) |
| torch.subtract(input, other, alpha, out) | torch.sub 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tan(input, out) | 逐元素正切。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tanh(input, out) | 逐元素双曲正切,输出在 (-1, 1)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.true_divide(input, other, out) | 真除法(torch.div 默认模式别名)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.trunc(input, out) | 向零方向截断取整数部分。 | 2.10 命名空间已核对(未逐项调用) |
| torch.xlogy(input, other, out) | 计算 input * log(other),当 input=0 时约定返回 0 而非 NaN。 | 2.10 已存在(本例已实测) |
数学运算 - 归约操作
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.argmax(input, dim, keepdim) | 返回全局或沿指定维度的最大值下标。 | 2.10 已存在(本例已实测) |
| torch.argmin(input, dim, keepdim) | 返回全局或沿指定维度的最小值下标。 | 2.10 命名空间已核对(未逐项调用) |
| torch.amax(input, dim, keepdim, out) | 返回沿一个或多个维度的最大值(不返回索引)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.amin(input, dim, keepdim, out) | 返回沿一个或多个维度的最小值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.aminmax(input, dim, keepdim, out) | 一次遍历同时返回最小值与最大值命名元组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.all(input, dim, keepdim, out) | 检查全局或沿维度是否全为真值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.any(input, dim, keepdim, out) | 检查全局或沿维度是否存在任意真值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.max(input, dim, keepdim, out) | 传 dim 时返回 (values, indices);无 dim 时返回全局最大标量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.min(input, dim, keepdim, out) | 传 dim 时返回 (values, indices);无 dim 时返回全局最小标量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.dist(input, other, p) | 计算两张量差值的 p-范数距离。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logsumexp(input, dim, keepdim, out) | 数值稳定地沿维度计算 log(sum(exp(x)))。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mean(input, dim, keepdim, out) | 计算浮点或复数张量的算术平均值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nanmean(input, dim, keepdim, out) | 忽略 NaN 后计算算术平均值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.median(input, dim, keepdim, out) | 返回中位数;传 dim 时返回 (values, indices)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nanmedian(input, dim, keepdim, out) | 忽略 NaN 后计算中位数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mode(input, dim, keepdim, out) | 沿指定维度返回众数及其最后出现位置索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.norm(input, p, dim, keepdim, out) | 计算向量或矩阵范数(2.x 推荐按需改用 torch.linalg.vector_norm / matrix_norm)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nansum(input, dim, keepdim, out) | 忽略 NaN 后沿维度求和。 | 2.10 命名空间已核对(未逐项调用) |
| torch.prod(input, dim, keepdim, dtype, out) | 计算所有元素或沿维度的连乘积。 | 2.10 命名空间已核对(未逐项调用) |
| torch.quantile(input, q, dim, keepdim, out, method) | 沿维度计算分位数 q(0..1),支持多种插值方法。 | 2.10 命名空间已核对(未逐项调用) |
| torch.nanquantile(input, q, dim, keepdim, out, method) | 忽略 NaN 后计算分位数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.std(input, dim, unbiased, keepdim, out) | 计算标准差(现代参数推荐用 correction 控制自由度)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.std_mean(input, dim, unbiased, keepdim) | 一次返回 (std, mean) 元组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sum(input, dim, keepdim, dtype, out) | 计算元素总和或沿维度求和。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unique(input, sorted, return_inverse, return_counts, dim) | 提取去重后的唯一元素或切片,可选返回逆索引与频次。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unique_consecutive(input, sorted, return_inverse, return_counts, dim) | 仅合并相邻重复元素。 | 2.10 命名空间已核对(未逐项调用) |
| torch.var(input, dim, unbiased, keepdim, out) | 计算方差(推荐用 correction 参数指定 Bessel 校正)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.var_mean(input, dim, unbiased, keepdim) | 一次返回 (var, mean) 元组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.count_nonzero(input, dim) | 统计全局或沿指定维度的非零元素个数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hash_tensor(input) | 沿指定维度对张量元素计算 XOR 哈希摘要标量/张量。 | 2.10 已存在(本例已实测) |
数学运算 - 比较与排序操作
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.allclose(input, other, rtol, atol, equal_nan) | 判断两张量全部元素是否满足 |a-b| <= atol + rtol*|b|,返回 Python bool。 | 2.10 已存在(本例已实测) |
| torch.argsort(input, dim, descending, stable) | 返回沿维度排序后的下标索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.eq(input, other, out) | 逐元素相等比较,返回布尔张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.equal(input, other) | 判断两张量形状与全部元素是否严格一致,返回 bool。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ge(input, other, out) | 逐元素大于等于比较(>=)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.greater_equal(input, other, out) | torch.ge 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.gt(input, other, out) | 逐元素严格大于比较(>)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.greater(input, other, out) | torch.gt 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isclose(input, other, rtol, atol, equal_nan) | 逐元素判断是否在相对/绝对容差内接近,返回布尔张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isfinite(input, out) | 逐元素判断是否既非无穷也非 NaN。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isin(elements, test_elements, assume_unique, invert) | 判断 elements 中各值是否出现在 test_elements 内。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isinf(input, out) | 逐元素判断是否为正无穷或负无穷。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isposinf(input, out) | 逐元素判断是否为 +inf。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isneginf(input, out) | 逐元素判断是否为 -inf。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isnan(input, out) | 逐元素判断是否为 NaN。 | 2.10 命名空间已核对(未逐项调用) |
| torch.isreal(input, out) | 逐元素判断虚部是否为 0(实数张量恒 True)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.kthvalue(input, k, dim, keepdim, out) | 返回沿维度第 k 小(1-based)元素及其索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.le(input, other, out) | 逐元素小于等于比较(<=)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.less_equal(input, other, out) | torch.le 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lt(input, other, out) | 逐元素严格小于比较(<)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.less(input, other, out) | torch.lt 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.maximum(input, other, out) | 逐元素取较大值(遇 NaN 传播 NaN)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.minimum(input, other, out) | 逐元素取较小值(遇 NaN 传播 NaN)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fmax(input, other, out) | 逐元素取较大值,一侧为 NaN 时取另一侧有限值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.fmin(input, other, out) | 逐元素取较小值,一侧为 NaN 时取另一侧有限值。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ne(input, other, out) | 逐元素不等比较(!=)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.not_equal(input, other, out) | torch.ne 的别名。 | 2.10 命名空间已核对(未逐项调用) |
| torch.sort(input, dim, descending, stable, out) | 沿指定维度排序,返回 (values, indices)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.topk(input, k, dim, largest, sorted, out) | 沿维度返回前 k 个最大或最小元素及其索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.msort(input, out) | 沿第 0 维升序排列并仅返回排序后的值张量(等价于 sort(dim=0).values)。 | 2.10 已存在(本例已实测) |
数学运算 - 谱操作与窗函数
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.stft(input, n_fft, hop_length, win_length, window, center, normalized, onesided, return_complex) | 计算一维信号短时傅里叶变换;现代用法须设 return_complex=True。 | 2.10 已存在(本例已实测) |
| torch.istft(input, n_fft, hop_length, win_length, window, center, normalized, onesided, length, return_complex) | 由 STFT 频谱重建时域信号。 | 2.10 已存在(本例已实测) |
| torch.bartlett_window(window_length, periodic, dtype, device) | 生成三角 Bartlett 窗函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.blackman_window(window_length, periodic, dtype, device) | 生成 Blackman 窗函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hamming_window(window_length, periodic, alpha, beta, dtype, device) | 生成广义 Hamming 窗函数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.hann_window(window_length, periodic, dtype, device) | 生成 Hann 窗函数,常与 STFT/ISTFT 配合使用。 | 2.10 已存在(本例已实测) |
| torch.kaiser_window(window_length, periodic, beta, dtype, device) | 生成参数可调的 Kaiser 窗函数。 | 2.10 已存在(本例已实测) |
数学运算 - 其他操作
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.atleast_1d(*tensors) | 将标量升维为 1D,已有 >=1D 张量保持原状。 | 2.10 已存在(本例已实测) |
| torch.atleast_2d(*tensors) | 确保每个张量至少为 2D。 | 2.10 命名空间已核对(未逐项调用) |
| torch.atleast_3d(*tensors) | 确保每个张量至少为 3D。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bincount(input, weights, minlength) | 统计非负一维整数张量各取值出现频次(或权重和)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.block_diag(*tensors) | 将若干二维张量沿主对角拼成块对角矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.broadcast_tensors(*tensors) | 按广播规则将一组张量扩展为相同形状的视图元组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.broadcast_to(input, shape) | 将张量广播为目标 shape(只读视图,语义同 expand)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.broadcast_shapes(*shapes) | 仅计算多个形状广播后的结果形状,不分配张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bucketize(input, boundaries, right) | 查找各元素落入有序边界 boundaries 的桶编号。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cartesian_prod(*tensors) | 计算多个一维张量的笛卡尔积组合。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cdist(x1, x2, p, compute_mode) | 计算两组行向量之间的成对 p-范数距离矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.clone(input, memory_format) | 返回张量深拷贝,并保留在自动求导计算图中。 | 2.10 命名空间已核对(未逐项调用) |
| torch.combinations(input, r, with_replacement) | 生成一维张量长度为 r 的所有组合。 | 2.10 命名空间已核对(未逐项调用) |
| torch.corrcoef(input) | 估计二维矩阵行变量间的皮尔逊相关系数矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cov(input, correction, fweights, aweights) | 估计二维矩阵行变量间的协方差矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cross(input, dim, out) | 计算三维向量叉积(需传两张量 input, other;推荐 torch.linalg.cross)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cummax(input, dim, out) | 沿维度计算前缀最大值与对应索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cummin(input, dim, out) | 沿维度计算前缀最小值与对应索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cumprod(input, dim, out) | 沿维度计算前缀连乘积。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cumsum(input, dim, out, dtype) | 沿维度计算前缀累加和。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diag(input, diagonal, out) | 一维输入构造对角矩阵,二维输入提取指定对角线。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diag_embed(input, offset, dim1, dim2, out) | 将末维向量嵌入为批量矩阵的对角线。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diagflat(input, offset, out) | 将展平后的所有元素放入二维矩阵对角线。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diagonal(input, offset, dim1, dim2, out) | 返回指定两维平面的对角线视图。 | 2.10 命名空间已核对(未逐项调用) |
| torch.diff(input, n, dim, prepend, append, out) | 沿维度计算 n 阶离散前向差分。 | 2.10 命名空间已核对(未逐项调用) |
| torch.einsum(equation, *operands) | 按爱因斯坦求和下标表达式执行张量缩并。 | 2.10 命名空间已核对(未逐项调用) |
| torch.flatten(input, start_dim, end_dim, out) | 将 [start_dim, end_dim] 连续维度合并为一维。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ravel(input, out) | 将张量展平为一维连续视图(必要时拷贝)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.kron(input, other, out) | 计算两个张量的克罗内克(Kronecker)积。 | 2.10 命名空间已核对(未逐项调用) |
| torch.meshgrid(*tensors, indexing) | 由一维坐标向量构造多维坐标网格,建议显式传 indexing='ij' 或 'xy'。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lcm(input, other, out) | 整型张量逐元素最小公倍数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.logcumsumexp(input, dim, out) | 沿维度计算数值稳定的前缀 log-sum-exp。 | 2.10 命名空间已核对(未逐项调用) |
| torch.renorm(input, p, dim, maxnorm, out) | 将沿 dim 切片范数超过 maxnorm 的子张量缩放回上限。 | 2.10 命名空间已核对(未逐项调用) |
| torch.roll(input, shifts, dims) | 沿指定轴循环平移张量元素。 | 2.10 命名空间已核对(未逐项调用) |
| torch.searchsorted(sorted_sequence, values, side, sorter) | 在有序序列上二分查找插入位置下标。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tensordot(a, b, dims) | 沿指定轴对执行广义张量缩并。 | 2.10 命名空间已核对(未逐项调用) |
| torch.trace(input, out) | 计算二维矩阵主对角线元素之和(迹)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tril(input, diagonal, out) | 保留矩阵下三角部分,其余置零。 | 2.10 命名空间已核对(未逐项调用) |
| torch.tril_indices(row, column, offset, dtype, device, layout) | 生成 row×column 矩阵下三角部分的坐标索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.triu(input, diagonal, out) | 保留矩阵上三角部分,其余置零。 | 2.10 命名空间已核对(未逐项调用) |
| torch.triu_indices(row, column, offset, dtype, device, layout) | 生成 row×column 矩阵上三角部分的坐标索引。 | 2.10 命名空间已核对(未逐项调用) |
| torch.unflatten(input, dim, sizes) | 将单个维度按 sizes 展开为多维。 | 2.10 命名空间已核对(未逐项调用) |
| torch.vander(x, N, increasing, out) | 由一维向量构造 Vandermonde 幂次矩阵。 | 2.10 已存在(本例已实测) |
线性代数(含 torch.linalg 迁移说明)
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.addbmm(input, batch1, batch2, beta, alpha, out) | 计算 beta*input + alpha*sum_i(batch1[i] @ batch2[i])。 | 2.10 已存在(本例已实测) |
| torch.addmm(input, mat1, mat2, beta, alpha, out) | 计算 beta*input + alpha*(mat1 @ mat2)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.addmv(input, mat, vec, beta, alpha, out) | 计算 beta*input + alpha*(mat @ vec)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.addr(input, vec1, vec2, beta, alpha, out) | 计算 beta*input + alpha*(vec1 ⊗ vec2)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.baddbmm(input, batch1, batch2, beta, alpha, out) | 逐批执行 beta*input[i] + alpha*(batch1[i] @ batch2[i])。 | 2.10 命名空间已核对(未逐项调用) |
| torch.bmm(input, mat2, out) | 三维批量矩阵乘法 [B, n, m] @ [B, m, p] -> [B, n, p]。 | 2.10 命名空间已核对(未逐项调用) |
| torch.chain_matmul(*matrices) | 多矩阵连乘(旧接口,2.x 推荐 torch.linalg.multi_dot)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.cholesky(input, upper, out) | 对称正定矩阵 Cholesky 分解(旧接口,推荐 torch.linalg.cholesky)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.cholesky_inverse(input, upper, out) | 由 Cholesky 因子求对称正定矩阵逆。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cholesky_solve(input, input2, upper, out) | 利用 Cholesky 因子求解线性方程组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.dot(input, other, out) | 计算两个等长一维向量的内积标量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.geqrf(input, out) | 调用 LAPACK geqrf 计算紧致 QR 分解表示。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ger(input, other, out) | 向量外积(torch.outer 的旧别名)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.inner(input, other, out) | 对两张量最后一维做内积缩并。 | 2.10 命名空间已核对(未逐项调用) |
| torch.inverse(input, out) | 方阵求逆(旧接口,推荐 torch.linalg.inv)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.det(input, out) | 方阵行列式(旧接口,推荐 torch.linalg.det)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.logdet(input, out) | 正行列式方阵的自然对数行列式。 | 2.10 命名空间已核对(未逐项调用) |
| torch.slogdet(input, out) | 返回行列式符号与绝对值对数(推荐 torch.linalg.slogdet)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lu(input, pivot, get_infos, out) | LU 分解(旧接口,推荐 torch.linalg.lu_factor)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.lu_solve(input, LU_data, LU_pivots, out) | 基于 LU 因子求解线性方程组。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lu_unpack(LU_data, LU_pivots, unpack_data, unpack_pivots) | 将紧致 LU 结果解包为 P、L、U 矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.matmul(input, other, out) | 通用矩阵乘法,支持 1D 点积、2D 乘及高维广播批量乘。 | 2.10 已存在(本例已实测) |
| torch.matrix_power(input, n, out) | 方阵整数次幂(旧接口,推荐 torch.linalg.matrix_power)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.matrix_exp(input, out) | 计算方阵矩阵指数(推荐 torch.linalg.matrix_exp)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mm(input, mat2, out) | 严格二维矩阵乘法,不做广播。 | 2.10 命名空间已核对(未逐项调用) |
| torch.mv(input, vec, out) | 严格二维矩阵乘一维向量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.orgqr(input, q, out) | 由 geqrf 输出重构正交矩阵 Q(推荐 torch.linalg.householder_product)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.ormqr(input, mat, vec, left, transpose, out) | 直接将 Householder 反射矩阵乘至目标矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.outer(input, other, out) | 计算两个一维向量的外积二维矩阵。 | 2.10 命名空间已核对(未逐项调用) |
| torch.pinverse(input, rcond, out) | Moore-Penrose 伪逆(旧接口,推荐 torch.linalg.pinv)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.qr(input, out) | QR 分解(旧接口,推荐 torch.linalg.qr)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.svd(input, some, compute_uv, out) | 奇异值分解(旧接口,推荐 torch.linalg.svd)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.svd_lowrank(input, q, niter, M) | 对大矩阵执行随机化低秩 SVD 近似。 | 2.10 命名空间已核对(未逐项调用) |
| torch.pca_lowrank(input, q, center, niter) | 基于低秩 SVD 的主成分分析近似。 | 2.10 命名空间已核对(未逐项调用) |
| torch.lobpcg(input, K, B, X, M, P, max_iter, tol, debug, ortho_iparams, fpfloor) | 对称正定矩阵前 K 特征对的 LOBPCG 迭代求解器。 | 2.10 命名空间已核对(未逐项调用) |
| torch.trapz(y, x, dim, out) | 梯形数值积分(已弃用,请改用 torch.trapezoid)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.trapezoid(y, x, dim, out) | 沿指定维度按梯形法则计算数值积分。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cumulative_trapezoid(y, x, dim, out) | 沿指定维度计算累积梯形数值积分。 | 2.10 命名空间已核对(未逐项调用) |
| torch.triangular_solve(input, A, upper, transpose, unitriangular, out) | 三角方程组求解(旧接口,推荐 torch.linalg.solve_triangular)。 | 2.10 仍保留(已弃用/旧别名) |
| torch.vdot(input, other, out) | 计算两个一维向量点积,复数时先对首个参数取共轭。 | 2.10 已存在(本例已实测) |
设备管理
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.cuda.is_available() | 检测当前 PyTorch 构建与驱动是否具备可用 CUDA GPU(CPU 构建恒 False)。 | 2.10 已存在(本例已实测) |
| torch.cuda.device_count() | 返回可见 CUDA GPU 数量(无 GPU 或 CPU 构建返回 0)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cuda.current_device() | 返回当前选中的 CUDA 设备索引(需先确认 CUDA 可用)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.cuda.device(name) | 【纠偏】切换当前 CUDA 设备的上下文管理器(创建通用设备对象请用 torch.device)。 | 2.10 已存在(本例已实测) |
| torch.cuda.device_context(device) | 【2.10 纠偏】PyTorch 2.10 中不存在 torch.cuda.device_context;上下文切换请直接使用 torch.cuda.device(device)。 | 2.10 顶层不存在(已实测缺失并给出替代) |
| torch.device(device) | 构造通用设备描述符(如 torch.device('cpu') 或 torch.device('cuda:0'))。 | 2.10 命名空间已核对(未逐项调用) |
| torch.Tensor.to(device) | 返回移动到目标设备或转换 dtype 后的张量。 | 2.10 命名空间已核对(未逐项调用) |
| torch.get_device_module(device_type) | 按设备类型名称返回对应后端模块(如 torch.cuda / torch.mps)。 | 2.10 已存在(本例已实测) |
并行计算(CPU 线程)
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.get_num_threads() | 获取当前进程 CPU 算子内(intra-op)并行线程数。 | 2.10 已存在(本例已实测) |
| torch.set_num_threads(int) | 设置 CPU 算子内并行线程数,常用于控制确定性与资源占用。 | 2.10 已存在(本例已实测) |
| torch.get_num_interop_threads() | 获取算子间(inter-op)线程池大小。 | 2.10 命名空间已核对(未逐项调用) |
| torch.set_num_interop_threads(int) | 设置算子间并行线程数(须在并行工作启动前调用一次)。 | 2.10 已存在(本例已实测) |
工具与确定性配置函数
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.compiled_with_cxx11_abi() | 返回当前 PyTorch C++ 扩展是否以 C++11 ABI 编译。 | 2.10 已存在(本例已实测) |
| torch.result_type(tensor, other) | 按类型提升规则推算二元运算的结果 dtype。 | 2.10 命名空间已核对(未逐项调用) |
| torch.can_cast(from_dtype, to_dtype) | 判断某 dtype 是否允许安全/显式转换为另一 dtype。 | 2.10 命名空间已核对(未逐项调用) |
| torch.promote_types(type1, type2) | 返回同时容纳两种 dtype 的最小公共 dtype。 | 2.10 命名空间已核对(未逐项调用) |
| torch.use_deterministic_algorithms(mode, warn_only) | 要求算子优先使用确定性实现,缺失时报错或仅告警。 | 2.10 命名空间已核对(未逐项调用) |
| torch.are_deterministic_algorithms_enabled() | 查询是否已开启强制确定性算法模式。 | 2.10 命名空间已核对(未逐项调用) |
| torch.is_deterministic_algorithms_warn_only_enabled() | 查询确定性算法违规是否设为仅告警。 | 2.10 命名空间已核对(未逐项调用) |
| torch.set_deterministic_debug_mode(debug_mode) | 按 0/1/2 或字符串级别设置确定性调试行为。 | 2.10 命名空间已核对(未逐项调用) |
| torch.get_deterministic_debug_mode() | 返回当前确定性调试级别整数。 | 2.10 命名空间已核对(未逐项调用) |
| torch.set_float32_matmul_precision(precision) | 在支持的硬件上调节 float32 矩阵乘精度策略(highest/high/medium)。 | 2.10 命名空间已核对(未逐项调用) |
| torch.get_float32_matmul_precision() | 获取当前 float32 矩阵乘精度策略。 | 2.10 命名空间已核对(未逐项调用) |
| torch.set_warn_always(enabled) | 控制同一警告是否每次重复输出而非仅首报一次。 | 2.10 命名空间已核对(未逐项调用) |
| torch.is_warn_always_enabled() | 查询是否启用始终重复警告。 | 2.10 命名空间已核对(未逐项调用) |
| torch.vmap(fn, in_dims, out_dims, randomness, chunk_size) | 将单样本纯函数沿指定批次维自动向量化执行。 | 2.10 命名空间已核对(未逐项调用) |
| torch._assert(condition, message) | 内部断言辅助函数,常规业务逻辑优先使用 Python assert。 | 2.10 命名空间已核对(未逐项调用) |
| torch.typename(t) | 返回张量或对象的完整类型名称字符串(如 torch.FloatTensor)。 | 2.10 已存在(本例已实测) |
编译优化
| API 签名 | 功能与版本要点 | PyTorch 2.10 核对 |
|---|---|---|
| torch.compile(model, backend, options, dynamic) | 使用 TorchDynamo/Inductor 等后端对模型或函数做即时编译优化(Windows 默认 C++ 编译器与后端支持需按实际环境单独核对)。 | 2.10 已存在(本例已实测) |
运行 torch 2.10 核心 API 与纠偏验证实验
"""Verify torch 2.10.0+cpu API presence, 4 source corrections, deprecations and core tensor operations."""
import json
from pathlib import Path
import platform
from tempfile import TemporaryDirectory
import warnings
import numpy as np
import torch
ABSENT_SOURCE_APIS = [
"torch.expand",
"torch.expand_as",
"torch.linalg.matrix_transpose",
"torch.cuda.device_context",
]
SAMPLE_PRESENT_APIS = [
"torch.is_tensor", "torch.is_storage", "torch.is_complex", "torch.is_conj",
"torch.is_floating_point", "torch.is_nonzero", "torch.set_default_dtype",
"torch.get_default_dtype", "torch.set_default_device", "torch.get_default_device",
"torch.set_default_tensor_type", "torch.numel", "torch.set_printoptions",
"torch.tensor", "torch.as_tensor", "torch.asarray", "torch.from_numpy",
"torch.zeros", "torch.ones", "torch.arange", "torch.range", "torch.linspace",
"torch.eye", "torch.full", "torch.heaviside", "torch.cat", "torch.stack",
"torch.chunk", "torch.split", "torch.masked_select", "torch.gather",
"torch.unravel_index", "torch.transpose", "torch.manual_seed",
"torch.rand", "torch.randn", "torch.randint", "torch.poisson",
"torch.save", "torch.load", "torch.no_grad", "torch.enable_grad",
"torch.set_grad_enabled", "torch.inference_mode", "torch.is_grad_enabled",
"torch.is_inference_mode_enabled", "torch.abs", "torch.add", "torch.xlogy",
"torch.argmax", "torch.hash_tensor", "torch.allclose", "torch.msort",
"torch.stft", "torch.istft", "torch.kaiser_window", "torch.atleast_1d",
"torch.vander", "torch.addbmm", "torch.matmul", "torch.vdot",
"torch.cuda.is_available", "torch.cuda.device", "torch.get_device_module",
"torch.get_num_threads", "torch.set_num_interop_threads",
"torch.compiled_with_cxx11_abi", "torch.typename", "torch.compile",
]
def resolve(dotted):
obj = torch
for part in dotted.split(".")[1:]:
if not hasattr(obj, part):
return False
obj = getattr(obj, part)
return True
def record(cases, name, inputs, conditions, action, expected, actual, **measurements):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, inputs=inputs, prerequisites=conditions, action=action,
expected=expected, actual=actual, passed=True, measurements=measurements))
def main():
torch.set_num_threads(1)
cases = []
t = torch.tensor([1.0, 2.0])
c = torch.tensor([1 + 2j])
prev_dtype = torch.get_default_dtype()
torch.set_default_dtype(torch.float64)
changed_dtype = torch.get_default_dtype()
torch.set_default_dtype(prev_dtype)
with warnings.catch_warnings(record=True) as w_legacy:
warnings.simplefilter("always")
torch.set_default_tensor_type(torch.FloatTensor)
record(cases, "tensor_type_and_defaults", {"tensor": [1.0, 2.0]},
"PyTorch 2.10.0+cpu type predicates and default dtype management",
"Check type predicates, default dtype round-trip and deprecation warning",
[True, True, True, True, 2, "torch.float64", "torch.float32", "cpu", True],
[torch.is_tensor(t), torch.is_floating_point(t), torch.is_complex(c),
torch.is_nonzero(torch.tensor(3)), torch.numel(t),
str(changed_dtype), str(torch.get_default_dtype()), str(torch.get_default_device()),
any("deprecated" in str(item.message).lower() for item in w_legacy)])
arr = np.array([2.0, 4.0], dtype=np.float32)
from_np = torch.from_numpy(arr)
hv = torch.heaviside(torch.tensor([-1.0, 0.0, 2.0]), torch.tensor([0.5]))
with warnings.catch_warnings(record=True) as w_range:
warnings.simplefilter("always")
r_old = torch.range(0, 2)
record(cases, "tensor_creation_and_range", {"numpy_arr": [2.0, 4.0]},
"Tensor constructors plus deprecated torch.range warning check",
"Verify from_numpy, arange, linspace, eye, heaviside and torch.range warning",
[[2.0, 4.0], [0, 1, 2], [0.0, 0.5, 1.0], [2, 2], [0.0, 0.5, 1.0], [0.0, 1.0, 2.0], True],
[from_np.tolist(), torch.arange(0, 3).tolist(), torch.linspace(0.0, 1.0, 3).tolist(),
list(torch.eye(2).shape), hv.tolist(), r_old.tolist(),
any("deprecated" in str(item.message).lower() for item in w_range)])
base = torch.tensor([[1], [2]])
expanded = base.expand(2, 3)
expanded_as = base.expand_as(torch.zeros(2, 3))
mat = torch.arange(6).reshape(2, 3)
mt = torch.transpose(mat, -2, -1)
cat_v = torch.cat([torch.tensor([1, 2]), torch.tensor([3])])
unr = [x.tolist() for x in torch.unravel_index(torch.tensor([0, 5]), (2, 3))]
record(cases, "indexing_slicing_and_missing_fixes", {"base_shape": [2, 1], "mat_shape": [2, 3]},
"Verify Tensor.expand/expand_as and Tensor.mT / torch.transpose instead of absent names",
"Confirm absent top-level attributes and validate real replacements plus cat/unravel_index",
[False, False, False, False, [2, 3], [2, 3], [3, 2], True, [1, 2, 3], [[0, 1], [0, 2]]],
[hasattr(torch, "expand"), hasattr(torch, "expand_as"),
hasattr(torch.linalg, "matrix_transpose"), hasattr(torch, "matrix_transpose"),
list(expanded.shape), list(expanded_as.shape), list(mt.shape),
torch.equal(mt, mat.mT), cat_v.tolist(), unr])
torch.manual_seed(123)
r1 = torch.rand(3)
torch.manual_seed(123)
r2 = torch.rand(3)
gen = torch.Generator().manual_seed(7)
pois = torch.poisson(torch.tensor([2.0, 5.0]), generator=gen)
with TemporaryDirectory(prefix="mbsky-torch-ser-") as tmp:
pt_file = Path(tmp) / "tensor.pt"
payload = {"w": torch.tensor([1.5, -2.5])}
torch.save(payload, pt_file)
loaded = torch.load(pt_file, map_location="cpu", weights_only=True)
ser_equal = torch.equal(loaded["w"], payload["w"])
record(cases, "random_and_serialization", {"seed": 123},
"Seeded CPU RNG and weights_only=True serialization in temp directory",
"Check deterministic manual_seed, poisson output and save/load round-trip",
[True, [2], True],
[torch.equal(r1, r2), list(pois.shape), ser_equal])
with torch.no_grad():
ng_enabled = torch.is_grad_enabled()
with torch.inference_mode():
im_enabled = torch.is_inference_mode_enabled()
xg = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
xg.sum().backward()
record(cases, "grad_control_and_autograd", {"x": [1.0, 2.0, 3.0]},
"Grad context managers and scalar sum backward",
"Verify no_grad, inference_mode and gradient values",
[False, True, True, [1.0, 1.0, 1.0]],
[ng_enabled, im_enabled, torch.is_grad_enabled(), xg.grad.tolist()])
vals = torch.tensor([-2.0, 0.0, 3.0])
xlogy_v = torch.xlogy(torch.tensor([0.0, 2.0]), torch.tensor([0.0, 1.0]))
sorted_v = torch.msort(torch.tensor([3, 1, 2]))
h_val = torch.hash_tensor(torch.tensor([1, 2, 3]))
record(cases, "math_pointwise_reduction_compare", {"vals": [-2.0, 0.0, 3.0]},
"Pointwise, reduction and comparison functions on CPU",
"Check abs, argmax, xlogy(0,0)==0, allclose, msort and hash_tensor",
[[2.0, 0.0, 3.0], 2, [0.0, 0.0], True, [1, 2, 3], True],
[torch.abs(vals).tolist(), int(torch.argmax(vals)), xlogy_v.tolist(),
torch.allclose(torch.tensor([1.0]), torch.tensor([1.0 + 1e-7])),
sorted_v.tolist(), h_val.ndim == 0])
sig = torch.sin(torch.linspace(0, 6.283185, 32))
spec = torch.stft(sig, n_fft=8, hop_length=4, window=torch.hann_window(8), return_complex=True)
rec = torch.istft(spec, n_fft=8, hop_length=4, window=torch.hann_window(8), length=32)
vand = torch.vander(torch.tensor([1, 2, 3]), N=3, increasing=True)
ab = torch.addbmm(torch.zeros(2, 2), torch.ones(3, 2, 2), torch.ones(3, 2, 2))
vd = torch.vdot(torch.tensor([1.0, 2.0]), torch.tensor([3.0, 4.0]))
record(cases, "spectral_other_and_linalg", {"signal_len": 32, "n_fft": 8},
"STFT/ISTFT round-trip, Vandermonde matrix, addbmm and vdot",
"Verify spectral reconstruction, vander, addbmm and vdot values",
[True, [[1, 1, 1], [1, 2, 4], [1, 3, 9]], [[6.0, 6.0], [6.0, 6.0]], 11.0],
[torch.allclose(sig, rec, atol=1e-5), vand.tolist(), ab.tolist(), float(vd)])
record(cases, "device_parallel_utils_compile", {"expected_cuda": False},
"Windows CPU build device/thread/utility inspection",
"Verify cuda.is_available, absent device_context vs real cuda.device, threads and compile",
[False, False, True, 1, True, "torch.FloatTensor"],
[torch.cuda.is_available(), hasattr(torch.cuda, "device_context"), hasattr(torch.cuda, "device"),
torch.get_num_threads(), callable(torch.compile), torch.typename(torch.tensor([1.0]))])
present_ok = [resolve(name) for name in SAMPLE_PRESENT_APIS]
absent_ok = [resolve(name) for name in ABSENT_SOURCE_APIS]
record(cases, "namespace_api_audit", {"checked_present": len(SAMPLE_PRESENT_APIS), "checked_absent": len(ABSENT_SOURCE_APIS)},
"PyTorch 2.10.0+cpu namespace inspection across all 16 reference groups",
"Verify representative APIs resolve and 4 misnamed source entries are absent",
[True, [False, False, False, False]],
[all(present_ok), absent_ok])
x = torch.tensor([1, 2, 3])
z = torch.add(x, 1)
selected = torch.masked_select(x, x > 1)
c_mat = torch.matmul(torch.randn(3, 4), torch.randn(4, 5))
xg2 = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
xg2.sum().backward()
record(cases, "reference_combined_example", {"x": [1, 2, 3]},
"Combined tensor creation, math, masked_select, matmul and autograd flow",
"Reproduce chapter end example outputs on CPU",
[[2, 3, 4], [2, 3], [3, 5], [1.0, 1.0, 1.0]],
[z.tolist(), selected.tolist(), list(c_mat.shape), xg2.grad.tolist()])
print(json.dumps(dict(
version=platform.python_version(), system=platform.system(), torch=torch.__version__,
numpy=np.__version__, cases=cases,
), allow_nan=False))
if __name__ == "__main__":
main()
- 在 CPU 上实测 10 组核心用例,验证 4 处不存在的顶层名称、2 处弃用警告、weights_only=True 序列化以及综合张量求导输出。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
当前源码 SHA256:61e0c333dddfd0b1fdad272555429c747583df4e4dacaa67053f6e46a40de8ea
本地运行
解压后按 README 选择对应构建并运行脚本。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
ZIP SHA256:1a92ad1f0b0ca80853dd0985e879a49553a2d9c2a2873cf0d5206e9d4f8cca1a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 PyTorch 2.10 中直接调用 torch.expand(x, (2, 3)) 或 torch.linalg.matrix_transpose(x) 会触发 AttributeError?应如何改写?
展开参考解答
这两项并非顶层函数;应分别改写为张量方法 x.expand(2, 3) 以及 x.mT(或 torch.transpose(x, -2, -1))。