|
| 1 | +from typing import Dict |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.fx |
| 5 | +from torch.fx.node import Node |
| 6 | + |
| 7 | + |
| 8 | +class Profiler: |
| 9 | + def __init__(self, mod, gpu, treeDB, data_collection_mode=False): |
| 10 | + self.mod = mod |
| 11 | + self.graph = mod.graph |
| 12 | + self.modules = dict(self.mod.named_modules()) |
| 13 | + self.tree_db = treeDB |
| 14 | + self.gpu = gpu |
| 15 | + self.data_collection_mode = data_collection_mode |
| 16 | + |
| 17 | + def propagate(self, *args): |
| 18 | + args_iter = iter(args) |
| 19 | + env: Dict[str, Node] = {} |
| 20 | + total_time = 0 |
| 21 | + |
| 22 | + def load_arg(a): |
| 23 | + return torch.fx.graph.map_arg(a, lambda n: env[n.name]) |
| 24 | + |
| 25 | + def fetch_attr(target: str): |
| 26 | + target_atoms = target.split('.') |
| 27 | + attr_itr = self.mod |
| 28 | + for i, atom in enumerate(target_atoms): |
| 29 | + if not hasattr(attr_itr, atom): |
| 30 | + raise RuntimeError(f"Node referenced nonexistant target {'.'.join(target_atoms[:i])}") |
| 31 | + attr_itr = getattr(attr_itr, atom) |
| 32 | + return attr_itr |
| 33 | + |
| 34 | + def get_flattened_shapes(args): |
| 35 | + flattened_shapes = [] |
| 36 | + dtypes = [] |
| 37 | + |
| 38 | + for arg in args: |
| 39 | + if isinstance(arg, (tuple, list)): |
| 40 | + if len(arg) > 0 and isinstance(arg[0], (tuple, list, torch.Tensor)): |
| 41 | + nested_shapes, nested_dtypes = get_flattened_shapes(arg[0]) |
| 42 | + shape = [len(arg)] + nested_shapes |
| 43 | + dtypes.extend(nested_dtypes.split(',')) |
| 44 | + else: |
| 45 | + shape = [len(arg)] |
| 46 | + elif isinstance(arg, torch.Tensor): |
| 47 | + shape = list(arg.shape) |
| 48 | + dtypes.append(str(arg.dtype)) |
| 49 | + elif isinstance(arg, bool): |
| 50 | + shape = [1 if arg is True else 0] |
| 51 | + elif isinstance(arg, (int, float)): |
| 52 | + shape = [arg] |
| 53 | + else: |
| 54 | + shape = [1] |
| 55 | + flattened_shapes.extend(shape) |
| 56 | + |
| 57 | + if len(flattened_shapes) < 2: |
| 58 | + flattened_shapes.extend([1]) |
| 59 | + |
| 60 | + input_dtypes = ','.join(dtypes) if dtypes else 'N/A' |
| 61 | + |
| 62 | + return flattened_shapes, input_dtypes |
| 63 | + |
| 64 | + def get_output_dtypes(results): |
| 65 | + def find_dtypes(results): |
| 66 | + if isinstance(results, torch.Tensor): |
| 67 | + return [str(results.dtype)] |
| 68 | + if isinstance(results, (list, tuple)): |
| 69 | + dtypes = [] |
| 70 | + for item in results: |
| 71 | + dtypes.extend(find_dtypes(item)) |
| 72 | + return dtypes |
| 73 | + return [] |
| 74 | + |
| 75 | + types = find_dtypes(results) |
| 76 | + |
| 77 | + if types: |
| 78 | + return ','.join(types) |
| 79 | + return 'N/A' |
| 80 | + |
| 81 | + def get_time_or_profile(key, inp_shapes, operation, *args, **kwargs): |
| 82 | + t = self.tree_db.get(key, inp_shapes) |
| 83 | + |
| 84 | + if self.data_collection_mode and t is None: |
| 85 | + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: |
| 86 | + result = operation(*args, **kwargs) |
| 87 | + event_time_total = 0 |
| 88 | + for event in prof.key_averages(): |
| 89 | + event_time_total += event.cuda_time_total |
| 90 | + t = event_time_total |
| 91 | + self.tree_db.add(key, inp_shapes, t) |
| 92 | + |
| 93 | + return t |
| 94 | + |
| 95 | + for node in self.graph.nodes: |
| 96 | + result = None |
| 97 | + if node.op == 'placeholder': |
| 98 | + result = next(args_iter) |
| 99 | + elif node.op == 'get_attr': |
| 100 | + result = fetch_attr(node.target) |
| 101 | + elif node.op == 'call_function': |
| 102 | + args = load_arg(node.args) |
| 103 | + kwargs = load_arg(node.kwargs) |
| 104 | + result = node.target(*args, **kwargs) |
| 105 | + |
| 106 | + inp_shapes, input_dtypes = get_flattened_shapes(args) |
| 107 | + output_dtypes = get_output_dtypes(result) |
| 108 | + |
| 109 | + key = (node.target.__name__, len(inp_shapes), input_dtypes, output_dtypes, self.gpu) |
| 110 | + |
| 111 | + t = get_time_or_profile(key, inp_shapes, node.target, *args, **kwargs) |
| 112 | + |
| 113 | + total_time += t |
| 114 | + elif node.op == 'call_method': |
| 115 | + self_obj, *args = load_arg(node.args) |
| 116 | + kwargs = load_arg(node.kwargs) |
| 117 | + result = getattr(self_obj, node.target)(*args, **kwargs) |
| 118 | + |
| 119 | + inp_shapes, input_dtypes = get_flattened_shapes(args) |
| 120 | + output_dtypes = get_output_dtypes(result) |
| 121 | + |
| 122 | + key = (node.target, len(inp_shapes), input_dtypes, output_dtypes, self.gpu) |
| 123 | + |
| 124 | + t = get_time_or_profile(key, inp_shapes, getattr(self_obj, node.target), *args, **kwargs) |
| 125 | + |
| 126 | + total_time += t |
| 127 | + elif node.op == 'call_module': |
| 128 | + mod = self.modules[node.target] |
| 129 | + args = load_arg(node.args) |
| 130 | + kwargs = load_arg(node.kwargs) |
| 131 | + result = mod(*args, **kwargs) |
| 132 | + |
| 133 | + inp_shapes, input_dtypes = get_flattened_shapes(args) |
| 134 | + |
| 135 | + param_shapes = [param.shape for name, param in mod.named_parameters()] |
| 136 | + param_dtypes = [str(param.dtype) for name, param in mod.named_parameters()] |
| 137 | + flattened_params = [dim for shape in param_shapes for dim in shape] |
| 138 | + |
| 139 | + inp_shapes = inp_shapes + flattened_params |
| 140 | + input_dtypes = input_dtypes + ',' + ','.join(param_dtypes) |
| 141 | + |
| 142 | + output_dtypes = get_output_dtypes(result) |
| 143 | + |
| 144 | + key = (mod._get_name(), len(inp_shapes), input_dtypes, output_dtypes, self.gpu) |
| 145 | + |
| 146 | + t = get_time_or_profile(key, inp_shapes, mod, *args, **kwargs) |
| 147 | + |
| 148 | + total_time += t |
| 149 | + elif node.op == 'output': |
| 150 | + args = load_arg(node.args) |
| 151 | + return args[0], total_time |
| 152 | + |
| 153 | + env[node.name] = result |
0 commit comments