"""Validate a local TensorFlow CPU environment and document what CPU can measure."""
from importlib.metadata import version
from pathlib import Path
from statistics import median
import subprocess
import sys
from time import perf_counter
import json
import platform
import tensorflow as tf
def finish(cases):
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)))
def observe(cases,name,operation,inputs,expected,actual):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
def main():
cases=[]
observe(cases,"verify_python_and_tf_versions","read the interpreter, TensorFlow and Keras versions",
{"interpreter":"project CPU environment"},["3.12.14","2.21.0","3.15.1"],
[platform.python_version(),tf.__version__,tf.keras.__version__])
observe(cases,"confirmed_isolated_python","verify that TensorFlow is installed beneath the independent interpreter",
{"entry":"sys.executable"},[True,True],[sys.prefix!=sys.base_prefix,
Path(tf.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())])
command=[sys.executable,"-m","pip","--isolated","--disable-pip-version-check"]
checks=subprocess.run([*command,"check"],check=True,capture_output=True,text=True,timeout=30)
recorded=subprocess.run([*command,"freeze"],check=True,capture_output=True,text=True,timeout=30)
normalized=recorded.stdout.lower().splitlines()
observe(cases,"installed_dependency_snapshot","run pip check and verify frozen TensorFlow/Keras metadata",
["tensorflow","keras"],[True,True,True],["No broken requirements" in checks.stdout,
"tensorflow==2.21.0" in normalized,"keras==3.15.1" in normalized])
cases[-1]["observed_package_versions"]={name:version(name) for name in ("tensorflow","keras","numpy","h5py")}
with tf.device("/CPU:0"):
result=tf.constant([1,2,3])+tf.constant([4,5,6])
observe(cases,"local_cpu_computation","compute values and verify the actual tensor placement",
[[1,2,3],[4,5,6]],[[5,7,9],True],[result.numpy().tolist(),result.device.endswith("CPU:0")])
inputs=tf.ones((128,128))
for _ in range(3):
tf.matmul(inputs,inputs).numpy()
timings=[]
for _ in range(5):
t=perf_counter()
output=tf.matmul(inputs,inputs).numpy()
timings.append(perf_counter()-t)
observe(cases,"cpu_benchmark_materializes_results","measure five synchronous products after three CPU warmups",
{"size":128,"warmups":3,"repetitions":5},[[128,128],128.,True],
[list(output.shape),float(output[0,-1]),median(timings)>0])
cases[-1]["observed_median_seconds"]=median(timings)
observe(cases,"native_windows_device_capabilities","enumerate installed CPU/GPU devices and the CUDA build flag",
{"tensorflow":"2.21.0","platform":"Windows native"},[True,False,0],
[bool(tf.config.list_physical_devices("CPU")),bool(tf.test.is_built_with_cuda()),len(tf.config.list_physical_devices("GPU"))])
original=tf.keras.mixed_precision.global_policy()
old=tf.config.optimizer.get_jit()
try:
tf.keras.mixed_precision.set_global_policy("mixed_float16")
layer=tf.keras.layers.Dense(1,kernel_initializer="ones")
answer=layer(tf.constant([[2.,3.]]))
tf.config.optimizer.set_jit("autoclustering")
observe(cases,"modern_mixed_precision_configuration","run a mixed-precision layer and read the optimizer configuration",
{"inputs":[2,3],"policy":"mixed_float16"},["float16","float32",5.,"autoclustering"],
[answer.dtype.name,str(layer.kernel.dtype),float(answer.numpy()[0,0]),tf.config.optimizer.get_jit()])
finally:
tf.keras.mixed_precision.set_global_policy(original)
tf.config.optimizer.set_jit(old if old else False)
finish(cases)
if __name__=="__main__":
main()
本例需在 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-setup-lab/verify-cpu-installation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
verify-cpu-installation.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a379.zip