Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python3
 
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
 
"""Smoke test for the onnxruntime-ep-webgpu Python package.
 
Tests:
1. Package import and library path resolution
2. EP registration with ONNX Runtime
3. Device discovery
4. Inference with a simple Mul model (requires WebGPU-capable hardware)
 
The inference test is skipped gracefully if no WebGPU device is available
(e.g., on CPU-only build agents), unless ORT_WEBGPU_TEST_REQUIRE_EP_DEVICE is enabled.
"""
 
import os
import platform
import sys
import tempfile
import traceback
from pathlib import Path
 
import numpy as np
import onnx
from onnx import TensorProto, helper
 
import onnxruntime as ort
 
VERBOSE = os.environ.get("ORT_TEST_VERBOSE", "").strip().lower() in ("1", "true", "yes")
REQUIRE_EP_DEVICE = os.environ.get("ORT_WEBGPU_TEST_REQUIRE_EP_DEVICE", "").strip().lower() in ("1", "true", "yes")
 
 
def debug_print(*args, **kwargs):
    """Print only when ORT_TEST_VERBOSE is set to a truthy value."""
    if VERBOSE:
        print(*args, **kwargs)
 
 
def print_ep_devices(ep_devices):
    """Print the EP and hardware properties for each discovered device."""
 
    for index, ep_device in enumerate(ep_devices):
        device = ep_device.device
        print(f"  EP device [{index}]:")
        print(f"    EP: name={ep_device.ep_name!r}, vendor={ep_device.ep_vendor!r}")
        print(f"    EP metadata: {ep_device.ep_metadata!r}")
        print(f"    EP options: {ep_device.ep_options!r}")
        print(
            f"    Hardware: type={device.type!r}, vendor_id={device.vendor_id}, "
            f"vendor={device.vendor!r}, device_id={device.device_id}"
        )
        print(f"    Hardware metadata: {device.metadata!r}")
 
 
def create_mul_model(output_dir: Path) -> Path:
    """Create a simple Mul model in `output_dir` and return the path to the saved .onnx file."""
    x = helper.make_tensor_value_info("x", TensorProto.FLOAT, [2, 3])
    y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [2, 3])
    z = helper.make_tensor_value_info("z", TensorProto.FLOAT, [2, 3])
 
    mul_node = helper.make_node("Mul", inputs=["x", "y"], outputs=["z"])
 
    graph = helper.make_graph([mul_node], "mul_graph", [x, y], [z])
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
    model.ir_version = 7
 
    model_path = output_dir / "mul.onnx"
    onnx.save(model, str(model_path))
    return model_path
 
 
def print_environment_info():
    """Print diagnostic information about the runtime environment."""
    print(f"  Python: {sys.version}")
    print(f"  Platform: {platform.platform()}")
    print(f"  Architecture: {platform.machine()}")
    print(f"  ONNX Runtime version: {ort.__version__}")
    print(f"  ONNX Runtime location: {ort.__file__}")
    print(f"  Available providers (built-in): {ort.get_available_providers()}")
    # Print relevant environment variables
    for var in sorted(os.environ):
        lower = var.lower()
        if any(kw in lower for kw in ["onnx", "ort", "gpu", "cuda", "vulkan", "webgpu", "dawn", "path", "ld_library"]):
            print(f"  ENV {var}={os.environ[var]}")
 
 
def test_import_and_library_path():
    """Test that the package imports and the library path is valid."""
    import onnxruntime_ep_webgpu as webgpu_ep  # noqa: PLC0415  # `import` should be at the top-level of a file.
 
    debug_print(f"  Package location: {webgpu_ep.__file__}")
    pkg_dir = Path(webgpu_ep.__file__).parent
    debug_print(f"  Package directory contents: {sorted(p.name for p in pkg_dir.iterdir())}")
 
    lib_path = webgpu_ep.get_library_path()
    assert Path(lib_path).is_file(), f"Library path does not exist: {lib_path}"
    print(f"OK: Library path: {lib_path}")
 
    ep_name = webgpu_ep.get_ep_name()
    assert ep_name == "WebGpuExecutionProvider", f"Unexpected EP name: {ep_name}"
    print(f"OK: EP name: {ep_name}")
 
    ep_names = webgpu_ep.get_ep_names()
    assert ep_names == ["WebGpuExecutionProvider"], f"Unexpected EP names: {ep_names}"
    print(f"OK: EP names: {ep_names}")
 
 
def test_registration_and_inference():
    """Test EP registration, device discovery, and inference."""
    import onnxruntime_ep_webgpu as webgpu_ep  # noqa: PLC0415  # `import` should be at the top-level of a file.
 
    lib_path = webgpu_ep.get_library_path()
    ep_name = webgpu_ep.get_ep_name()
    registration_name = "webgpu_plugin_test"
 
    # Register the plugin EP
    debug_print(f"  Registering library: {lib_path}")
    debug_print(f"  Library file size: {Path(lib_path).stat().st_size} bytes")
    ort.register_execution_provider_library(registration_name, lib_path)
    print(f"OK: Registered EP library as '{registration_name}'")
 
    try:
        # Get EP devices
        all_ep_devices = ort.get_ep_devices()
 
        if VERBOSE:
            print("\n--- ORT EP devices ---")
            print_ep_devices(all_ep_devices)
 
        webgpu_ep_devices = [d for d in all_ep_devices if d.ep_name == ep_name]
        print(f"Found {len(webgpu_ep_devices)} WebGPU EP device(s)")
 
        if not webgpu_ep_devices:
            if REQUIRE_EP_DEVICE:
                raise RuntimeError("No WebGPU EP devices available, but ORT_WEBGPU_TEST_REQUIRE_EP_DEVICE is enabled")
            print("SKIP: No WebGPU EP devices available — skipping inference test")
            return
 
        # WebGPU selects the GPU independently, so any non-virtual WebGPU EP device is sufficient here.
        webgpu_ep_device = webgpu_ep_devices[0]
 
        # Create session with WebGPU EP
        sess_options = ort.SessionOptions()
        sess_options.add_session_config_entry("session.disable_cpu_ep_fallback", "1")
        sess_options.add_provider_for_devices([webgpu_ep_device], {})
        assert sess_options.has_providers(), "SessionOptions should have providers after add_provider_for_devices"
        print("OK: Session options configured with WebGPU EP")
 
        with tempfile.TemporaryDirectory() as model_dir:
            model_path = create_mul_model(Path(model_dir))
            debug_print(f"  Model path: {model_path}")
            sess = ort.InferenceSession(model_path, sess_options=sess_options)
            debug_print(f"  Session providers: {sess.get_providers()}")
            print("OK: InferenceSession created")
 
            # Run inference
            x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32)
            y = np.array([[2.0, 3.0, 4.0], [5.0, 6.0, 7.0]], dtype=np.float32)
            expected = x * y
 
            outputs = sess.run(None, {"x": x, "y": y})
            result = outputs[0]
 
            np.testing.assert_allclose(result, expected, rtol=1e-5, atol=1e-5)
            print("OK: Inference result matches expected output")
 
            del sess
            print("OK: Session released")
 
    finally:
        ort.unregister_execution_provider_library(registration_name)
        print(f"OK: Unregistered EP library '{registration_name}'")
 
 
def main():
    print("=== WebGPU Plugin EP Python Package Test ===")
 
    if VERBOSE:
        # Set verbose ORT logging so ORT internals are visible in CI logs
        ort.set_default_logger_severity(0)
 
        print("\n--- Environment ---")
        print_environment_info()
 
    print("\n--- Test 1: Import and library path ---")
    test_import_and_library_path()
 
    print("\n--- Test 2: Registration and inference ---")
    test_registration_and_inference()
 
    print("\n=== All tests passed ===")
 
 
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"\nFAILED: {e}", file=sys.stderr)
        traceback.print_exc()
        sys.exit(1)