microsoft/onnxruntime-extensions

Public

mirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
a6012b383e329c194ba2a3e21368a409800eb8ab

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

docs/pyop.md

27lines · modecode

1# PyOp
2
3Custom operators are a powerful feature in ONNX Runtime that allows users to extend the functionality of the runtime by implementing their own operators to perform specific operations not available in the standard ONNX operator set.
4
5In this document, we will introduce how to create a custom operator using Python functions and integrate it into ONNX Runtime for inference.
6
7
8## Step 1: Define the Python function for the custom operator
9Start by defining the Python function that will serve as the implementation for your custom operator. Ensure that the function is compatible with the input and output tensor shapes you expect for your custom operator.
10the Python decorator @onnx_op will convert the function to be a custom operator implementation. The following is example we create a function for a tokenizer
11
12```Python
13@onnx_op(op_type="GPT2Tokenizer",
14 inputs=[PyCustomOpDef.dt_string],
15 outputs=[PyCustomOpDef.dt_int64, PyCustomOpDef.dt_int64],
16 attrs={"padding_length": PyCustomOpDef.dt_int64})
17def bpe_tokenizer(s, **kwargs):
18 padding_length = kwargs["padding_length"]
19 input_ids, attention_mask = cls.tokenizer.tokenizer_sentence([s[0]], padding_length)
20 return input_ids, attention_mask
21```
22Because ONNXRuntimme needs the custom operator schema on loading a model, please specify them by onnx_op arguments. Also 'attrs' is needed if there are attributes for the ONNX node, which can be dict that mapping from its name to its type, or be a list if all types are string only.
23
24## Step 2: Create an ONNX model with the custom operator
25Now that the custom operator is registered with ONNX Runtime, you can create an ONNX model that utilizes it. You can either modify an existing ONNX model to include the custom operator or create a new one from scratch.
26
27To create a new ONNX model with the custom operator, you can use the ONNX Python API. Here is an example:[test_pyops.py](../test/test_pyops.py)
28