|
| 1 | +""" |
| 2 | +Monkey-patch SGLang's GroupCoordinator.all_reduce to log tensor shapes |
| 3 | +entering the custom allreduce kernel (cross_device_reduce_2stage). |
| 4 | +
|
| 5 | +Usage: Set PYTHONPATH to include the directory containing sitecustomize.py |
| 6 | +which imports this module, OR call patch() directly before launching SGLang. |
| 7 | +
|
| 8 | +Logs are written to /workspace/allreduce_shapes.log (one line per call on rank 0). |
| 9 | +After the run, the log can be post-processed to get unique shapes and counts. |
| 10 | +""" |
| 11 | + |
| 12 | +import atexit |
| 13 | +import collections |
| 14 | +import os |
| 15 | + |
| 16 | +_shape_counts = collections.Counter() |
| 17 | +_log_file = None |
| 18 | +_original_all_reduce = None |
| 19 | +_original_all_reduce_out_place = None |
| 20 | +_patched = False |
| 21 | +# Limit per-call logging to avoid flooding stdout; summary is printed at exit. |
| 22 | +_MAX_LOG_LINES = 200 |
| 23 | +_log_line_count = 0 |
| 24 | + |
| 25 | + |
| 26 | +def _get_rank(): |
| 27 | + try: |
| 28 | + import torch.distributed as dist |
| 29 | + if dist.is_initialized(): |
| 30 | + return dist.get_rank() |
| 31 | + except Exception: |
| 32 | + pass |
| 33 | + return 0 |
| 34 | + |
| 35 | + |
| 36 | +def _patched_all_reduce_out_place(self, input_, outplace_all_reduce_method): |
| 37 | + """Wrapper around _all_reduce_out_place that logs shapes for custom AR calls.""" |
| 38 | + global _log_line_count |
| 39 | + rank = _get_rank() |
| 40 | + if rank == 0: |
| 41 | + shape_key = (tuple(input_.shape), str(input_.dtype), outplace_all_reduce_method) |
| 42 | + _shape_counts[shape_key] += 1 |
| 43 | + if _log_line_count < _MAX_LOG_LINES: |
| 44 | + print( |
| 45 | + f"[AR_SHAPE] method={outplace_all_reduce_method} " |
| 46 | + f"shape={list(input_.shape)} dtype={input_.dtype} " |
| 47 | + f"numel={input_.numel()} bytes={input_.numel() * input_.element_size()}", |
| 48 | + flush=True, |
| 49 | + ) |
| 50 | + _log_line_count += 1 |
| 51 | + return _original_all_reduce_out_place(self, input_, outplace_all_reduce_method) |
| 52 | + |
| 53 | + |
| 54 | +def _patched_all_reduce(self, input_): |
| 55 | + """Wrapper around all_reduce that logs shapes for ALL allreduce calls (including in-place/deterministic).""" |
| 56 | + global _log_line_count |
| 57 | + rank = _get_rank() |
| 58 | + if rank == 0 and _log_line_count < _MAX_LOG_LINES: |
| 59 | + shape_key = (tuple(input_.shape), str(input_.dtype), "all") |
| 60 | + _shape_counts[shape_key] += 1 |
| 61 | + if _log_line_count < _MAX_LOG_LINES: |
| 62 | + print( |
| 63 | + f"[AR_SHAPE_ENTRY] shape={list(input_.shape)} dtype={input_.dtype} " |
| 64 | + f"numel={input_.numel()} bytes={input_.numel() * input_.element_size()}", |
| 65 | + flush=True, |
| 66 | + ) |
| 67 | + _log_line_count += 1 |
| 68 | + return _original_all_reduce(self, input_) |
| 69 | + |
| 70 | + |
| 71 | +def _print_summary(): |
| 72 | + """Print aggregated shape summary at process exit.""" |
| 73 | + rank = _get_rank() |
| 74 | + if rank != 0 or not _shape_counts: |
| 75 | + return |
| 76 | + |
| 77 | + log_path = os.environ.get("AR_SHAPE_LOG", "/workspace/allreduce_shapes.log") |
| 78 | + lines = [] |
| 79 | + lines.append("\n" + "=" * 80) |
| 80 | + lines.append("[AR_SHAPE_SUMMARY] AllReduce tensor shapes (rank 0):") |
| 81 | + lines.append(f"{'Count':>8} {'Method':<12} {'Shape':<30} {'Dtype':<16} {'Bytes':<12}") |
| 82 | + lines.append("-" * 80) |
| 83 | + |
| 84 | + for (shape, dtype, method), count in _shape_counts.most_common(): |
| 85 | + import torch |
| 86 | + # Compute element size from dtype string |
| 87 | + elem_size = 2 # default bf16 |
| 88 | + if "float32" in dtype: |
| 89 | + elem_size = 4 |
| 90 | + elif "float16" in dtype or "bfloat16" in dtype: |
| 91 | + elem_size = 2 |
| 92 | + elif "float8" in dtype: |
| 93 | + elem_size = 1 |
| 94 | + numel = 1 |
| 95 | + for s in shape: |
| 96 | + numel *= s |
| 97 | + nbytes = numel * elem_size |
| 98 | + lines.append(f"{count:>8} {method:<12} {str(list(shape)):<30} {dtype:<16} {nbytes:<12}") |
| 99 | + |
| 100 | + lines.append("=" * 80) |
| 101 | + summary = "\n".join(lines) |
| 102 | + print(summary, flush=True) |
| 103 | + |
| 104 | + try: |
| 105 | + with open(log_path, "w") as f: |
| 106 | + f.write(summary + "\n") |
| 107 | + print(f"[AR_SHAPE] Summary written to {log_path}", flush=True) |
| 108 | + except Exception as e: |
| 109 | + print(f"[AR_SHAPE] Failed to write log: {e}", flush=True) |
| 110 | + |
| 111 | + |
| 112 | +def patch(): |
| 113 | + """Apply the monkey-patch to GroupCoordinator.""" |
| 114 | + global _original_all_reduce, _original_all_reduce_out_place, _patched |
| 115 | + if _patched: |
| 116 | + return |
| 117 | + |
| 118 | + try: |
| 119 | + from sglang.srt.distributed.parallel_state import GroupCoordinator |
| 120 | + except ImportError: |
| 121 | + print("[AR_SHAPE] Could not import GroupCoordinator, skipping patch", flush=True) |
| 122 | + return |
| 123 | + |
| 124 | + _original_all_reduce = GroupCoordinator.all_reduce |
| 125 | + _original_all_reduce_out_place = GroupCoordinator._all_reduce_out_place |
| 126 | + |
| 127 | + GroupCoordinator.all_reduce = _patched_all_reduce |
| 128 | + GroupCoordinator._all_reduce_out_place = _patched_all_reduce_out_place |
| 129 | + _patched = True |
| 130 | + |
| 131 | + atexit.register(_print_summary) |
| 132 | + print("[AR_SHAPE] Monkey-patch installed: logging allreduce tensor shapes on rank 0", flush=True) |
0 commit comments