d5b754559490ecd2884aab163a7c829f4ac757a3
[platform/core/ml/nnfw.git] / compiler / visq / visqlib / DumpFP32FM.py
1 # Copyright (c) 2022 Samsung Electronics Co., Ltd. All Rights Reserved
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Script that dumps FM of FP32 model
16 # NOTE This script runs on dalgona
17
18 import numpy as np
19
20 from pathlib import Path
21 from Util import to_filename
22
23
24 # Dump FP32 model's intermediate FM data and their names
25 #
26 # Before
27 # self._dir/
28 #
29 # After
30 # self._dir/
31 #  tensors.txt
32 #  <TENSOR_NAME>.npy
33 # NOTE TENSOR_NAME is transformed by to_filename
34 class DumpFP32FM:
35     def StartAnalysis(self, args):
36         self._dir = Path(args)
37         self._num_data = 0
38         self._tensor_names = set()
39
40     def EndNetworkExecution(self, outputs):
41         self._num_data += 1
42
43     def DefaultOpPost(self, name, opcode, inputs, output):
44         # Save intermediate FM into tensor_name.npy
45         data_path = self._dir / str(self._num_data)
46         data_path.mkdir(parents=False, exist_ok=True)
47         np.save(str(data_path / to_filename(name)), output['data'])
48         self._tensor_names.add(name)
49
50     def EndAnalysis(self):
51         # Save tensor names line by line
52         with open(self._dir / 'tensors.txt', 'w') as f:
53             for name in self._tensor_names:
54                 f.write("%s\n" % name)