Исходный код СУБД 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
#!/usr/bin/env python3
"""Smoke test for the onnxruntime-ep-cuda 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 CUDA-capable hardware)
 
The inference test is skipped gracefully if no CUDA device is available
(e.g., on CPU-only build agents).
"""
 
import os
import platform
import sys
import tempfile
import traceback
from contextlib import suppress
from pathlib import Path
 
# On Windows, Python 3.8+ no longer searches PATH when loading DLLs. Add each
# PATH entry explicitly so that CUDA and cuDNN libraries placed there (e.g. via
# ##vso[task.prependpath] in Azure Pipelines) are visible to LoadLibraryExW
# when ORT loads the CUDA plugin EP shared library.
if sys.platform == "win32" and sys.version_info >= (3, 8):
    for _path_entry in os.environ.get("PATH", "").split(os.pathsep):
        _normalized_path_entry = _path_entry.strip().strip('"').strip("'")
        if _normalized_path_entry and os.path.isdir(_normalized_path_entry):
            with suppress(OSError):
                os.add_dll_directory(_normalized_path_entry)
 
import numpy as np
import onnx
 
import onnxruntime as ort
 
VERBOSE = os.environ.get("ORT_TEST_VERBOSE", "").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 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 = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [2, 3])
    y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [2, 3])
    z = onnx.helper.make_tensor_value_info("z", onnx.TensorProto.FLOAT, [2, 3])
 
    mul_node = onnx.helper.make_node("Mul", inputs=["x", "y"], outputs=["z"])
 
    graph = onnx.helper.make_graph([mul_node], "mul_graph", [x, y], [z])
    model = onnx.helper.make_model(graph, opset_imports=[onnx.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", "nv", "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_cuda as cuda_ep  # noqa: PLC0415
 
    debug_print(f"  Package location: {cuda_ep.__file__}")
    pkg_dir = Path(cuda_ep.__file__).parent
    debug_print(f"  Package directory contents: {sorted(p.name for p in pkg_dir.iterdir())}")
 
    lib_path = cuda_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 = cuda_ep.get_ep_name()
    assert ep_name == "CUDAExecutionProvider", f"Unexpected EP name: {ep_name}"
    print(f"OK: EP name: {ep_name}")
 
    ep_names = cuda_ep.get_ep_names()
    assert ep_names == ["CUDAExecutionProvider"], 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_cuda as cuda_ep  # noqa: PLC0415
 
    lib_path = cuda_ep.get_library_path()
    ep_name = cuda_ep.get_ep_name()
    registration_name = "cuda_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:
        # Discover devices
        all_devices = ort.get_ep_devices()
        debug_print(f"  All devices: {[(d.ep_name, getattr(d, 'device_id', 'N/A')) for d in all_devices]}")
        cuda_devices = [d for d in all_devices if d.ep_name == ep_name]
        print(f"Found {len(cuda_devices)} CUDA plugin device(s)")
 
        if not cuda_devices:
            print("SKIP: No CUDA plugin devices available — skipping inference test")
            return
 
        # Create session with CUDA plugin EP
        sess_options = ort.SessionOptions()
        sess_options.add_session_config_entry("session.disable_cpu_ep_fallback", "1")
        sess_options.add_provider_for_devices(cuda_devices, {})
        assert sess_options.has_providers(), "SessionOptions should have providers after add_provider_for_devices"
        print("OK: Session options configured with CUDA plugin 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(str(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("=== CUDA 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)