The topology of Google’s TPU v4 and v5 supercomputers is formally a 3D Torus (and specifically a Twisted 3D Torus). This architecture is chosen to maximize bisection bandwidth and minimize latency for the collective communication patterns dominated by “All-Reduce” operations in Large Language Model (LLM) training.

Below is the mathematically rigorous explanation and the Python code to visualize it.

1. Mathematical Formalism: The 3D Torus Graph

Let the TPU cluster be represented as a graph .
The vertices represent the TPU chips (or slices). The total number of chips is .

The set of vertices is defined by the Cartesian coordinates:

In a standard 3D Mesh, edges only connect adjacent nodes to .
In a 3D Torus, we add “wrap-around” links connecting the boundary faces. The edges are defined as:

This means every node has exactly degree 6. For example, the neighbor in the positive -direction is:

The “Twisted” Torus

Google’s TPU v4/v5 uses a Twisted Torus. In a standard torus, the wrap-around link connects directly back to . In a twisted torus, the wrap-around link is permuted (shifted) to reduce the network diameter.

Mathematically, the wrap-around connection for the -dimension connects to:

where are “twist” or “shift” constants.

  • Effect: A packet traveling “straight” along the X-axis eventually wraps around to a different Y/Z coordinate. This turns the torus into a structure similar to a higher-dimensional Möbius strip, distributing traffic more evenly and reducing the average path length (diameter) significantly.

2. Theoretical Performance Metrics

Diameter (Latency Lower Bound)

The diameter is the maximum shortest path between any two nodes.

  • 3D Mesh:
  • 3D Torus: Because of the wrap-around, you never travel more than halfway across any dimension.
    • Result: Latency is effectively halved compared to a mesh.

Bisection Bandwidth (Scale-out Efficiency)

This is the most critical metric for AI. It is the minimum bandwidth crossing a cut that splits the network into two equal halves.

  • For a 2D Torus (TPU v2/v3) with chips, bisection bandwidth scales as .
  • For a 3D Torus (TPU v4/v5), the cut is a plane of area .
    • Result: As you scale to thousands of chips, the 3D torus offers vastly superior bandwidth for global operations like All-Reduce (gradient averaging).

3. Mapping AI Parallelism to the Axes

Training LLMs requires “3D Parallelism.” The TPU topology axes () physically map to these logical parallelism strategies:

  1. Data Parallelism (X-axis): Different chips process different batches of data. They must synchronize gradients globally. The ring-based All-Reduce algorithm runs efficiently along the X-axis rings.
  2. Tensor (Model) Parallelism (Y-axis): A single matrix multiplication is split across chips. This requires ultra-high bandwidth (frequent communication per layer). Neighbor-to-neighbor links in the Y-axis handle this.
  3. Pipeline Parallelism (Z-axis): Different layers of the neural network are placed on different chips (e.g., Layers 1-10 on Chip A, 11-20 on Chip B). Data flows in a “pipe” along the Z-axis.

4. Visualization Code

This Python script uses matplotlib to generate an interactive-style 3D wireframe of a TPU Torus. It visualizes the nodes and explicitly draws the wrap-around links (curved lines) to demonstrate the toroidal connectivity.

import matplotlib.pyplot as plt
import numpy as np
from itertools import product
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import matplotlib.patches as mpatches
 
def bezier_curve_3d(p0, p1, control_offset, n_points=30):
    """
    Generate a quadratic Bézier curve in 3D space.
    The control point is offset perpendicular to the line connecting p0 and p1.
    """
    p0, p1 = np.array(p0), np.array(p1)
    midpoint = (p0 + p1) / 2
    
    # Create control point by offsetting the midpoint
    control = midpoint + np.array(control_offset)
    
    t = np.linspace(0, 1, n_points)
    # Quadratic Bézier: B(t) = (1-t)²P0 + 2(1-t)tP1 + t²P2
    curve = np.outer((1-t)**2, p0) + np.outer(2*(1-t)*t, control) + np.outer(t**2, p1)
    return curve
 
 
def plot_tpu_torus_clean(X=3, Y=3, Z=3):
    """
    Clean visualization of TPU 3D Torus topology with curved wrap-around connections.
    """
    fig = plt.figure(figsize=(16, 14))
    ax = fig.add_subplot(111, projection='3d')
    
    # --- Color Scheme (softer, more distinct) ---
    COLORS = {
        'node': '#4A90D9',           # Soft blue for nodes
        'node_edge': '#2C5282',      # Darker blue edge
        'x_link': '#48BB78',         # Green - X axis
        'y_link': '#805AD5',         # Purple - Y axis  
        'z_link': '#ED8936',         # Orange - Z axis
        'x_wrap': '#276749',         # Dark green - X wrap
        'y_wrap': '#553C9A',         # Dark purple - Y wrap
        'z_wrap': '#C05621',         # Dark orange - Z wrap
    }
    
    # Generate node positions
    nodes = list(product(range(X), range(Y), range(Z)))
    xs, ys, zs = zip(*nodes)
    
    # Scaling factor for wrap-around curve height
    wrap_scale = max(X, Y, Z) * 0.6
    
    # --- Draw Internal Links (straight lines) ---
    for x, y, z in nodes:
        # X-axis internal links
        if x + 1 < X:
            ax.plot([x, x+1], [y, y], [z, z], 
                   color=COLORS['x_link'], alpha=0.5, linewidth=1.5, zorder=1)
        
        # Y-axis internal links
        if y + 1 < Y:
            ax.plot([x, x], [y, y+1], [z, z], 
                   color=COLORS['y_link'], alpha=0.5, linewidth=1.5, zorder=1)
        
        # Z-axis internal links
        if z + 1 < Z:
            ax.plot([x, x], [y, y], [z, z+1], 
                   color=COLORS['z_link'], alpha=0.5, linewidth=1.5, zorder=1)
    
    # --- Draw Wrap-Around Connections (curved lines showing torus) ---
    drawn_wraps = set()
    
    for x, y, z in nodes:
        # X-axis wrap-around (x=X-1 to x=0)
        if x == X - 1:
            key = ('x', y, z)
            if key not in drawn_wraps:
                p0, p1 = (x, y, z), (0, y, z)
                # Curve outward in the X direction
                offset = (wrap_scale, 0, 0)
                curve = bezier_curve_3d(p0, p1, offset)
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=COLORS['x_wrap'], alpha=0.7, linewidth=2, 
                       linestyle='--', zorder=2)
                drawn_wraps.add(key)
        
        # Y-axis wrap-around (y=Y-1 to y=0)
        if y == Y - 1:
            key = ('y', x, z)
            if key not in drawn_wraps:
                p0, p1 = (x, y, z), (x, 0, z)
                # Curve outward in the Y direction
                offset = (0, wrap_scale, 0)
                curve = bezier_curve_3d(p0, p1, offset)
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=COLORS['y_wrap'], alpha=0.7, linewidth=2,
                       linestyle='--', zorder=2)
                drawn_wraps.add(key)
        
        # Z-axis wrap-around (z=Z-1 to z=0)
        if z == Z - 1:
            key = ('z', x, y)
            if key not in drawn_wraps:
                p0, p1 = (x, y, z), (x, y, 0)
                # Curve outward in the Z direction
                offset = (0, 0, wrap_scale)
                curve = bezier_curve_3d(p0, p1, offset)
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=COLORS['z_wrap'], alpha=0.7, linewidth=2,
                       linestyle='--', zorder=2)
                drawn_wraps.add(key)
    
    # --- Draw Nodes (on top) ---
    ax.scatter(xs, ys, zs, c=COLORS['node'], s=200, 
              edgecolors=COLORS['node_edge'], linewidths=2, 
              alpha=0.9, zorder=10, depthshade=False)
    
    # Add node labels
    for x, y, z in nodes:
        ax.text(x, y, z + 0.15, f'({x},{y},{z})', fontsize=7, 
               ha='center', va='bottom', alpha=0.7)
    
    # --- Formatting ---
    ax.set_xlabel('X Axis\n(Data Parallelism)', fontsize=11, labelpad=10)
    ax.set_ylabel('Y Axis\n(Model Parallelism)', fontsize=11, labelpad=10)
    ax.set_zlabel('Z Axis\n(Pipeline Parallelism)', fontsize=11, labelpad=10)
    
    ax.set_title(f'TPU 3D Torus Topology ({X}×{Y}×{Z})\n'
                 f'Curved lines show wrap-around connections forming the torus',
                 fontsize=14, pad=20, fontweight='bold')
    
    # Set axis limits with padding for curves
    padding = wrap_scale * 0.3
    ax.set_xlim(-padding, X - 1 + wrap_scale + padding)
    ax.set_ylim(-padding, Y - 1 + wrap_scale + padding)
    ax.set_zlim(-padding, Z - 1 + wrap_scale + padding)
    
    # Clean up the plot
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False
    ax.xaxis.pane.set_edgecolor('lightgray')
    ax.yaxis.pane.set_edgecolor('lightgray')
    ax.zaxis.pane.set_edgecolor('lightgray')
    ax.grid(True, alpha=0.3, linestyle=':')
    
    # --- Legend ---
    legend_elements = [
        Line2D([0], [0], marker='o', color='w', markerfacecolor=COLORS['node'],
               markersize=12, markeredgecolor=COLORS['node_edge'], markeredgewidth=2,
               label='TPU Chip'),
        Line2D([0], [0], color=COLORS['x_link'], linewidth=2, label='X-Axis Link (Internal)'),
        Line2D([0], [0], color=COLORS['y_link'], linewidth=2, label='Y-Axis Link (Internal)'),
        Line2D([0], [0], color=COLORS['z_link'], linewidth=2, label='Z-Axis Link (Internal)'),
        Line2D([0], [0], color=COLORS['x_wrap'], linewidth=2, linestyle='--', 
               label='X-Axis Wrap (Torus)'),
        Line2D([0], [0], color=COLORS['y_wrap'], linewidth=2, linestyle='--',
               label='Y-Axis Wrap (Torus)'),
        Line2D([0], [0], color=COLORS['z_wrap'], linewidth=2, linestyle='--',
               label='Z-Axis Wrap (Torus)'),
    ]
    
    ax.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(0, 1),
             fontsize=9, framealpha=0.95)
    
    ax.view_init(elev=20, azim=45)
    plt.tight_layout()
    
    return fig, ax
 
 
def plot_torus_explanation():
    """
    Create a side-by-side explanation showing 1D ring, 2D torus surface, and 3D torus.
    """
    fig = plt.figure(figsize=(18, 6))
    
    # --- Panel 1: 1D Ring (simplest torus) ---
    ax1 = fig.add_subplot(131)
    n_nodes = 6
    theta = np.linspace(0, 2*np.pi, n_nodes, endpoint=False)
    x_ring = np.cos(theta)
    y_ring = np.sin(theta)
    
    # Draw connections
    for i in range(n_nodes):
        next_i = (i + 1) % n_nodes
        ax1.plot([x_ring[i], x_ring[next_i]], [y_ring[i], y_ring[next_i]], 
                'b-', linewidth=2, alpha=0.7)
    
    # Draw nodes
    ax1.scatter(x_ring, y_ring, c='#4A90D9', s=300, edgecolors='#2C5282', 
               linewidths=2, zorder=10)
    for i in range(n_nodes):
        ax1.annotate(f'{i}', (x_ring[i], y_ring[i]), ha='center', va='center',
                    fontsize=10, fontweight='bold', color='white')
    
    ax1.set_xlim(-1.5, 1.5)
    ax1.set_ylim(-1.5, 1.5)
    ax1.set_aspect('equal')
    ax1.axis('off')
    ax1.set_title('1D Torus (Ring)\n\nNode 5 connects back to Node 0\n→ No "edge" in the topology',
                 fontsize=11, pad=10)
    
    # --- Panel 2: 2D Torus concept ---
    ax2 = fig.add_subplot(132)
    
    # Draw a grid with wrap-around arrows
    grid_size = 4
    for i in range(grid_size):
        for j in range(grid_size):
            ax2.scatter(i, j, c='#4A90D9', s=200, edgecolors='#2C5282', 
                       linewidths=2, zorder=10)
            # Horizontal links
            if i < grid_size - 1:
                ax2.plot([i, i+1], [j, j], 'g-', linewidth=1.5, alpha=0.6)
            # Vertical links
            if j < grid_size - 1:
                ax2.plot([i, i], [j, j+1], 'purple', linewidth=1.5, alpha=0.6)
    
    # Draw wrap-around indicators
    for j in range(grid_size):
        # Right edge wraps to left
        ax2.annotate('', xy=(-0.3, j), xytext=(grid_size - 1 + 0.1, j),
                    arrowprops=dict(arrowstyle='->', color='green', lw=2,
                                   connectionstyle='arc3,rad=0.3'))
    for i in range(grid_size):
        # Top edge wraps to bottom
        ax2.annotate('', xy=(i, -0.3), xytext=(i, grid_size - 1 + 0.1),
                    arrowprops=dict(arrowstyle='->', color='purple', lw=2,
                                   connectionstyle='arc3,rad=-0.3'))
    
    ax2.set_xlim(-0.8, grid_size - 0.2)
    ax2.set_ylim(-0.8, grid_size - 0.2)
    ax2.set_aspect('equal')
    ax2.axis('off')
    ax2.set_title('2D Torus (Grid with Wrap-Around)\n\nRight edge → Left edge\n'
                 'Top edge → Bottom edge',
                 fontsize=11, pad=10)
    
    # --- Panel 3: 3D Torus explanation ---
    ax3 = fig.add_subplot(133, projection='3d')
    
    # Small 2x2x2 cube for clarity
    nodes = list(product(range(2), range(2), range(2)))
    xs, ys, zs = zip(*nodes)
    
    # Internal links
    for x, y, z in nodes:
        if x + 1 < 2:
            ax3.plot([x, x+1], [y, y], [z, z], 'g-', linewidth=2, alpha=0.6)
        if y + 1 < 2:
            ax3.plot([x, x], [y, y+1], [z, z], 'purple', linewidth=2, alpha=0.6)
        if z + 1 < 2:
            ax3.plot([x, x], [y, y], [z, z+1], 'orange', linewidth=2, alpha=0.6)
    
    # Wrap-around with curves
    wrap_scale = 0.8
    for y in range(2):
        for z in range(2):
            curve = bezier_curve_3d((1, y, z), (0, y, z), (wrap_scale, 0, 0))
            ax3.plot(curve[:, 0], curve[:, 1], curve[:, 2], 'g--', linewidth=2, alpha=0.7)
    for x in range(2):
        for z in range(2):
            curve = bezier_curve_3d((x, 1, z), (x, 0, z), (0, wrap_scale, 0))
            ax3.plot(curve[:, 0], curve[:, 1], curve[:, 2], 'purple', linestyle='--', 
                    linewidth=2, alpha=0.7)
    for x in range(2):
        for y in range(2):
            curve = bezier_curve_3d((x, y, 1), (x, y, 0), (0, 0, wrap_scale))
            ax3.plot(curve[:, 0], curve[:, 1], curve[:, 2], 'orange', linestyle='--',
                    linewidth=2, alpha=0.7)
    
    ax3.scatter(xs, ys, zs, c='#4A90D9', s=200, edgecolors='#2C5282', 
               linewidths=2, zorder=10, depthshade=False)
    
    ax3.set_xlabel('X')
    ax3.set_ylabel('Y')
    ax3.set_zlabel('Z')
    ax3.set_title('3D Torus (2×2×2)\n\nAll 3 axes wrap around\n→ Every node has 6 neighbors',
                 fontsize=11, pad=10)
    ax3.view_init(elev=20, azim=45)
    
    plt.suptitle('Understanding Torus Topology: From 1D to 3D', 
                fontsize=14, fontweight='bold', y=1.02)
    plt.tight_layout()
    
    return fig
 
 
def plot_single_axis_highlight(X=3, Y=3, Z=3, highlight_axis='x'):
    """
    Highlight connections along a single axis to reduce visual clutter.
    """
    fig = plt.figure(figsize=(14, 12))
    ax = fig.add_subplot(111, projection='3d')
    
    # Color scheme
    HIGHLIGHT_COLOR = {'x': '#48BB78', 'y': '#805AD5', 'z': '#ED8936'}
    WRAP_COLOR = {'x': '#276749', 'y': '#553C9A', 'z': '#C05621'}
    DIM_COLOR = '#E2E8F0'
    
    nodes = list(product(range(X), range(Y), range(Z)))
    xs, ys, zs = zip(*nodes)
    wrap_scale = max(X, Y, Z) * 0.5
    
    # Draw all internal links (dimmed)
    for x, y, z in nodes:
        for dx, dy, dz, axis in [(1,0,0,'x'), (0,1,0,'y'), (0,0,1,'z')]:
            nx, ny, nz = x + dx, y + dy, z + dz
            if 0 <= nx < X and 0 <= ny < Y and 0 <= nz < Z:
                color = HIGHLIGHT_COLOR[axis] if axis == highlight_axis else DIM_COLOR
                alpha = 0.8 if axis == highlight_axis else 0.2
                lw = 2.5 if axis == highlight_axis else 1
                ax.plot([x, nx], [y, ny], [z, nz], color=color, alpha=alpha, linewidth=lw)
    
    # Draw wrap-around connections
    drawn = set()
    for x, y, z in nodes:
        if highlight_axis == 'x' and x == X - 1:
            key = ('x', y, z)
            if key not in drawn:
                curve = bezier_curve_3d((x, y, z), (0, y, z), (wrap_scale, 0, 0))
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=WRAP_COLOR['x'], alpha=0.9, linewidth=3, linestyle='--')
                drawn.add(key)
        elif highlight_axis == 'y' and y == Y - 1:
            key = ('y', x, z)
            if key not in drawn:
                curve = bezier_curve_3d((x, y, z), (x, 0, z), (0, wrap_scale, 0))
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=WRAP_COLOR['y'], alpha=0.9, linewidth=3, linestyle='--')
                drawn.add(key)
        elif highlight_axis == 'z' and z == Z - 1:
            key = ('z', x, y)
            if key not in drawn:
                curve = bezier_curve_3d((x, y, z), (x, y, 0), (0, 0, wrap_scale))
                ax.plot(curve[:, 0], curve[:, 1], curve[:, 2],
                       color=WRAP_COLOR['z'], alpha=0.9, linewidth=3, linestyle='--')
                drawn.add(key)
    
    # Draw nodes
    ax.scatter(xs, ys, zs, c='#4A90D9', s=180, edgecolors='#2C5282', 
              linewidths=2, alpha=0.9, zorder=10, depthshade=False)
    
    axis_names = {'x': 'X-Axis (Data Parallelism)', 
                  'y': 'Y-Axis (Model Parallelism)', 
                  'z': 'Z-Axis (Pipeline Parallelism)'}
    
    ax.set_xlabel('X', fontsize=11)
    ax.set_ylabel('Y', fontsize=11)
    ax.set_zlabel('Z', fontsize=11)
    ax.set_title(f'TPU Torus: {axis_names[highlight_axis]} Highlighted\n'
                f'Dashed curves show wrap-around connections',
                fontsize=14, pad=20, fontweight='bold')
    
    # Clean up
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False
    ax.grid(True, alpha=0.3, linestyle=':')
    ax.view_init(elev=20, azim=45)
    
    plt.tight_layout()
    return fig, ax
 
 
def create_all_visualizations():
    """Generate all visualization figures."""
    
    print("Generating TPU Torus visualizations...")
    
    # 1. Main clean visualization
    fig1, _ = plot_tpu_torus_clean(3, 3, 3)
    fig1.savefig('/home/claude/tpu_torus_main.png', dpi=150, bbox_inches='tight',
                facecolor='white', edgecolor='none')
    print("✓ Main visualization saved")
    
    # 2. Explanation panel
    fig2 = plot_torus_explanation()
    fig2.savefig('/home/claude/tpu_torus_explanation.png', dpi=150, bbox_inches='tight',
                facecolor='white', edgecolor='none')
    print("✓ Explanation panel saved")
    
    # 3. Single-axis highlights
    for axis in ['x', 'y', 'z']:
        fig, _ = plot_single_axis_highlight(3, 3, 3, axis)
        fig.savefig(f'/home/claude/tpu_torus_highlight_{axis}.png', dpi=150, 
                   bbox_inches='tight', facecolor='white', edgecolor='none')
        plt.close(fig)
    print("✓ Axis highlight visualizations saved")
    
    plt.close('all')
    print("\nAll visualizations complete!")
 
 
if __name__ == "__main__":
    create_all_visualizations()

Interpretation of the Visual

When you run the code:

  1. Blue Dots: Represent individual TPU chips.
  2. Gray Lines: Represent the standard “mesh” connections. A chip connects to its immediate neighbor .
  3. Red Dashed Lines: Represent the Torus Wraparounds.
    • Notice how the chip at the far right connects directly back to the far left .
    • In a real “Twisted Torus,” this red line would not go to but perhaps to , creating a spiraling effect through the volume.

This interconnect graph is the physical foundation that allows models like Gemini and GPT to scale, as mathematical operations (matrix multiplies) are literally mapped onto this 3D coordinate system.