Manim is a powerful Python library for creating mathematical animations, made famous by 3Blue1Brown. This tutorial will introduce Manim’s basics and guide you through visualizing neural network architectures and their forward-pass computations. We will cover core Manim concepts (Scenes, Mobjects, Animations), then build static and animated neural network diagrams, illustrate tensor flow through the network, and discuss advanced tips for customization and performance. Each section includes runnable Python code examples for clarity.

Basic Concepts of Manim

Overview of Manim’s Structure: Manim organizes animations using Scenes, Mobjects, and Animations (Manim’s building blocks - Manim Community v0.19.0). A Scene is essentially the canvas or timeline for your animation – you create a Scene by subclassing Scene and writing a construct() method that defines what happens (Scene - Manim Community v0.19.0). Within a scene, you generate Mobjects (mathematical objects) like shapes or text, and use Animations to bring them to life. Manim orchestrates these to produce the final video.

Scenes, Mobjects, and Animations: Mobjects (short for mathematical objects) are any onscreen items: shapes (circles, rectangles), text, images, etc. For example, classes like Circle, Square, Dot, Text all produce Mobjects you can display (Manim’s building blocks - Manim Community v0.19.0). You typically add Mobjects to a Scene with self.add(mobject) or animate them with self.play(animation). An Animation in Manim is a transformation or action applied to Mobjects over time – such as moving, fading, or transforming one shape into another. Common animations include Create (draw an object), Write (write letters of a Text), FadeIn/FadeOut, Transform, etc. Manim provides many built-in animations for different effects.

Basic Example – Rendering a Shape and Text: Let’s create a simple scene that draws a circle and then writes some text. We’ll define a Scene subclass and use self.play to animate the objects:

from manim import *
 
class BasicScene(Scene):
    def construct(self):
        # Create a circle mobject and set its style
        circle = Circle(radius=1.0, color=BLUE)               # a circle of radius 1
        circle.set_fill(BLUE, opacity=0.5)                    # fill with semi-transparent blue
 
        # Create a text mobject
        text = Text("Hello, Manim!", font_size=48)
        text.next_to(circle, RIGHT + UP)                      # position text relative to circle
 
        # Animate the circle and text
        self.play(Create(circle))                             # draw the circle
        self.play(Write(text))                                # write the text
        self.wait(1)                                          # pause for a second

Running this scene (for example with manim -pql your_script.py BasicScene) will produce an animation where a blue circle is drawn, then the text “Hello, Manim!” appears next to it. In this code:

  • We created a Circle and a Text – both are Mobjects added to the scene.
  • We used Create(circle) to animate the drawing of the circle and Write(text) to animate writing the text on screen.
  • The self.play(...) method queues these animations in sequence on the scene (Scene - Manim Community v0.19.0). Finally, self.wait(1) keeps the final frame on screen for 1 second.

This basic example demonstrates the typical structure of Manim code: define Mobjects, add or animate them in a Scene. Next, we’ll apply these fundamentals to visualizing a neural network.

Visualizing Neural Network Architectures

A neural network can be visualized as layers of nodes (neurons) connected by edges (weights). Using Manim, we can create static diagrams of feedforward neural networks and even animate them. We’ll represent neurons as small circles (or dots) and connections as lines or arrows. Let’s construct a simple feedforward network diagram with an input layer, one hidden layer, and an output layer.

(python - creating deep neural network with text of code next to it using manim - Stack Overflow) An example of a feedforward neural network diagram: neurons are drawn as circles in layers (input, hidden, output), and connections between them are shown as lines. Manim can be used to programmatically create such network visualizations.

Creating Nodes (Neurons) and Layers: We can use Manim’s shape primitives to represent neurons. For example, Dot() creates a small filled circle which is useful as a neuron marker. We’ll arrange dots in columns for each layer. Manim’s VGroup and arrange methods help in positioning multiple mobjects. In the code below, we define layer sizes and automatically generate positioned dots for each layer:

from manim import *
 
class NetworkDiagram(Scene):
    def construct(self):
        # Define the network layer structure, e.g., 3 neurons -> 4 neurons -> 2 neurons
        layer_sizes = [3, 4, 2]  
        layer_positions = []  # will hold the Dot mobjects for each layer
 
        # Create neurons for each layer
        for i, layer_size in enumerate(layer_sizes):
            layer = VGroup()  # group of neurons in this layer
            for j in range(layer_size):
                neuron = Dot(radius=0.15, color=WHITE)
                # Position neurons vertically with some spacing
                neuron.set_y((layer_size - 1) * 0.5 - j * 1.0)  # center the layer at y=0
                layer.add(neuron)
            # Position the layer horizontally apart
            layer.shift(RIGHT * i * 2.5) 
            layer_positions.append(layer)
            self.add(layer)
        
        # Add layer labels underneath (optional for clarity)
        labels = ["Input Layer", "Hidden Layer", "Output Layer"]
        for layer, label in zip(layer_positions, labels):
            text = Text(label, font_size=24).next_to(layer, DOWN)
            self.add(text)

In this snippet, we specified layer_sizes = [3, 4, 2] for a 3-node input layer, 4-node hidden layer, and 2-node output layer. We then looped through each layer index i:

  • Created a VGroup of Dot objects.
  • Positioned each dot in the group vertically (set_y) so that the layer is centered (the first neuron is at a positive y, last at negative y).
  • Shifted each whole layer group to the right by some amount to separate layers horizontally.

After this loop, we have the neurons placed in three columns. We also added text labels below each layer for clarity (“Input Layer”, etc.). At this point, running the scene would show the neurons and labels, but no connections yet.

Drawing Connections (Edges) between Neurons: To represent weighted connections, we can draw lines or arrows between neurons of adjacent layers. For simplicity, we’ll use Line to connect every neuron in one layer to every neuron in the next (fully connected layers). We can style these lines (e.g., thinner lines for clarity). Here’s how to add connections:

        # ... (continuing from previous code within construct)
        # Draw connection lines between adjacent layers
        for layer_index in range(len(layer_positions) - 1):
            layer_a = layer_positions[layer_index]
            layer_b = layer_positions[layer_index + 1]
            for neuron_a in layer_a:
                for neuron_b in layer_b:
                    connection = Line(neuron_a.get_center(), neuron_b.get_center(), stroke_width=2)
                    connection.set_color(GREY)
                    self.add(connection)

This double loop goes through each neuron in layer A and each neuron in layer B, and draws a line from neuron A’s center to neuron B’s center. We set a gray color for the connections to distinguish them from the white neuron dots. The result is a static network graph. You could replace Line with Arrow if you want directed arrows; Manim’s Arrow class can automatically include arrowheads and has a buff parameter to pad space so arrow tips don’t overlap the nodes.

Styling and Formatting: Manim allows extensive styling to improve clarity:

  • You can color-code different layers or use shapes: e.g., use a different color for input vs output nodes.
  • Adjust stroke_width or color of connections to indicate weight magnitude (thicker line for larger weight).
  • Add labels on connections to show weight values. For example, Manim provides LabeledArrow which attaches a text label along an arrow (Using Manim and Python to Create Animations Like 3Blue1Brown). You could use it to place a weight value (like “0.8”) mid-connection for documentation.

For instance, to label one of the connections we drew above, you could do:

label = MathTex("w_{ij}=0.8")
labeled_conn = LabeledLine(neuron_a.get_center(), neuron_b.get_center(), label_text=label)

This isn’t fully integrated in our loop (to avoid clutter), but demonstrates how you might annotate a graph.

Animating the Network Diagram: So far we just added mobjects (neurons, lines) statically. We can animate the construction of the network to make it more engaging:

  • Animate each layer’s appearance with a fade-in or creation animation.
  • Animate drawing the connections using Create(connection) for each line (perhaps staggered or layer-by-layer).

For example, to animate layer by layer:

for layer in layer_positions:
    self.play(FadeIn(layer))
    self.wait(0.5)
# then animate connections similarly, e.g., in groups or individually

However, be mindful that animating every line individually in a dense network can be slow. You might group connections and animate a group at once for efficiency.

Using Pre-built Neural Network Mobjects: Manim doesn’t natively have a “NeuralNetwork” object, but the community-developed ManimML library offers convenient abstractions. With ManimML, you can create a network with a single call, e.g.:

from manim_ml.neural_network import NeuralNetwork, FeedForwardLayer
nn = NeuralNetwork([
    FeedForwardLayer(num_nodes=3),
    FeedForwardLayer(num_nodes=5),
    FeedForwardLayer(num_nodes=3)
])
self.add(nn)

This would automatically construct a 3–5–3 network for you (GitHub - helblazer811/ManimML: ManimML is a project focused on providing animations and visualizations of common machine learning concepts with the Manim Community Library.). It even provides methods to animate the forward pass, which we’ll discuss next. If you prefer not to install additional packages, the manual approach we illustrated is fully workable.

By the end of this section, you should be able to generate a diagram of a neural network architecture. Next, we’ll bring this diagram to life by visualizing a forward pass of data through the network.

Visualizing Forward Pass Computation

Now that we can draw a neural network, the next step is to animate how data (tensors) flows through it during a forward pass. This involves showing activations propagating from the input layer to the output layer, applying weights and activation functions at each step. We’ll demonstrate techniques to visualize this, such as moving “activation dots” along connections and updating neuron values in real-time.

Displaying Tensors Moving Through Layers: A simple yet effective visualization is to use small colored dots or flashes traveling along the connections to represent signals or tensor values moving from one layer to the next. Manim’s animations make this straightforward:

  • We can create a tiny dot (say in a bright color like yellow) at a neuron and animate it moving to a neuron in the next layer using MoveAlongPath.
  • Alternatively, use ShowPassingFlash on a line to briefly highlight it, simulating a pulse.

For example, to animate a pulse from one neuron to another:

# Assume neuron_a and neuron_b are Dot objects from layer A and B respectively
pulse = Dot(radius=0.05, color=YELLOW).move_to(neuron_a.get_center())
self.play(MoveAlongPath(pulse, Line(neuron_a.get_center(), neuron_b.get_center())), run_time=0.5)
self.remove(pulse)  # remove the pulse dot after moving

This will create a small yellow dot at neuron A’s position and slide it along a line to neuron B over 0.5 seconds. You could repeat or generalize this for all connections. Doing so for every single connection in a fully connected layer might be overkill; often it’s sufficient to show one neuron’s outputs or highlight a few example paths for clarity.

Illustrating Activation Functions and Transformations: As the data reaches a neuron in the next layer, it gets transformed by a weighted sum and activation function. To visualize this, you might:

  • Display the numerical value that each neuron computes.
  • Change the color or size of a neuron to reflect the magnitude of its activation (e.g., a brighter fill for higher activation).
  • Show a brief formula or text when applying the activation (like a sigma “σ” for a sigmoid or “ReLU” text near a neuron).

For instance, we can attach a text label to each neuron showing its current value. Initially, these could be zeros or inputs, then update them as values propagate. Here’s an example with a small network forward pass, updating text values:

from manim import *
 
class ForwardPassScene(Scene):
    def construct(self):
        # Simple 2-2-1 network
        inputs = [0.5, 0.8]  # example input values
        W1 = [[0.7, -1.2], [0.5, 0.1]]  # weights from input to hidden (2x2 matrix)
        b1 = [0.0, 0.0]                # biases for hidden layer
        W2 = [1.0, -0.5]              # weights from hidden to output (1x2 vector)
        b2 = 0.0                      # bias for output
 
        # Create input layer dots and value labels
        input_layer = VGroup(*[Dot(radius=0.15) for _ in inputs]).arrange(DOWN, buff=1)
        input_layer.shift(LEFT*2)
        input_texts = VGroup(*[Text(f"{val:.1f}", font_size=36).next_to(dot, LEFT) 
                                for val, dot in zip(inputs, input_layer)])
        self.add(input_layer, input_texts)
 
        # Create hidden layer dots and initialize labels to 0
        hidden_layer = VGroup(*[Dot(radius=0.15) for _ in range(2)]).arrange(DOWN, buff=1)
        hidden_layer.shift(RIGHT*0)  # center
        hidden_texts = VGroup(*[Text("0.0", font_size=36).next_to(dot, LEFT) 
                                for dot in hidden_layer])
        self.add(hidden_layer, hidden_texts)
 
        # Create output layer dot and label
        output_layer = Dot(radius=0.15).shift(RIGHT*2)
        output_text = Text("0.0", font_size=36).next_to(output_layer, LEFT)
        self.add(output_layer, output_text)
 
        # Draw connections (for visualization, we’ll animate pulses on these)
        connections = []
        for inp in input_layer:
            for hid in hidden_layer:
                conn = Line(inp.get_center(), hid.get_center(), color=GREY)
                connections.append(conn)
                self.add(conn)
        for hid in hidden_layer:
            conn = Line(hid.get_center(), output_layer.get_center(), color=GREY)
            connections.append(conn)
            self.add(conn)
 
        # Animate forward pass: input -> hidden
        hidden_values = []
        for j, hid in enumerate(hidden_layer):
            # compute weighted sum for this hidden neuron
            z = inputs[0]*W1[j][0] + inputs[1]*W1[j][1] + b1[j]
            hidden_values.append(z)
            # animate pulses from each input to this hidden neuron
            for i, inp in enumerate(input_layer):
                pulse = Dot(radius=0.05, color=YELLOW).move_to(inp.get_center())
                self.play(MoveAlongPath(pulse, Line(inp.get_center(), hid.get_center())), run_time=0.3)
                self.remove(pulse)
            # update hidden neuron value text (after activation, say ReLU)
            activated = max(0, z)  # ReLU activation
            new_text = Text(f"{activated:.1f}", font_size=36).next_to(hid, LEFT)
            self.play(Transform(hidden_texts[j], new_text))
        
        # Animate forward pass: hidden -> output
        output_value = hidden_values[0]*W2[0] + hidden_values[1]*W2[1] + b2
        # pulses from each hidden neuron to output
        for hid in hidden_layer:
            pulse = Dot(radius=0.05, color=YELLOW).move_to(hid.get_center())
            self.play(MoveAlongPath(pulse, Line(hid.get_center(), output_layer.get_center())), run_time=0.3)
            self.remove(pulse)
        # activation (identity in this case) and update output text
        new_out_text = Text(f"{output_value:.1f}", font_size=36).next_to(output_layer, LEFT)
        self.play(Transform(output_text, new_out_text))
        self.wait(2)

This code sets up a very simple 2-input, 2-hidden, 1-output network with some made-up weights. It then:

  • Shows input values next to input neurons.
  • Initializes hidden and output values to “0.0”.
  • Animates small yellow dots traveling from each input neuron to each hidden neuron to represent the weighted contributions.
  • Calculates the hidden neuron values (using a ReLU activation for illustration), and updates the hidden neuron text labels with the new values (using Transform to smoothly change the text).
  • Repeats the process from hidden to output: pulses along connections and updating the output value text.

The result is an animation where you can see the numbers “0.5” and “0.8” feed into the hidden layer, producing some new values, which then feed into the output, resulting in an output value. While this example is rudimentary (and the network is not learning, just a single forward pass), it demonstrates how you can show real-time changes in tensor values during forward propagation. In practice, you could extend this with more layers or even loop through multiple time steps or inputs.

Note: Instead of manually computing activations as above, you could integrate a library like NumPy or PyTorch to do the math. For example, you might use NumPy arrays for matrix multiplication or a trained PyTorch model to generate activations and then use those in your Manim animation. This brings us to using external libraries and advanced tips.

Advanced Features and Best Practices

Finally, let’s discuss some advanced Manim capabilities and best practices that will help you create complex neural network visualizations more effectively.

Customizing Animations for Clarity: Manim offers a variety of animations and parameters to fine-tune your visualization:

  • Transformations: Use Transform or ReplacementTransform to smoothly change one mobject into another (we used this to change numeric text). You can also morph shapes (e.g., transform a node into a highlighted version).
  • Highlighting: Use animations like Indicate(mobject) to momentarily highlight a mobject (it flashes a color) or Wiggle(mobject) to draw attention.
  • Timing and Easing: Control the duration of animations with run_time and how the rate of change feels with rate_func (e.g., linear, smooth, there-and-back). Slowing down key moments (like a particular weight update) can help viewers catch important details.
  • Grouping: If you have many objects to animate similarly, group them (VGroup or Group) and animate the group. This can simplify code and ensure synchronization (e.g., fading out a whole layer at once).

Optimizing Performance for Complex Scenes: Visualizing an entire neural network with hundreds of connections can be performance-heavy. Here are some tips:

Dynamic Updates with External Libraries (NumPy/PyTorch): One of Manim’s strengths is that it’s just Python – you can integrate calculations from other libraries directly. For example, you could use NumPy to generate data for an animation (perhaps the outputs of each layer at each frame) or even run a PyTorch model inside your scene to get results to display. Two mechanisms are particularly useful here:

  • Precompute then Animate: Do heavy computations (like running a neural network on a dataset) before constructing the scene, and store the results. Then use those results in your animations (as we did by computing hidden_values and then animating them). This way, Manim isn’t trying to do large computations during rendering.
  • Updaters and Trackers: Manim provides ValueTracker objects to track numeric values over time (ValueTracker - Manim Community v0.19.0), and updaters which let a Mobject update its state on each frame. For instance, you can link a number mobject to a ValueTracker so that as the tracker’s value changes, the number displayed updates continuously (Variable - Manim Community v0.19.0). This is great for showing metrics like a loss value decreasing during training, or weights changing over iterations.

Example – Dynamic Value Update: Suppose you want to display a live-updating loss value during training. You could do:

class TrainingViz(Scene):
    def construct(self):
        loss_tracker = ValueTracker(1.0)  # start with loss = 1.0
        loss_text = Text("Loss: ").to_corner(UP+LEFT)
        # DecimalNumber to display the value with two decimals
        loss_number = DecimalNumber(loss_tracker.get_value(), num_decimal_places=2)
        loss_number.next_to(loss_text, RIGHT)
        # Make the number update with the tracker
        loss_number.add_updater(lambda m: m.set_value(loss_tracker.get_value()))
        self.add(loss_text, loss_number)
        # Animate the loss decreasing
        self.play(loss_tracker.animate.set_value(0.05), run_time=4, rate_func=smooth)
        self.wait()

In this snippet, loss_number is tied to loss_tracker via an updater. As we animate the tracker’s value from 1.0 to 0.05 over 4 seconds, the displayed number smoothly counts down, thanks to the updater. We didn’t explicitly re-add or transform the text each frame – Manim’s updater took care of it. Updaters are extremely useful for reflecting continuous changes without manually animating every frame.

Integration with ML frameworks: You can similarly integrate PyTorch or TensorFlow for real model predictions. For example, you might load a trained model and for each layer, extract the activations for a given input, then use Manim to display those activations (as numbers or perhaps a heatmap). Just remember to keep these computations efficient – if you call a heavy model inside an updater every frame, it will slow things down. Often it’s better to compute a sequence of outputs and then animate them as a precomputed list.

Summing up: We covered a lot of ground – from the basics of creating shapes and text in Manim, to drawing neural network architectures, to animating a forward pass with tensor values, and finally some advanced tips for customization and performance. With these tools, you can create clear and engaging visualizations of neural networks and their computations. Experiment with the code examples provided, and tweak styles and animations to suit your story. Happy animating!

References:

  1. Manim Community Documentation – Building Blocks (Mobjects, Animations, Scenes) (Manim’s building blocks - Manim Community v0.19.0) (Manim’s building blocks - Manim Community v0.19.0)
  2. Manim Community Documentation – Scene Class (structure of Scenes) (Scene - Manim Community v0.19.0) (Scene - Manim Community v0.19.0)
  3. Manim Community Documentation – Quickstart Example (Circle and Transform) (Quickstart - Manim Community v0.19.0) (Quickstart - Manim Community v0.19.0)
  4. Manim Community Documentation – LabeledArrow for labeling connections (Using Manim and Python to Create Animations Like 3Blue1Brown)
  5. Helblazer811 – ManimML Library (NeuralNetwork and FeedForwardLayer usage) (GitHub - helblazer811/ManimML: ManimML is a project focused on providing animations and visualizations of common machine learning concepts with the Manim Community Library.) (GitHub - helblazer811/ManimML: ManimML is a project focused on providing animations and visualizations of common machine learning concepts with the Manim Community Library.)
  6. Stack Overflow – Neural network Manim visualization with forward pass animation (python - creating deep neural network with text of code next to it using manim - Stack Overflow) (python - creating deep neural network with text of code next to it using manim - Stack Overflow)
  7. Manim Community Documentation – ValueTracker and Variable for dynamic values (ValueTracker - Manim Community v0.19.0) (Variable - Manim Community v0.19.0)
  8. Helblazer811 – ManimML Guide (quality settings for rendering)