22# Licensed under the MIT License.
33"""A utility and an example showing how onnxscript functions can be used to define function expansions
44and 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."""
5+ This is useful to perform certain classes of graph surgery easily.
6+ """
67
78import onnx
8- import onnxscript
9- from onnxscript import script , FLOAT , opset22 as op
109
10+ import onnxscript
1111
12+ script = onnxscript .script
13+ FLOAT = onnxscript .FLOAT
14+ op = onnxscript .values .opset22
1215local = onnxscript .values .Opset ("local" , 1 )
1316
17+
1418# Example Model: Actual models can come from ModelBuilder or Exporter or any other source.
1519# Models can contain calls to custom operations (from a custom domain like 'local' here or
1620# even "com.microsoft" etc.)
@@ -24,17 +28,20 @@ def model_script(X: FLOAT["N"], Y: FLOAT["N"]) -> FLOAT["N"]:
2428 Temp2 = local .CustomOp2 (Temp1 , alp = 0.9 )
2529 return Temp2
2630
31+
2732# Define expansions for custom operations as onnxscript functions
2833@script (opset = local )
2934def CustomOp1 (X : FLOAT ["N" ], Y : FLOAT ["N" ]) -> FLOAT ["N" ]:
3035 Temp1 = op .Sub (X , Y )
3136 return op .Div (Temp1 , X )
3237
38+
3339@script (opset = local )
3440def CustomOp2 (X : FLOAT ["N" ], alp : float ) -> FLOAT ["N" ]:
3541 Temp2 = op .Elu (X , alpha = alp )
3642 return op .Mul (Temp2 , Temp2 )
3743
44+
3845# Now, we can replace the custom operations in the model with their expansions:
3946
4047functions = [CustomOp1 .to_function_proto (), CustomOp2 .to_function_proto ()]
@@ -45,8 +52,8 @@ def CustomOp2(X: FLOAT["N"], alp: float) -> FLOAT["N"]:
4552print (onnx .printer .to_text (model ))
4653
4754import onnxscript .utils .replace as replace
55+
4856updated_model = replace .replace_functions (model , functions )
4957
5058print ("\n Updated Model after replacing custom operations with their expansions:" )
5159print (onnx .printer .to_text (updated_model ))
52-
0 commit comments