|
| 1 | +from graph_net.torch import utils |
| 2 | +import argparse |
| 3 | +import importlib.util |
| 4 | +import inspect |
| 5 | +import shutil |
| 6 | +import torch |
| 7 | +import logging |
| 8 | +from pathlib import Path |
| 9 | +from typing import Type, Any |
| 10 | +import sys |
| 11 | +import json |
| 12 | +import base64 |
| 13 | +from contextlib import contextmanager |
| 14 | + |
| 15 | +from torch.profiler import profile, record_function, ProfilerActivity |
| 16 | + |
| 17 | + |
| 18 | +class PostExtractProcess: |
| 19 | + def __init__(self, config): |
| 20 | + self.config = config |
| 21 | + |
| 22 | + def __call__(self, model_path=None): |
| 23 | + print("PostExtractProcess") |
| 24 | + if model_path is None: |
| 25 | + return False |
| 26 | + import json |
| 27 | + import base64 |
| 28 | + import sys |
| 29 | + import os |
| 30 | + |
| 31 | + json_string = json.dumps(self.config) |
| 32 | + json_bytes = json_string.encode("utf-8") |
| 33 | + b64_encoded_bytes = base64.b64encode(json_bytes) |
| 34 | + decorator_config = b64_encoded_bytes.decode("utf-8") |
| 35 | + |
| 36 | + # args |
| 37 | + parser = argparse.ArgumentParser(description="load and run model") |
| 38 | + parser.add_argument( |
| 39 | + "--model-path", |
| 40 | + type=str, |
| 41 | + required=True, |
| 42 | + help="Path to folder e.g '../../samples/torch/resnet18'", |
| 43 | + ) |
| 44 | + parser.add_argument( |
| 45 | + "--decorator-config", |
| 46 | + type=str, |
| 47 | + required=False, |
| 48 | + default=None, |
| 49 | + help="decorator configuration string", |
| 50 | + ) |
| 51 | + args = parser.parse_args() |
| 52 | + |
| 53 | + # model |
| 54 | + model_class = load_class_from_file( |
| 55 | + f"{model_path}/model.py", class_name="GraphModule" |
| 56 | + ) |
| 57 | + assert model_class is not None |
| 58 | + model = model_class() |
| 59 | + print(f"{model_path=}") |
| 60 | + |
| 61 | + model = _get_decorator(args)(model) |
| 62 | + |
| 63 | + inputs_params = utils.load_converted_from_text(f"{model_path}") |
| 64 | + params = inputs_params["weight_info"] |
| 65 | + state_dict = {k: utils.replay_tensor(v) for k, v in params.items()} |
| 66 | + |
| 67 | + compiled_num_of_kernels = compile_and_count_kernels(model, state_dict) |
| 68 | + print("compiled: nums_of_kernels = ", compiled_num_of_kernels) |
| 69 | + if compiled_num_of_kernels == 1: |
| 70 | + print("Graph is fully fusionable") |
| 71 | + return True |
| 72 | + else: |
| 73 | + print(f"Graph is not fully fusionable ({compiled_num_of_kernels} kernels)") |
| 74 | + shutil.rmtree(model_path) |
| 75 | + return False |
| 76 | + |
| 77 | + |
| 78 | +def _convert_to_dict(config_str): |
| 79 | + if config_str is None: |
| 80 | + return {} |
| 81 | + config_str = base64.b64decode(config_str).decode("utf-8") |
| 82 | + config = json.loads(config_str) |
| 83 | + assert isinstance(config, dict), f"config should be a dict. {config_str=}" |
| 84 | + return config |
| 85 | + |
| 86 | + |
| 87 | +def _get_decorator(args): |
| 88 | + if args.decorator_config is None: |
| 89 | + return lambda model: model |
| 90 | + decorator_config = _convert_to_dict(args.decorator_config) |
| 91 | + if "decorator_path" not in decorator_config: |
| 92 | + return lambda model: model |
| 93 | + class_name = decorator_config.get("decorator_class_name", "RunModelDecorator") |
| 94 | + decorator_class = load_class_from_file( |
| 95 | + decorator_config["decorator_path"], |
| 96 | + class_name=class_name, |
| 97 | + ) |
| 98 | + return decorator_class(decorator_config.get("decorator_config", {})) |
| 99 | + |
| 100 | + |
| 101 | +def load_class_from_file(file_path: str, class_name: str) -> Type[torch.nn.Module]: |
| 102 | + spec = importlib.util.spec_from_file_location("unnamed", file_path) |
| 103 | + unnamed = importlib.util.module_from_spec(spec) |
| 104 | + spec.loader.exec_module(unnamed) |
| 105 | + model_class = getattr(unnamed, class_name, None) |
| 106 | + return model_class |
| 107 | + |
| 108 | + |
| 109 | +def compile_and_count_kernels(gm, sample_inputs) -> int: |
| 110 | + """ |
| 111 | + Count the number of CUDA kernel launches performed during a model's forward pass. |
| 112 | +
|
| 113 | + Args: |
| 114 | + gm(graph models) |
| 115 | + sample_inputs(tensors) |
| 116 | +
|
| 117 | + Returns: |
| 118 | + int: The number of kernels used. |
| 119 | +
|
| 120 | + Behavior: |
| 121 | + - Runs the model once inside a PyTorch profiler context. |
| 122 | + - Identifies the event with key = 'cudaLaunchKernel', which corresponds |
| 123 | + to the number of CUDA kernel launches. |
| 124 | + """ |
| 125 | + gm.eval() |
| 126 | + # Use PyTorch Profiler |
| 127 | + compiled_gm = torch.compile(gm) |
| 128 | + _ = compiled_gm(**sample_inputs) |
| 129 | + |
| 130 | + with profile( |
| 131 | + activities=[ProfilerActivity.CUDA, ProfilerActivity.CPU], |
| 132 | + record_shapes=True, |
| 133 | + ) as prof: |
| 134 | + with record_function("model_inference"): |
| 135 | + output = compiled_gm(**sample_inputs) |
| 136 | + print(prof.key_averages().table()) # print a table of profiler result |
| 137 | + events = prof.key_averages() |
| 138 | + if_compile_work = any(e.key == "TorchDynamo Cache Lookup" for e in events) |
| 139 | + if not if_compile_work: |
| 140 | + print("Compile failed") |
| 141 | + return -1 |
| 142 | + for e in events: |
| 143 | + if e.key == "cuLaunchKernel": |
| 144 | + return e.count |
0 commit comments