|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | +"""A utility and an example showing how onnxscript functions can be used to define function expansions |
| 4 | +and be used with the inliner to replace calls to the custom function with an expanded subgraph. |
| 5 | +This is useful to perform certain classes of graph surgery easily.""" |
| 6 | + |
| 7 | +import onnx |
| 8 | +import onnxscript |
| 9 | +from onnxscript import script, FLOAT, opset22 as op |
| 10 | + |
| 11 | + |
| 12 | +local = onnxscript.values.Opset("local", 1) |
| 13 | + |
| 14 | +# Example Model: Actual models can come from ModelBuilder or Exporter or any other source. |
| 15 | +# Models can contain calls to custom operations (from a custom domain like 'local' here or |
| 16 | +# even "com.microsoft" etc.) |
| 17 | +@script() |
| 18 | +def model_script(X: FLOAT["N"], Y: FLOAT["N"]) -> FLOAT["N"]: |
| 19 | + DoubleX = op.Add(X, X) |
| 20 | + YSquare = op.Mul(Y, Y) |
| 21 | + # Example call to a custom operation |
| 22 | + Temp1 = local.CustomOp1(DoubleX, YSquare) |
| 23 | + # Another call to a custom operation with an attribute |
| 24 | + Temp2 = local.CustomOp2(Temp1, alp=0.9) |
| 25 | + return Temp2 |
| 26 | + |
| 27 | +# Define expansions for custom operations as onnxscript functions |
| 28 | +@script(opset=local) |
| 29 | +def CustomOp1(X: FLOAT["N"], Y: FLOAT["N"]) -> FLOAT["N"]: |
| 30 | + Temp1 = op.Sub(X, Y) |
| 31 | + return op.Div(Temp1, X) |
| 32 | + |
| 33 | +@script(opset=local) |
| 34 | +def CustomOp2(X: FLOAT["N"], alp: float) -> FLOAT["N"]: |
| 35 | + Temp2 = op.Elu(X, alpha=alp) |
| 36 | + return op.Mul(Temp2, Temp2) |
| 37 | + |
| 38 | +# Now, we can replace the custom operations in the model with their expansions: |
| 39 | + |
| 40 | +functions = [CustomOp1.to_function_proto(), CustomOp2.to_function_proto()] |
| 41 | + |
| 42 | +model = model_script.to_model_proto() |
| 43 | + |
| 44 | +print("Original Model with custom operations:") |
| 45 | +print(onnx.printer.to_text(model)) |
| 46 | + |
| 47 | +import onnxscript.utils.replace as replace |
| 48 | +updated_model = replace.replace_functions(model, functions) |
| 49 | + |
| 50 | +print("\nUpdated Model after replacing custom operations with their expansions:") |
| 51 | +print(onnx.printer.to_text(updated_model)) |
| 52 | + |
0 commit comments