Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions runtime/onert/api/python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ endif()
# Add the Python module
file(GLOB_RECURSE NNFW_API_PYBIND_SOURCES "src/*.cc")
pybind11_add_module(nnfw_api_pybind ${NNFW_API_PYBIND_SOURCES})

target_include_directories(nnfw_api_pybind PRIVATE include)
target_link_libraries(nnfw_api_pybind PRIVATE nnfw-dev)
target_link_libraries(nnfw_api_pybind PRIVATE nnfw_common nnfw_coverage)
Expand Down
32 changes: 32 additions & 0 deletions runtime/onert/api/python/include/nnfw_exception_bindings.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef __ONERT_API_PYTHON_NNFW_EXCEPTION_BINDINGS_H__
#define __ONERT_API_PYTHON_NNFW_EXCEPTION_BINDINGS_H__

#include <pybind11/pybind11.h>

namespace onert::api::python
{

namespace py = pybind11;

// Declare binding exceptions
void bind_nnfw_exceptions(py::module_ &m);

} // namespace onert::api::python

#endif // __ONERT_API_PYTHON_NNFW_EXCEPTION_BINDINGS_H__
55 changes: 55 additions & 0 deletions runtime/onert/api/python/include/nnfw_exceptions.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef __ONERT_API_PYTHON_NNFW_EXCEPTIONS_H__
#define __ONERT_API_PYTHON_NNFW_EXCEPTIONS_H__

#include <stdexcept>
#include <string>

namespace onert::api::python
{

// Base for all NNFW errors
struct NnfwError : public std::runtime_error
{
explicit NnfwError(const std::string &msg) : std::runtime_error(msg) {}
};

struct NnfwUnexpectedNullError : public NnfwError
{
using NnfwError::NnfwError;
};
struct NnfwInvalidStateError : public NnfwError
{
using NnfwError::NnfwError;
};
struct NnfwOutOfMemoryError : public NnfwError
{
using NnfwError::NnfwError;
};
struct NnfwInsufficientOutputError : public NnfwError
{
using NnfwError::NnfwError;
};
struct NnfwDeprecatedApiError : public NnfwError
{
using NnfwError::NnfwError;
};

} // namespace onert::api::python

#endif // __ONERT_API_PYTHON_NNFW_EXCEPTIONS_H__
106 changes: 100 additions & 6 deletions runtime/onert/api/python/package/common/basesession.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from typing import List
import numpy as np

from ..native import libnnfw_api_pybind
from ..native.libnnfw_api_pybind import infer, tensorinfo
from ..native.libnnfw_api_pybind.exception import OnertError


def num_elems(tensor_info):
Expand Down Expand Up @@ -52,19 +54,73 @@ def _recreate_session(self, backend_session):
del self.session # Clean up the existing session
self.session = backend_session

def get_inputs_tensorinfo(self) -> List[tensorinfo]:
"""
Retrieve tensorinfo for all input tensors.

Raises:
OnertError: If the underlying C‑API call fails.

Returns:
list[tensorinfo]: A list of tensorinfo objects for each input.
"""
num_inputs: int = self.session.input_size()
infos: List[tensorinfo] = []
for i in range(num_inputs):
try:
infos.append(self.session.input_tensorinfo(i))
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to get input tensorinfo #{i}: {e}") from e
return infos

def get_outputs_tensorinfo(self) -> List[tensorinfo]:
"""
Retrieve tensorinfo for all output tensors.

Raises:
OnertError: If the underlying C‑API call fails.

Returns:
list[tensorinfo]: A list of tensorinfo objects for each output.
"""
num_outputs: int = self.session.output_size()
infos: List[tensorinfo] = []
for i in range(num_outputs):
try:
infos.append(self.session.output_tensorinfo(i))
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to get output tensorinfo #{i}: {e}") from e
return infos

def set_inputs(self, size, inputs_array=[]):
"""
Set the input tensors for the session.

Args:
size (int): Number of input tensors.
inputs_array (list): List of numpy arrays for the input data.

Raises:
ValueError: If session uninitialized.
OnertError: If any C‑API call fails.
"""
if self.session is None:
raise ValueError(
"Session is not initialized with a model. Please compile with a model before setting inputs."
)

self.inputs = []
for i in range(size):
input_tensorinfo = self.session.input_tensorinfo(i)
try:
input_tensorinfo = self.session.input_tensorinfo(i)
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to get input tensorinfo #{i}: {e}") from e

if len(inputs_array) > i:
input_array = np.array(inputs_array[i], dtype=input_tensorinfo.dtype)
Expand All @@ -75,26 +131,64 @@ def set_inputs(self, size, inputs_array=[]):
input_array = np.zeros((num_elems(input_tensorinfo)),
dtype=input_tensorinfo.dtype)

self.session.set_input(i, input_array)
try:
self.session.set_input(i, input_array)
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to set input #{i}: {e}") from e

self.inputs.append(input_array)

def set_outputs(self, size):
"""
Set the output tensors for the session.

Args:
size (int): Number of output tensors.

Raises:
ValueError: If session uninitialized.
OnertError: If any C‑API call fails.
"""
if self.session is None:
raise ValueError(
"Session is not initialized with a model. Please compile a model before setting outputs."
)

self.outputs = []
for i in range(size):
output_tensorinfo = self.session.output_tensorinfo(i)
try:
output_tensorinfo = self.session.output_tensorinfo(i)
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to get output tensorinfo #{i}: {e}") from e

output_array = np.zeros((num_elems(output_tensorinfo)),
dtype=output_tensorinfo.dtype)
self.session.set_output(i, output_array)

try:
self.session.set_output(i, output_array)
except ValueError:
raise
except Exception as e:
raise OnertError(f"Failed to set output #{i}: {e}") from e

self.outputs.append(output_array)


def tensorinfo():
return libnnfw_api_pybind.infer.nnfw_tensorinfo()
"""
Shortcut to create a fresh tensorinfo instance.

Raises:
OnertError: If the C‑API call fails.
"""

try:
return infer.nnfw_tensorinfo()
except OnertError:
raise
except Exception as e:
raise OnertError(f"Failed to create tensorinfo: {e}") from e
Loading