"""Exercise CPU process groups, sharded matrix algebra and checkpoint recovery."""
from hashlib import sha256
import multiprocessing as mp
import torch
from torch import nn
from torch.nn import functional as F
from lab_tools import run_exercise
def rank_worker(rank,channel):
with channel:
torch.set_num_threads(1)
layer=nn.Linear(1,1,bias=False,dtype=torch.float64)
with torch.no_grad():
layer.weight.zero_()
x=torch.tensor([[1.+2*rank],[2.+2*rank]],dtype=torch.float64)
opt=torch.optim.SGD(layer.parameters(),lr=.01)
F.mse_loss(layer(x),3*x).backward()
channel.send([rank,x.flatten().tolist(),layer.weight.grad.item()])
if not channel.poll(15):
raise TimeoutError("averaged gradient did not arrive")
layer.weight.grad.fill_(channel.recv())
opt.step()
channel.send(layer.weight.item())
def data_parallel(checks):
context=mp.get_context("spawn")
workers=[]
try:
for rank in range(2):
parent,child=context.Pipe()
process=context.Process(target=rank_worker,args=(rank,child))
process.start()
child.close()
workers.append((process,parent))
rows=[]
for _,channel in workers:
if not channel.poll(18):
raise TimeoutError("worker gradient did not arrive")
rows.append(channel.recv())
mean=sum(row[2] for row in rows)/len(rows)
for _,channel in workers:
channel.send(mean)
parameters=[]
for _,channel in workers:
if not channel.poll(10):
raise TimeoutError("worker parameter did not arrive")
parameters.append(round(channel.recv(),6))
for process,_ in workers:
process.join(timeout=8)
assert process.exitcode==0
finally:
for process,channel in workers:
channel.close()
if process.is_alive():
process.terminate()
process.join(timeout=5)
full=torch.arange(1,5,dtype=torch.float64).reshape(-1,1)
single=torch.zeros(1,requires_grad=True,dtype=torch.float64)
F.mse_loss(full*single,3*full).backward()
checks.expect("architecture_cpu_parallel",[[1.,2.],[3.,4.]],
"Compute gradients in two CPU processes, aggregate via pipes and compare a full batch",
[[0,1],[[1.,2.],[3.,4.]],[-15.,-75.],-45.,[.45,.45],-45.],
[[row[0] for row in rows],[row[1] for row in rows],[row[2] for row in rows],
mean,parameters,single.grad.item()])
def sharding(checks):
x=torch.arange(1,13,dtype=torch.int64).reshape(4,3)
w=torch.tensor([[1,2],[0,1],[3,-1]],dtype=torch.int64)
full=x@w
columns=torch.cat([x@col for col in w.split(1,dim=1)],dim=1)
inner=(x[:,:1]@w[:1])+(x[:,1:]@w[1:])
checks.expect("architecture_tensor_splits",[x.tolist(),w.tolist()],
"Compare output-column concatenation and inner-dimension reduction with a full matrix product",
[True,True,[10,1]],[bool(torch.equal(columns,full)),bool(torch.equal(inner,full)),full[0].tolist()])
steps=(lambda data:data+1,lambda data:data*2,lambda data:data-3)
pipeline={}
active=[]
for tick in range(len(steps)+len(x)-1):
current=[]
for stage in reversed(range(len(steps))):
chunk=tick-stage
if 0<=chunk<len(x):
data=x[chunk] if stage==0 else pipeline[stage-1,chunk]
pipeline[stage,chunk]=steps[stage](data)
current.append([stage,chunk])
active.append(current)
result=torch.stack([pipeline[2,chunk] for chunk in range(len(x))])
full=steps[2](steps[1](steps[0](x)))
checks.expect("architecture_pipeline_slots",[4,3],
"Use a discrete three-stage microbatch schedule and check fill, drain and output",
[6,[1,2,3,3,2,1],True],[len(active),[len(row) for row in active],bool(torch.equal(result,full))])
def components():
model=nn.Linear(1,1,dtype=torch.float64)
with torch.no_grad():
model.weight.zero_()
model.bias.zero_()
opt=torch.optim.SGD(model.parameters(),lr=.015,momentum=.8)
return model,opt,torch.Generator().manual_seed(411)
def update(model,opt,generator,steps):
observed=[]
for _ in range(steps):
x=torch.randint(-3,4,(3,1),generator=generator).to(torch.float64)
opt.zero_grad(set_to_none=True)
loss=F.mse_loss(model(x),2*x+1)
loss.backward()
opt.step()
observed.append([x.flatten().tolist(),round(loss.item(),7)])
return observed
def recovery(checks,folder):
model,opt,generator=components()
update(model,opt,generator,3)
checkpoint=folder/"owned-checkpoint.pt"
torch.save({"model":model.state_dict(),"optimizer":opt.state_dict(),"rng":generator.get_state(),"step":3},checkpoint)
digest=sha256(checkpoint.read_bytes()).hexdigest()
uninterrupted=update(model,opt,generator,4)
restored,other,random=components()
assert sha256(checkpoint.read_bytes()).hexdigest()==digest
saved=torch.load(checkpoint,map_location="cpu",weights_only=True)
restored.load_state_dict(saved["model"])
other.load_state_dict(saved["optimizer"])
random.set_state(saved["rng"])
continued=update(restored,other,random,4)
equal=all(torch.equal(a,b) for a,b in zip(model.parameters(),restored.parameters(),strict=True))
buffers_equal=all(torch.equal(opt.state[a]["momentum_buffer"],other.state[b]["momentum_buffer"])
for a,b in zip(model.parameters(),restored.parameters(),strict=True))
checks.expect("architecture_checkpoint_resume",[3,4,411],
"Restore owned model, optimizer and sampling state and replay four steps",
[3,True,True,True,True],[saved["step"],uninterrupted==continued,equal,buffers_equal,len(digest)==64])
checks.rows[-1]["report"]={"replayed_inputs_and_losses":continued}
def exercise(checks,folder):
torch.set_num_threads(1)
data_parallel(checks)
sharding(checks)
recovery(checks,folder)
if __name__=="__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14、PyTorch 2.10.0+cpu、本机两进程与固定数据。SQLite 案例使用 CPython 标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、PyTorch 2.10.0+cpu、本机两进程与固定数据。SQLite 案例使用 CPython 标准库。
入口文件:projects/ai-system-architecture/training_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
training_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、PyTorch 2.10.0+cpu、本机两进程与固定数据。SQLite 案例使用 CPython 标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a26.zip