|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +""" |
| 6 | +Script to gather and compare memory usage from training logs. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + python gather_memory.py --log_dir logs/20231201_120000 |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import os |
| 14 | +import re |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | + |
| 18 | +def parse_summary_line(line): |
| 19 | + """Parse the SUMMARY line from log output.""" |
| 20 | + pattern = r"SUMMARY: config=(\S+) params=(\d+) peak_mem_bytes=(\d+) alloc_mem_bytes=(\d+) avg_step_time=(\S+)" |
| 21 | + match = re.search(pattern, line) |
| 22 | + if match: |
| 23 | + return { |
| 24 | + "config": match.group(1), |
| 25 | + "params": int(match.group(2)), |
| 26 | + "peak_mem_bytes": int(match.group(3)), |
| 27 | + "alloc_mem_bytes": int(match.group(4)), |
| 28 | + "avg_step_time": float(match.group(5)), |
| 29 | + } |
| 30 | + return None |
| 31 | + |
| 32 | + |
| 33 | +def format_bytes(bytes_val): |
| 34 | + """Format bytes to human-readable string.""" |
| 35 | + gb = bytes_val / (1024 ** 3) |
| 36 | + return f"{gb:.2f} GB" |
| 37 | + |
| 38 | + |
| 39 | +def format_bytes_mb(bytes_val): |
| 40 | + """Format bytes to MB.""" |
| 41 | + mb = bytes_val / (1024 ** 2) |
| 42 | + return f"{mb:.1f} MB" |
| 43 | + |
| 44 | + |
| 45 | +def get_config_name(config_path): |
| 46 | + """Extract clean config name from path.""" |
| 47 | + name = Path(config_path).stem |
| 48 | + if name == "baseline": |
| 49 | + return "Baseline (fp32 master)" |
| 50 | + elif name == "bf16_master_wg": |
| 51 | + return "bf16_master_weights_and_grads" |
| 52 | + elif name == "bf16_full": |
| 53 | + return "bf16_full (master + opt states)" |
| 54 | + return name |
| 55 | + |
| 56 | + |
| 57 | +def main(): |
| 58 | + parser = argparse.ArgumentParser(description="Gather memory usage from training logs") |
| 59 | + parser.add_argument("--log_dir", type=str, required=True, help="Directory containing log files") |
| 60 | + parser.add_argument("--output", type=str, default=None, help="Output file for summary") |
| 61 | + args = parser.parse_args() |
| 62 | + |
| 63 | + log_dir = Path(args.log_dir) |
| 64 | + if not log_dir.exists(): |
| 65 | + print(f"Error: Log directory '{log_dir}' does not exist") |
| 66 | + return 1 |
| 67 | + |
| 68 | + # Find and parse all log files |
| 69 | + results = [] |
| 70 | + log_files = ["baseline.log", "bf16_full.log"] |
| 71 | + |
| 72 | + for log_file in log_files: |
| 73 | + log_path = log_dir / log_file |
| 74 | + if not log_path.exists(): |
| 75 | + print(f"Warning: Log file '{log_path}' not found, skipping") |
| 76 | + continue |
| 77 | + |
| 78 | + with open(log_path, "r") as f: |
| 79 | + for line in f: |
| 80 | + summary = parse_summary_line(line) |
| 81 | + if summary: |
| 82 | + results.append(summary) |
| 83 | + break |
| 84 | + |
| 85 | + if not results: |
| 86 | + print("No results found in log files") |
| 87 | + return 1 |
| 88 | + |
| 89 | + # Calculate baseline for comparison |
| 90 | + baseline_peak = None |
| 91 | + for r in results: |
| 92 | + if "baseline" in r["config"]: |
| 93 | + baseline_peak = r["peak_mem_bytes"] |
| 94 | + break |
| 95 | + |
| 96 | + # Generate summary |
| 97 | + output_lines = [] |
| 98 | + output_lines.append("=" * 80) |
| 99 | + output_lines.append("BF16 Low-Precision Master Weights - Memory Usage Comparison") |
| 100 | + output_lines.append("=" * 80) |
| 101 | + output_lines.append("") |
| 102 | + |
| 103 | + # Table header |
| 104 | + output_lines.append(f"{'Configuration':<40} {'Peak Memory':<15} {'Reduction':<15} {'Step Time':<12}") |
| 105 | + output_lines.append("-" * 80) |
| 106 | + |
| 107 | + for r in results: |
| 108 | + config_name = get_config_name(r["config"]) |
| 109 | + peak_mem = format_bytes(r["peak_mem_bytes"]) |
| 110 | + step_time = f"{r['avg_step_time']:.4f}s" |
| 111 | + |
| 112 | + if baseline_peak and baseline_peak > 0: |
| 113 | + reduction = ((baseline_peak - r["peak_mem_bytes"]) / baseline_peak) * 100 |
| 114 | + reduction_str = f"{reduction:+.1f}%" if reduction != 0 else "-" |
| 115 | + else: |
| 116 | + reduction_str = "-" |
| 117 | + |
| 118 | + output_lines.append(f"{config_name:<40} {peak_mem:<15} {reduction_str:<15} {step_time:<12}") |
| 119 | + |
| 120 | + output_lines.append("-" * 80) |
| 121 | + output_lines.append("") |
| 122 | + |
| 123 | + # Detailed breakdown |
| 124 | + output_lines.append("Detailed Results:") |
| 125 | + output_lines.append("-" * 40) |
| 126 | + for r in results: |
| 127 | + config_name = get_config_name(r["config"]) |
| 128 | + output_lines.append(f"\n{config_name}:") |
| 129 | + output_lines.append(f" Parameters: {r['params']:,}") |
| 130 | + output_lines.append(f" Peak Memory: {format_bytes(r['peak_mem_bytes'])} ({r['peak_mem_bytes']:,} bytes)") |
| 131 | + output_lines.append(f" Allocated Memory: {format_bytes(r['alloc_mem_bytes'])} ({r['alloc_mem_bytes']:,} bytes)") |
| 132 | + output_lines.append(f" Avg Step Time: {r['avg_step_time']:.4f}s") |
| 133 | + |
| 134 | + output_lines.append("") |
| 135 | + output_lines.append("=" * 80) |
| 136 | + |
| 137 | + # Generate markdown table |
| 138 | + output_lines.append("") |
| 139 | + output_lines.append("Markdown Table (for README):") |
| 140 | + output_lines.append("-" * 40) |
| 141 | + output_lines.append("") |
| 142 | + output_lines.append("| Configuration | Peak Memory | Memory Reduction | Avg Step Time |") |
| 143 | + output_lines.append("|---------------|-------------|------------------|---------------|") |
| 144 | + |
| 145 | + for r in results: |
| 146 | + config_name = get_config_name(r["config"]) |
| 147 | + peak_mem = format_bytes(r["peak_mem_bytes"]) |
| 148 | + step_time = f"{r['avg_step_time']:.4f}s" |
| 149 | + |
| 150 | + if baseline_peak and baseline_peak > 0: |
| 151 | + reduction = ((baseline_peak - r["peak_mem_bytes"]) / baseline_peak) * 100 |
| 152 | + reduction_str = f"{reduction:+.1f}%" if reduction != 0 else "-" |
| 153 | + else: |
| 154 | + reduction_str = "-" |
| 155 | + |
| 156 | + output_lines.append(f"| {config_name} | {peak_mem} | {reduction_str} | {step_time} |") |
| 157 | + |
| 158 | + output_lines.append("") |
| 159 | + |
| 160 | + # Print to stdout |
| 161 | + summary_text = "\n".join(output_lines) |
| 162 | + print(summary_text) |
| 163 | + |
| 164 | + # Save to file |
| 165 | + output_path = args.output or (log_dir / "summary.txt") |
| 166 | + with open(output_path, "w") as f: |
| 167 | + f.write(summary_text) |
| 168 | + |
| 169 | + print(f"\nSummary saved to: {output_path}") |
| 170 | + |
| 171 | + return 0 |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + exit(main()) |
0 commit comments