Skip to content

Commit a321bfa

Browse files
committed
[F] Fix errors
1 parent bde1ad8 commit a321bfa

8 files changed

Lines changed: 105 additions & 60 deletions

File tree

.github/workflows/cuda-ci.yml

Lines changed: 58 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,41 +4,80 @@ on:
44
pull_request:
55
branches: [main]
66
paths-ignore:
7+
- "**/version.h"
78
- "doc/**"
89
- "**.md"
910

11+
env:
12+
LOCAL_REGISTRY: localhost:5000
13+
DOCKERFILE: docker/pr.dockerfile
14+
1015
jobs:
16+
get_runner_and_uid:
17+
name: Get Runner
18+
runs-on: [self-hosted, unicorn]
19+
steps:
20+
- name: Get UID and GID
21+
id: uid_gid
22+
run: |
23+
echo "uid_gid=$(id -u):$(id -g)" >> "$GITHUB_OUTPUT"
24+
outputs:
25+
runner: ${{ runner.name }}
26+
uid: ${{ steps.uid_gid.outputs.uid_gid }}
27+
28+
build_docker_image:
29+
name: Build Docker Image
30+
needs: [get_runner_and_uid]
31+
runs-on: ${{ needs.get_runner_and_uid.outputs.runner }}
32+
33+
steps:
34+
- name: Checkout Repository
35+
uses: actions/checkout@v4
36+
37+
- name: Build Docker Image
38+
id: docker_build
39+
uses: docker/build-push-action@v3
40+
with:
41+
file: ${{ env.DOCKERFILE }}
42+
no-cache: false
43+
push: true
44+
tags: ${{ env.LOCAL_REGISTRY }}/capybara-container:ci
45+
46+
outputs:
47+
image: ${{ env.LOCAL_REGISTRY }}/capybara-container:ci
48+
1149
ci:
1250
name: CI
51+
needs: [get_runner_and_uid, build_docker_image]
52+
runs-on: ${{ needs.get_runner_and_uid.outputs.runner }}
1353
strategy:
14-
fail-fast: false
1554
matrix:
16-
python-version: ["3.10", "3.12"]
17-
18-
runs-on: ["self-hosted", "unicorn"]
55+
python-version:
56+
- "3.10"
57+
container:
58+
image: ${{ needs.build_docker_image.outputs.image }}
59+
options: --user ${{ needs.get_runner_and_uid.outputs.uid }} --gpus all
1960

2061
steps:
21-
- name: Checkout repository
62+
- name: Checkout Repository
2263
uses: actions/checkout@v4
23-
with:
24-
lfs: true
2564

26-
- name: Set up Python ${{ matrix.python-version }}
27-
uses: actions/setup-python@v5
28-
with:
29-
python-version: ${{ matrix.python-version }}
30-
check-latest: true
65+
- name: Install Dependencies
66+
run: |
67+
python3 -m pip install pytest wheel pylint pylint-flask pytest-cov typeguard
3168
32-
- name: Install dependencies
69+
- name: Build and Install Package
3370
run: |
34-
python -m pip install -U pip wheel "numpy>=2" "cython>=3.0.12" "setuptools>=69"
35-
python setup.py build_ext --inplace
36-
python -m pip install .
71+
python3 setup.py bdist_wheel --universal && \
72+
wheel_file=$(ls dist/*.whl 2>/dev/null || echo '') && \
73+
if [ -z "$wheel_file" ]; then
74+
echo 'Error: No wheel file found in dist directory.' && exit 1
75+
fi && \
76+
python3 -m pip install $wheel_file --force-reinstall
3777
38-
- name: Lint with pylint
78+
- name: Lint with Pylint
3979
run: |
40-
python -m pip install pylint
41-
python -m pylint capybara --rcfile=.github/workflows/.pylintrc
80+
python3 -m pylint capybara --rcfile=.github/workflows/.pylintrc --load-plugins pylint_flask
4281
4382
- name: Run tests with pytest
4483
run: |

capybara/onnxengine/__init__.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
from .engine import Backend, ONNXEngine
1+
from .engine import ONNXEngine
22
from .engine_io_binding import ONNXEngineIOBinding
3-
from .metadata import (
4-
get_onnx_metadata,
5-
parse_metadata_from_onnx,
6-
write_metadata_into_onnx,
7-
)
8-
from .tools import get_onnx_input_infos, get_onnx_output_infos, make_onnx_dynamic_axes
3+
from .enum import Backend
4+
from .metadata import get_onnx_metadata, parse_metadata_from_onnx, write_metadata_into_onnx
5+
from .tools import get_onnx_input_infos, get_onnx_output_infos, get_recommended_backend, make_onnx_dynamic_axes
96

107
# 暫時無法使用
118
# from .quantize import quantize, quantize_static

capybara/onnxengine/engine.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,15 @@
1-
from enum import Enum
21
from pathlib import Path
32
from typing import Any, Dict, Union
43

54
import colored
65
import numpy as np
76
import onnxruntime as ort
87

9-
from ..enums import EnumCheckMixin
8+
from .enum import Backend
109
from .metadata import parse_metadata_from_onnx
1110
from .tools import get_onnx_input_infos, get_onnx_output_infos
1211

1312

14-
class Backend(EnumCheckMixin, Enum):
15-
cpu = 0
16-
cuda = 1
17-
coreml = 2
18-
19-
2013
class ONNXEngine:
2114
def __init__(
2215
self,

capybara/onnxengine/engine_io_binding.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,7 @@ def __init__(
6262

6363
input_infos, output_infos = self._init_io_infos(model_path, input_initializer)
6464

65-
io_binding, x_ortvalues, y_ortvalues = self._setup_io_binding(
66-
input_infos, output_infos
67-
)
65+
io_binding, x_ortvalues, y_ortvalues = self._setup_io_binding(input_infos, output_infos)
6866
self.io_binding = io_binding
6967
self.x_ortvalues = x_ortvalues
7068
self.y_ortvalues = y_ortvalues
@@ -121,14 +119,10 @@ def _setup_io_binding(self, input_infos, output_infos):
121119
y_ortvalues = {}
122120
for k, v in input_infos.items():
123121
m = np.zeros(**v)
124-
x_ortvalues[k] = ort.OrtValue.ortvalue_from_numpy(
125-
m, device_type="cuda", device_id=self.device_id
126-
)
122+
x_ortvalues[k] = ort.OrtValue.ortvalue_from_numpy(m, device_type="cuda", device_id=self.device_id)
127123
for k, v in output_infos.items():
128124
m = np.zeros(**v)
129-
y_ortvalues[k] = ort.OrtValue.ortvalue_from_numpy(
130-
m, device_type="cuda", device_id=self.device_id
131-
)
125+
y_ortvalues[k] = ort.OrtValue.ortvalue_from_numpy(m, device_type="cuda", device_id=self.device_id)
132126

133127
io_binding = self.sess.io_binding()
134128
for k, v in x_ortvalues.items():
@@ -158,11 +152,7 @@ def format_nested_dict(dict_data, indent=0):
158152
if isinstance(value, dict):
159153
info.append(f"{prefix}{key}:")
160154
info.append(format_nested_dict(value, indent + 1))
161-
elif (
162-
isinstance(value, str)
163-
and value.startswith("{")
164-
and value.endswith("}")
165-
):
155+
elif isinstance(value, str) and value.startswith("{") and value.endswith("}"):
166156
try:
167157
nested_dict = eval(value)
168158
if isinstance(nested_dict, dict):
@@ -179,9 +169,7 @@ def format_nested_dict(dict_data, indent=0):
179169
title = "DOCSAID X ONNXRUNTIME"
180170
divider_length = 50
181171
divider = f"+{'-' * divider_length}+"
182-
styled_title = colored.stylize(
183-
title, [colored.fg("blue"), colored.attr("bold")]
184-
)
172+
styled_title = colored.stylize(title, [colored.fg("blue"), colored.attr("bold")])
185173

186174
def center_text(text, width):
187175
"""Center text within a fixed width, handling ANSI escape codes."""

capybara/onnxengine/enum.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from enum import Enum
2+
3+
from ..enums import EnumCheckMixin
4+
5+
6+
class Backend(EnumCheckMixin, Enum):
7+
cpu = 0
8+
cuda = 1
9+
coreml = 2

capybara/onnxengine/tools.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@
22
from typing import Dict, List, Optional, Union
33

44
import onnx
5+
import onnxruntime as ort
56
import onnxslim
67
from onnx.helper import make_graph, make_model, make_opsetid, tensor_dtype_to_np_dtype
78

9+
from .enum import Backend
10+
811
__all__ = [
912
"get_onnx_input_infos",
1013
"get_onnx_output_infos",
1114
"make_onnx_dynamic_axes",
15+
"get_recommended_backend",
1216
]
1317

1418

@@ -77,3 +81,13 @@ def make_onnx_dynamic_axes(
7781

7882
new_model = onnxslim.slim(new_model)
7983
onnx.save(new_model, output_fpath)
84+
85+
86+
def get_recommended_backend() -> Backend:
87+
providers = ort.get_available_providers()
88+
if "CUDAExecutionProvider" in providers:
89+
return Backend.cuda
90+
elif "CoreMLExecutionProvider" in providers:
91+
return Backend.coreml
92+
else:
93+
return Backend.cpu

tests/onnxruntime/test_engine.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@
33
import numpy as np
44
import pytest
55

6-
from capybara import ONNXEngine, get_curdir
6+
from capybara import Backend, ONNXEngine, get_curdir, get_recommended_backend
77

88

9-
@pytest.mark.skipif(platform.system() != "Linux", reason="Linux only")
10-
def test_ONNXEngine_CUDA():
9+
def test_ONNXEngine_CPU():
1110
model_path = get_curdir(__file__).parent / "resources/model_dynamic-axes.onnx"
12-
engine = ONNXEngine(model_path, backend="cuda")
11+
engine = ONNXEngine(model_path, backend="cpu")
1312
for i in range(5):
1413
xs = {"input": np.random.randn(32, 3, 224, 224).astype("float32")}
1514
outs = engine(**xs)
@@ -18,9 +17,13 @@ def test_ONNXEngine_CUDA():
1817
prev_outs = outs
1918

2019

21-
def test_ONNXEngine_CPU():
20+
PLATFORM = platform.system()
21+
22+
23+
@pytest.mark.skipif(PLATFORM != "Linux" and BACKEND == Backend.cuda, reason="Linux with GPU only")
24+
def test_ONNXEngine_CUDA():
2225
model_path = get_curdir(__file__).parent / "resources/model_dynamic-axes.onnx"
23-
engine = ONNXEngine(model_path, backend="cpu")
26+
engine = ONNXEngine(model_path, backend=get_recommended_backend())
2427
for i in range(5):
2528
xs = {"input": np.random.randn(32, 3, 224, 224).astype("float32")}
2629
outs = engine(**xs)
@@ -29,7 +32,7 @@ def test_ONNXEngine_CPU():
2932
prev_outs = outs
3033

3134

32-
@pytest.mark.skipif(platform.system() != "Darwin", reason="Mac only")
35+
@pytest.mark.skipif(PLATFORM != "Darwin", reason="Mac only")
3336
def test_ONNXEngine_COREML():
3437
model_path = get_curdir(__file__).parent / "resources/model_dynamic-axes.onnx"
3538
engine = ONNXEngine(model_path, backend="coreml")

tests/onnxruntime/test_engine_io_binding.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import numpy as np
44
import pytest
55

6-
from capybara import ONNXEngineIOBinding, get_curdir
6+
from capybara import Backend, ONNXEngineIOBinding, get_curdir, get_recommended_backend
77

8+
PLATFORM = platform.system()
89

9-
@pytest.mark.skipif(platform.system() != "Linux", reason="Linux only")
10+
11+
@pytest.mark.skipif(PLATFORM != "Linux" and get_recommended_backend() != Backend.cuda, reason="Linux with GPU only")
1012
def test_ONNXEngineIOBinding_CUDAonly():
1113
model_path = get_curdir(__file__).parent / "resources/model_dynamic-axes.onnx"
1214
input_initializer = {"input": np.random.randn(32, 3, 448, 448).astype("float32")}

0 commit comments

Comments
 (0)