repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
onnxruntime | onnxruntime/test/testdata/transform/fusion/reshape_fusion_gen.py | .py | import onnx
from onnx import TensorProto, helper
def save_model(graph, file_name):
model = helper.make_model(graph)
onnx.checker.check_model(model)
onnx.save(model, file_name)
graph = helper.make_graph(
[ # nodes
helper.make_node("Shape", ["SubgraphRoot"], ["shape1_out"], "shape1"),
... | 570 | 23,827 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/dynamic_quantize_matmul.py | .py | import onnx
from onnx import TensorProto, helper
def GenerateModel(model_name, b_has_zp=True, has_bias=False, bias_ND=False): # noqa: N802
mul_output = "Mul_output" if has_bias else "output"
nodes = [ # construct graph
helper.make_node(
"DynamicQuantizeLinear",
["input"],
... | 77 | 2,654 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/attention_gen.py | .py | import sys
import onnx
from onnx import TensorProto, helper
matmul_q_weights = [
-0.10791015625,
-0.04193115234375,
0.09051513671875,
0.025787353515625,
-0.11572265625,
-0.126953125,
-0.043304443359375,
-0.02984619140625,
0.033538818359375,
-0.05755615234375,
-0.04986572265... | 635 | 20,033 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/embed_layer_norm_gen.py | .py | import onnx
from onnx import TensorProto, helper
from packaging import version
if version.parse(onnx.__version__) == version.parse("1.8.0"):
opset_version = 13
elif version.parse(onnx.__version__) == version.parse("1.6.0"):
opset_version = 11
else:
raise RuntimeError("Please pip install onnx==1.8.0 or 1.6.... | 989 | 33,312 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/gemm_sum_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
# The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.ver... | 185 | 7,106 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/matmul_scale_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
# The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.ver... | 282 | 9,276 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/fast_gelu.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
# Gelu formula: x * 0.5 * (1.0 + tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x)))
has_bias = True # change it to True to generate fast_gelu_with_bias.onnx
gelu_use_graph_input = True # change it to False to... | 111 | 3,944 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/matmul_integer_to_float_large_tensor.py | .py | import onnx
from onnx import TensorProto, helper
def GenerateModel(model_name): # noqa: N802
inputs = []
outputs = []
initializers = []
nodes = []
inputs.append(helper.make_tensor_value_info("inputA", TensorProto.FLOAT, [16, 32, 1280, 1280]))
inputs.append(helper.make_tensor_value_info("inpu... | 48 | 1,540 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/isinf_reducesum.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
opsets = []
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
onnxdomain.domain = "" # The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
opsets.append(onnxdomain)
msdo... | 50 | 1,496 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/div_mul.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
opsets = []
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
onnxdomain.domain = "" # The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
opsets.append(onnxdomain)
msdo... | 71 | 2,667 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/constant_folding_with_shape_to_initializer.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
X = helper.make_tensor_value_info("input", TensorProto.FLOAT, [2, 4, 8])
Y = helper.make_tensor_value_info("output", TensorProto.FLOAT, [2, 4, 16])
matmul_weight_vals = (0.01 * np.arange(2 * 4 * 4, dtype=np.float32))... | 111 | 4,383 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/label_encoder.py | .py | from onnx import OperatorSetIdProto, TensorProto, helper, save
opsets = []
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 19
onnxdomain.domain = "" # The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
opsets.append(onnxdomain)
msdomain =... | 164 | 5,010 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/bias_dropout_residual_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
# inputs/outputs
A = helper.make_tensor_value_info("A", TensorProto.FLOAT, ["unk_1", "unk_2", 3072])
B = helper.make_tensor_value_info("B", TensorProto.FLOAT, [3072])
R = helper.make_tensor_value_info("R", TensorProto.FLOAT, ["unk_1", "unk_2", 3072])... | 297 | 9,426 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/matmul_integer_to_float.py | .py | import onnx
from onnx import TensorProto, helper
def MakeSubGraph(suffix, has_bias): # noqa: N802
mul_bottom_output = "mul_output" + suffix if has_bias else "output" + suffix
nodes = [
helper.make_node(
"MatMulInteger",
["a_quantized", "b_quantized" + suffix, "a_zp", "b_zp" + ... | 106 | 3,309 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/gemm_transpose_gen_2.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
# The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.ver... | 71 | 2,750 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/bias_softmax_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
add = helper.make_node("Add", ["input", "bias"], ["add_out"], "add")
reverseadd = helper.make_node("Add", ["bias", "input"], ["add_out"], "add")
softmax1 = helper.make_node("Softmax", ["add_out"], ["output"], "softmax", axis=1)
softmax3 = helper.make... | 245 | 7,755 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/create_conv_hardsigmoid.py | .py | import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[ # nodes
# fusable, const_min_negative should be replaced
helper.make_node("Conv", ["X", "W"], ["conv0_out"], "Conv0"),
helper.make_node("HardSigmoid", ["conv0_out"], ["hardsigmoid0_out"], "HardSigmoid0"),
],
... | 22 | 716 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/fast_gelu2.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
# Gelu formula: x * 0.5 * (1.0 + tanh((sqrt(2 / pi) * (x + 0.044715 * pow(x, 3)))))
has_bias = False # change it to True to generate fast_gelu_openai_with_bias.onnx
gelu_use_graph_input = True # change it to False t... | 107 | 3,844 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/gemm_transpose_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
# The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.ver... | 100 | 3,493 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/layer_norm_t5_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
def GenerateModel(model_name, has_casts=False): # noqa: N802
nodes = [ # SimplifiedLayerNorm subgraph
helper.make_node("Pow", ["cast_A" if has_casts else "A", "pow_in_2"], ["pow_out"], "pow"),
helper.make_node("ReduceMean", ["p... | 64 | 2,359 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/qdq_fusion_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
# inputs/outputs
A = helper.make_tensor_value_info("A", TensorProto.FLOAT, ["unk_1", "unk_2", 1024, 4096])
B = helper.make_tensor_value_info("B", TensorProto.FLOAT, ["unk_1", "unk_2", 1024, 4096])
# initializers
quant_scale = helper.make_tensor("qua... | 74 | 2,299 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/layer_norm_shared_input.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
# in gpt_j_residual, there will be 2 LN share the same input
def GenerateModel(model_name): # noqa: N802
nodes = [
# LN1 subgraph
help... | 72 | 3,578 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/bias_gelu_gen.py | .py | import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[ # nodes
# Add node before Gelu
helper.make_node("Add", ["A", "B"], ["add0_out"], "add0"),
# Gelu subgraph
helper.make_node("Div", ["add0_out", "div_const"], ["div_out"], "div"),
helper.make_node("... | 69 | 2,457 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/bias_gelu_matmul_gen.py | .py | import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[ # nodes
# Add node before Gelu
helper.make_node("Add", ["A", "B"], ["add0_out"], "add0"),
# Gelu subgraph
helper.make_node("Div", ["add0_out", "div_const"], ["div_out"], "div"),
helper.make_node("... | 35 | 1,487 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/fuse-pad-avgpool-gen.py | .py | from pathlib import Path
import numpy as np
import onnx
HERE = Path(__file__).parent.resolve(strict=True)
TEST = False
if TEST:
import onnxruntime
def generate_fuse_pad_avgpool():
parameters = {
"fuse-pad-avgpool": (
{},
[[1.333333, 2.333333, 1.777778], [3.0, 5.0, 3.666667],... | 69 | 3,038 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/create_conv_with_padding_relu.py | .py | import onnx
from onnx import TensorProto, helper
# copied and adapted from here:
# https://github.com/onnx/onnx/blob/c940fa3fea84948e46603cab2f86467291443beb/docs/Operators.md?plain=1#L3494-L3502
graph = helper.make_graph(
[ # nodes
# Convolution with padding
helper.make_node("Conv", ["x", "W"], ... | 25 | 833 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/bitmask_dropout_fusion_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 13
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.version = 1
msdomain.domain = "com.microsoft"
opsets = [onnxdomain, msdomain]
def save(model_path, nodes, inputs, outputs, ini... | 119 | 4,749 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/skip_layer_norm_gen.py | .py | from enum import Enum
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
class Format(Enum):
Format1 = (1,)
Format2 = (2,)
Format3 = 3
def generate_model(model_format, model_name, multi_output_add=False, add_output_in_graph_output=False, with_cast=False):
nodes = [] # LayerNorm s... | 163 | 6,182 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/create_conv_clip11.py | .py | import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[ # nodes
# fusable, min/max from constant inputs.
helper.make_node("Conv", ["X0", "W"], ["conv0_out"], "Conv0"),
helper.make_node("Clip", ["conv0_out", "const_min", "const_max"], ["clip0_out"], "Clip0"),
#... | 38 | 1,801 |
onnxruntime | onnxruntime/test/testdata/training_api/ort_format/prepare_artifacts.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""This file is used to generate test data for ort format model tests in
orttraining/orttraining/test/training_api/core/training_capi_tests.cc."""
import onnx
import torch
import torch.nn as nn
from onnxruntime.training imp... | 71 | 1,977 |
onnxruntime | onnxruntime/test/testdata/transformers/tiny_t5/tiny_t5.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import os
from sentencepiece import SentencePieceProcessor, SentencePi... | 86 | 2,685 |
onnxruntime | onnxruntime/test/testdata/lora/two_params_lora_model.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import numpy as np
import onnx
import onnxruntime as ort
model_path = "two_params_lora_model.onnx"
adapter_path = "two_params_lora_model.onnx_adapter"
def create_model(model_path: os.PathLike):
#### Inputs
... | 157 | 5,076 |
onnxruntime | onnxruntime/test/providers/cpu/nn/deform_conv_expected_gen.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Generate expected outputs for DeformConv tests using torchvision.ops.deform_conv2d.
Run with: .venv/bin/python onnxruntime/test/providers/cpu/nn/deform_conv_expected_gen.py
Outputs C++-friendly std::vector<float> initiali... | 181 | 5,890 |
onnxruntime | onnxruntime/test/providers/cpu/nn/lp_pool_test_generator.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import torch
from torch import nn
# use this code to generate test data for PoolTest.LpPool1d and PoolTest.LpPool2d
def generate_lppool_1d_test_cases() -> None:
p = 2
x = np.array(
[
... | 63 | 1,577 |
onnxruntime | onnxruntime/test/providers/cpu/tensor/resize_sample_test_gen.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This code is used to generate test data for the test case:
# TEST(ResizeOpTest, NoAntialias_AlignCorners_Cubic_Floor_NHWC)
# located in onnxruntime/test/providers/cpu/tensor/resize_op_test.cc
import torch
import torch.nn.f... | 35 | 1,003 |
onnxruntime | onnxruntime/test/providers/cpu/tensor/grid_sample_test_gen.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This code is used to generate the test cases for the GridSample operator
# in onnxruntime/test/providers/cpu/tensor/grid_sample_test.cc
import torch
# Define the input dimensions
N, C, D, H, W = 2, 2, 3, 3, 2
# Define th... | 98 | 4,681 |
onnxruntime | onnxruntime/test/providers/cpu/tensor/gen_mvn_test_data.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--shape", type=int, nargs="+", required=True)
parser.add_argument("--axes", type=int, nargs="+", required=True)
args = parser.parse_... | 38 | 1,025 |
onnxruntime | onnxruntime/test/providers/cpu/tensor/affine_grid_test_gen.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This code is used to generate the test cases for the AffineGrid operator
# in onnxruntime/test/providers/cpu/tensor/affine_grid_test.cc
import argparse
import numpy as np
import torch
from torch.nn.functional import affin... | 118 | 5,620 |
onnxruntime | onnxruntime/test/providers/cpu/rnn/LSTM.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
DebugOutput = True
np.set_printoptions(suppress=True) # , precision=16, floatmode='maxprec')
def print_with_shape(name, a, force_output=False):
if force_output or DebugOutput:
print(name + ... | 744 | 25,978 |
onnxruntime | onnxruntime/test/providers/cpu/rnn/GRU.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
DebugOutput = False
np.set_printoptions(suppress=True) # , precision=16, floatmode='maxprec')
def print_with_shape(name, a, force_output=False):
if force_output or DebugOutput:
print(name + ... | 451 | 16,172 |
onnxruntime | onnxruntime/test/providers/cpu/reduction/reduction_test_cases_generator.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
def TestReduction(op, data, axes, keepdims): # noqa: N802
if op == "ReduceL1":
return np.sum(a=np.abs(data), axis=axes, keepdims=keepdims)
elif op == "ReduceL2":
return np.sqrt(np... | 159 | 4,618 |
onnxruntime | onnxruntime/lora/adapter_format/compile_schema.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import pathlib
import subprocess
SCRIPT_DIR = pathlib.Path(__file__).parent.resolve()
def generate_cpp(flatc: pathlib.Path, schema_path: pathlib.Path):
# run flatc to generate C++... | 56 | 1,635 |
onnxruntime | tools/python/onnx_test_data_utils.py | .py | import argparse
import glob
import os
import sys
import numpy as np
import onnx
from onnx import numpy_helper
def read_tensorproto_pb_file(filename):
"""Return tuple of tensor name and numpy.ndarray of the data from a pb file containing a TensorProto."""
tensor = onnx.load_tensor(filename)
np_array = nu... | 247 | 9,255 |
onnxruntime | tools/python/run_workflows_for_branch.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import os
import subprocess
import yaml
def get_repo_root():
result = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=False)
if re... | 150 | 5,437 |
onnxruntime | tools/python/resolve_absl_deps_dynamic.py | .py | #!/usr/bin/env python3
"""Resolve and topologically sort Abseil library dependencies."""
from __future__ import annotations
import argparse
import io
import os
import re
import sys
import tempfile
import zipfile
from typing import TYPE_CHECKING
import requests
if TYPE_CHECKING:
from collections.abc import Seque... | 247 | 8,709 |
onnxruntime | tools/python/update_version.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import re
import shutil
import sys
from pathlib import Path
# --- Helper Functions for Updating Files ---
def update_versioning_md(file_path: Path, new_version: str):
"""Updates the version table... | 219 | 9,156 |
onnxruntime | tools/python/materialize_onnx_node_tests.py | .py | #!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Materialize ONNX node-test artifacts from ONNX's Python generators.
ONNX PR onnx/onnx#7959 deletes the on-disk node-test corpus
(``onnx/backend/test/data/node/**``) that ONNX Runtime's C++ ``onnx_tes... | 649 | 31,946 |
onnxruntime | tools/python/create_reduced_build_config.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import pathlib
import sys
import typing
import onnx
from util.file_utils import files_from_file_or_dir, path_match_suffix_ignore_case
def _get_suffix_match_predicate(suffix: str):
... | 158 | 6,058 |
onnxruntime | tools/python/compare_node_test_corpora.py | .py | #!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Byte-equivalence comparator for ONNX node-test corpora.
This is the CANONICAL, build-wired equivalence check (the ``onnx_node_tests_equivalence``
ctest invokes it): it compares an ALREADY-materialize... | 104 | 4,183 |
onnxruntime | tools/python/update_ctest_path.py | .py | #!/usr/bin/env python3
# We have some Azure DevOps pipelines that each has two parts: the first part
# builds source code into binary then uploads it, then the second part downloads
# the binary and runs tests. Because the second part may need GPUs. We use
# CMake and CTest to run tests. However, in the first part cma... | 133 | 5,437 |
onnxruntime | tools/python/remove_initializer_from_input.py | .py | import argparse
import onnx
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="input model")
parser.add_argument("--output", required=True, help="output model")
args = parser.parse_args()
return args
def remove_initializer_from_input(model: on... | 38 | 994 |
onnxruntime | tools/python/sparsify_initializers.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
# This script opens an existing model in onnx format and attempts to
# mo... | 185 | 7,209 |
onnxruntime | tools/python/gen_contrib_doc.py | .py | #!/usr/bin/env python
# This file is copied and adapted from https://github.com/onnx/onnx repository.
# There was no copyright statement on the file at the time of copying.
import argparse
import os
import pathlib
import sys
from collections import defaultdict
import numpy as np
import onnxruntime.capi.onnxruntime_... | 399 | 13,644 |
onnxruntime | tools/python/compile_contributors.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Compile Contributors Script
---------------------------
Description:
This script compiles contributor information by comparing two git branches/commits.
It identifies Pull Requests, handles cherry-picked commits (... | 519 | 20,958 |
onnxruntime | tools/python/find_optimizer_opset_version_updates_required.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import glob
import logging
import os
import re
logging.basicConfig(format="[%(levelname)s] - %(message)s", level=logging.DEBUG)
log = logging.getLogger()
def parse_args():
parser ... | 216 | 8,372 |
onnxruntime | tools/python/example_operator_perf_test.py | .py | """
Example python code for creating a model with a single operator and performance testing it with various
input combinations.
"""
import time
import timeit
import numpy as np
import onnx
# if you copy this script elsewhere you may need to add the tools\python dir to the sys.path for this
# import to work.
# e.g. s... | 150 | 5,439 |
onnxruntime | tools/python/trigger_and_wait_pipelines.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import argparse
import datetime
import json
import logging
import os
import sys
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
import pan... | 516 | 16,839 |
onnxruntime | tools/python/cherry_pick_utils.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import re
import subprocess
import sys
def run_command(command_list, cwd=None, silent=False):
"""Run a command using a list of arguments for security (no shell=True)."""
try:
result = subprocess.run(command_... | 102 | 3,901 |
onnxruntime | tools/python/onnx2tfevents.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
# This tool is to convert ONNX model to TensorBoard events file so that we can visualize the model in TensorBoard.
# this is especially useful for debugging large models that cannot be visualized in Netron.
#
# Usage: python... | 373 | 14,253 |
onnxruntime | tools/python/dump_subgraphs.py | .py | import argparse
import os
import onnx
def export_and_recurse(node, attribute, output_dir, level):
name = node.name
name = name.replace("/", "_")
sub_model = onnx.ModelProto()
sub_model.graph.MergeFrom(attribute.g)
filename = "L" + str(level) + "_" + node.op_type + "_" + attribute.name + "_" + nam... | 55 | 1,806 |
onnxruntime | tools/python/wgsl_gen.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""CLI entry point for the WGSL template generator.
Invoked from CMake during the WebGPU EP build to translate
``*.wgsl.template`` files into C++ headers.
Usage::
python wgsl_gen.py \\
-i ... | 156 | 4,795 |
onnxruntime | tools/python/run_android_emulator.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import argparse
import contextlib
import shlex
import sys
import util.android as android
from util import get_logger
log = get_logger("run_android_emulator")
def p... | 95 | 3,265 |
onnxruntime | tools/python/convert_onnx_models_to_ort.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This script is a stub that uses the model conversion script from the util subdirectory.
# We do it this way so we can use relative imports in that script, which makes it easy to include
# in the ORT p... | 22 | 956 |
onnxruntime | tools/python/ort_test_dir_utils.py | .py | import glob
import os
import shutil
import numpy as np
import onnx
import onnx_test_data_utils
from onnx import TensorProto, numpy_helper
import onnxruntime as ort
def _get_numpy_type(model_info, name) -> np.dtype:
for i in model_info:
if i.name == name:
type_name = i.type.WhichOneof("value"... | 267 | 10,896 |
onnxruntime | tools/python/gen_opkernel_doc.py | .py | #!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import io # noqa: F401
import os
import pathlib
from collections import defaultdict
import onnxruntime.capi.onnxruntime_pybind11_state as rtpy
def format_version_range(v):
if v[1]... | 237 | 8,709 |
onnxruntime | tools/python/dump_ort_model.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import contextlib
import os
import sys
import typing
# the import of FbsTypeInfo sets up the path so we can import ort_flatbuffers_py
from util.ort_format_model.types import FbsTypeInfo # isort:skip
import o... | 152 | 6,063 |
onnxruntime | tools/python/run_packaging_pipelines.py | .py | # See PythonTools.md in this folder
import argparse
import json
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta
from typing import Literal, TypedDict
from urllib.parse import urlparse
import requests
import yaml
# --- Data Structur... | 506 | 21,687 |
onnxruntime | tools/python/run_adb.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import logging
import os
import sys
from util import run
from util.android import get_sdk_tool_paths
def run_adb(android_sdk_root: str, args: list[str]):
sdk_to... | 36 | 891 |
onnxruntime | tools/python/upload_and_run_browserstack_tests.py | .py | import argparse
import os
import sys
import time
from pathlib import Path
import requests
script_description = """
After building ONNXRuntime for Android or iOS, use this script to upload the app and test files to BrowserStack then
run the tests on the specified devices.
Find the Android test app in the repo here (a... | 179 | 5,988 |
onnxruntime | tools/python/cherry_pick.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Cherry-Pick Helper Script
-------------------------
Description:
This script automates the process of cherry-picking commits for a release branch.
It fetches merged PRs with a specific label, sorts them by merge d... | 319 | 11,535 |
onnxruntime | tools/python/get_submodules.py | .py | import argparse
import configparser
import json
import re
from pathlib import Path
import pygit2
def format_component(submod):
return {"component": {"type": "git", "git": {"commitHash": str(submod.head_id), "repositoryUrl": submod.url}}}
def lookup_submodule(repo, submodule_path):
submodule = repo.lookup_s... | 69 | 2,586 |
onnxruntime | tools/python/benchmark_mmap_ort.py | .py | #!/usr/bin/env python3
"""
Developer benchmark for memory-mapped .ort model loading.
Compares session construction time and process memory across loading configurations:
1. Standard .ort load (file read into heap buffer)
2. Memory-mapped .ort load (session.use_memory_mapped_ort_model)
3. Memory-mapped + direct i... | 386 | 13,938 |
onnxruntime | tools/python/fix_long_lines.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import logging
import os
import pathlib
import shutil
import tempfile
from util import logger, run
_log = logger.get_logger("fix_long_lines", logging.INFO)
# look for long lines in the file, and if found r... | 134 | 4,156 |
onnxruntime | tools/python/wgsl_template/types.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Shared data structures for the WGSL template engine."""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class CodeReference:
"""Where a parsed line came from in the original so... | 88 | 2,091 |
onnxruntime | tools/python/wgsl_template/parser.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""PASS1: comment stripping, #include expansion, #define substitution.
Three sub-passes run in order on each top-level template:
1. :func:`_strip_comments` — replace ``//`` and ``/* */`` regions with
empty text while pres... | 353 | 13,564 |
onnxruntime | tools/python/wgsl_template/errors.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Exception types for the WGSL template engine."""
from __future__ import annotations
class WgslTemplateError(Exception):
"""Base class for all WGSL template errors."""
def __init__(
self,
message:... | 39 | 989 |
onnxruntime | tools/python/wgsl_template/__init__.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""WGSL template engine.
The public entry point is :func:`build`, which orchestrates the
load -> parse -> generate -> emit pipeline.
"""
from __future__ import annotations
import os
import shutil
from collections.abc import... | 147 | 4,690 |
onnxruntime | tools/python/wgsl_template/generator.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""PASS2: pattern matching, directives, and code generation.
The state machine in :func:`_generate_impl` tracks parentheses,
brackets, a function-call stack, the ``$MAIN`` context, and a separate
output bucket for ``#if``/``#... | 783 | 34,504 |
onnxruntime | tools/python/wgsl_template/loader.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""PASS0: load template files from one or more source directories."""
from __future__ import annotations
import os
import re
from collections.abc import Sequence
from pathlib import Path
from typing import Union
from .error... | 195 | 5,561 |
onnxruntime | tools/python/wgsl_template/code_pattern.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Built-in code patterns and indices-helper rewrite table.
A :class:`CodePattern` is a single rewrite rule consumed by the PASS2
generator. ``DEFAULT_PATTERNS`` are always active; the named entries
in :func:`lookup_pattern` ... | 233 | 7,504 |
onnxruntime | tools/python/wgsl_template/code_generator/static_cpp.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Static C++ code generator.
The single :class:`StaticCodeGenerator` class implements both
``static-cpp`` (uses a string table) and ``static-cpp-literal``
(inlines string literals); the only difference is the constructor
fla... | 356 | 13,675 |
onnxruntime | tools/python/wgsl_template/code_generator/__init__.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Code generators that emit C++ from PASS2 results.
The single :class:`StaticCodeGenerator` covers both ``static-cpp`` and
``static-cpp-literal`` (the difference is whether a string table is
used).
"""
from __future__ impor... | 42 | 1,160 |
onnxruntime | tools/python/wgsl_template/test/test_loader.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Unit tests for the PASS0 loader.
Uses temporary directories with inline fixtures.
"""
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
# Make the wgsl_template packa... | 216 | 7,903 |
onnxruntime | tools/python/wgsl_template/test/test_build.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""End-to-end tests for the top-level build() orchestrator.
Combines focused unit tests with a fixture-driven runner over the
``build-*`` cases in ``testcases/``. Generated files are compared
against the ``expected/<generator... | 262 | 9,843 |
onnxruntime | tools/python/wgsl_template/test/test_parser.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Unit tests for the PASS1 parser.
Mixes inline temp-dir tests for tightly scoped behaviors with a
fixture-driven runner that pulls ``parser-*`` and ``loader-*`` cases
from the ``testcases/`` fixtures next to this file.
"""
... | 314 | 11,559 |
onnxruntime | tools/python/wgsl_template/test/golden_compare.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Shared helpers for comparing generated WGSL output against goldens.
Some details of the generated file set are host-dependent and NOT part
of the equivalence contract (see DESIGN_wgsl_python_port.md,
"Determinism"): ``__st... | 62 | 2,545 |
onnxruntime | tools/python/wgsl_template/test/run_tests.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Test runner for the WGSL template Python port.
Discovers ``test_*.py`` siblings and aggregates them into one suite.
Invoked manually or via ``ctest`` (see CMake's ``add_test`` wiring).
"""
from __fu... | 35 | 978 |
onnxruntime | tools/python/wgsl_template/test/test_in_tree_smoke.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Golden tests against the real in-tree wgsl.template files.
These templates back shipped WebGPU operators (Pad, Transpose,
im2col-matmul, and others under core/providers/webgpu). The generated
C++ is compared against a comm... | 110 | 3,734 |
onnxruntime | tools/python/wgsl_template/test/test_generator.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Unit tests for the PASS2 generator.
Combines focused unit tests with a fixture-driven runner that pulls
``generator-*`` cases from the ``testcases/`` fixtures next to this
file. We only fixture-test cases where:
* The fix... | 298 | 10,775 |
onnxruntime | tools/python/util/__init__append.py | .py | # appended to the __init__.py in the onnxruntime module's 'tools' folder from /tools/python/util/__init__append.py
import importlib.util
have_torch = importlib.util.find_spec("torch")
if have_torch:
from .pytorch_export_helpers import infer_input_info # noqa: F401
| 7 | 271 |
onnxruntime | tools/python/util/qnn_helpers.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
def parse_qnn_version_from_sdk_yaml(qnn_home):
sdk_file = os.path.join(qnn_home, "sdk.yaml")
with open(sdk_file) as f:
for line in f:
if line.strip().startswith("... | 16 | 478 |
onnxruntime | tools/python/util/logger.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import logging
def get_logger(name, level=logging.DEBUG):
logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s] - %(message)s")
logger = logging.getLogger(name)
logger.setLevel(level)
return logge... | 12 | 322 |
onnxruntime | tools/python/util/platform_helpers.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
def is_windows():
return sys.platform.startswith("win")
def is_macOS(): # noqa: N802
return sys.platform.startswith("darwin")
def is_linux():
return sys.platform.startswith("linux")
| 17 | 307 |
onnxruntime | tools/python/util/reduced_build_config_parser.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import os
# Check if the flatbuffers module is available. If not we cannot handle type reduction information in the config.
try:
import flatbuffers # noqa: F401
have_flatbuffers =... | 204 | 9,958 |
onnxruntime | tools/python/util/__init__.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .get_azcopy import get_azcopy # noqa: F401
from .logger import get_logger
from .platform_helpers import is_linux, is_macOS, is_windows # noqa: F401
from .qnn_helpers import parse_qnn_version_from_sdk_yaml # noqa: F401... | 30 | 1,027 |
onnxruntime | tools/python/util/run.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import logging
import os
import shlex
import subprocess
_log = logging.getLogger("util.run")
def run(
*args,
cwd=None,
input=None,
capture_stdout=False,
capture_stderr... | 64 | 1,703 |
onnxruntime | tools/python/util/add_openvino_win_libs.py | .py | # Copyright (C) 2022-2023 Intel Corporation
# Licensed under the MIT License
import os
import site
import sys
def add_openvino_libs_to_path() -> None:
"""Adds OpenVINO libraries to the PATH environment variable on Windows."""
if sys.platform == "win32":
# Installer, pip installs openvino dlls to the ... | 36 | 1,637 |
onnxruntime | tools/python/util/file_utils.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import os
import pathlib
import typing
def path_match_suffix_ignore_case(path: pathlib.Path | str, suffix: str) -> bool:
"""
Returns whether `path` ends in `suffix`, ignoring case.... | 48 | 1,525 |
onnxruntime | tools/python/util/update_onnx_opset.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import os
import pathlib
from .onnx_model_utils import update_onnx_opset
def update_onnx_opset_helper():
parser = argparse.ArgumentParser(
f"{os.path.basename(__file__)}:{... | 32 | 1,151 |
onnxruntime | tools/python/util/pytorch_export_helpers.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import inspect
from collections import abc
import torch
def _parse_inputs_for_onnx_export(all_input_parameters, inputs, kwargs):
# extracted from https://github.com/microsoft/onnxrun... | 134 | 5,876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.