|
| 1 | +import logging |
| 2 | +import math |
| 3 | +import operator |
| 4 | +import os |
| 5 | +from dataclasses import dataclass, field |
| 6 | +from typing import Any, Dict, List, Union |
| 7 | + |
| 8 | +import torch |
| 9 | +from torch_tensorrt.dynamo._settings import CompilationSettings |
| 10 | +from torch_tensorrt.dynamo.conversion._ConverterRegistry import ConverterRegistry |
| 11 | +from torch_tensorrt.dynamo.conversion.converter_utils import get_node_name |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class PerSubgraphData: |
| 18 | + """Class to track data on a per-subgraph level |
| 19 | +
|
| 20 | + Args: |
| 21 | + subgraph_name (str): Name of the subgraph in the GraphModule |
| 22 | + subgraph_op_count (int): Number of operations in the subgraph |
| 23 | + subgraph_input_shapes (Any): Shapes of input Tensors of the subgraph |
| 24 | + subgraph_input_dtypes (Any): Input data types of the subgraph |
| 25 | + subgraph_output_shapes (Any): Shapes of output Tensors of the subgraph |
| 26 | + subgraph_output_dtypes (Any): Output data types of the subgraph |
| 27 | + """ |
| 28 | + |
| 29 | + subgraph_name: str = "" |
| 30 | + subgraph_op_count: int = 0 |
| 31 | + subgraph_input_shapes: Any = field(default_factory=list) |
| 32 | + subgraph_input_dtypes: Any = field(default_factory=list) |
| 33 | + subgraph_output_shapes: Any = field(default_factory=list) |
| 34 | + subgraph_output_dtypes: Any = field(default_factory=list) |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class DryRunTracker: |
| 39 | + """Class to track data on a graph-wide level |
| 40 | +
|
| 41 | + Args: |
| 42 | + total_ops_in_graph (int): Total number of operators in graph |
| 43 | + supported_ops_in_graph (int): Number of supported operators in graph |
| 44 | + graph_input_shapes (Any): Shapes of input Tensors of the graph |
| 45 | + graph_input_dtypes (Any): Input data types of the graph |
| 46 | + graph_output_shapes (Any): Shapes of output Tensors of the graph |
| 47 | + graph_output_dtypes (Any): Output data types of the graph |
| 48 | + per_subgraph_data (List[PerSubgraphData]): Per-subgraph data, see above class |
| 49 | + tensorrt_graph_count (int): Number of TensorRT engines to be generated |
| 50 | + compilation_settings (CompilationSettings): User Compilation Settings |
| 51 | + unsupported_ops (Dict[str, int]): Set of operators not supported in TRT |
| 52 | + to_run_in_torch (List[str]): Set of nodes to run in Torch |
| 53 | + """ |
| 54 | + |
| 55 | + total_ops_in_graph: int = 0 |
| 56 | + supported_ops_in_graph: int = 0 |
| 57 | + graph_input_shapes: Any = field(default_factory=list) |
| 58 | + graph_input_dtypes: Any = field(default_factory=list) |
| 59 | + graph_output_shapes: Any = field(default_factory=list) |
| 60 | + graph_output_dtypes: Any = field(default_factory=list) |
| 61 | + per_subgraph_data: List[PerSubgraphData] = field(default_factory=list) |
| 62 | + tensorrt_graph_count: int = 0 |
| 63 | + compilation_settings: CompilationSettings = field( |
| 64 | + default_factory=CompilationSettings |
| 65 | + ) |
| 66 | + unsupported_ops: Dict[str, int] = field(default_factory=dict) |
| 67 | + to_run_in_torch: List[str] = field(default_factory=list) |
| 68 | + |
| 69 | + |
| 70 | +def dryrun_stats_display( |
| 71 | + dryrun_tracker: DryRunTracker, dryrun_enabled: Union[bool, str] |
| 72 | +) -> None: |
| 73 | + """Displays statistics about the dryrun either to debug logs or stdout""" |
| 74 | + formatted_stats = "\n" |
| 75 | + |
| 76 | + # Print overall stats about the graph, operator counts, etc. |
| 77 | + formatted_stats += "+" * 50 + " Dry-Run Results for Graph " + "+" * 50 + "\n\n" |
| 78 | + formatted_stats += ( |
| 79 | + f"The graph consists of {dryrun_tracker.total_ops_in_graph} Total Operators, " |
| 80 | + f"of which {dryrun_tracker.supported_ops_in_graph} operators are supported, " |
| 81 | + f"{round(dryrun_tracker.supported_ops_in_graph*100/dryrun_tracker.total_ops_in_graph, 2)}% coverage\n\n" |
| 82 | + ) |
| 83 | + if dryrun_tracker.unsupported_ops: |
| 84 | + parsed_ops = "\n".join( |
| 85 | + [f"{str(k)}: {str(v)}" for k, v in dryrun_tracker.unsupported_ops.items()] |
| 86 | + ) |
| 87 | + formatted_stats += f"The following ops are currently unsupported or excluded from conversion, and are listed with their op-count in the graph:\n {parsed_ops}\n\n" |
| 88 | + |
| 89 | + if dryrun_tracker.to_run_in_torch: |
| 90 | + formatted_nodes = "\n".join(dryrun_tracker.to_run_in_torch) |
| 91 | + formatted_stats += ( |
| 92 | + f"The following nodes are currently set to run in Torch:\n{formatted_nodes}\n" |
| 93 | + "Note: Some of the above nodes may be supported, but were not included in a TRT graph by the partitioner\n\n" |
| 94 | + ) |
| 95 | + |
| 96 | + formatted_stats += f"Compiled with: {dryrun_tracker.compilation_settings}\n\n" |
| 97 | + |
| 98 | + assert len(dryrun_tracker.per_subgraph_data) == dryrun_tracker.tensorrt_graph_count |
| 99 | + |
| 100 | + # Print schematic of the graph structure, as in: |
| 101 | + # |
| 102 | + # Inputs: List[Tensor: (1, 3, 224, 224)@float32] |
| 103 | + # ... |
| 104 | + # TRT Engine #1 - Submodule name: _run_on_acc_0 |
| 105 | + # Engine Inputs: List[Tensor: (1, 3, 224, 224)@float32] |
| 106 | + # Number of Operators in Engine: 1 |
| 107 | + # Engine Outputs: Tensor: (1, 64, 112, 112)@float32 |
| 108 | + # ... |
| 109 | + # Outputs: List[Tensor: (1, 1000)@float32] |
| 110 | + # |
| 111 | + formatted_stats += " " * 2 + "Graph Structure:\n\n" |
| 112 | + formatted_stats += ( |
| 113 | + " " * 3 |
| 114 | + + f"Inputs: {input_formatter(dryrun_tracker.graph_input_shapes, dryrun_tracker.graph_input_dtypes)}\n" |
| 115 | + ) |
| 116 | + |
| 117 | + for i, trt_subgraph_data in enumerate(dryrun_tracker.per_subgraph_data): |
| 118 | + formatted_stats += " " * 4 + "...\n" |
| 119 | + formatted_stats += ( |
| 120 | + " " * 4 |
| 121 | + + f"TRT Engine #{i+1} - Submodule name: {trt_subgraph_data.subgraph_name}\n" |
| 122 | + ) |
| 123 | + formatted_stats += ( |
| 124 | + " " * 5 |
| 125 | + + f"Engine Inputs: {input_formatter(trt_subgraph_data.subgraph_input_shapes, trt_subgraph_data.subgraph_input_dtypes)}\n" |
| 126 | + ) |
| 127 | + formatted_stats += ( |
| 128 | + " " * 5 |
| 129 | + + f"Number of Operators in Engine: {trt_subgraph_data.subgraph_op_count}\n" |
| 130 | + ) |
| 131 | + formatted_stats += ( |
| 132 | + " " * 5 |
| 133 | + + f"Engine Outputs: {input_formatter(trt_subgraph_data.subgraph_output_shapes, trt_subgraph_data.subgraph_output_dtypes)}\n" |
| 134 | + ) |
| 135 | + |
| 136 | + formatted_stats += " " * 4 + "...\n" |
| 137 | + formatted_stats += ( |
| 138 | + " " * 3 |
| 139 | + + f"Outputs: {input_formatter(dryrun_tracker.graph_output_shapes, dryrun_tracker.graph_output_dtypes)}\n" |
| 140 | + ) |
| 141 | + |
| 142 | + # Print aggregate statistics about the graph structure, including recommended "min_block_size" options |
| 143 | + if dryrun_tracker.tensorrt_graph_count > 0: |
| 144 | + min_ops_in_an_engine = min( |
| 145 | + trt_subgraph.subgraph_op_count |
| 146 | + for trt_subgraph in dryrun_tracker.per_subgraph_data |
| 147 | + ) |
| 148 | + avg_ops_per_engine = ( |
| 149 | + sum( |
| 150 | + trt_subgraph.subgraph_op_count |
| 151 | + for trt_subgraph in dryrun_tracker.per_subgraph_data |
| 152 | + ) |
| 153 | + / dryrun_tracker.tensorrt_graph_count |
| 154 | + ) |
| 155 | + avg_ops_per_engine = round(avg_ops_per_engine, 2) |
| 156 | + most_ops_in_an_engine = max( |
| 157 | + trt_subgraph.subgraph_op_count |
| 158 | + for trt_subgraph in dryrun_tracker.per_subgraph_data |
| 159 | + ) |
| 160 | + |
| 161 | + formatted_stats += "\n" + " " * 2 + "-" * 25 + " Aggregate Stats " + "-" * 25 |
| 162 | + formatted_stats += ( |
| 163 | + "\n\n" |
| 164 | + + " " * 3 |
| 165 | + + "Average Number of Operators per TRT Engine: " |
| 166 | + + f"{avg_ops_per_engine}" |
| 167 | + ) |
| 168 | + |
| 169 | + formatted_stats += ( |
| 170 | + "\n" |
| 171 | + + " " * 3 |
| 172 | + + "Most Operators in a TRT Engine: " |
| 173 | + + f"{most_ops_in_an_engine}" |
| 174 | + ) |
| 175 | + |
| 176 | + formatted_stats += "\n\n" + " " * 2 + "*" * 10 + " Recommendations " + "*" * 10 |
| 177 | + formatted_stats += ( |
| 178 | + "\n\n" |
| 179 | + + " " * 3 |
| 180 | + + "- For minimal graph segmentation, select min_block_size=" |
| 181 | + + f"{most_ops_in_an_engine} which would generate " |
| 182 | + + f"{len([1 for trt_subgraph in dryrun_tracker.per_subgraph_data if trt_subgraph.subgraph_op_count >= most_ops_in_an_engine])} TRT engine(s)" |
| 183 | + ) |
| 184 | + if math.ceil(avg_ops_per_engine) != most_ops_in_an_engine: |
| 185 | + formatted_stats += ( |
| 186 | + "\n" |
| 187 | + + " " * 3 |
| 188 | + + "- For moderate graph segmentation, select min_block_size=" |
| 189 | + + f"{math.ceil(avg_ops_per_engine)} which would generate " |
| 190 | + + f"{len([1 for trt_subgraph in dryrun_tracker.per_subgraph_data if trt_subgraph.subgraph_op_count >= math.ceil(avg_ops_per_engine)])} TRT engine(s)" |
| 191 | + ) |
| 192 | + |
| 193 | + formatted_stats += ( |
| 194 | + "\n" |
| 195 | + + " " * 3 |
| 196 | + + "- The current level of graph segmentation is equivalent to selecting min_block_size=" |
| 197 | + + f"{min_ops_in_an_engine} which generates " |
| 198 | + + f"{len([1 for trt_subgraph in dryrun_tracker.per_subgraph_data if trt_subgraph.subgraph_op_count >= min_ops_in_an_engine])} TRT engine(s)" |
| 199 | + ) |
| 200 | + else: |
| 201 | + formatted_stats += ( |
| 202 | + "\n" |
| 203 | + + " " * 2 |
| 204 | + + "Aggregate stats not available since no TRT Engines were generated." |
| 205 | + ) |
| 206 | + |
| 207 | + # If user specified "dryrun=True", print to stdout, else debug |
| 208 | + # If user specified a filepath, save the output to the path as well |
| 209 | + if dryrun_enabled: |
| 210 | + print(formatted_stats) |
| 211 | + if isinstance(dryrun_enabled, str): |
| 212 | + if os.path.exists(dryrun_enabled): |
| 213 | + logger.warning( |
| 214 | + f"File already exists at path {dryrun_enabled}, not saving dryrun output" |
| 215 | + ) |
| 216 | + else: |
| 217 | + with open(dryrun_enabled, "w+") as f: |
| 218 | + f.write(formatted_stats) |
| 219 | + else: |
| 220 | + logger.debug(formatted_stats) |
| 221 | + |
| 222 | + |
| 223 | +def input_formatter(shapes: Any, dtypes: Any) -> str: |
| 224 | + """Format shapes and dtypes of input Tensors into a readable string""" |
| 225 | + |
| 226 | + def input_formatter_helper(shapes: Any, dtypes: Any) -> str: |
| 227 | + """Helper for input formatter""" |
| 228 | + # Base case - single shape, single dtype |
| 229 | + if isinstance(shapes, tuple) and all(isinstance(elt, int) for elt in shapes): |
| 230 | + return f"Tensor: {shapes}@{str(dtypes)[6:]}, " |
| 231 | + |
| 232 | + # Base case - dynamic shape, single dtype |
| 233 | + elif ( |
| 234 | + isinstance(shapes, dict) |
| 235 | + and len(shapes) == 3 |
| 236 | + and all( |
| 237 | + ( |
| 238 | + isinstance(shape, tuple) |
| 239 | + and all(isinstance(elt, int) for elt in shape) |
| 240 | + and k in ("min_shape", "opt_shape", "max_shape") |
| 241 | + ) |
| 242 | + for k, shape in shapes.items() |
| 243 | + ) |
| 244 | + ): |
| 245 | + return f"Tensor: {shapes}@{str(dtypes)[6:]}, " |
| 246 | + |
| 247 | + # Shapes is a sequence |
| 248 | + elif isinstance(shapes, (list, tuple)): |
| 249 | + formatted_str = "List[" if isinstance(shapes, list) else "Tuple(" |
| 250 | + for shape, dtype in zip(shapes, dtypes): |
| 251 | + formatted_str += input_formatter_helper(shape, dtype) |
| 252 | + formatted_str = formatted_str[:-2] + ( |
| 253 | + "], " if isinstance(shapes, list) else "), " |
| 254 | + ) |
| 255 | + return formatted_str |
| 256 | + |
| 257 | + # Shapes is a dictionary |
| 258 | + elif isinstance(shapes, dict): |
| 259 | + formatted_str = "Dict{" |
| 260 | + |
| 261 | + for key, shape in shapes.items(): |
| 262 | + formatted_str += input_formatter_helper(shape, dtypes[key]) |
| 263 | + |
| 264 | + formatted_str = formatted_str[:-2] + "}, " |
| 265 | + return formatted_str |
| 266 | + |
| 267 | + else: |
| 268 | + raise ValueError( |
| 269 | + f"Invalid input type {type(shapes)} encountered in parse_complex_tensor_structs parsing." |
| 270 | + ) |
| 271 | + |
| 272 | + return input_formatter_helper(shapes, dtypes)[:-2] |
| 273 | + |
| 274 | + |
| 275 | +def parse_non_trt_nodes(graph_module: torch.fx.GraphModule) -> List[str]: |
| 276 | + """Parses call_function and call_method nodes from a GraphModule |
| 277 | + Excludes getitem nodes |
| 278 | +
|
| 279 | + Returns a string representation of the nodes |
| 280 | + """ |
| 281 | + to_run_in_torch = [] |
| 282 | + for node in graph_module.graph.nodes: |
| 283 | + # getitem nodes are excluded since they are a Tensor-collection op |
| 284 | + if ( |
| 285 | + node.op in ("call_function", "call_method") |
| 286 | + and node.target != operator.getitem |
| 287 | + ): |
| 288 | + to_run_in_torch.append( |
| 289 | + f"Node: {ConverterRegistry.qualified_name_or_str(node.target)}, " |
| 290 | + f"with layer location: {get_node_name(node)}" |
| 291 | + ) |
| 292 | + return to_run_in_torch |
0 commit comments