"""Run TensorFlow data parallel operations and an actual two-worker local experiment."""
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import json
import os
import socket
import subprocess
import sys
def addresses():
with socket.socket() as left,socket.socket() as right:
sockets=(left,right)
for endpoint in sockets:
endpoint.bind(("127.0.0.1",0))
return [f"127.0.0.1:{endpoint.getsockname()[1]}" for endpoint in sockets]
def run_local_cluster():
workers=addresses()
command=[sys.executable,"-I","-X","utf8","-B",str(Path(__file__).resolve()),"--worker"]
options={**os.environ,"TF_NUM_INTRAOP_THREADS":"1","TF_NUM_INTEROP_THREADS":"1",
"OMP_NUM_THREADS":"1","TF_CPP_MIN_LOG_LEVEL":"0","TF_ENABLE_ONEDNN_OPTS":"0",
"TF_GRPC_REUSE_PORT":"0"}
processes=[]
try:
for index in range(2):
configured=json.dumps(dict(cluster={"worker":workers},task={"type":"worker","index":index}))
processes.append(subprocess.Popen(command,env={**options,"TF_CONFIG":configured},
stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf8"))
with ThreadPoolExecutor(max_workers=2) as pool:
submissions=[pool.submit(proc.communicate,timeout=45) for proc in processes]
outcomes=[]
for i,(proc,pending) in enumerate(zip(processes,submissions,strict=True)):
try:
stdout,stderr=pending.result()
except subprocess.TimeoutExpired:
proc.kill()
stdout,stderr=proc.communicate()
outcomes.append(dict(worker=i,timeout_seconds=45,returncode=proc.returncode,stderr=stderr))
else:
outcomes.append(dict(worker=i,returncode=proc.returncode,stderr=stderr,
actual=json.loads(stdout) if proc.returncode==0 and stdout.strip() else None))
passed=all(row.get("actual") and row["actual"]["total"]==3. and row["actual"]["replicas"]==2 for row in outcomes)
return dict(mode="loopback MultiWorkerMirroredStrategy",worker_count=2,passed=passed,workers=outcomes)
finally:
for proc in processes:
if proc.poll() is None:
proc.kill()
proc.communicate()
def worker():
import tensorflow as tf
communication=tf.distribute.experimental.CommunicationOptions(
implementation=tf.distribute.experimental.CommunicationImplementation.RING,timeout_seconds=20)
strategy=tf.distribute.MultiWorkerMirroredStrategy(communication_options=communication)
@tf.function
def coordinated():
def replica():
context=tf.distribute.get_replica_context()
local=tf.cast(context.replica_id_in_sync_group+1,tf.float32)
return context.all_reduce(tf.distribute.ReduceOp.SUM,local)
return strategy.run(replica)
result=strategy.experimental_local_results(coordinated())
print(json.dumps(dict(replicas=strategy.num_replicas_in_sync,tensorflow=tf.__version__,
total=float(result[0]),task=read_task())),flush=True)
def read_task():
return json.loads(os.environ["TF_CONFIG"])["task"]["index"]
def mirrored():
import tensorflow as tf
physical,=tf.config.list_physical_devices("CPU")
tf.config.set_logical_device_configuration(physical,[tf.config.LogicalDeviceConfiguration() for _ in range(2)])
names=[item.name for item in tf.config.list_logical_devices("CPU")]
strategy=tf.distribute.MirroredStrategy(devices=names,
cross_device_ops=tf.distribute.ReductionToOneDevice(reduce_to_device="/CPU:0"))
with strategy.scope():
weight=tf.Variable(0.)
optimizer=tf.keras.optimizers.SGD(.1)
def samples(context):
value=tf.cast(context.replica_id_in_sync_group+1,tf.float32)
return tf.reshape(value,[1]),tf.reshape(value*2,[1])
local=strategy.experimental_distribute_values_from_function(samples)
@tf.function
def coordinated(data):
def replica(records):
x,y=records
with tf.GradientTape() as tape:
per_example=tf.square(weight*x-y)
loss=tf.nn.compute_average_loss(per_example,global_batch_size=2)
gradient=tape.gradient(loss,weight)
optimizer.apply_gradients([(gradient,weight)])
return loss
return strategy.reduce(tf.distribute.ReduceOp.SUM,strategy.run(replica,args=(data,)),axis=None)
results=[]
for _ in range(2):
full_loss=float(coordinated(local).numpy())
results.append([full_loss,float(weight.numpy())])
assert results==[[10.,1.],[2.5,1.5]]
return dict(tensorflow=tf.__version__,logical_cpu=names,global_batch=2,local_batch=1,targets=[2,4],
expected=[[10.,1.],[2.5,1.5]],actual=results,passed=True)
from hashlib import file_digest
import platform
import tarfile
import numpy as np
def case(cases,name,operation,inputs,expected,actual,measurements=None):
assert actual==expected,(name,expected,actual)
item=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
if measurements is not None:
item["measurements"]=measurements
cases.append(item)
def fit_cifar(archive,cases):
if archive is None:
return
import tensorflow as tf
expected_digest="c4a38c50a1bc5f3a1c5537f2155ab9d68f9f25eb1ed8d9ddda3db29a59bca1dd"
with archive.open("rb") as file:
assert file_digest(file,"sha256").hexdigest()==expected_digest
with tarfile.open(archive,"r|gz") as package:
for member in package:
if member.name=="cifar-10-batches-bin/data_batch_1.bin":
assert member.isfile() and member.size==30730000
with package.extractfile(member) as stream:
part=np.frombuffer(stream.read(3073*32),dtype=np.uint8).reshape(32,3073)
break
else:
raise ValueError("Expected the first official CIFAR binary batch.")
images=part[:,1:].reshape(32,3,32,32).transpose(0,2,3,1).astype(np.float32)/255.
labels=part[:,0].astype(np.int32)
devices=[item.name for item in tf.config.list_logical_devices("CPU")]
strategy=tf.distribute.MirroredStrategy(devices=devices,
cross_device_ops=tf.distribute.ReductionToOneDevice(reduce_to_device="/CPU:0"))
options=tf.data.Options()
options.threading.private_threadpool_size=1
ds=tf.data.Dataset.from_tensor_slices((images,labels)).with_options(options).cache().batch(8,drop_remainder=True).prefetch(1)
distributed=strategy.experimental_distribute_dataset(ds)
x,y=next(iter(distributed))
shapes=[list(part.shape) for part in strategy.experimental_local_results(x)]
host_data=[]
for _ in range(2):
host_data.append([batch[1].numpy().tolist() for batch in ds])
case(cases,"matched_data_shards","Check global/local batch sizes, shard ordering and repeated cached data",
{"global_batch":8,"cpu_replicas":2},[[[4,32,32,3],[4,32,32,3]],True,True],
[shapes,[value for part in strategy.experimental_local_results(y) for value in part.numpy().tolist()]==labels[:8].tolist(),
host_data[0]==host_data[1]])
with strategy.scope():
model=tf.keras.Sequential([tf.keras.Input((32,32,3)),tf.keras.layers.Conv2D(4,3,activation="relu"),
tf.keras.layers.GlobalAveragePooling2D(),tf.keras.layers.Dense(10)])
model.compile(optimizer="sgd",loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
history=model.fit(ds,epochs=2,verbose=0,shuffle=False).history
case(cases,"mirrored_cifar_fit","Train a small CNN with real CIFAR rows and two logical CPU replicas",
{"sample_count":32,"epochs":2,"batch":8},[8,2,True],
[int(model.optimizer.iterations.numpy()),len(history["loss"]),bool(np.isfinite(history["loss"]).all())],
{"history":history,"gpu_performance_measured":False,"archive_sha256":expected_digest})
def main(archive):
import tensorflow as tf
cases=[]
checked=mirrored()
case(cases,"mirrored_global_loss","Run two synchronous weight updates using the global batch denominator",
{"global_batch":2,"replicas":2,"targets":[2,4]},[[10.,1.],[2.5,1.5]],checked["actual"],checked)
cluster=run_local_cluster()
case(cases,"real_loopback_workers","Run two worker processes and compare their collective sum",
{"workers":2,"communication":"RING"},[3.,3.],
[entry.get("actual",{}).get("total") for entry in cluster["workers"] if entry.get("actual")],cluster)
fit_cifar(archive,cases)
with tf.device("/CPU:0"):
left=tf.Variable([[2.]])
with tf.device("/CPU:1"):
right=tf.Variable([[3.]])
total=tf.matmul(left,right)
case(cases,"device_sections","Place parameters on separate logical devices and run a split elementary computation",
{"left":2.,"right":3.},[True,True,6.],
[left.device.endswith("CPU:0"),right.device.endswith("CPU:1"),float(total[0,0])])
low=tf.keras.layers.Dense(2,dtype=tf.keras.mixed_precision.Policy("mixed_float16"))
out=low(tf.ones((2,3)))
case(cases,"mixed_precision_dtype","Inspect the local CPU computation dtype and variable dtype",
{"policy":"mixed_float16"},["float16","float32"],[out.dtype.name,low.variable_dtype])
grads=tf.constant([2.,8.])
local_average=float(tf.reduce_mean(grads))
case(cases,"gradient_accumulation_control","Verify the effect of averaging two partial gradients before one step",
{"partials":[2,8],"rate":.1},[5.,-.5],[local_average,-.1*local_average])
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=tf.keras.__version__,
system=platform.system(),devices=[d.name for d in tf.config.list_physical_devices()],cases=cases)))
if __name__=="__main__":
parser=ArgumentParser()
parser.add_argument("--worker",action="store_true")
parser.add_argument("--archive",type=Path)
opts=parser.parse_args()
if opts.worker:
worker()
else:
main(opts.archive)
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-distributed-training-lab/run-local-distributed-training.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
run-local-distributed-training.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a364.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip