|
| 1 | +""" |
| 2 | +.. _l-plot-export-dim1: |
| 3 | +
|
| 4 | +0, 1, 2 for a Dynamic Dimension in the dummy example to export a model |
| 5 | +====================================================================== |
| 6 | +
|
| 7 | +:func:`torch.export.export` does not work if a tensor given to the function |
| 8 | +has 0 or 1 for dimension declared as dynamic dimension. |
| 9 | +
|
| 10 | +Simple model, no dimension with 0 or 1 |
| 11 | +++++++++++++++++++++++++++++++++++++++ |
| 12 | +""" |
| 13 | + |
| 14 | +import torch |
| 15 | +from onnx_diagnostic import doc |
| 16 | + |
| 17 | + |
| 18 | +class Model(torch.nn.Module): |
| 19 | + def forward(self, x, y, z): |
| 20 | + return torch.cat((x, y), axis=1) + z |
| 21 | + |
| 22 | + |
| 23 | +model = Model() |
| 24 | +x = torch.randn(2, 3) |
| 25 | +y = torch.randn(2, 5) |
| 26 | +z = torch.randn(2, 8) |
| 27 | +model(x, y, z) |
| 28 | + |
| 29 | +DYN = torch.export.Dim.DYNAMIC |
| 30 | +ds = {0: DYN, 1: DYN} |
| 31 | + |
| 32 | +ep = torch.export.export(model, (x, y, z), dynamic_shapes=(ds, ds, ds)) |
| 33 | +print(ep.graph) |
| 34 | + |
| 35 | +# %% |
| 36 | +# Same model, a dynamic dimension = 1 |
| 37 | +# +++++++++++++++++++++++++++++++++++ |
| 38 | + |
| 39 | +z = z[:1] |
| 40 | + |
| 41 | +DYN = torch.export.Dim.DYNAMIC |
| 42 | +ds = {0: DYN, 1: DYN} |
| 43 | + |
| 44 | +try: |
| 45 | + ep = torch.export.export(model, (x, y, z), dynamic_shapes=(ds, ds, ds)) |
| 46 | + print(ep.graph) |
| 47 | +except Exception as e: |
| 48 | + print("ERROR", e) |
| 49 | + |
| 50 | +# %% |
| 51 | +# It failed. Let's try a little trick. |
| 52 | + |
| 53 | +# %% |
| 54 | +# Same model, a dynamic dimension = 1 and backed_size_oblivious=True |
| 55 | +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 56 | + |
| 57 | +with torch.fx.experimental._config.patch(backed_size_oblivious=True): |
| 58 | + ep = torch.export.export(model, (x, y, z), dynamic_shapes=(ds, ds, ds)) |
| 59 | + print(ep.graph) |
| 60 | + |
| 61 | +# %% |
| 62 | +# It worked. |
| 63 | + |
| 64 | +doc.plot_legend("dynamic dimension\nworking with\n0 or 1", "torch.export.export", "green") |
0 commit comments