|
| 1 | +import gc |
| 2 | +from pathlib import Path |
| 3 | +from typing import Callable |
| 4 | + |
| 5 | +import torch |
| 6 | +from settings import DEVICE |
| 7 | +from torch.profiler import ProfilerActivity, profile |
| 8 | +from utils.architectures import ( |
| 9 | + AlexNet, |
| 10 | + Cifar10Model, |
| 11 | + GroupNormMobileNetV3Small, |
| 12 | + InstanceNormMobileNetV2, |
| 13 | + InstanceNormResNet18, |
| 14 | + ModuleFactory, |
| 15 | + SqueezeNet, |
| 16 | + WithTransformerLarge, |
| 17 | +) |
| 18 | +from utils.forward_backwards import ( |
| 19 | + autogram_forward_backward, |
| 20 | + autojac_forward_backward, |
| 21 | + make_mse_loss_fn, |
| 22 | +) |
| 23 | +from utils.tensors import make_inputs_and_targets |
| 24 | + |
| 25 | +from torchjd.aggregation import UPGrad, UPGradWeighting |
| 26 | +from torchjd.autogram import Engine |
| 27 | + |
| 28 | +PARAMETRIZATIONS = [ |
| 29 | + (ModuleFactory(WithTransformerLarge), 4), |
| 30 | + (ModuleFactory(Cifar10Model), 64), |
| 31 | + (ModuleFactory(AlexNet), 4), |
| 32 | + (ModuleFactory(InstanceNormResNet18), 4), |
| 33 | + (ModuleFactory(GroupNormMobileNetV3Small), 8), |
| 34 | + (ModuleFactory(SqueezeNet), 4), |
| 35 | + (ModuleFactory(InstanceNormMobileNetV2), 2), |
| 36 | +] |
| 37 | + |
| 38 | + |
| 39 | +def profile_method( |
| 40 | + method_name: str, |
| 41 | + forward_backward_fn: Callable, |
| 42 | + factory: ModuleFactory, |
| 43 | + batch_size: int, |
| 44 | +) -> None: |
| 45 | + """ |
| 46 | + Profiles memory and computation time of a forward and backward pass. |
| 47 | +
|
| 48 | + :param method_name: Name of the method being profiled (for output paths) |
| 49 | + :param forward_backward_fn: Function to execute the forward and backward pass. |
| 50 | + :param factory: A ModuleFactory that creates the model to profile. |
| 51 | + :param batch_size: The batch size to use for profiling. |
| 52 | + """ |
| 53 | + print(f"{method_name}: {factory} with batch_size={batch_size} on {DEVICE}:") |
| 54 | + |
| 55 | + _clear_unused_memory() |
| 56 | + model = factory() |
| 57 | + inputs, targets = make_inputs_and_targets(model, batch_size) |
| 58 | + loss_fn = make_mse_loss_fn(targets) |
| 59 | + |
| 60 | + activities = _get_profiler_activities() |
| 61 | + |
| 62 | + # Warmup run |
| 63 | + forward_backward_fn(model, inputs, loss_fn) |
| 64 | + model.zero_grad() |
| 65 | + _clear_unused_memory() |
| 66 | + |
| 67 | + # Profiled run |
| 68 | + with profile( |
| 69 | + activities=activities, |
| 70 | + profile_memory=True, |
| 71 | + record_shapes=False, # Otherwise some tensors may be referenced longer than normal |
| 72 | + with_stack=True, |
| 73 | + ) as prof: |
| 74 | + forward_backward_fn(model, inputs, loss_fn) |
| 75 | + |
| 76 | + _save_and_print_trace(prof, method_name, factory, batch_size) |
| 77 | + |
| 78 | + |
| 79 | +def _clear_unused_memory() -> None: |
| 80 | + gc.collect() |
| 81 | + if torch.cuda.is_available(): |
| 82 | + torch.cuda.empty_cache() |
| 83 | + |
| 84 | + |
| 85 | +def _get_profiler_activities() -> list[ProfilerActivity]: |
| 86 | + activities = [ProfilerActivity.CPU] |
| 87 | + if DEVICE.type == "cuda": |
| 88 | + activities.append(ProfilerActivity.CUDA) |
| 89 | + return activities |
| 90 | + |
| 91 | + |
| 92 | +def _save_and_print_trace( |
| 93 | + prof: profile, method_name: str, factory: ModuleFactory, batch_size: int |
| 94 | +) -> None: |
| 95 | + filename = f"{factory}-bs{batch_size}-{DEVICE.type}.json" |
| 96 | + torchjd_dir = Path(__file__).parent.parent.parent |
| 97 | + traces_dir = torchjd_dir / "traces" / method_name |
| 98 | + traces_dir.mkdir(parents=True, exist_ok=True) |
| 99 | + trace_path = traces_dir / filename |
| 100 | + |
| 101 | + prof.export_chrome_trace(str(trace_path)) |
| 102 | + print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=20)) |
| 103 | + |
| 104 | + |
| 105 | +def profile_autojac(factory: ModuleFactory, batch_size: int) -> None: |
| 106 | + def forward_backward_fn(model, inputs, loss_fn): |
| 107 | + aggregator = UPGrad() |
| 108 | + autojac_forward_backward(model, inputs, loss_fn, aggregator) |
| 109 | + |
| 110 | + profile_method("autojac", forward_backward_fn, factory, batch_size) |
| 111 | + |
| 112 | + |
| 113 | +def profile_autogram(factory: ModuleFactory, batch_size: int) -> None: |
| 114 | + def forward_backward_fn(model, inputs, loss_fn): |
| 115 | + engine = Engine(model, batch_dim=0) |
| 116 | + weighting = UPGradWeighting() |
| 117 | + autogram_forward_backward(model, inputs, loss_fn, engine, weighting) |
| 118 | + |
| 119 | + profile_method("autogram", forward_backward_fn, factory, batch_size) |
| 120 | + |
| 121 | + |
| 122 | +def main(): |
| 123 | + for factory, batch_size in PARAMETRIZATIONS: |
| 124 | + profile_autojac(factory, batch_size) |
| 125 | + print("\n" + "=" * 80 + "\n") |
| 126 | + profile_autogram(factory, batch_size) |
| 127 | + print("\n" + "=" * 80 + "\n") |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + # To test this on cuda, add the following environment variables when running this: |
| 132 | + # CUBLAS_WORKSPACE_CONFIG=:4096:8;PYTEST_TORCH_DEVICE=cuda:0 |
| 133 | + main() |
0 commit comments