ONE - On-device Neural Engine
Loading...
Searching...
No Matches
basesession.py
Go to the documentation of this file.
1import numpy as np
2
3from ..native import libnnfw_api_pybind
4
5
6def num_elems(tensor_info):
7 """Get the total number of elements in nnfw_tensorinfo.dims."""
8 n = 1
9 for x in range(tensor_info.rank):
10 n *= tensor_info.dims[x]
11 return n
12
13
15 """
16 Base class providing common functionality for inference and training sessions.
17 """
18 def __init__(self, backend_session=None):
19 """
20 Initialize the BaseSession with a backend session.
21 Args:
22 backend_session: A backend-specific session object (e.g., nnfw_session).
23 """
24 self.session = backend_session
25 self.inputs = []
26 self.outputs = []
27
28 def __getattr__(self, name):
29 """
30 Delegate attribute access to the bound NNFW_SESSION instance.
31 Args:
32 name (str): The name of the attribute or method to access.
33 Returns:
34 The attribute or method from the bound NNFW_SESSION instance.
35 """
36 if name in self.__dict__:
37 # First, try to get the attribute from the instance's own dictionary
38 return self.__dict__[name]
39 elif hasattr(self.session, name):
40 # If not found, delegate to the session object
41 return getattr(self.session, name)
42 else:
43 raise AttributeError(
44 f"'{type(self).__name__}' object has no attribute '{name}'")
45
46 def _recreate_session(self, backend_session):
47 """
48 Protected method to recreate the session.
49 Subclasses can override this method to provide custom session recreation logic.
50 """
51 if self.session is not None:
52 del self.session # Clean up the existing session
53 self.session = backend_session
54
55 def set_inputs(self, size, inputs_array=[]):
56 """
57 Set the input tensors for the session.
58 Args:
59 size (int): Number of input tensors.
60 inputs_array (list): List of numpy arrays for the input data.
61 """
62 if self.session is None:
63 raise ValueError(
64 "Session is not initialized with a model. Please compile with a model before setting inputs."
65 )
66 for i in range(size):
67 input_tensorinfo = self.session.input_tensorinfo(i)
68
69 if len(inputs_array) > i:
70 input_array = np.array(inputs_array[i], dtype=input_tensorinfo.dtype)
71 else:
72 print(
73 f"Model's input size is {size}, but given inputs_array size is {len(inputs_array)}.\n{i}-th index input is replaced by an array filled with 0."
74 )
75 input_array = np.zeros((num_elems(input_tensorinfo)),
76 dtype=input_tensorinfo.dtype)
77
78 self.session.set_input(i, input_array)
79 self.inputs.append(input_array)
80
81 def set_outputs(self, size):
82 """
83 Set the output tensors for the session.
84 Args:
85 size (int): Number of output tensors.
86 """
87 if self.session is None:
88 raise ValueError(
89 "Session is not initialized with a model. Please compile a model before setting outputs."
90 )
91 for i in range(size):
92 output_tensorinfo = self.session.output_tensorinfo(i)
93 output_array = np.zeros((num_elems(output_tensorinfo)),
94 dtype=output_tensorinfo.dtype)
95 self.session.set_output(i, output_array)
96 self.outputs.append(output_array)
97
98
100 return libnnfw_api_pybind.infer.nnfw_tensorinfo()
set_inputs(self, size, inputs_array=[])
_recreate_session(self, backend_session)
__init__(self, backend_session=None)