ONE - On-device Neural Engine
Loading...
Searching...
No Matches
test_utils.py
Go to the documentation of this file.
1import json
2import typing
3import numpy as np
4import os
5
6
7def _dump_npy_included_json(output_dir: str, json_content: dict):
8 """
9 Dump json and npy files to output_dir
10 """
11 # Create output_dir if not exists
12 if not os.path.exists(output_dir):
13 os.makedirs(output_dir)
14
15 # file name for npy data (ex: 0.npy, 1.npy, ...)
16 _index = 0
17 _index_to_value = dict()
18
19 # Replace npy to the path to the npy file
20 for tensor_name, qparam in json_content.items():
21 assert type(tensor_name) == str
22 assert type(qparam) == dict
23 for field, value in qparam.items():
24 if isinstance(value, np.ndarray):
25 npy_name = str(_index) + '.npy'
26
27 # Save npy file
28 np.save(os.path.join(output_dir, npy_name), value)
29
30 # Replace to the path to the npy file
31 json_content[tensor_name][field] = npy_name
32
33 # Save the mapping from index to tensor name
34 _index_to_value[_index] = tensor_name + "_" + field
35 _index += 1
36
37 # Dump json
38 with open(os.path.join(output_dir, 'qparam.json'), 'w') as f:
39 json.dump(json_content, f, indent=2)
40
41
42def _str_to_npy_dtype(dtype_str: str):
43 if dtype_str == "uint8":
44 return np.uint8
45 if dtype_str == "int16":
46 return np.int16
47 if dtype_str == "int32":
48 return np.int32
49 if dtype_str == "int64":
50 return np.int64
51 raise SystemExit("Unsupported npy dtype", dtype_str)
52
53
54def gen_random_tensor(dtype_str: str,
55 scale_shape: typing.Tuple[int],
56 zerop_shape: typing.Tuple[int],
57 quantized_dimension: int,
58 value_shape: typing.Optional[typing.Tuple[int]] = None) -> dict:
59 content = dict()
60 content['dtype'] = dtype_str
61 content['scale'] = np.random.rand(scale_shape).astype(np.float32)
62 # Why 256? To ensure the smallest dtype (uint8) range [0, 256)
63 content['zerop'] = np.random.randint(256, size=zerop_shape, dtype=np.int64)
64 content['quantized_dimension'] = quantized_dimension
65
66 if value_shape != None:
67 dtype = _str_to_npy_dtype(dtype_str)
68 content['value'] = np.random.randint(256, size=value_shape, dtype=dtype)
69 return content
70
71
73 def __init__(self):
74 pass
75
76 def generate(self) -> dict:
77 pass
78
79
80class TestRunner:
81 def __init__(self, output_dir: str):
82 self.test_cases = list()
83 self.output_dir = output_dir
84
85 def register(self, test_case: TestCase):
86 self.test_cases.append(test_case)
87
88 def run(self):
89 for test_case in self.test_cases:
90 print("Generate test case: " + test_case.name)
91 _dump_npy_included_json(self.output_dir + '/' + test_case.name,
92 test_case.generate())
dict generate(self)
Definition test_utils.py:76
__init__(self, str output_dir)
Definition test_utils.py:81
register(self, TestCase test_case)
Definition test_utils.py:85
_str_to_npy_dtype(str dtype_str)
Definition test_utils.py:42
_dump_npy_included_json(str output_dir, dict json_content)
Definition test_utils.py:7