|
| 1 | +"""Benchmarks Host-to-Device and Device-to-Host transfer performance (Simple Baseline).""" |
| 2 | + |
| 3 | +import time |
| 4 | +import os |
| 5 | +from typing import Any, Dict, Tuple, List |
| 6 | + |
| 7 | +import jax |
| 8 | +from jax import sharding |
| 9 | +import numpy as np |
| 10 | +from benchmark_utils import MetricsStatistics |
| 11 | + |
| 12 | + |
| 13 | +libtpu_init_args = [ |
| 14 | + "--xla_tpu_dvfs_p_state=7", |
| 15 | +] |
| 16 | +os.environ["LIBTPU_INIT_ARGS"] = " ".join(libtpu_init_args) |
| 17 | +# 64 GiB |
| 18 | +os.environ["TPU_PREMAPPED_BUFFER_SIZE"] = "68719476736" |
| 19 | +os.environ["TPU_PREMAPPED_BUFFER_TRANSFER_THRESHOLD_BYTES"] = "68719476736" |
| 20 | + |
| 21 | +def get_tpu_devices(num_devices: int): |
| 22 | + devices = jax.devices() |
| 23 | + if len(devices) < num_devices: |
| 24 | + raise RuntimeError(f"Require {num_devices} devices, found {len(devices)}") |
| 25 | + return devices[:num_devices] |
| 26 | + |
| 27 | +def benchmark_host_device( |
| 28 | + num_devices: int, |
| 29 | + data_size_mb: int, |
| 30 | + num_runs: int = 100, |
| 31 | + trace_dir: str = None, |
| 32 | +) -> Dict[str, Any]: |
| 33 | + """Benchmarks H2D/D2H transfer using simple device_put/device_get.""" |
| 34 | + tpu_devices = get_tpu_devices(num_devices) |
| 35 | + |
| 36 | + num_elements = 1024 * 1024 * data_size_mb // np.dtype(np.float32).itemsize |
| 37 | + |
| 38 | + # Allocate Host Source Buffer |
| 39 | + host_data = np.random.normal(size=(num_elements,), dtype=np.float32) |
| 40 | + |
| 41 | + print( |
| 42 | + f"Benchmarking (Simple) Transfer with Data Size: {data_size_mb} MB on" |
| 43 | + f" {num_devices} devices for {num_runs} iterations" |
| 44 | + ) |
| 45 | + |
| 46 | + # Setup Mesh Sharding (1D) |
| 47 | + mesh = sharding.Mesh( |
| 48 | + np.array(tpu_devices).reshape((num_devices,)), axis_names=("x",) |
| 49 | + ) |
| 50 | + # Shard the 1D array across "x" |
| 51 | + partition_spec = sharding.PartitionSpec("x") |
| 52 | + |
| 53 | + data_sharding = sharding.NamedSharding(mesh, partition_spec) |
| 54 | + |
| 55 | + # Performance Lists |
| 56 | + h2d_perf, d2h_perf = [], [] |
| 57 | + |
| 58 | + # Profiling Context |
| 59 | + import contextlib |
| 60 | + if trace_dir: |
| 61 | + profiler_context = jax.profiler.trace(trace_dir) |
| 62 | + else: |
| 63 | + profiler_context = contextlib.nullcontext() |
| 64 | + |
| 65 | + with profiler_context: |
| 66 | + # Warmup |
| 67 | + for _ in range(2): |
| 68 | + device_array = jax.device_put(host_data, data_sharding) |
| 69 | + device_array.block_until_ready() |
| 70 | + host_out = np.array(device_array) |
| 71 | + device_array.delete() |
| 72 | + del host_out |
| 73 | + |
| 74 | + for i in range(num_runs): |
| 75 | + # Step Context |
| 76 | + if trace_dir: |
| 77 | + step_context = jax.profiler.StepTraceAnnotation("host_device", step_num=i) |
| 78 | + else: |
| 79 | + step_context = contextlib.nullcontext() |
| 80 | + |
| 81 | + with step_context: |
| 82 | + # H2D |
| 83 | + t0 = time.perf_counter() |
| 84 | + |
| 85 | + # Simple device_put |
| 86 | + device_array = jax.device_put(host_data, data_sharding) |
| 87 | + device_array.block_until_ready() |
| 88 | + |
| 89 | + t1 = time.perf_counter() |
| 90 | + h2d_perf.append((t1 - t0) * 1000) |
| 91 | + |
| 92 | + # Verify H2D shape/sharding |
| 93 | + assert device_array.shape == host_data.shape |
| 94 | + assert device_array.sharding == data_sharding |
| 95 | + |
| 96 | + # D2H |
| 97 | + t2 = time.perf_counter() |
| 98 | + |
| 99 | + # Simple device_get |
| 100 | + # Note: device_get returns a numpy array (copy) |
| 101 | + _ = jax.device_get(device_array) |
| 102 | + |
| 103 | + t3 = time.perf_counter() |
| 104 | + d2h_perf.append((t3 - t2) * 1000) |
| 105 | + |
| 106 | + device_array.delete() |
| 107 | + |
| 108 | + return { |
| 109 | + "H2D_Bandwidth_ms": h2d_perf, |
| 110 | + "D2H_Bandwidth_ms": d2h_perf, |
| 111 | + } |
| 112 | + |
| 113 | +def benchmark_host_device_calculate_metrics( |
| 114 | + num_devices: int, |
| 115 | + data_size_mb: int, |
| 116 | + H2D_Bandwidth_ms: List[float], |
| 117 | + D2H_Bandwidth_ms: List[float], |
| 118 | +) -> Tuple[Dict[str, Any], Dict[str, Any]]: |
| 119 | + """Calculates metrics for Host-Device transfer.""" |
| 120 | + params = locals().items() |
| 121 | + |
| 122 | + data_size_mib = data_size_mb |
| 123 | + |
| 124 | + # Filter out list params from metadata to avoid explosion |
| 125 | + metadata_keys = { |
| 126 | + "num_devices", |
| 127 | + "data_size_mib", |
| 128 | + } |
| 129 | + metadata = {k: v for k, v in params if k in metadata_keys} |
| 130 | + |
| 131 | + metrics = {} |
| 132 | + |
| 133 | + def add_metric(name, ms_list): |
| 134 | + # Report Bandwidth (GiB/s) |
| 135 | + # Handle division by zero if ms is 0 |
| 136 | + bw_list = [ |
| 137 | + ((data_size_mb / 1024) / (ms / 1000)) if ms > 0 else 0.0 |
| 138 | + for ms in ms_list |
| 139 | + ] |
| 140 | + stats_bw = MetricsStatistics(bw_list, f"{name}_bw (GiB/s)") |
| 141 | + metrics.update(stats_bw.serialize_statistics()) |
| 142 | + |
| 143 | + add_metric("H2D", H2D_Bandwidth_ms) |
| 144 | + add_metric("D2H", D2H_Bandwidth_ms) |
| 145 | + |
| 146 | + return metadata, metrics |
0 commit comments