"""Run basic neural-network component and learning checks with local data."""
import json
import math
import platform
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, TensorDataset
def record(cases, name, inputs, condition, action, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name, inputs=inputs, prerequisites=condition, action=action,
expected=expected, actual=actual, passed=True))
class Mixer(nn.Module):
def __init__(self):
super().__init__()
self.scale = nn.Parameter(torch.tensor(2.0))
layer = nn.Linear(2, 1, bias=False)
with torch.no_grad():
layer.weight.copy_(torch.tensor([[2.0, -1.0]]))
self.layers = nn.ModuleList([layer, nn.ReLU()])
def forward(self, inputs):
first, activation = self.layers
return activation(self.scale*first(inputs))
def container_examples(cases):
inputs = torch.tensor([[3.0,5.0],[0.0,1.0]])
net = Mixer()
result = net(inputs)
result.sum().backward()
sequential = nn.Sequential(nn.Identity(),nn.ReLU())
record(cases,"containers_and_parameter",inputs.tolist(),"Registered ModuleList and trainable scalar",
"Call a module, inspect registrations, observe gradients and compare sequential order",
[[[2.0],[0.0]],["scale","layers.0.weight"],1.0,[0.0,3.0]],
[result.tolist(),sorted(net.state_dict(),key=lambda n:0 if n=="scale" else 1),net.scale.grad.item(),
sequential(torch.tensor([-4.,3.])).tolist()])
bilinear = nn.Bilinear(2,2,1,bias=False)
with torch.no_grad():
bilinear.weight.copy_(torch.tensor([[[1.,2.],[3.,4.]]]))
out = bilinear(torch.tensor([[1.,2.]]),torch.tensor([[3.,5.]]))
record(cases,"linear_and_bilinear",[[1.,2.],[3.,5.]],"Bilinear uses a weight matrix for each output",
"Compute the single bilinear score and check Linear's registered weight shape",
[71.0,[1,2]],[out.item(),list(net.layers[0].weight.shape)])
def activations(cases):
x = torch.tensor([-1.,0.,2.])
gelu = F.gelu(x)
sigmoid = torch.sigmoid(x)
silu = F.silu(x)
softmax = nn.Softmax(dim=1)(x[None])
logsoft = nn.LogSoftmax(dim=1)(x[None])
observed = [
F.relu(x).tolist(),bool(torch.equal(F.relu(x),nn.ReLU()(x))),
bool(torch.allclose(gelu,x*(1+torch.erf(x/math.sqrt(2)))/2)),
bool(torch.allclose(gelu,nn.GELU()(x))),
bool(torch.allclose(silu,x*sigmoid) and torch.allclose(silu,nn.SiLU()(x))),
torch.tanh(torch.tensor(0.)).item(),float(sigmoid[1]),
bool(torch.equal(torch.tanh(x),nn.Tanh()(x))),bool(torch.equal(sigmoid,nn.Sigmoid()(x))),
bool(torch.equal(softmax,F.softmax(x[None],dim=1))),
bool(torch.allclose(logsoft.exp(),softmax)),float(nn.LeakyReLU(0.125)(x)[0]),
bool(torch.isclose(nn.ELU()(x)[0],torch.tensor(math.exp(-1)-1))),
]
record(cases,"activation_functions",x.tolist(),"Floating input; softmax class axis is 1",
"Check module and function outputs as well as the exact negative branch where convenient",
[[0.0,0.0,2.0],True,True,True,True,0.0,0.5,True,True,True,True,-0.125,True],observed)
def losses(cases):
prediction = torch.tensor([-2.,0.,1.])
zeros = torch.zeros_like(prediction)
logits = torch.tensor([[0.,1.],[3.,-1.]])
cls = torch.tensor([1,0])
ce = nn.CrossEntropyLoss()(logits,cls)
nll = nn.NLLLoss()(logits.log_softmax(dim=1),cls)
bce = nn.BCEWithLogitsLoss()
moderate = bce(torch.zeros(2),torch.tensor([0.,1.]))
high = bce(torch.tensor([-1000.,1000.]),torch.tensor([0.,1.]))
observed = [
bool(torch.allclose(nn.MSELoss()(prediction,zeros),torch.tensor(5/3))),
nn.L1Loss()(prediction,zeros).item(),
bool(torch.allclose(nn.HuberLoss()(prediction,zeros),torch.tensor(2/3))),
bool(torch.allclose(ce,nll) and torch.allclose(F.cross_entropy(logits,cls),ce)),
bool(torch.isclose(moderate,torch.tensor(math.log(2)))),
float(high),bool(torch.equal(F.mse_loss(prediction,zeros),nn.MSELoss()(prediction,zeros))),
(logits.argmax(dim=1)==torch.tensor([1,1])).float().mean().item(),
]
record(cases,"losses_and_raw_scores",{"errors":prediction.tolist(),"labels":cls.tolist()},
"Class labels use integer indices; BCE accepts matching floats",
"Compute six actual loss module variants and compare independent expected values",
[True,1.0,True,True,True,0.0,True,0.5],observed)
def optimization(cases):
results=[]
for algorithm in (torch.optim.SGD,torch.optim.Adam,torch.optim.RMSprop):
weight=nn.Parameter(torch.tensor(2.0))
opt=algorithm([weight],lr=0.1)
opt.zero_grad(set_to_none=True)
weight.square().backward()
assert weight.grad.item()==4.0
opt.step()
results.append(round(weight.item(),5))
record(cases,"optimizer_updates",2.0,"Scalar parameter, loss w², first step, lr=0.1",
"Apply the default SGD, Adam and RMSprop update to separate equal initial parameters",
[1.6,1.9,1.0],results)
inputs=torch.tensor([[1.0],[2.0]])
train=DataLoader(TensorDataset(inputs,2*inputs),batch_size=2)
test=torch.tensor([[3.0],[4.0]])
model=nn.Linear(1,1,bias=False)
nn.init.zeros_(model.weight)
opt=torch.optim.SGD(model.parameters(),lr=0.1)
history=[]
model.train()
for _ in range(6):
for x,y in train:
opt.zero_grad(set_to_none=True)
loss=F.mse_loss(model(x),y)
loss.backward()
opt.step()
history.append(loss.item())
model.eval()
with torch.no_grad():
value=model(test)
score=F.mse_loss(value,2*test).item()
record(cases,"loader_training_and_eval",{"train":[1,2],"test":[3,4],"epochs":6},
"Deterministic DataLoader; one batch per epoch",
"Train, check loss decay and independently evaluate the final model without grad",
[6,10.0,2.5,1.96875,True,False,False],
[len(history),history[0],history[1],model.weight.item(),score<0.02,model.training,value.requires_grad])
cases[-1]["metrics"]=dict(history=history,heldout_mse=score)
def spatial(cases):
conv1 = nn.Conv1d(1,1,2,bias=False)
conv2 = nn.Conv2d(1,1,2,bias=False)
conv3 = nn.Conv3d(1,1,2,bias=False)
up = nn.ConvTranspose2d(1,1,2,stride=2,bias=False)
with torch.no_grad():
conv1.weight.copy_(torch.tensor([[[1.0,-1.0]]]))
for operation in (conv2,conv3,up):
operation.weight.fill_(1.0)
sequence = torch.arange(1.,5.).reshape(1,1,4)
plane = torch.arange(1.,10.).reshape(1,1,3,3)
volume = torch.arange(1.,9.).reshape(1,1,2,2,2)
doubled = up(torch.tensor([[[[2.,3.]]]]))
record(cases,"convolution_shapes",{"length":4,"plane":[3,3],"volume":[2,2,2]},
"Channel-first layouts; unit kernels except the first-order difference; transposed stride 2",
"Evaluate four convolution operators and verify functional Conv2d's matching kernel",
[[-1.,-1.,-1.],[[12.,16.],[24.,28.]],36.,[[2.,2.,3.,3.],[2.,2.,3.,3.]],True],
[conv1(sequence)[0,0].tolist(),conv2(plane)[0,0].tolist(),conv3(volume).item(),doubled[0,0].tolist(),
bool(torch.equal(conv2(plane),F.conv2d(plane,conv2.weight)))])
data = torch.arange(1.,17.).reshape(1,1,4,4)
max_pool = nn.MaxPool2d(2)(data)
avg_pool = nn.AvgPool2d(2)(data)
global_mean = nn.AdaptiveAvgPool2d((1,1))(data)
global_max = nn.AdaptiveMaxPool2d((1,1))(data)
scaled = F.interpolate(avg_pool,scale_factor=2,mode="nearest")
record(cases,"pooling_and_resize",[4,4],"One 4x4 channel with monotonically increasing entries",
"Compare each 2x2 reduction, fixed-size global averages and maxima, then nearest resize",
[[[6.,8.],[14.,16.]],[[3.5,5.5],[11.5,13.5]],8.5,16.0,[1,1,4,4],[3.5,3.5,5.5,5.5]],
[max_pool[0,0].tolist(),avg_pool[0,0].tolist(),global_mean.item(),global_max.item(),
list(scaled.shape),scaled[0,0,0].tolist()])
def normalization(cases):
plane = torch.arange(8.,dtype=torch.float32).reshape(1,2,2,2)
batch = nn.BatchNorm2d(2,affine=False,momentum=1.0)
normalized_batch = batch(plane)
batch.eval()
evaluated = batch(plane)
grouped = nn.GroupNorm(2,2,affine=False)(plane)
instance = nn.InstanceNorm2d(2,affine=False)(plane)
pair = torch.tensor([[1.,3.],[2.,8.]])
normalized_layer = nn.LayerNorm(2,elementwise_affine=False)(pair)
record(cases,"normalization_axes",list(plane.shape),"NCHW, two groups for two channels; separate layer example uses final axis",
"Compare training channel means, actual running mean and variance in evaluation, and alternate axes",
[True,[1.5,5.5],True,True,True],
[bool(torch.allclose(normalized_batch.mean(dim=(0,2,3)),torch.zeros(2),atol=1e-6)),
batch.running_mean.tolist(),
bool(torch.allclose(evaluated,(plane-batch.running_mean[None,:,None,None])/
(batch.running_var[None,:,None,None]+batch.eps).sqrt())),
bool(torch.allclose(grouped,instance,atol=1e-6)),
bool(torch.allclose(normalized_layer.mean(1),torch.zeros(2),atol=1e-6))])
def recurrence(cases):
network = nn.RNN(1,1,nonlinearity="relu",batch_first=True,bias=False)
gru = nn.GRU(1,1,batch_first=True)
lstm = nn.LSTM(1,1,batch_first=True)
with torch.no_grad():
for parameter in network.parameters():
parameter.fill_(1.)
for model in (gru,lstm):
for parameter in model.parameters():
parameter.zero_()
x = torch.tensor([[[1.],[2.],[3.]]])
zeros = torch.zeros((1,2,1))
prior = torch.ones((1,1,1))
simple,last = network(x)
gated,gh = gru(zeros,prior)
tracked,(lh,lc) = lstm(zeros,(prior,prior))
record(cases,"recurrent_hidden_and_cell",[1,2,3],"Single features; fixed RNN weights and zero gate weights",
"Accumulate a running sum, then compare known half-retention in GRU and LSTM states",
[[1.,3.,6.],6.,[0.5,0.25],0.25,[1,2,1],0.25,True],
[simple[0,:,0].tolist(),last.item(),gated[0,:,0].tolist(),gh.item(),
list(tracked.shape),lc.item(),math.isclose(lh.item(),0.5*math.tanh(0.25),rel_tol=1e-6)])
def attention_examples(cases):
attention = nn.MultiheadAttention(2,1,dropout=0.,bias=False,batch_first=True)
with torch.no_grad():
attention.in_proj_weight.copy_(torch.eye(2).repeat(3,1))
attention.out_proj.weight.copy_(torch.eye(2))
tokens = torch.eye(2)[None]
mask = torch.tensor([[False,True],[False,False]])
attended, weights = attention(tokens,tokens,tokens,attn_mask=mask)
expected_weights = torch.softmax(torch.tensor([[0.,1/math.sqrt(2)]]),dim=-1)
layer = nn.TransformerEncoderLayer(4,2,dim_feedforward=8,dropout=0.,batch_first=True)
encoder = nn.TransformerEncoder(layer,1,enable_nested_tensor=False)
decoder_layer = nn.TransformerDecoderLayer(4,2,dim_feedforward=8,dropout=0.,batch_first=True)
decoder = nn.TransformerDecoder(decoder_layer,1)
full = nn.Transformer(4,2,1,1,dim_feedforward=8,dropout=0.,batch_first=True)
source = torch.arange(12.,dtype=torch.float32).reshape(1,3,4)/10
target = source[:,:2]
memory = encoder(source)
decoded = decoder(target,memory)
end = full(source,target)
record(cases,"attention_masks_and_transformer",["length 3 source","length 2 target"],
"CPU, batch-first, dropout disabled; explicit identity attention to isolate mask effect",
"Validate masked attention weights and compare each container to its real layer computation",
[[1.,0.],True,True,[1,3,4],[1,2,4],True,True,True,True],
[weights[0,0].tolist(),bool(torch.allclose(weights[0,1],expected_weights[0])),
bool(torch.allclose(attended,weights@tokens)),list(memory.shape),list(end.shape),
bool(torch.allclose(memory,encoder.layers[0](source))),
bool(torch.allclose(decoded,decoder.layers[0](target,memory))),
bool(torch.allclose(end,full.decoder(target,full.encoder(source)))),
not torch.allclose(decoded,decoder(target,torch.zeros_like(memory)))])
def embeddings_and_dropout(cases):
weights = torch.tensor([[1.,2.],[3.,4.],[5.,6.]])
lookup = nn.Embedding.from_pretrained(weights)
bags = nn.EmbeddingBag.from_pretrained(weights, mode="sum")
ids = torch.tensor([0,2,1,2])
values = lookup(ids.reshape(2,2))
pooled = bags(ids,torch.tensor([0,2]))
record(cases,"embeddings_and_bag",ids.tolist(),"Three entries, two-dimensional values, two sums",
"Compare individual lookup, functional equivalence and offset-driven aggregation",
[[[1.,2.],[5.,6.]],[[6.,8.],[8.,10.]],True],
[values[0].tolist(),pooled.tolist(),bool(torch.equal(values,F.embedding(ids.reshape(2,2),weights)))])
torch.manual_seed(83)
unit = torch.ones(64)
channels = torch.ones((2,8,2,2))
mode = nn.Dropout(0.5)
channel = nn.Dropout2d(0.5)
ordinary = mode(unit)
channel_output = channel(channels)
mode.eval()
channel.eval()
record(cases,"dropout_train_eval",{"p":0.5,"shape":[2,8,2,2]},
"Sampled masks with fixed CPU seed and matching input modes",
"Check per-element values, channel-wise mask consistency, and identity in evaluation",
[[0.,2.],True,True,True,True],
[sorted(ordinary.unique().tolist()),
bool((channel_output==channel_output[:,:,0:1,0:1]).all()),
bool(torch.equal(mode(unit),unit)),bool(torch.equal(channel(channels),channels)),
bool(torch.equal(F.dropout(unit,p=0.5,training=False),unit))])
def initializer_examples(cases):
torch.manual_seed(511)
matrix = torch.empty((128,128))
def compare(operation, expected_std, bound=None):
assert operation(matrix) is matrix
within = True if bound is None else bool((matrix.abs()<=bound+1e-7).all())
return within and abs(matrix.std().item()-expected_std)<0.012
fan = matrix.shape[1]
xavier = math.sqrt(1.0/fan)
kaiming = math.sqrt(2.0/fan)
observed = [
compare(nn.init.xavier_uniform_,xavier,math.sqrt(3)*xavier),
compare(nn.init.xavier_normal_,xavier),
compare(lambda x:nn.init.kaiming_uniform_(x,nonlinearity="relu"),kaiming,math.sqrt(3)*kaiming),
compare(lambda x:nn.init.kaiming_normal_(x,nonlinearity="relu"),kaiming),
bool(nn.init.zeros_(matrix).count_nonzero().item()==0),
compare(lambda x:nn.init.normal_(x,mean=0.2,std=0.35),0.35),
abs(matrix.mean().item()-0.2)<0.012,
]
record(cases,"initializer_distributions",list(matrix.shape),"Fixed 128x128 fan shape and torch random seed",
"Apply six initializers in place and verify bounds, zero storage or observed moments",
[True]*7,observed)
def utility_examples(cases):
weight = nn.Parameter(torch.ones((2,)))
weight.grad = torch.tensor([6.,8.])
norm = nn.utils.clip_grad_norm_([weight],max_norm=5.)
normalized = nn.Linear(2,2,bias=False)
with torch.no_grad():
normalized.weight.copy_(torch.tensor([[3.,4.],[0.,2.]]))
weight_norm = nn.utils.parametrizations.weight_norm(normalized)
with torch.no_grad():
weight_norm.parametrizations.weight.original0.fill_(1.)
spectral = nn.Linear(2,2,bias=False)
with torch.no_grad():
spectral.weight.copy_(torch.diag(torch.tensor([3.,1.])))
spectral = nn.utils.parametrizations.spectral_norm(spectral,n_power_iterations=8)
spectral(torch.ones((1,2)))
batch = torch.tensor([[[1.],[2.],[0.]],[[4.],[5.],[6.]]])
packed = nn.utils.rnn.pack_padded_sequence(batch,[2,3],batch_first=True,enforce_sorted=False)
restored,lengths = nn.utils.rnn.pad_packed_sequence(packed,batch_first=True)
functional = F.linear(torch.tensor([[2.,3.]]),torch.tensor([[1.,-2.]]),torch.tensor([1.]))
record(cases,"norm_pack_and_functional_linear",{"gradient":[6,8],"lengths":[2,3]},
"CPU norm clipping, current parameterizations and unsorted padded sequences",
"Read old norm and new gradient, compare weight constraints, restore batch order and check linear output",
[10.,True,True,True,[2,3],True,[[-3.]]],
[norm.item(),bool(torch.allclose(weight.grad,torch.tensor([3.,4.]),atol=1e-6)),
bool(torch.allclose(weight_norm.weight.norm(dim=1),torch.ones(2),atol=1e-6)),
math.isclose(torch.linalg.matrix_norm(spectral.weight,ord=2).item(),1.,rel_tol=1e-5),
lengths.tolist(),bool(torch.equal(restored,batch)),functional.tolist()])
def main():
torch.set_num_threads(1)
cases=[]
container_examples(cases)
activations(cases)
losses(cases)
optimization(cases)
spatial(cases)
normalization(cases)
recurrence(cases)
attention_examples(cases)
embeddings_and_dropout(cases)
initializer_examples(cases)
utility_examples(cases)
print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),cases=cases)))
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-neural-network-lab/run-neural-network.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
run-neural-network.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a432.zip