How to use the old value and the new value of a Variable in Tensorflow?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
TensorFlow variables hold mutable state, so it is common to ask for both the value before an update and the value after it. This comes up in custom training loops, debugging, metric collection, and optimizer experiments.
Snapshot the Old Value Before You Update
In TensorFlow 2, tf.Variable is mutable, which means the variable object itself keeps changing over time. If you want the previous value, do not keep another reference to the same variable object. Instead, create a tensor snapshot before calling assign, assign_add, or assign_sub.
tf.identity(counter) reads the current value and returns a tensor snapshot. After the assignment, new_value reflects the updated state while old_value still contains the pre-update number.
If you write old_value = counter, both names refer to the same mutable variable object. That does not preserve the earlier state.
Using Old and New Values Inside tf.function
The same pattern works inside compiled TensorFlow functions. Read the variable first, then update it, then read it again if you need both results.
This is the basic recipe for any custom state transition:
- Read the current value into a tensor
- Perform the assignment
- Read the new value if needed
- Compute any derived quantity from the two snapshots
Because both before and after are tensors, they are safe to return from tf.function and log later.
Example in a Custom Training Step
The pattern becomes especially useful when you want to monitor how much a parameter changes after an optimization step.
This example captures the parameter before the optimizer mutates it, then reads it again after the update. That makes it easy to inspect the true step size and verify that your learning rate behaves as expected.
When You Need More Than One Previous Value
If you need a longer history, store explicit snapshots in a Python list or a TensorFlow data structure. Variables only keep the current state. TensorFlow will not automatically remember earlier versions for you.
For example, a debugging callback might append tf.identity(variable) every few steps. That approach is more predictable than trying to recover previous values after the mutation has already happened.
Common Pitfalls
- '
old_value = variabledoes not copy the current value. It only creates another reference to the same mutable variable.' - Calling
.numpy()too early can move data out of TensorFlow execution flow and is usually unnecessary insidetf.function. - If an optimizer updates several variables, snapshot each one before
apply_gradientsif you need reliable before-and-after comparisons. - Remember that variables store current state only. TensorFlow does not keep built-in history for previous assignments.
Summary
- Use
tf.identity(variable)or another tensor read to snapshot the old value before mutation. - Update the variable with
assignor an optimizer step, then read it again for the new value. - The same pattern works in eager mode and inside
tf.function. - Never rely on a second Python reference to preserve an earlier variable state.
Related reading
- how to use to_categorical when using ImageDataGenerator
- how to use to_categorical when using ImageDataGenerator
- How to visualize a tensor summary in tensorboard
- How to visualize a TFRecord?
- How to use Transformers for text classification?
- how to use weight when training a weak learner for adaboost
- How to use the timeit module?
- How to use XPath in Python?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.