TensorFlow and Keras: from GradientTape to checkable training steps
Reconciling gradient records, variable updates, data flow lines and tracing boundaries with the same linear model.
Learning objectives and first steps4 objectives 2 first repairs
Try to do it after reading
- Explain Tape Records and Variable Monitor
- Recompute a linear model update
- Distinction eager Debug with tf . function tracing
- Arrange Dataset, indicators and preservation duties
Suggested first
- Gradient Down
- Python function averaged batch
Same loss. Which ones are there after the change of framework
Migration of proven algorithms to another training environment often involves the most dangerous changes not in network structures, but in loss denominators, whether variables are recorded and whether training and verification are shared in error situations. Keras can manage loops with fit and allow itself to write training steps; Regardless of the type used, it is still important to know what the model read, which gradient comes from, and which units of the indicators are accumulated.
Use of this chapter TensorFlow eager and TensorFlow Backend Keras 3 Semantics. 2026-10-29 Browse and check official information; Session/ placeholder without TF1, nor does a specific TensorFlow operation be described as any backend common. This machine has not installed the framework code for the implementation of this chapter, and the expected value of the standard Python is given below as an independent check.
Tape recorded as an operating relationship
Set input is a mark x=1Label y=2, the model predicts wx+b, the loss is half the error square. w, b are two trainable variables, initially zero. (a) zero forward projection, negative two error and loss two; The local lead numbers return along the model, and both parameters have a negative gradient of two. Learning rates of 0.1 and updated w, b are 0.2, new forecast of 0.4, new loss of 1.28.
# 标准 Python,已执行算术检查。w = b = 0.0x, y, learning_rate = 1.0, 2.0, 0.1error = w*x + b - ygrad_w, grad_b = error*x, errorbefore = 0.5*error*errorw, b = w-learning_rate*grad_w, b-learning_rate*grad_bafter = 0.5*(w*x+b-y)**2assert abs(before-2.0)<1e-12 and abs(after-1.28)<1e-12Frame snippets express the same calculation, using float64 to facilitate comparison with manual; This does not mean that actual models should be double-precision. You have to be clear on batch data reduce_mean Cover which axes.
import tensorflow as tfw = tf.Variable(0.0, dtype=tf.float64)b = tf.Variable(0.0, dtype=tf.float64)with tf.GradientTape() as tape: prediction = w*tf.constant(1.0, dtype=tf.float64)+b loss = 0.5*tf.square(prediction-2.0)gw, gb = tape.gradient(loss, [w, b])w.assign_sub(0.1*gw)b.assign_sub(0.1*gb)# 预期 gw=gb=-2,w=b=0.2;本段未在 TF 环境执行。None Gradient Reliance and value
Defaults that Tape will monitor the accessible training Variable, but that the ordinary Tensor does not automatically have the same status; To guide it, a visible watch is required. Even when variables are monitored, the expected dependency may be lost if the loss is calculated outside the Tape window or if the intermediate is converted to NumPy and then repackaged. The gradient is None, which should be checked first whether the loss is connected to the variable and cannot be filled directly and training continues.
A zero gradient may be the result of a correct calculation, such as a dead ReLU or a current position at the right location. Integer indexing and discrete selections cannot be reduced simply as indexes. Official Automatic Micro-dimension Guide Listing the scope of the records and the conduct of surveillance; When it is wrong, it is reduced to a single variable example and then the model structure is restored.
Keras tube model, loop protocol
In the custom loop,model(features, training=True) Identification of training modules; Authentication is usually used training=FalseI don't know. Tape for right model.trainable_variables , the optimizer and apply_gradients. Use the matching model for the final output of logits from_logits=True Losses, not added to softmax, explained by logits.
If a positive or additional loss of Keras exists, it should be included in the target as an official circular example and cannot be assumed to have calculated for itself a data loss covering all training objectives. Indicators usually have cumulative status across batch; The new epoch or new validation phase requires design reset_state. Combining the proven state with the training indicators will result in a curve that appears to be smooth but with a wrong calibre.
The order of transformation for Dataset is also part of the algorithm
shuffle, batch and prefetch for training data are common arrangements, but for different purposes. shuffle Changes the order of the sampling, batch Changes the sample group for a single operation, prefetch Only pre-empts. cache placed after random enhancements, which may fix the results of the first enhancements; batch first, and shuffle, the disruption is a single sample of batches rather than the same particle size. These differences must be consistent with the data process that is expected to be simulated.
eager first, error, then understanding tracing
tf.function calculates the volume of the function to be a repeatable map; It is not "to turn any Python statement into a plot for every step of execution". The side effects of the Python printing, branch or object may occur in the tracing stage; Dynamic weight conditions should follow the synonym of TensorFlow. Entering changes in the parameters of shape, dtype or Python may lead to a re-entry of tracing, which does not mix the first cycle with the same performance problem.
Actual development begins with a sample, gradient and indicator check in the eager mode and then completes the training steps. The records are time-consuming to compile and stabilize and maintain the correct baseline for non-compilation. Keras 3 contains different entrances to the preservation of replicable models and the export reasoning service, and does not apply the experience of the old version "Any directory can directly load_model".
Once the results are right, a verification step is required
Authentication is not just a failure to call the optimist. A stand-alone sample, a clear training = False and the same pre-treatment version should be used to accumulate losses and indicators as agreed. If there are different quantities of valid token per batch at the time of the training, it is not possible to suddenly convert each batch to equivalent rights at the time of validation; When comparing old and new achievements, valid counts should be kept simultaneously. The empty target batch should have decided in advance to skip or misstate and cannot be divided by zero and only see NaN in the final curve.
A minimum migration acceptance may consist of three fixed inputs: normal samples, samples with missing sources of mask filled in. Compare the previous shape, the target loss, the existence of the gradient and the range of parameters to be updated, and complete epoch. The error tolerance should match dtype; A fine rounding difference for float32 cannot be treated as a large difference due to a mislabel.
When organizing training in Keras through fit, it should also be known which compile is configured for loss, which metric is, and what sample_weight covers. These duties will not automatically be inherited into all imagined behaviour by switching to a self-defined cycle. Recording the dictionaries of the dictionaries or features prior to the preservation of the model, the unicoded parameters and the input signature is used to determine whether the forecast after reloading uses the same protocol.
Self-measurement and interpretation
Is a Tensor guide always automatically monitored?
No, I won't. Default surveillance of Variable and visible watch objects; It is also important that there be a trace of return from the loss within the records.
This example updates only w, not b, and what are the new losses?
w = 0.2, b = 0, projected at 0.2, loss of 0.5 x 1.82 = 1.62. It is different from the 1.28 which is updated simultaneously by the two parameters.
Can you fix the breakchart by replacing the None gradient with zero?
Can't. This only allows the process to continue, and the branches that were to be trained are still unguided. Pre-position records range, NumPy conversion and variable dependency.
Is training = False equal to non-training?
No, it's not. It controls the forward behaviour of the layer; Whether the variable receives the gradient and whether the optimist is updated still needs to be judged separately.
Why the same paragraph? Python print ♪ Not every single one ♪ batch All out?
In tf. function, it may only be performed as a Python side effect at tracing. Use the appropriate TensorFlow operation when you need to log in each step.
Test indicators are getting better, but never reset_state. What does that mean?
The current value may mix the history of more than one epoch, and cannot be interpreted as the independent achievement of this round of models in the current validation set. The statistical window is first modified.
Continue with Data Severage and Leakage and Efficient Training and Recoverability Experiments. This chapter uses the official Tape, Keras custom loop and tf. data document reconciliation duties, diagrams and digital originals; Standard Python has been calculated and the TensorFlow/ Keras code has not been installed.
Sources and reconciliations
Definitions, methods and interfaces are available.
- TensorFlow — Introduction to gradients and automatic differentiation
- Keras — Writing a training loop from scratch in TensorFlow
- TensorFlow — tf.data: Build input pipelines
Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.