Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compiler / dio-hdf5 / include / dio_hdf5 / HDF5Importer.h
1 /*
2  * Copyright (c) 2022 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 #ifndef __DIO_HDF5_H__
18 #define __DIO_HDF5_H__
19
20 #include <H5Cpp.h>
21
22 #include <loco.h>
23
24 #include <string>
25 #include <vector>
26
27 namespace dio
28 {
29 namespace hdf5
30 {
31
32 // HDF5Importer reads an input data saved in the hdf5 file in the given path
33 // The hierarchy of the hdf5 file is as follows.
34 // Group "/"
35 //  > Group <group_name>
36 //    > Group <data_idx>
37 //      > Dataset <input_idx>
38 // data_idx : index of the data (dataset file can contain multiple data)
39 // input_idx : index of the input (DNN model can have multiple inputs)
40 // Ex: the j'th input of the i'th data of group 'value' can be accessed by "/value/i/j"
41 class HDF5Importer final
42 {
43 public:
44   explicit HDF5Importer(const std::string &path);
45
46 public:
47   /**
48    * @note importGroup has to be called before readTensor is called
49    *        Otherwise, readTensor will throw an exception
50    */
51   void importGroup(const std::string &group) { _group = _file.openGroup(group); }
52
53   /**
54    * @brief Read tensor data from file and store it into buffer
55    * @details A tensor in the file can be retrieved with (data_idx, input_idx)
56    * @param data_idx : index of the data
57    * @param input_idx : index of the input
58    * @param dtype : pointer to write the tensor's data type
59    * @param shape : pointer to write the tensor's shape
60    * @param buffer : pointer to write the tensor's data
61    * @param buffer_bytes : byte size of the buffer
62    */
63   void readTensor(int32_t data_idx, int32_t input_idx, loco::DataType *dtype,
64                   std::vector<loco::Dimension> *shape, void *buffer, size_t buffer_bytes);
65
66   // Read a raw tensor (no type/shape is specified)
67   void readTensor(int32_t data_idx, int32_t input_idx, void *buffer, size_t buffer_bytes);
68
69   bool isRawData() { return _group.attrExists("rawData"); }
70
71   int32_t numData() { return _group.getNumObjs(); }
72
73   int32_t numInputs(int32_t data_idx);
74
75 private:
76   H5::H5File _file;
77   H5::Group _group;
78 };
79
80 } // namespace hdf5
81 } // namespace dio
82
83 #endif // __DIO_HDF5_H__