|
| 1 | +import inspect |
| 2 | +import itertools |
| 3 | +import time |
| 4 | +from typing import Any, Dict, List, Optional, Tuple, Union |
| 5 | +import torch |
| 6 | +from ..helpers import string_type, max_diff, string_diff |
| 7 | +from ..helpers.torch_test_helper import torch_deepcopy |
| 8 | +from .dynamic_shapes import CoupleInputsDynamicShapes |
| 9 | + |
| 10 | + |
| 11 | +def compare_modules( |
| 12 | + modep: torch.nn.Module, |
| 13 | + mod: Optional[torch.nn.Module] = None, |
| 14 | + args: Optional[Tuple[Any, ...]] = None, |
| 15 | + kwargs: Optional[Dict[str, Any]] = None, |
| 16 | + copy: bool = False, |
| 17 | + exc: bool = True, |
| 18 | + verbose: int = 0, |
| 19 | + atol: float = 1e-2, |
| 20 | + rtol: float = 1e-1, |
| 21 | +) -> Dict[str, Any]: |
| 22 | + """ |
| 23 | + Compares two torch modules, usually one coming from an exported program, |
| 24 | + the other being the origin model. |
| 25 | +
|
| 26 | + :param model: first module |
| 27 | + :param mod: second module (it produces the expected values) |
| 28 | + :param args: positional arguments |
| 29 | + :param kwargs: named arguments |
| 30 | + :param copy: copy the inputs before executing the model (they may modify them inplace) |
| 31 | + :param exc: raise exception if discrepancies are too high |
| 32 | + :param verbose: verbosity level |
| 33 | + :param atol: absolute tolerance |
| 34 | + :param rtol: relative tolerance |
| 35 | + :return: dictionary with inputs, outputs and tolerance |
| 36 | +
|
| 37 | + Example: |
| 38 | +
|
| 39 | + .. runpython:: |
| 40 | + :showcode: |
| 41 | +
|
| 42 | + import torch |
| 43 | + from onnx_diagnostic.export import validate_ep, CoupleInputsDynamicShapes |
| 44 | +
|
| 45 | + class Model(torch.nn.Module): |
| 46 | + def forward(self, x, y): |
| 47 | + return x + y |
| 48 | +
|
| 49 | + model = Model() |
| 50 | + x = torch.randn((5, 6)) |
| 51 | + y = torch.randn((1, 6)) |
| 52 | + model(x, y) # to make it is running |
| 53 | +
|
| 54 | + ds = ({0: "a", 1: "b"}, {1: "b"}) |
| 55 | + cpl = CoupleInputsDynamicShapes((x, y), {}, ds) |
| 56 | + ep = torch.export.export(model, (x, y), dynamic_shapes=cpl.replace_string_by()) |
| 57 | + validate_ep( |
| 58 | + ep, |
| 59 | + model, |
| 60 | + args=(x, y), |
| 61 | + verbose=2, |
| 62 | + copy=True, |
| 63 | + dynamic_shapes=ds, |
| 64 | + values_to_try={"a": [5, 10], "b": [10, 20]}, |
| 65 | + ) |
| 66 | +
|
| 67 | + """ |
| 68 | + args = args or () |
| 69 | + kwargs = kwargs or {} |
| 70 | + |
| 71 | + def _get(a): |
| 72 | + return torch_deepcopy(a) if copy else a |
| 73 | + |
| 74 | + if verbose: |
| 75 | + begin = time.perf_counter() |
| 76 | + print( |
| 77 | + f"[compare_modules] check ep with " |
| 78 | + f"args={string_type(args, with_shape=True)}, " |
| 79 | + f"kwargs={string_type(kwargs, with_shape=True)}..." |
| 80 | + ) |
| 81 | + got = modep(*_get(args), **_get(kwargs)) |
| 82 | + if verbose: |
| 83 | + d = time.perf_counter() - begin |
| 84 | + print(f"[compare_modules] done in {d} with output={string_type(got, with_shape=True)}") |
| 85 | + if mod: |
| 86 | + if verbose: |
| 87 | + begin = time.perf_counter() |
| 88 | + print("[compare_modules] run torch module...") |
| 89 | + expected = mod(*_get(args), **_get(kwargs)) |
| 90 | + diff = max_diff(expected, got) |
| 91 | + if verbose: |
| 92 | + d = time.perf_counter() - begin |
| 93 | + print( |
| 94 | + f"[compare_modules] done in {d} with " |
| 95 | + f"output={string_type(expected, with_shape=True)}" |
| 96 | + ) |
| 97 | + print(f"[compare_modules] discrepancies={string_diff(diff)}") |
| 98 | + assert not exc or ( |
| 99 | + diff["abs"] <= atol and diff["rel"] <= rtol |
| 100 | + ), f"Discrepancies={string_diff(diff)} higher than expected." |
| 101 | + return dict(args=args, kwargs=kwargs, expected=expected, got=got, diff=diff) |
| 102 | + return dict(args=args, kwargs=kwargs, got=got) |
| 103 | + |
| 104 | + |
| 105 | +def validate_ep( |
| 106 | + ep: Union[torch.nn.Module, torch.export.ExportedProgram], |
| 107 | + mod: Optional[torch.nn.Module] = None, |
| 108 | + args: Optional[Tuple[Any, ...]] = None, |
| 109 | + kwargs: Optional[Dict[str, Any]] = None, |
| 110 | + copy: bool = False, |
| 111 | + dynamic_shapes: Optional[Any] = None, |
| 112 | + values_to_try: Optional[Dict[str, List[int]]] = None, |
| 113 | + exc: bool = True, |
| 114 | + verbose: int = 0, |
| 115 | + atol: float = 1e-2, |
| 116 | + rtol: float = 1e-1, |
| 117 | +) -> List[Dict[str, Any]]: |
| 118 | + """ |
| 119 | + Validates an exported program. |
| 120 | +
|
| 121 | + :param model: first module |
| 122 | + :param mod: second module (it produces the expected values) |
| 123 | + :param args: positional arguments |
| 124 | + :param kwargs: named arguments |
| 125 | + :param copy: copy the inputs before executing the model (they may modify them inplace) |
| 126 | + :param dynamic_shapes: dynamic shapes, string should be used not ``torch.export.Dim`` |
| 127 | + :param values_to_try: dictionary with the values to try for every dynamic dimension |
| 128 | + :param exc: raise exception if discrepancies are too high |
| 129 | + :param verbose: verbosity level |
| 130 | + :param atol: absolute tolerance |
| 131 | + :param rtol: relative tolerance |
| 132 | + :return: dictionary with inputs, outputs and tolerance |
| 133 | + """ |
| 134 | + modep = ep.module() if isinstance(ep, torch.export.ExportedProgram) else ep |
| 135 | + |
| 136 | + results = [ |
| 137 | + compare_modules( |
| 138 | + modep, mod, args, kwargs, copy=copy, verbose=verbose, atol=atol, rtol=rtol |
| 139 | + ) |
| 140 | + ] |
| 141 | + |
| 142 | + assert (dynamic_shapes and values_to_try) or ( |
| 143 | + not dynamic_shapes and not values_to_try |
| 144 | + ), "Either both dynamic_shapes and values_to_try are specified, either none." |
| 145 | + if not dynamic_shapes or not values_to_try: |
| 146 | + return results |
| 147 | + |
| 148 | + items = list(values_to_try.items()) |
| 149 | + keys = [_[0] for _ in items] |
| 150 | + values = [_[1] for _ in items] |
| 151 | + all_vals = list(itertools.product(*values)) |
| 152 | + cpl = CoupleInputsDynamicShapes( |
| 153 | + args or (), |
| 154 | + kwargs or {}, |
| 155 | + dynamic_shapes, |
| 156 | + args_names=( |
| 157 | + list(inspect.signature(modep.forward).parameters) if args and kwargs else None |
| 158 | + ), |
| 159 | + ) |
| 160 | + for i, vals in enumerate(all_vals): |
| 161 | + change_dims = dict(zip(keys, vals)) |
| 162 | + if verbose: |
| 163 | + print(f"[validate_ep] try {i}/{len(all_vals)}: {change_dims}") |
| 164 | + new_params = cpl.change_dynamic_dimensions(change_dims, args_kwargs=True) |
| 165 | + na, nkw = new_params |
| 166 | + c = compare_modules( |
| 167 | + modep, mod, na, nkw, copy=copy, verbose=max(verbose - 1, 0), atol=atol, rtol=rtol |
| 168 | + ) |
| 169 | + results.append(c) |
| 170 | + return results |
0 commit comments