Understand TensorFlow by mimicking its API from scratch

TensorFlow is a very powerful and open source library for implementing and deploying large-scale machine learning models. This makes it perfect for research and production. Over the years it has become one of the most popular libraries for deep learning.
The goal of this post is to build an intuition and understanding for how deep learning libraries work under the hood, specifically TensorFlow. To achieve this goal, we will mimic its API and implement its core building blocks from scratch. This has the neat little side effect that, by the end of this post, you will be able to use TensorFlow with confidence, because you’ll have a deep conceptual understanding of the inner workings. You will also gain further understanding of things like variables, tensors, sessions or operations.
So let’s get started, shall we?
Note: If you are familiar with the basics of TensorFlow including how computational graphs work, you may skip the theory and jump straight to the implementation part.
Theory
TensorFlow is a framework composed of two core building blocks — a library for defining computational graphs and a runtime for executing such graphs on a variety of different hardware. A computational graph has many advantages but more on that in just a moment.
Now the question you might ask yourself is, what exactly is a computational graph?
Computational Graphs
In a nutshell, a computational graph is an abstract way of describing computations as a directed graph. A directed graph is a data structure consisting of nodes (vertices) and edges. It’s a set of vertices connected pairwise by directed edges.
Here’s a very simple example:

Graphs come in many shapes and sizes and are used to solve many real-life problems, such as representing networks including telephone networks, circuit networks, road networks, and even social networks. They are also commonly used in computer science to describe dependencies, for scheduling or within compilers to represent straight line code (a sequence of statements without loops and conditional branches). Using a graph for the latter allows the compiler to efficiently eliminate common subexpression.
And of course they are used to grill people in coding interviews 😈.
Now that we have a basic understanding of directed graphs, let’s come back to computational graphs.
TensorFlow uses directed graphs internally to represent computations, and they call this data flow graphs (or computational graphs).
While nodes in a directed graph can be anything, nodes in a computational graph mostly represent operations, variables, or placeholders.
Operations create or manipulate data according to specific rules. In TensorFlow those rules are called Ops, short for operations. Variables on the other hand represent shared, persistent state that can be manipulated by running Ops on those variables.
The edges correspond to data, or multidimensional arrays (so-called Tensors) that flow through the different operations. In other words, edges carry information from one node to another. The output of one operation (one node) becomes the input to another operation and the edge connecting the two nodes carry the value.
Here’s an example of a very simple program:

To create a computational graph out of this program, we create nodes for each of the operations in our program, along with the input variables a and b. In fact, a and b could be constants if they don’t change. If one node is used as the input to another operation we draw a directed arrow that goes from one node to another.
The computational graph for this program might look like this:

This graph is drawn from left to right but you may also find graphs that are drawn from top to bottom or vice versa. The reason why I chose the former is simply because I find it more readable.
The computational graph above represents distinct computational steps that we need to execute to arrive at our final outcome. First, we create two constants a and b . Then, we multiply them, take their sum and use the results of those two operations to divide one by the other. And finally, we print out the result.
This is not too difficult, but the question is why do we need a computational graph for this? What are the advantages of organizing computations as a directed graph?
First of all, a computational graph is a more abstract way of describing a computer program and its computations. At the most fundamental level, most computer programs are mainly composed of two things — primitive operations and an order in which these operations are executed, often sequentially, line by line. This means we would first multiply a and b and only when this expression was evaluated we would take their sum. So, the program specifies the order of execution, but computational graphs exclusively specify the dependencies across the operations. In other words, how would the output of these operations flow from one operation to another.
This allows for parallelism or dependency driving scheduling. If we look at our computational graph we see that we could execute the multiplication and addition in parallel. That’s because these two operations do not depend on each other. So we can use the topology of the graph to drive the scheduling of operations and execute them in the most efficient manner, e.g. using multiple GPUs on a single machine or even distribute the execution across multiple machines 🤯. TensorFlow does exactly this, it can assign the operations that do not depend on each other to different cores with minimal input from the person who actually writes the program, just by constructing a directed graph. That’s awesome, don’t you think?
Another key advantage is portability. The graph is a language-independent representation of our code. So we can build the graph in Python, save the model (TensorFlow uses protocol buffers), and restore the model in a different language, say C++, if you want to go really fast.
Now that we have a solid foundation let’s look at the core parts that constitute a computational graph in TensorFlow. These are the parts that we will later on re-implement from scratch.
TensorFlow Basics
A computational graph in TensorFlow consists of several parts:
- Variables: Think of TensorFlow variables like normal variables in our computer programs. A variable can be modified at any point in time, but the difference is that they have to be initialized before running the graph in a session. They represent changeable parameters within the graph. A good example for variables would be the weights or biases in a neural network.
- Placeholders: A placeholder allows us to feed data into the graph from outside and unlike variables they don’t need to be initialized. Placeholders simply define the shape and the data type. We can think of placeholders as empty nodes in the graph where the value is provided later on. They are typically used for feeding in inputs and labels.
- Constants: Parameters that cannot be changed.
- Operations: Operations represent nodes in the graph that perform computations on Tensors.
- Graph: A graph is like a central hub that connects all the variables, placeholders, constants to operations.
- Session: A session creates a runtime in which operations are executed and Tensors are evaluated. It also allocates memory and holds the values of intermediate results and variables.
Remember from the beginning that we said TensorFlow is composed of two parts, a library for defining computational graphs and a runtime for executing these graphs? That’s the Graph and Session. The Graph class is used to construct the computational graph and the Session is used to execute and evaluate all or a subset of nodes. The main advantage of deferred execution is that during the definition of the computational graph we can construct very complex expressions without directly evaluating them and allocating the space in memory that is needed.
For example, if we use NumPy to define a large matrix, say a trillion by a trillion, we would immediately get an out of memory error. In TensorFlow we would define a Tensor that is a description of a multidimensional array. It may have a shape and a data type but it does not have an actual value.

In the snippet above we use both tf.zeros and np.zeros to create a matrix with all elements set to zero. While NumPy will immediately instantiate the amount of memory that is needed for a trillion by a trillion matrix filled with zeros, TensorFlow will only declare the shape and the data type but not allocate the memory until this part of the graph is executed. Cool, right?
This core distinction between declaration and execution is very important to keep in mind, because this is what allows TensorFlow to distribute the computational load across different devices (CPUs, GPUs, TPUs) attached to different machines.
With those core building blocks in place, let’s convert our simple program into a TensorFlow program. In general, this can be divided into two phases:
- Construction of the computational graph.
- Running a session
Here’s what our simple program could look like in TensorFlow:

We start off by importing tensorflow. Next, we create a Session object within a with statement. This has the advantage that the session is automatically closed after the block was executed and we don’t have to call sess.close() ourselves. Also, these with blocks are very commonly used.
Now, inside the with-block, we can start constructing new TensorFlow operations (nodes) and thereby define the edges (Tensors). For example:
a = tf.constant(15, name="a")This creates a new Constant Tensor with the name a that produces the value15. The name is optional but useful when you want to look at the generated graph, as we’ll see in just a moment.
But the question now is, where is our graph? I mean, we haven’t created a graph yet but we are already adding these operations. That’s because TensorFlow provides a default graph for the current thread that is an implicit argument to all API functions in the same context. In general, it’s enough to rely solely on the default graph. However, for advanced use cases we can also create multiple graphs.
Ok, now we can create another constant for b and also define our basic arithmetic operations, such as multiply, add, and divide. All of these operations are added automatically to the default graph.
That’s it! We completed the first step and constructed our computational graph. Now it’s time to compute the result. Remember, until now nothing has been evaluated and no actual numeric values have been assigned to any of those Tensors. What we have to do is to run the session to explicitly tell TensorFlow to execute the graph.
Ok, this one is easy. We already created a session object and all we have to do is to call sess.run(res) and pass along an operation (here res) that want to evaluate. This will only run as much of the computational graph as needed to compute the value for res. This means that in order to compute res we have to compute prod and sum as well as a and b. Finally, we can print the result, that is the Tensor returned by run().
Cool! Let’s export the graph and visualize it with TensorBoard:

This looks very familiar, doesn’t it?
By the way, TensorBoard is not only great for visualizing learning but also to look and debug your computational graphs, so definitely check it out.
Ok, enough theory! Let’s get straight into coding.
Implementing TensorFlow’s API from scratch
Our goal here is to mimic the basic operations from TensorFlow in order to mirror our simple program with our own API, just like we did a moment ago with TensorFlow.
Earlier, we learned about some of the core building block, such as Variable, Operation, or Graph. These are the building blocks we want to implement from scratch, so let’s get started.
Graph
The first missing piece is the graph. A Graph contains a set of Operation objects, which represent units of computation. In addition, a graph contains a set of Placeholder and Variable objects, which represent the units of data that flow between operations.
For our implementation we essentially need three lists to store all those objects. Furthermore, our graph needs a method called as_default which we can call to create a global variable that is used to store the current graph instance. This way, we don’t have to pass around the reference to the graph when creating operations, placeholders or variables.
So, here we go:

