"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-torch-ref-lab/verify-torch-api-reference.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
verify-torch-api-reference.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a438.zip