|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# NOTE: This test/benchmark requires a multislice TPU setup to run correctly. |
| 16 | +# It is excluded from standard pytest discovery. |
| 17 | + |
| 18 | +"""A microbenchmark to test DCN network bandwidth using shard map. |
| 19 | +
|
| 20 | +This script should be run on a multi-slice TPU cluster (specifically across 2 slices |
| 21 | +with any ICI/slice dimensions |
| 22 | +""" |
| 23 | + |
| 24 | +import datetime |
| 25 | +import functools |
| 26 | +import subprocess |
| 27 | +from types import SimpleNamespace |
| 28 | + |
| 29 | +import jax |
| 30 | +from jax.experimental import mesh_utils |
| 31 | +from jax.experimental.shard_map import shard_map |
| 32 | +import jax.numpy as jnp |
| 33 | +from jax.sharding import Mesh |
| 34 | +from jax.sharding import PartitionSpec as P |
| 35 | + |
| 36 | +from maxtext.utils import train_utils |
| 37 | + |
| 38 | + |
| 39 | +def get_default_interface(): |
| 40 | + try: |
| 41 | + route_output = subprocess.check_output("ip route show", shell=True, text=True) |
| 42 | + for line in route_output.splitlines(): |
| 43 | + if "default" in line: |
| 44 | + return line.split("dev")[1].strip().split()[0] |
| 45 | + except (subprocess.SubprocessError, IndexError): |
| 46 | + pass |
| 47 | + return "eth0" |
| 48 | + |
| 49 | + |
| 50 | +def simple_timeit(f, *args, tries=10, task=None): |
| 51 | + """Simple utility to time a function for multiple runs.""" |
| 52 | + assert task is not None |
| 53 | + outcomes_ms = [] |
| 54 | + |
| 55 | + # Warm up |
| 56 | + jax.block_until_ready(f(*args)) |
| 57 | + |
| 58 | + for _ in range(tries): |
| 59 | + jax.devices() # Force synchronization |
| 60 | + s = datetime.datetime.now() |
| 61 | + jax.block_until_ready(f(*args)) |
| 62 | + e = datetime.datetime.now() |
| 63 | + outcomes_ms.append(1000 * (e - s).total_seconds()) |
| 64 | + |
| 65 | + average_time_ms = sum(outcomes_ms) / len(outcomes_ms) |
| 66 | + return average_time_ms |
| 67 | + |
| 68 | + |
| 69 | +def create_mesh(dcn_size: int, ici_size: int): |
| 70 | + """Creates a hybrid mesh with DCN and ICI axes.""" |
| 71 | + dcn_parallelism = [dcn_size, 1] |
| 72 | + ici_parallelism = [1, ici_size] |
| 73 | + |
| 74 | + total_devices = jax.device_count() |
| 75 | + if total_devices != (dcn_size * ici_size): |
| 76 | + raise ValueError(f"Need {dcn_size * ici_size} devices, but found {total_devices}") |
| 77 | + mesh_devices = mesh_utils.create_hybrid_device_mesh(ici_parallelism, dcn_parallelism, devices=jax.devices()) |
| 78 | + mesh = Mesh(mesh_devices, ("dcn", "ici")) |
| 79 | + return mesh |
| 80 | + |
| 81 | + |
| 82 | +def run_dcn_benchmark(case=None, limit=None, burst=None, latency="50ms"): |
| 83 | + """Runs the DCN bandwidth benchmark for specified throttling cases.""" |
| 84 | + print(f"JAX process index: {jax.process_index()} / {jax.process_count()}") |
| 85 | + print(f"Total devices: {jax.device_count()}, local devices: {jax.local_device_count()}") |
| 86 | + |
| 87 | + dcn_size = 2 |
| 88 | + total_devices = jax.device_count() |
| 89 | + if total_devices % dcn_size != 0: |
| 90 | + raise ValueError(f"Total devices ({total_devices}) must be divisible by dcn_size ({dcn_size}) for 2-slice setup.") |
| 91 | + ici_size = total_devices // dcn_size |
| 92 | + mesh = create_mesh(dcn_size, ici_size) |
| 93 | + |
| 94 | + # Predefined cases |
| 95 | + all_cases = [ |
| 96 | + ("none", "NO THROTTLING (Baseline)", False, None, None), |
| 97 | + ("100g", "100G Throttling", True, "100gbit", "600mb"), |
| 98 | + ("50g", "50G Throttling", True, "50gbit", "300mb"), |
| 99 | + ] |
| 100 | + |
| 101 | + # Filter based on arguments if requested |
| 102 | + if case: |
| 103 | + cases_to_run = [c for c in all_cases if c[0] == case] |
| 104 | + if not cases_to_run: |
| 105 | + # If custom limit/burst are provided |
| 106 | + if limit and burst: |
| 107 | + cases_to_run = [(case, f"CUSTOM Throttling ({case})", True, limit, burst)] |
| 108 | + else: |
| 109 | + raise ValueError(f"Unknown case: {case}") |
| 110 | + else: |
| 111 | + cases_to_run = all_cases |
| 112 | + |
| 113 | + # Qwen3-30B MoE layer weight shape: (128, 2048, 768) |
| 114 | + shape = (128, 2048, 768) |
| 115 | + dtype = jnp.bfloat16 |
| 116 | + |
| 117 | + # Calculate size |
| 118 | + num_elements = 1 |
| 119 | + for d in shape: |
| 120 | + num_elements *= d |
| 121 | + matrix_size_gbyte = num_elements * dtype.dtype.itemsize / 1e9 |
| 122 | + |
| 123 | + # We define shard map collective psum along the DCN axis. |
| 124 | + # Input x is sharded across 'dcn' axis. |
| 125 | + @functools.partial(shard_map, mesh=mesh, in_specs=P("dcn", None, None), out_specs=P(None, None, None)) |
| 126 | + def psum_dcn_op(x): |
| 127 | + return jax.lax.psum(x, "dcn") |
| 128 | + |
| 129 | + # Initialize matrix |
| 130 | + matrix = jnp.ones(shape, dtype=dtype) |
| 131 | + |
| 132 | + # Pre-distribute the matrix shard onto devices |
| 133 | + sharded_matrix = jax.device_put(matrix, jax.sharding.NamedSharding(mesh, P("dcn", None, None))) |
| 134 | + |
| 135 | + jitted_op = jax.jit(psum_dcn_op) |
| 136 | + |
| 137 | + interface = get_default_interface() |
| 138 | + |
| 139 | + for _, name, apply_throttling, dcn_limit, dcn_burst in cases_to_run: |
| 140 | + if jax.process_index() == 0: |
| 141 | + print("\n==================================================") |
| 142 | + print(f"Running Case: {name}") |
| 143 | + if apply_throttling: |
| 144 | + print(f" Throttling Config: limit={dcn_limit}, burst={dcn_burst}, latency={latency}") |
| 145 | + print("==================================================") |
| 146 | + |
| 147 | + if apply_throttling: |
| 148 | + config = SimpleNamespace( |
| 149 | + dcn_bandwidth_limit=dcn_limit, |
| 150 | + dcn_bandwidth_burst=dcn_burst, |
| 151 | + dcn_bandwidth_latency=latency, |
| 152 | + dcn_bandwidth_interface=interface, |
| 153 | + ) |
| 154 | + train_utils.maybe_apply_dcn_throttling(config) |
| 155 | + else: |
| 156 | + config = None |
| 157 | + |
| 158 | + try: |
| 159 | + # Sync before starting benchmark |
| 160 | + jax.block_until_ready(jax.device_put(0.0) + 1.0) |
| 161 | + |
| 162 | + if jax.process_index() == 0: |
| 163 | + print(f"Starting benchmark for shape: {shape} ({matrix_size_gbyte * 1000:.1f} MB)") |
| 164 | + |
| 165 | + # Run time test |
| 166 | + time_ms = simple_timeit(jitted_op, sharded_matrix, task=f"psum_dcn_{shape}") |
| 167 | + |
| 168 | + # Calculate Bandwidth |
| 169 | + achieved_bandwidth_gbyte_s = matrix_size_gbyte * (dcn_size - 1) * 2 / dcn_size / dcn_size / (time_ms / 1e3) |
| 170 | + achieved_bandwidth_gbps = achieved_bandwidth_gbyte_s * 8.0 |
| 171 | + |
| 172 | + if jax.process_index() == 0: |
| 173 | + print(f"Results for {name}:") |
| 174 | + print(f" Avg Latency: {time_ms:.2f} ms") |
| 175 | + print( |
| 176 | + f" Achieved DCN Bandwidth: {achieved_bandwidth_gbyte_s:.3f} GB/s ({achieved_bandwidth_gbps:.2f} Gbps) per slice" |
| 177 | + ) |
| 178 | + finally: |
| 179 | + if apply_throttling and config: |
| 180 | + if jax.process_index() == 0: |
| 181 | + print(f"Cleaning up throttling for {name}...") |
| 182 | + train_utils.maybe_cleanup_dcn_throttling(config) |
| 183 | + |
| 184 | + # Sync after cleanup |
| 185 | + jax.block_until_ready(jax.device_put(0.0) + 1.0) |
| 186 | + |
| 187 | + |
| 188 | +if __name__ == "__main__": |
| 189 | + import argparse |
| 190 | + |
| 191 | + parser = argparse.ArgumentParser(description="DCN Bandwidth Benchmark") |
| 192 | + parser.add_argument( |
| 193 | + "--case", choices=["none", "100g", "50g"], help="Predefined throttling case (optional, runs all if omitted)" |
| 194 | + ) |
| 195 | + parser.add_argument("--limit", help="Custom DCN bandwidth limit (e.g. 100gbit)") |
| 196 | + parser.add_argument("--burst", help="Custom DCN bandwidth burst (e.g. 600mb)") |
| 197 | + parser.add_argument("--latency", default="50ms", help="DCN bandwidth latency (default: 50ms)") |
| 198 | + parsed_args = parser.parse_args() |
| 199 | + |
| 200 | + run_dcn_benchmark(case=parsed_args.case, limit=parsed_args.limit, burst=parsed_args.burst, latency=parsed_args.latency) |
0 commit comments