CodeSampleX

Exemplo

onnxruntime 1.28.0: ExecutionMode

Amostra verificada para pypi onnxruntime 1.28.0: ExecutionMode. O contrato rodou em python 3.12 · linux debian/x64 · docker e passou.

sha256:ca3490c8dabbf0d3ef8bd8acf92fe017782d4c636d3ca7c813b933ed46a08332

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 pip

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-07

Caso

HOW
Objetivo
verify onnxruntime.ExecutionMode in pkg:pypi/onnxruntime@1.28.0
Pacotes
Símbolos
  • onnxruntime.ExecutionMode
Criado
2026-09-07T06:56:38Z

Contrato

  1. onnxruntime.ExecutionMode provides ORT_SEQUENTIAL (0) and ORT_PARALLEL (1) enum members
  2. onnxruntime.SessionOptions execution_mode defaults to ExecutionMode.ORT_SEQUENTIAL
  3. onnxruntime.SessionOptions execution_mode can be set to ExecutionMode.ORT_PARALLEL and ExecutionMode.ORT_SEQUENTIAL
  4. onnxruntime.SessionOptions execution_mode rejects invalid types with TypeError
  5. onnxruntime.InferenceSession executes inference with SessionOptions configured for ORT_SEQUENTIAL and ORT_PARALLEL

Arquivos

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify onnxruntime.ExecutionMode in pkg:pypi/onnxruntime@1.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/onnxruntime@1.28.0
Demonstrate these symbols/APIs:
  - onnxruntime.ExecutionMode

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:1db1dde32d094fcf692b9aa68ed9154ecdb1eb20b8567b21483cbc9e3a58572c","contract":["onnxruntime.ExecutionMode provides ORT_SEQUENTIAL (0) and ORT_PARALLEL (1) enum members","onnxruntime.SessionOptions execution_mode defaults to ExecutionMode.ORT_SEQUENTIAL","onnxruntime.SessionOptions execution_mode can be set to ExecutionMode.ORT_PARALLEL and ExecutionMode.ORT_SEQUENTIAL","onnxruntime.SessionOptions execution_mode rejects invalid types with TypeError","onnxruntime.InferenceSession executes inference with SessionOptions configured for ORT_SEQUENTIAL and ORT_PARALLEL"],"goal":"verify onnxruntime.ExecutionMode in pkg:pypi/onnxruntime@1.28.0","kind":"HOW","packages":["pkg:pypi/onnxruntime@1.28.0"],"schemaVersion":1,"symbols":["onnxruntime.ExecutionMode"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/onnxruntime@1.28.0"],"schemaVersion":1,"subject":"pkg:pypi/onnxruntime@1.28.0","symbols":["onnxruntime.ExecutionMode"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-onnxruntime-execution-mode"
version = "0.1.0"
dependencies = [
    "onnxruntime==1.28.0",
]
requirements.txt
onnxruntime==1.28.0
sample.py
"""Sample module demonstrating onnxruntime.ExecutionMode configuration."""

from typing import Any, List
import onnxruntime as ort

# A minimal valid ONNX model (opset 21) containing a single Identity node: Y = Identity(X)
# This allows offline verification of InferenceSession without downloading models or external tools.
MINIMAL_IDENTITY_MODEL = (
    b"\x08\r\x12\ncsx-sample:H\n\x10\n\x01X\x12\x01Y\"\x08Identity\x12\ntest-model"
    b"Z\x13\n\x01X\x12\x0e\n\x0c\x08\x01\x12\x08\n\x02\x08\x01\n\x02\x08\x02"
    b"b\x13\n\x01Y\x12\x0e\n\x0c\x08\x01\x12\x08\n\x02\x08\x01\n\x02\x08\x02"
    b"B\x04\n\x00\x10\x15"
)


def create_session_options(
    execution_mode: ort.ExecutionMode,
    intra_op_num_threads: int = 1,
    inter_op_num_threads: int = 1,
) -> ort.SessionOptions:
    """Create and configure SessionOptions with the given execution mode."""
    options = ort.SessionOptions()
    options.execution_mode = execution_mode
    options.intra_op_num_threads = intra_op_num_threads
    options.inter_op_num_threads = inter_op_num_threads
    return options


def run_identity_model(
    model_bytes: bytes,
    execution_mode: ort.ExecutionMode,
    input_data: Any,
) -> List[Any]:
    """Execute inference on the identity model with specified execution mode."""
    options = create_session_options(execution_mode)
    session = ort.InferenceSession(
        model_bytes,
        sess_options=options,
        providers=["CPUExecutionProvider"],
    )
    input_name = session.get_inputs()[0].name
    return session.run(None, {input_name: input_data})
spec.json
{
  "schemaVersion": 1,
  "goal": "verify onnxruntime.ExecutionMode in pkg:pypi/onnxruntime@1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/onnxruntime@1.28.0"
  ],
  "symbols": [
    "onnxruntime.ExecutionMode"
  ]
}
test/contract.py
"""Contract verification tests for onnxruntime.ExecutionMode."""

import os
import sys

# Ensure sample root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import onnxruntime as ort
from sample import MINIMAL_IDENTITY_MODEL, create_session_options, run_identity_model


def test_execution_mode_enum_members():
    """Assertion 1: onnxruntime.ExecutionMode provides ORT_SEQUENTIAL (0) and ORT_PARALLEL (1) enum members."""
    assert hasattr(ort.ExecutionMode, "ORT_SEQUENTIAL")
    assert hasattr(ort.ExecutionMode, "ORT_PARALLEL")

    seq = ort.ExecutionMode.ORT_SEQUENTIAL
    par = ort.ExecutionMode.ORT_PARALLEL

    assert int(seq) == 0
    assert int(par) == 1
    assert seq.value == 0
    assert par.value == 1
    assert seq.name == "ORT_SEQUENTIAL"
    assert par.name == "ORT_PARALLEL"
    assert seq != par
    assert ort.ExecutionMode(0) == seq
    assert ort.ExecutionMode(1) == par


def test_default_session_options_execution_mode():
    """Assertion 2: onnxruntime.SessionOptions execution_mode defaults to ExecutionMode.ORT_SEQUENTIAL."""
    options = ort.SessionOptions()
    assert options.execution_mode == ort.ExecutionMode.ORT_SEQUENTIAL
    assert int(options.execution_mode) == 0


def test_configure_execution_mode():
    """Assertion 3: onnxruntime.SessionOptions execution_mode can be set to ExecutionMode.ORT_PARALLEL and ExecutionMode.ORT_SEQUENTIAL."""
    options = ort.SessionOptions()

    options.execution_mode = ort.ExecutionMode.ORT_PARALLEL
    assert options.execution_mode == ort.ExecutionMode.ORT_PARALLEL
    assert int(options.execution_mode) == 1

    options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
    assert options.execution_mode == ort.ExecutionMode.ORT_SEQUENTIAL
    assert int(options.execution_mode) == 0

    opts_par = create_session_options(ort.ExecutionMode.ORT_PARALLEL)
    assert opts_par.execution_mode == ort.ExecutionMode.ORT_PARALLEL

    opts_seq = create_session_options(ort.ExecutionMode.ORT_SEQUENTIAL)
    assert opts_seq.execution_mode == ort.ExecutionMode.ORT_SEQUENTIAL


def test_invalid_execution_mode_type():
    """Assertion 4: onnxruntime.SessionOptions execution_mode rejects invalid types with TypeError."""
    options = ort.SessionOptions()
    invalid_values = ["ORT_PARALLEL", 1, None, 3.14, []]

    for val in invalid_values:
        try:
            options.execution_mode = val
            assert False, f"Setting execution_mode to {val!r} should have raised TypeError"
        except TypeError:
            pass


def test_inference_session_with_execution_modes():
    """Assertion 5: onnxruntime.InferenceSession executes inference with SessionOptions configured for ORT_SEQUENTIAL and ORT_PARALLEL."""
    test_input = [[1.5, -2.5]]

    # Test with ORT_SEQUENTIAL
    out_seq = run_identity_model(MINIMAL_IDENTITY_MODEL, ort.ExecutionMode.ORT_SEQUENTIAL, test_input)
    assert len(out_seq) == 1
    assert out_seq[0].shape == (1, 2)
    assert abs(out_seq[0][0, 0] - 1.5) < 1e-5
    assert abs(out_seq[0][0, 1] - (-2.5)) < 1e-5

    # Test with ORT_PARALLEL
    out_par = run_identity_model(MINIMAL_IDENTITY_MODEL, ort.ExecutionMode.ORT_PARALLEL, test_input)
    assert len(out_par) == 1
    assert out_par[0].shape == (1, 2)
    assert abs(out_par[0][0, 0] - 1.5) < 1e-5
    assert abs(out_par[0][0, 1] - (-2.5)) < 1e-5


def main():
    test_execution_mode_enum_members()
    test_default_session_options_execution_mode()
    test_configure_execution_mode()
    test_invalid_execution_mode_type()
    test_inference_session_with_execution_modes()
    print("All onnxruntime.ExecutionMode contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder de origem

anônimo