"""Exercise Keras custom layers, objectives and a compiled training step."""
import json
from pathlib import Path
import platform
from tempfile import TemporaryDirectory
import tensorflow as tf
@tf.keras.utils.register_keras_serializable(package="BlueSky")
class SumProjection(tf.keras.layers.Layer):
def __init__(self, width, **kwargs):
super().__init__(**kwargs)
self.width = width
def build(self, input_shape):
self.kernel = self.add_weight(
name="kernel", shape=(input_shape[-1], self.width), initializer="ones"
)
self.offset = self.add_weight(name="offset", shape=(self.width,), initializer="zeros")
def call(self, value):
return tf.linalg.matmul(value, self.kernel) + self.offset
def get_config(self):
return {**super().get_config(), "width": self.width}
def row_mse(target, prediction):
return tf.reduce_mean(tf.square(target - prediction), axis=-1)
@tf.keras.utils.register_keras_serializable(package="BlueSky")
class PenalizedMSE(tf.keras.losses.Loss):
def __init__(self, strength=0.5, **kwargs):
super().__init__(**kwargs)
self.strength = strength
def call(self, target, prediction):
penalty = self.strength * tf.reduce_mean(tf.abs(prediction), axis=-1)
return row_mse(target, prediction) + penalty
def get_config(self):
return {**super().get_config(), "strength": self.strength}
def percentile_loss(target, predictions, quantiles):
error = target - predictions
return tf.reduce_sum(tf.maximum(quantiles * error, (quantiles - 1) * error), axis=-1)
class BatchLossMean(tf.keras.metrics.Metric):
def __init__(self, name="batch_loss_mean"):
super().__init__(name=name)
self.total = self.add_weight(name="total", initializer="zeros")
self.count = self.add_weight(name="count", initializer="zeros")
def update_state(self, losses):
self.total.assign_add(tf.reduce_sum(losses))
self.count.assign_add(tf.cast(tf.size(losses), self.count.dtype))
def result(self):
return tf.math.divide_no_nan(self.total, self.count)
def reset_state(self):
self.total.assign(0)
self.count.assign(0)
class UntrackedVariableLayer(tf.keras.layers.Layer):
def build(self, input_shape):
self.scaling = tf.Variable(2.0, trainable=True)
def call(self, inputs):
return inputs * self.scaling
class ProjectionTests(tf.test.TestCase):
def test_output_shape_and_values(self):
layer = SumProjection(2, name="example")
output = layer(tf.constant([[4.0, 7.0], [3.0, -2.0]]))
self.assertEqual(output.shape, (2, 2))
self.assertAllClose(output, [[11.0, 11.0], [1.0, 1.0]])
def observe(cases, name, inputs, prerequisites, action, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name, inputs=inputs, prerequisites=prerequisites,
action=action, expected=expected, actual=actual, passed=True))
def examples(cases):
data = tf.constant([[4.0, 7.0], [3.0, -2.0]])
test = ProjectionTests("test_output_shape_and_values")
test.test_output_shape_and_values()
layer = SumProjection(2, name="tied_projection")
first = layer(data)
observe(cases, "custom_layer_build", data.numpy().tolist(), "First call builds kernel and bias",
"Check shape, values and tracked weights, including the tf.test.TestCase assertions",
[[2, 2], [[11.0, 11.0], [1.0, 1.0]], 2],
[list(first.shape), first.numpy().tolist(), len(layer.trainable_weights)])
model = tf.keras.Sequential([tf.keras.Input((2,)), layer])
layer.kernel.assign([[2.0, 3.0], [2.0, 3.0]])
layer.offset.assign([1.0, -1.0])
with TemporaryDirectory(prefix="tf-custom-layer-") as directory:
path = Path(directory) / "sum.keras"
model.save(path)
reload = tf.keras.models.load_model(path)
actual = [reload.layers[0].name, reload.layers[0].width, reload(data).numpy().tolist()]
observe(cases, "keras_config_roundtrip", [2, "tied_projection"], "Registered custom class and .keras file",
"Reload config, trained-like weights and prediction in a new model",
["tied_projection", 2, [[23.0, 32.0], [3.0, 2.0]]], actual)
raw = UntrackedVariableLayer()
direct = float(raw(tf.constant(3.0)))
left = tf.keras.Input((2,))
right = tf.keras.Input((2,))
tied = tf.keras.Model([left, right], [layer(left), layer(right)])
outputs = tied([data[:1], data[1:]])
observe(cases, "weight_tracking_and_sharing", [3, 2], "Keras 3, direct tf.Variable and reused tracked layer",
"Compare direct variable discovery with a layer shared by both branches",
[6.0, 0, 2, [[23.0, 32.0]], [[3.0, 2.0]]],
[direct, len(raw.trainable_weights), len(tied.trainable_weights),
outputs[0].numpy().tolist(), outputs[1].numpy().tolist()])
estimate = tf.Variable([[0.0, 3.0], [2.0, 6.0]])
zeros = tf.zeros_like(estimate)
mse = row_mse(zeros, estimate)
observe(cases, "per_sample_mse", estimate.numpy().tolist(), "Match shape [batch, channels]",
"Reduce channels while preserving the two samples", [4.5, 20.0], mse.numpy().tolist())
loss = PenalizedMSE(reduction="none")
with tf.GradientTape() as tape:
values = loss(zeros, estimate)
objective = tf.reduce_mean(values)
gradient = tape.gradient(objective, estimate)
restored = tf.keras.losses.deserialize(tf.keras.losses.serialize(loss))
observe(cases, "penalized_loss_class", estimate.numpy().tolist(), "Batch of two with per-sample penalty",
"Verify loss, registered config, expected gradients and reduction",
[[5.25, 22.0], 0.5, [[0.0, 1.625], [1.125, 3.125]]],
[values.numpy().tolist(), restored.strength, gradient.numpy().tolist()])
linear = tf.keras.Sequential([tf.keras.Input((1,)),
tf.keras.layers.Dense(1, use_bias=False, kernel_initializer="zeros")])
optimizer = tf.keras.optimizers.SGD(0.1)
optimizer.build(linear.trainable_weights)
metric = BatchLossMean()
@tf.function(input_signature=[tf.TensorSpec([None, 1], tf.float32),
tf.TensorSpec([None, 1], tf.float32)])
def update(features, targets):
with tf.GradientTape() as tape:
losses = row_mse(targets, linear(features, training=True))
mean = tf.reduce_mean(losses)
gradients = tape.gradient(mean, linear.trainable_weights)
optimizer.apply_gradients(zip(gradients, linear.trainable_weights))
metric.update_state(losses)
return mean
features = tf.constant([[1.0], [2.0]])
targets = 2 * features
before = [float(update(features, targets)), float(update(features, targets))]
observe(cases, "compiled_custom_step", [1, 2], "Built variables; CPU; fixed rank and dynamic batch axis",
"Run two real optimizer steps and read the weight, graph trace count and iteration counter",
[[10.0, 2.5], 1.5, 2, 1],
[before, float(linear.layers[0].kernel[0, 0]), int(optimizer.iterations),
update.experimental_get_tracing_count()])
seen = float(metric.result())
metric.reset_state()
observe(cases, "metric_state_and_reset", [4, 16, 1, 4], "Two updates populated a four-sample state",
"Read the accumulated metric and reset it",
[6.25, 0.0], [seen, float(metric.result())])
invalid = tf.math.divide_no_nan(0.0, 0.0)
nan = tf.math.divide(0.0, 0.0)
clipped, norm = tf.clip_by_global_norm([tf.constant([6.0, 8.0])], 5.0)
observe(cases, "stability_and_clip", [0, 0, 6, 8], "Use an explicitly chosen zero-denominator convention",
"Observe NaN, guarded division and gradient vector with reduced norm",
[True, 0.0, 10.0, [3.0, 4.0]],
[bool(tf.math.is_nan(nan)), float(invalid), float(norm), clipped[0].numpy().tolist()])
saved = tf.keras.mixed_precision.global_policy()
try:
tf.keras.mixed_precision.set_global_policy("mixed_float16")
mixed = SumProjection(2)
values = mixed(data)
actual = [mixed.compute_dtype, mixed.variable_dtype, values.dtype.name]
finally:
tf.keras.mixed_precision.set_global_policy(saved)
observe(cases, "mixed_precision_policy", "mixed_float16", "CPU exercise observes types only",
"Construct after changing policy, infer and restore the previous policy",
["float16", "float32", "float16", True], actual + [tf.keras.mixed_precision.global_policy() == saved])
@tf.function(jit_compile=True)
def compiled(vector):
return tf.reduce_sum(tf.square(vector) + 1)
vector = tf.constant([2, 3, 4])
value = int(compiled(vector))
hlo = compiled.experimental_get_compiler_ir(vector)(stage="optimized_hlo")
observe(cases, "cpu_xla", [2, 3, 4], "TensorFlow CPU with XLA compilation",
"Compile with jit_compile and inspect optimized HLO",
[32, True], [value, "HloModule" in hlo and "ENTRY" in hlo])
packed = tf.constant([[[[1.0, 2.0, 3.0, 4.0]]]])
transformed = tf.nn.depth_to_space(packed, 2)
observe(cases, "pixel_shuffle", [1, 1, 1, 4], "NHWC, scale 2, channels divisible by scale squared",
"Rearrange four channels into two rows of pixels",
[[1, 2, 2, 1], [[1.0, 2.0], [3.0, 4.0]]],
[list(transformed.shape), tf.squeeze(transformed).numpy().tolist()])
quantiles = tf.constant([0.25, 0.5, 0.75])
target = tf.constant([[4.0], [1.0]])
expected = [0.5, 2.25]
predictions = tf.constant([[3.0, 4.0, 5.0], [3.0, 1.0, 0.0]])
result = percentile_loss(target, predictions, quantiles)
observe(cases, "pinball_percentiles", [0.25, 0.5, 0.75],
"Each column predicts one quantile, one target is broadcast per sample",
"Observe asymmetric loss for under- and overprediction",
expected, result.numpy().tolist())
if __name__ == "__main__":
observations = []
examples(observations)
print(json.dumps(dict(version=platform.python_version(), tensorflow=tf.__version__,
keras=tf.keras.__version__, system=platform.system(),
devices=[device.name for device in tf.config.list_physical_devices()],
cases=observations), ensure_ascii=True))
本例需在 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-custom-components-lab/verify-custom-components.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
verify-custom-components.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a362.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip