Tensorflow Creating a graph in a class and running it outside
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
In TensorFlow 1.x, creating a computation graph inside a class and running it outside required careful management of graphs and sessions. TensorFlow 2.x eliminates most of this complexity with eager execution and tf.function. This article covers both the legacy TF1 approach and the modern TF2 approach for encapsulating models in classes.
TensorFlow 1.x Approach (Legacy)
In TF1, you had to explicitly manage graphs and sessions:
Persistent Session
For repeated calls, keep the session alive:
TensorFlow 2.x Approach (Recommended)
TF2 uses eager execution by default. No graphs or sessions to manage:
Using tf.Module
Using Keras (Most Common)
Using @tf.function for Graph Optimization
@tf.function converts a Python function to a TensorFlow graph for performance:
Saving and Loading Models
TF2 SavedModel
Keras Save/Load
Migrating from TF1 to TF2
| TF1 Concept | TF2 Equivalent |
tf.Graph() | Not needed (eager by default) |
tf.Session() | Not needed |
tf.placeholder() | Function arguments |
tf.Variable() | tf.Variable() (same) |
sess.run(op, feed_dict) | Direct function call |
tf.global_variables_initializer() | Variables init on creation |
| Graph inside a class | tf.Module or tf.keras.Model |
Common Pitfalls
- TF1 graph leaks: In TF1, if you create ops without
with self.graph.as_default():, they go to the default global graph, causing cross-contamination between model instances. Always scope your ops. - Session lifecycle: In TF1 with persistent sessions, forgetting to close the session leaks GPU memory. Use context managers (
with tf.Session() as sess:) or call.close()explicitly. - @tf.function retracing: In TF2,
@tf.functiontraces a new graph for each unique input signature. Passing Python values (not tensors) causes retracing. Useinput_signatureto fix the trace. - Variable creation in @tf.function: Creating
tf.Variableinside@tf.functionon the first call works but raises errors on subsequent calls. Create variables in__init__, not in the decorated function. - Training vs inference: In Keras, pass
training=Trueduring training (enables dropout, batch norm) andtraining=Falseduring inference. Forgetting this affects model behavior.
Summary
- TF1 requires explicit graph and session management — create graphs in
__init__, run in methods with sessions - TF2 uses eager execution — define models as
tf.Moduleortf.keras.Modelsubclasses with no session boilerplate - Use
@tf.functionto convert methods to optimized graph operations for performance - Prefer
tf.keras.Modelfor full training/saving/loading support - When migrating from TF1, replace
tf.placeholderwith function arguments and remove alltf.Sessionusage
Related reading
- tensorflow creating mask of varied lengths
- Tensorflow Cross Device Communication
- Tensorflow CUDA - CUPTI error CUPTI could not be loaded or symbol could not be found
- Tensorflow Cuda compute capability 3.0. The minimum required Cuda capability is 3.5
- Tensorflow custom data load asynchronous computation
- TensorFlow custom estimator stuck when calling evaluate after training
- Tensorflow Data Adapter Error ValueError Failed to find data adapter that can handle input
- TensorFlow equivalent of numpy.all
.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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.