xmos-ai-tools 1.3.2.dev40__py3-none-win_amd64.whl → 1.3.2.dev82__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xmos_ai_tools/__init__.py CHANGED
@@ -1,7 +1,7 @@
1
- from importlib.metadata import version, PackageNotFoundError
2
-
3
- try:
4
- __version__ = version(__name__)
5
- except PackageNotFoundError:
6
- # package is not installed
7
- pass
1
+ from importlib.metadata import version, PackageNotFoundError
2
+
3
+ try:
4
+ __version__ = version(__name__)
5
+ except PackageNotFoundError:
6
+ # package is not installed
7
+ pass
@@ -1,151 +1,151 @@
1
- # Copyright (c) 2020, XMOS Ltd, All rights reserved
2
-
3
- import usb
4
- from typing import Tuple
5
- import numpy as np
6
-
7
- IOSERVER_INVOKE = int(0x01)
8
- IOSERVER_TENSOR_SEND_OUTPUT = int(0x02)
9
- IOSERVER_TENSOR_RECV_INPUT = int(0x03)
10
- IOSERVER_RESET = int(0x07)
11
- IOSERVER_EXIT = int(0x08)
12
-
13
-
14
- class IOServerError(Exception):
15
- """Error from device"""
16
-
17
- pass
18
-
19
-
20
- class IOError(IOServerError):
21
- """IO Error from device"""
22
-
23
- pass
24
-
25
-
26
- def handle_usb_error(func):
27
- def wrapper(*args, **kwargs):
28
- try:
29
- return func(*args, **kwargs)
30
- except usb.core.USBError as e:
31
- print(f"USB error {e}")
32
- if e.backend_error_code == usb.backend.libusb1.LIBUSB_ERROR_PIPE:
33
- raise IOError()
34
- else:
35
- raise IOServerError(f"Wow...") from e
36
-
37
- return wrapper
38
-
39
-
40
- class IOServer:
41
- def __init__(self, output_details: Tuple[dict, ...] = None, timeout=5000):
42
- self.__out_ep = None
43
- self.__in_ep = None
44
- self._dev = None
45
- self._output_details = output_details
46
- self._timeout = timeout
47
- self._max_block_size = 512 # TODO read from (usb) device?
48
- super().__init__()
49
-
50
- def bytes_to_arr(self, data_bytes, tensor_num):
51
- if self._output_details:
52
- d = self._output_details[tensor_num]
53
- s = d["shape"]
54
- return np.frombuffer(data_bytes, dtype=d["dtype"])[: np.prod(s)].reshape(s)
55
- return np.frombuffer(data_bytes, dtype=np.uint8)
56
-
57
- def write_input_tensor(self, raw_img, tensor_num=0, model_num=0):
58
- self._download_data(
59
- IOSERVER_TENSOR_RECV_INPUT,
60
- raw_img,
61
- tensor_num=tensor_num,
62
- model_num=model_num,
63
- )
64
-
65
- def read_output_tensor(self, tensor_num=0, model_num=0):
66
- # Retrieve result from device
67
- data_read = self._upload_data(
68
- IOSERVER_TENSOR_SEND_OUTPUT,
69
- model_num=model_num,
70
- tensor_num=tensor_num,
71
- )
72
- assert type(data_read) is bytearray
73
- return self.bytes_to_arr(data_read, tensor_num)
74
-
75
- def close(self):
76
- if self._dev is not None:
77
- self._dev.write(self._out_ep, bytes([IOSERVER_EXIT, 0, 0]), 1000)
78
- usb.util.dispose_resources(self._dev)
79
- self._dev = None
80
-
81
- @handle_usb_error
82
- def _download_data(self, cmd, data_bytes, tensor_num=0, model_num=0):
83
- # TODO rm this extra CMD packet
84
- self._out_ep.write(bytes([cmd, model_num, tensor_num]))
85
- self._out_ep.write(data_bytes, 1000)
86
- if (len(data_bytes) % self._max_block_size) == 0:
87
- self._out_ep.write(bytearray(), 1000)
88
-
89
- @handle_usb_error
90
- def _upload_data(self, cmd, tensor_num=0, model_num=0):
91
- read_data = bytearray()
92
- self._out_ep.write(bytes([cmd, model_num, tensor_num]), self._timeout)
93
- buff = usb.util.create_buffer(self._max_block_size)
94
- read_len = self._dev.read(self._in_ep, buff, 10000)
95
- read_data.extend(buff[:read_len])
96
- while read_len == self._max_block_size:
97
- read_len = self._dev.read(self._in_ep, buff, 10000)
98
- read_data.extend(buff[:read_len])
99
-
100
- return read_data
101
-
102
- def _clear_error(self):
103
- self._dev.clear_halt(self._out_ep)
104
- self._dev.clear_halt(self._in_ep)
105
-
106
- def connect(self):
107
- self._dev = None
108
- while self._dev is None:
109
- # TODO - more checks that we have the right device..
110
- self._dev = usb.core.find(idVendor=0x20B1, product="xAISRV")
111
-
112
- # set the active configuration. With no arguments, the first
113
- # configuration will be the active one
114
- self._dev.set_configuration()
115
-
116
- # get an endpoint instance
117
- cfg = self._dev.get_active_configuration()
118
- intf = cfg[(0, 0)]
119
- self._out_ep = usb.util.find_descriptor(
120
- intf,
121
- # match the first OUT endpoint
122
- custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
123
- == usb.util.ENDPOINT_OUT,
124
- )
125
-
126
- self._in_ep = usb.util.find_descriptor(
127
- intf,
128
- # match the first IN endpoint
129
- custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
130
- == usb.util.ENDPOINT_IN,
131
- )
132
-
133
- assert self._out_ep is not None
134
- assert self._in_ep is not None
135
-
136
- print("Connected to XCORE_IO_SERVER via USB")
137
-
138
- # TODO move to super()
139
- def start_inference(self):
140
- # Send cmd
141
- self._out_ep.write(bytes([IOSERVER_INVOKE, 0, 0]), 1000)
142
-
143
- # Send out a 0 length packet
144
- self._out_ep.write(bytes([]), 1000)
145
-
146
- def reset(self):
147
- # Send cmd
148
- self._out_ep.write(bytes([IOSERVER_RESET, 0, 0]), 1000)
149
-
150
- # Send out a 0 length packet
151
- self._out_ep.write(bytes([]), 1000)
1
+ # Copyright (c) 2020, XMOS Ltd, All rights reserved
2
+
3
+ import usb
4
+ from typing import Tuple
5
+ import numpy as np
6
+
7
+ IOSERVER_INVOKE = int(0x01)
8
+ IOSERVER_TENSOR_SEND_OUTPUT = int(0x02)
9
+ IOSERVER_TENSOR_RECV_INPUT = int(0x03)
10
+ IOSERVER_RESET = int(0x07)
11
+ IOSERVER_EXIT = int(0x08)
12
+
13
+
14
+ class IOServerError(Exception):
15
+ """Error from device"""
16
+
17
+ pass
18
+
19
+
20
+ class IOError(IOServerError):
21
+ """IO Error from device"""
22
+
23
+ pass
24
+
25
+
26
+ def handle_usb_error(func):
27
+ def wrapper(*args, **kwargs):
28
+ try:
29
+ return func(*args, **kwargs)
30
+ except usb.core.USBError as e:
31
+ print(f"USB error {e}")
32
+ if e.backend_error_code == usb.backend.libusb1.LIBUSB_ERROR_PIPE:
33
+ raise IOError()
34
+ else:
35
+ raise IOServerError(f"Wow...") from e
36
+
37
+ return wrapper
38
+
39
+
40
+ class IOServer:
41
+ def __init__(self, output_details: Tuple[dict, ...] = None, timeout=5000):
42
+ self.__out_ep = None
43
+ self.__in_ep = None
44
+ self._dev = None
45
+ self._output_details = output_details
46
+ self._timeout = timeout
47
+ self._max_block_size = 512 # TODO read from (usb) device?
48
+ super().__init__()
49
+
50
+ def bytes_to_arr(self, data_bytes, tensor_num):
51
+ if self._output_details:
52
+ d = self._output_details[tensor_num]
53
+ s = d["shape"]
54
+ return np.frombuffer(data_bytes, dtype=d["dtype"])[: np.prod(s)].reshape(s)
55
+ return np.frombuffer(data_bytes, dtype=np.uint8)
56
+
57
+ def write_input_tensor(self, raw_img, tensor_num=0, model_num=0):
58
+ self._download_data(
59
+ IOSERVER_TENSOR_RECV_INPUT,
60
+ raw_img,
61
+ tensor_num=tensor_num,
62
+ model_num=model_num,
63
+ )
64
+
65
+ def read_output_tensor(self, tensor_num=0, model_num=0):
66
+ # Retrieve result from device
67
+ data_read = self._upload_data(
68
+ IOSERVER_TENSOR_SEND_OUTPUT,
69
+ model_num=model_num,
70
+ tensor_num=tensor_num,
71
+ )
72
+ assert type(data_read) is bytearray
73
+ return self.bytes_to_arr(data_read, tensor_num)
74
+
75
+ def close(self):
76
+ if self._dev is not None:
77
+ self._dev.write(self._out_ep, bytes([IOSERVER_EXIT, 0, 0]), 1000)
78
+ usb.util.dispose_resources(self._dev)
79
+ self._dev = None
80
+
81
+ @handle_usb_error
82
+ def _download_data(self, cmd, data_bytes, tensor_num=0, model_num=0):
83
+ # TODO rm this extra CMD packet
84
+ self._out_ep.write(bytes([cmd, model_num, tensor_num]))
85
+ self._out_ep.write(data_bytes, 1000)
86
+ if (len(data_bytes) % self._max_block_size) == 0:
87
+ self._out_ep.write(bytearray(), 1000)
88
+
89
+ @handle_usb_error
90
+ def _upload_data(self, cmd, tensor_num=0, model_num=0):
91
+ read_data = bytearray()
92
+ self._out_ep.write(bytes([cmd, model_num, tensor_num]), self._timeout)
93
+ buff = usb.util.create_buffer(self._max_block_size)
94
+ read_len = self._dev.read(self._in_ep, buff, 10000)
95
+ read_data.extend(buff[:read_len])
96
+ while read_len == self._max_block_size:
97
+ read_len = self._dev.read(self._in_ep, buff, 10000)
98
+ read_data.extend(buff[:read_len])
99
+
100
+ return read_data
101
+
102
+ def _clear_error(self):
103
+ self._dev.clear_halt(self._out_ep)
104
+ self._dev.clear_halt(self._in_ep)
105
+
106
+ def connect(self):
107
+ self._dev = None
108
+ while self._dev is None:
109
+ # TODO - more checks that we have the right device..
110
+ self._dev = usb.core.find(idVendor=0x20B1, product="xAISRV")
111
+
112
+ # set the active configuration. With no arguments, the first
113
+ # configuration will be the active one
114
+ self._dev.set_configuration()
115
+
116
+ # get an endpoint instance
117
+ cfg = self._dev.get_active_configuration()
118
+ intf = cfg[(0, 0)]
119
+ self._out_ep = usb.util.find_descriptor(
120
+ intf,
121
+ # match the first OUT endpoint
122
+ custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
123
+ == usb.util.ENDPOINT_OUT,
124
+ )
125
+
126
+ self._in_ep = usb.util.find_descriptor(
127
+ intf,
128
+ # match the first IN endpoint
129
+ custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
130
+ == usb.util.ENDPOINT_IN,
131
+ )
132
+
133
+ assert self._out_ep is not None
134
+ assert self._in_ep is not None
135
+
136
+ print("Connected to XCORE_IO_SERVER via USB")
137
+
138
+ # TODO move to super()
139
+ def start_inference(self):
140
+ # Send cmd
141
+ self._out_ep.write(bytes([IOSERVER_INVOKE, 0, 0]), 1000)
142
+
143
+ # Send out a 0 length packet
144
+ self._out_ep.write(bytes([]), 1000)
145
+
146
+ def reset(self):
147
+ # Send cmd
148
+ self._out_ep.write(bytes([IOSERVER_RESET, 0, 0]), 1000)
149
+
150
+ # Send out a 0 length packet
151
+ self._out_ep.write(bytes([]), 1000)
@@ -1,13 +1,13 @@
1
- set(XMOS_AITOOLSLIB_DEFINITIONS
2
- "TF_LITE_STATIC_MEMORY"
3
- "TF_LITE_STRIP_ERROR_STRINGS"
4
- "XCORE"
5
- "NO_INTERPRETER"
6
- )
7
-
8
- if("${APP_BUILD_ARCH}" STREQUAL xs3a OR ${CMAKE_SYSTEM_PROCESSOR} STREQUAL XCORE_XS3A)
9
- set(XMOS_AITOOLSLIB_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/../lib/libxtflitemicro.a")
10
- else()
11
- set(XMOS_AITOOLSLIB_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/../lib/libhost_xtflitemicro.a")
12
- endif()
13
- set(XMOS_AITOOLSLIB_INCLUDES "${CMAKE_CURRENT_LIST_DIR}/../include")
1
+ set(XMOS_AITOOLSLIB_DEFINITIONS
2
+ "TF_LITE_STATIC_MEMORY"
3
+ "TF_LITE_STRIP_ERROR_STRINGS"
4
+ "XCORE"
5
+ "NO_INTERPRETER"
6
+ )
7
+
8
+ if("${APP_BUILD_ARCH}" STREQUAL xs3a OR ${CMAKE_SYSTEM_PROCESSOR} STREQUAL XCORE_XS3A)
9
+ set(XMOS_AITOOLSLIB_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/../lib/libxtflitemicro.a")
10
+ else()
11
+ set(XMOS_AITOOLSLIB_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/../lib/libhost_xtflitemicro.a")
12
+ endif()
13
+ set(XMOS_AITOOLSLIB_INCLUDES "${CMAKE_CURRENT_LIST_DIR}/../include")
@@ -1,8 +1,8 @@
1
- XMOS_AITOOLSLIB_DEFINITIONS = \
2
- -DTF_LITE_STATIC_MEMORY \
3
- -DTF_LITE_STRIP_ERROR_STRINGS \
4
- -DXCORE \
5
- -DNO_INTERPRETER
6
-
7
- XMOS_AITOOLSLIB_LIBRARIES = $(XMOS_AITOOLSLIB_PATH)/lib/libxtflitemicro.a
8
- XMOS_AITOOLSLIB_INCLUDES = -I$(XMOS_AITOOLSLIB_PATH)/include
1
+ XMOS_AITOOLSLIB_DEFINITIONS = \
2
+ -DTF_LITE_STATIC_MEMORY \
3
+ -DTF_LITE_STRIP_ERROR_STRINGS \
4
+ -DXCORE \
5
+ -DNO_INTERPRETER
6
+
7
+ XMOS_AITOOLSLIB_LIBRARIES = $(XMOS_AITOOLSLIB_PATH)/lib/libxtflitemicro.a
8
+ XMOS_AITOOLSLIB_INCLUDES = -I$(XMOS_AITOOLSLIB_PATH)/include
Binary file
@@ -1,60 +1,60 @@
1
- import subprocess
2
- import typing
3
- from pathlib import Path
4
- from typing import Union, List, Optional
5
- from .flash import generate_flash
6
- import re
7
-
8
- __compilation_output = ""
9
- __arena_size = 0
10
-
11
-
12
- def convert(
13
- filename: Union[str, Path],
14
- outfile: Union[str, Path],
15
- params: Optional[typing.Dict[str, Optional[str]]],
16
- ) -> int:
17
- args: List[str] = ["xcore-opt", "-o", str(outfile)]
18
-
19
- if params is not None:
20
- for key, val in params.items():
21
- if len(key) > 1:
22
- flag: str = "--" + str(key)
23
- else:
24
- flag = "-" + str(key)
25
- if str(val) == "" or val is None:
26
- args.append(flag)
27
- else:
28
- args.append(f"{flag}={val}")
29
-
30
- args.append(str(filename))
31
-
32
- process_call: subprocess.CompletedProcess = subprocess.run(
33
- [arg for arg in args],
34
- stdout=subprocess.PIPE,
35
- stderr=subprocess.STDOUT,
36
- check=True,
37
- )
38
-
39
- global __compilation_output, __arena_size
40
- __compilation_output = process_call.stdout.decode("utf-8")
41
- size_str = re.sub("((.|\n|\r)*)Tensor arena size :", "", __compilation_output)
42
- size_str = re.sub("(\n|\r)((.|\n|\r)*)", "", size_str)
43
- __arena_size = int(size_str.strip())
44
-
45
- return process_call.returncode
46
-
47
-
48
- def tensor_arena_size() -> int:
49
- return __arena_size
50
-
51
-
52
- def print_optimization_report():
53
- print(__compilation_output)
54
-
55
-
56
- def print_help(show_hidden: Optional[bool] = False) -> int:
57
- if show_hidden:
58
- return subprocess.run(["xcore-opt", "--help-list-hidden"]).returncode
59
-
60
- return subprocess.run(["xcore-opt", "--help-list"]).returncode
1
+ import subprocess
2
+ import typing
3
+ from pathlib import Path
4
+ from typing import Union, List, Optional
5
+ from .flash import generate_flash
6
+ import re
7
+
8
+ __compilation_output = ""
9
+ __arena_size = 0
10
+
11
+
12
+ def convert(
13
+ filename: Union[str, Path],
14
+ outfile: Union[str, Path],
15
+ params: Optional[typing.Dict[str, Optional[str]]],
16
+ ) -> int:
17
+ args: List[str] = ["xcore-opt", "-o", str(outfile)]
18
+
19
+ if params is not None:
20
+ for key, val in params.items():
21
+ if len(key) > 1:
22
+ flag: str = "--" + str(key)
23
+ else:
24
+ flag = "-" + str(key)
25
+ if str(val) == "" or val is None:
26
+ args.append(flag)
27
+ else:
28
+ args.append(f"{flag}={val}")
29
+
30
+ args.append(str(filename))
31
+
32
+ process_call: subprocess.CompletedProcess = subprocess.run(
33
+ [arg for arg in args],
34
+ stdout=subprocess.PIPE,
35
+ stderr=subprocess.STDOUT,
36
+ check=True,
37
+ )
38
+
39
+ global __compilation_output, __arena_size
40
+ __compilation_output = process_call.stdout.decode("utf-8")
41
+ size_str = re.sub("((.|\n|\r)*)Tensor arena size :", "", __compilation_output)
42
+ size_str = re.sub("(\n|\r)((.|\n|\r)*)", "", size_str)
43
+ __arena_size = int(size_str.strip())
44
+
45
+ return process_call.returncode
46
+
47
+
48
+ def tensor_arena_size() -> int:
49
+ return __arena_size
50
+
51
+
52
+ def print_optimization_report():
53
+ print(__compilation_output)
54
+
55
+
56
+ def print_help(show_hidden: Optional[bool] = False) -> int:
57
+ if show_hidden:
58
+ return subprocess.run(["xcore-opt", "--help-list-hidden"]).returncode
59
+
60
+ return subprocess.run(["xcore-opt", "--help-list"]).returncode