"""Verify tensor constructors, operations, views and NumPy ownership on CPU."""
import json
import platform
import numpy as np
import torch
def record(cases, name, data, condition, action, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, inputs=data, prerequisites=condition, action=action,
expected=expected, actual=actual, passed=True))
def rejects(operation, exception):
try:
operation()
except exception:
return True
return False
def observe():
cases = []
device = torch.device("cpu")
raw = [4, -1, 9]
from_list = torch.tensor(raw, device=device, dtype=torch.int64)
raw[0] = 22
arr = np.array([3, 8], dtype=np.int64)
copy = torch.tensor(arr)
arr[0] = 5
zero = torch.zeros((2, 3), dtype=torch.int32)
ones = torch.ones((2, 3), dtype=torch.float32)
scratch = torch.empty((2, 3), dtype=torch.float32)
scratch.fill_(2.5)
record(cases, "creation_initialized", {"list":[4,-1,9],"array":[3,8],"shape":[2,3]},
"Read empty only after writing every element",
"Compare list and array copy constructors with zeros, ones and initialized scratch space",
[[4,-1,9],[3,8],0,6.0,[2,3],15.0],
[from_list.tolist(),copy.tolist(),zero.sum().item(),ones.sum().item(),list(scratch.shape),scratch.sum().item()])
rng = torch.Generator(device="cpu").manual_seed(147)
uniform = torch.rand((2, 3), generator=rng)
normal = torch.randn((2, 3), generator=rng)
replay = torch.Generator(device="cpu").manual_seed(147)
torch.rand((2, 3), generator=replay)
again = torch.randn((2, 3), generator=replay)
record(cases,"random_factories",{"seed":147,"size":[2,3]},"Same installed CPU generator",
"Check the uniform interval and reproduce the second draw from the normal factory",
[[2,3],True,[2,3],True],
[list(uniform.shape),bool(((uniform>=0)&(uniform<1)).all()),list(normal.shape),bool(torch.equal(normal,again))])
record(cases,"ranges_and_eye",[1,8,3],"Integral arange; explicit floating spacing for linspace",
"Compare excluded end, included linspace ends, and square identity",
[[1,4,7],[0.0,0.25,0.5,0.75,1.0],[[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]]],
[torch.arange(1,8,3).tolist(),torch.linspace(0,1,5).tolist(),torch.eye(3).tolist()])
scalar = torch.tensor(-2)
vector = torch.arange(10)
plane = torch.arange(20).reshape(4,5)
cube = torch.stack((plane,plane+20,plane+40))
fourth = torch.stack((cube,cube+60))
fifth = torch.stack((fourth,fourth+120))
record(cases,"ranks_zero_to_five","An arange matrix and nested stacks", "Stack adds one axis per operation",
"Inspect size and rank for the scalar, vector, matrix and three stacks",
[[],[10],[4,5],[3,4,5],[2,3,4,5],[2,2,3,4,5],239],
[*[list(t.shape) for t in (scalar,vector,plane,cube,fourth,fifth)],fifth[-1,-1,-1,-1,-1].item()])
a = torch.tensor([[2.,5.,7.],[3.,11.,13.]],requires_grad=True)
b = torch.tensor([[2.,1.,4.],[1.,3.,2.]])
at = a.T
record(cases,"tensor_metadata",[[2,5,7],[3,11,13]],"Contiguous float32 CPU input with grad enabled",
"Inspect properties, transposed layout and scalar extraction boundary",
[[2,3],[2,3],"torch.float32","cpu",2,True,6,False,True,[[2.,3.],[5.,11.],[7.,13.]],False,11.0,True],
[list(a.shape),list(a.size()),str(a.dtype),a.device.type,a.dim(),a.requires_grad,
a.numel(),a.is_cuda,a.is_contiguous(),at.tolist(),at.is_contiguous(),a[1,1].item(),rejects(a.item,RuntimeError)])
row = torch.tensor([1.,2.,4.])
record(cases,"arithmetic_and_index",row.tolist(),"Last-axis broadcast, no zero divisors",
"Run four operators and read row, scalar, column, flatten and boolean filter",
[[[3.,7.,11.],[4.,13.,17.]],[[1.,3.,3.],[2.,9.,9.]],[[2.,10.,28.],[3.,22.,52.]],
[[2.,2.5,1.75],[3.,5.5,3.25]],[2.,5.,7.],2.,[5.,11.],[2.,5.,7.,3.,11.,13.],[7.,11.,13.]],
[(a+row).tolist(),(a-row).tolist(),(a*row).tolist(),(a/row).tolist(),
a[0].tolist(),a[0,0].item(),a[:,1].tolist(),a.flatten().tolist(),a[a>5].tolist()])
record(cases,"matrix_and_vector_products",b.tolist(),"Match matrix inner dimensions and one-dimensional dot inputs",
"Compare two shapes and check that dot rejects matrices",
[[[37.,31.],[69.,62.]],37.0,True],
[torch.matmul(a,b.T).tolist(),torch.dot(a[0],b[0]).item(),rejects(lambda:torch.dot(a,b),RuntimeError)])
extrema = torch.tensor([[4.,4.,1.],[-3.,8.,1.]])
logits = torch.tensor([[1000.,1000.,1000.],[-1000.,-1001.,-1001.]])
distribution = torch.softmax(logits,dim=1)
record(cases,"reduce_select_and_softmax",extrema.tolist(),"Float32 data; reduce along declared dimension",
"Check global and axis reductions, argmax tie order and stable class distribution",
[15.,[3.,2.],8.,-3.,[0,1],[0,0],True,True,True],
[extrema.sum().item(),extrema.mean(dim=1).tolist(),
extrema.max().item(),extrema.min().item(),extrema.argmax(dim=1).tolist(),distribution.argmax(dim=1).tolist(),
bool(torch.allclose(distribution.sum(dim=1),torch.ones(2))),bool(torch.isfinite(distribution).all()),
rejects(lambda:torch.arange(3).mean(),RuntimeError)])
direct = a.view(3,2)
reshaped = at.reshape(-1)
expanded = a.unsqueeze(0)
combined = torch.cat((a,b),dim=1)
record(cases,"shape_view_reshape_concat",list(a.shape),"Contiguous input and a deliberately incompatible transposed view",
"Observe sharing, reshape order, failed view, squeeze/unsqueeze and concatenation",
[[[2.,5.],[7.,3.],[11.,13.]],True,[2.,3.,5.,11.,7.,13.],True,True,True,[1,2,3],[2,3],[2,3],
[[2.,5.,7.,2.,1.,4.],[3.,11.,13.,1.,3.,2.]]],
[direct.tolist(),direct.data_ptr()==a.data_ptr(),reshaped.tolist(),
reshaped.data_ptr()!=a.data_ptr(),rejects(lambda:at.view(-1),RuntimeError),bool(torch.equal(a.t(),at)),
list(expanded.shape),list(expanded.squeeze(0).shape),list(a.squeeze(0).shape),combined.tolist()])
parent = np.array([4.,6.,8.],dtype=np.float32)
aliases = torch.from_numpy(parent)
parent[1] = 22
aliases[2] = 29
back = aliases.numpy()
back[0] = 17
independent = aliases.clone().numpy()
aliases[0] = 19
allowed = a.detach().numpy()
record(cases,"numpy_in_both_directions",{"array":[4,6,8],"changes":[22,29,17,19]},
"Writable compatible NumPy storage and CPU strided tensor",
"Observe writes in both directions, independently copy via clone and reject default gradient export",
[[19.,22.,29.],[19.,22.,29.],[17.,22.,29.],True,[2,3],True],
[parent.tolist(),back.tolist(),independent.tolist(),rejects(a.numpy,RuntimeError),
list(allowed.shape),rejects(lambda:torch.from_numpy(parent[::-1]),ValueError)])
selected = torch.device("cuda" if torch.cuda.is_available() else "cpu")
value = a.to(selected)
record(cases,"device_check",str(selected),"This run uses the CPU wheel", "Check CUDA availability and the actual output device",
[False,"cpu",True],[torch.cuda.is_available(),value.device.type,value is a])
return cases
if __name__ == "__main__":
print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),
numpy=np.__version__,cases=observe())))
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-tensor-lab/check-tensor-layout.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
check-tensor-layout.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a434.zip