Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / runtime / onert / core / src / dumper / h5 / MinMaxDumper.cc
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "MinMaxDumper.h"
18
19 #include <iostream>
20 #include <sstream>
21 #include <stdexcept>
22
23 namespace onert
24 {
25 namespace dumper
26 {
27 namespace h5
28 {
29
30 static const char *h5_value_grpname = "value";
31
32 /*
33  * ensure grp_name exists in parent
34  */
35 H5::Group ensureGroup(H5::Group parent, const char *child)
36 {
37   H5::Exception::dontPrint();
38   try
39   {
40     return parent.openGroup(child);
41   }
42   catch (H5::Exception &e)
43   {
44     return parent.createGroup(child);
45   }
46 }
47
48 MinMaxDumper::MinMaxDumper(const std::string &filepath) : Dumper(filepath)
49 {
50   auto root_grp = _file.openGroup("/");
51   ensureGroup(root_grp, h5_value_grpname);
52 }
53
54 void MinMaxDumper::dump(const exec::SMMinMaxMap &mmmap) const
55 {
56   auto val_grp = _file.openGroup(h5_value_grpname);
57   auto num_run = val_grp.getNumObjs();
58   auto num_grp = val_grp.createGroup(std::to_string(num_run));
59   auto model_grp = ensureGroup(num_grp, "0");
60   hsize_t dims[] = {2};
61   H5::DataSpace dspace(1, dims); // rank=1, dim(0)=2, {min, max}
62   for (auto &&e : mmmap)
63   {
64     // key = {subg_idx, op_idx} = e.first
65     const auto subg_idx = e.first.first.value();
66     const auto op_idx = e.first.second.value();
67     auto subg_grp = ensureGroup(model_grp, std::to_string(subg_idx).c_str());
68     auto op_dset = subg_grp.createDataSet(std::to_string(op_idx), H5::PredType::IEEE_F32BE, dspace);
69     op_dset.write(e.second.data, H5::PredType::NATIVE_FLOAT);
70   }
71 }
72
73 } // namespace h5
74 } // namespace dumper
75 } // namespace onert