Skip to content

Commit 7e42bfc

Browse files
committed
onnx -> h5
1 parent b324c95 commit 7e42bfc

7 files changed

Lines changed: 76 additions & 104 deletions

File tree

app/Converters/parser.py

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,79 @@
11
import json
22
import os
3-
43
import tensorflow as tf
54
from tensorflow.keras.initializers import GlorotUniform as OriginalGlorotUniform, Zeros as OriginalZeros
65
from tensorflow.keras.models import load_model
76

7+
88
class CustomGlorotUniform(OriginalGlorotUniform):
99
def __init__(self, seed=None, **kwargs):
10-
kwargs.pop('dtype', None) # Remove the unexpected dtype keyword if present
10+
kwargs.pop('dtype', None)
1111
super().__init__(seed=seed, **kwargs)
1212

13+
1314
class CustomZeros(OriginalZeros):
1415
def __init__(self, **kwargs):
15-
kwargs.pop('dtype', None) # Remove the unexpected dtype keyword if present
16+
kwargs.pop('dtype', None)
1617
super().__init__(**kwargs)
1718

18-
# Пути к модели и JSON файлу
19+
1920
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
2021
MODEL_PATH = os.path.join(BASE_DIR, 'docs\\models', 'AlexNet-model.h5')
2122
MODEL_DATA_PATH = os.path.join(BASE_DIR, 'docs\\jsons', 'model_data_alexnet_1.json')
2223

23-
# Загрузка модели
2424
model = load_model(MODEL_PATH, custom_objects={'GlorotUniform': CustomGlorotUniform, 'Zeros': CustomZeros})
2525

26-
# Получение весов модели и информации о порядке слоев
2726
layer_info = []
2827
for index, layer in enumerate(model.layers):
2928
layer_name = layer.name
30-
layer_type = type(layer).__name__ # Тип слоя (например, Conv2D, Dense, Activation и т.д.)
29+
layer_type = type(layer).__name__
3130
layer_config = layer.get_config()
31+
weights = layer.get_weights()
3232

33-
# Извлечение параметров слоя
34-
layer_padding = None
35-
layer_activation = None
36-
37-
if isinstance(layer, tf.keras.layers.Conv2D):
38-
layer_padding = layer_config.get('padding', None) # Считываем padding у Conv2D
39-
layer_activation = layer_config.get('activation', None) # Получаем функцию активации
40-
41-
# Сохранение информации о слое: его тип, имя, padding и веса
4233
layer_data = {
43-
'index': len(layer_info), # Порядковый номер слоя
34+
'index': len(layer_info),
4435
'name': layer_name,
45-
'type': layer_type
36+
'type': layer_type,
37+
'weights': [],
38+
'bias': []
4639
}
4740

48-
if layer_padding is not None:
49-
layer_data['padding'] = layer_padding
41+
# Обработка параметров слоя
42+
if isinstance(layer, tf.keras.layers.Conv2D):
43+
layer_data['padding'] = layer_config.get('padding', None)
44+
layer_activation = layer_config.get('activation', None)
45+
46+
# Для Conv2D веса имеют форму (kernel_size[0], kernel_size[1], in_channels, out_channels)
47+
if len(weights) > 0:
48+
layer_data['weights'] = weights[0].tolist()
49+
if len(weights) > 1:
50+
layer_data['bias'] = weights[1].tolist()
51+
52+
elif isinstance(layer, tf.keras.layers.Dense):
53+
if len(weights) > 0:
54+
layer_data['weights'] = weights[0].tolist()
55+
if len(weights) > 1:
56+
layer_data['bias'] = weights[1].tolist()
5057

51-
layer_data['weights'] = [w.tolist() for w in layer.get_weights()]
58+
else:
59+
# Для других слоев сохраняем все веса как есть
60+
if weights:
61+
layer_data['weights'] = [w.tolist() for w in weights]
5262

5363
layer_info.append(layer_data)
5464

55-
# Если активация встроена в слой, добавляем её как отдельный слой
56-
if layer_activation and not isinstance(layer, tf.keras.layers.Activation):
65+
# Обработка встроенной активации
66+
if isinstance(layer, (tf.keras.layers.Conv2D)) and layer_activation:
5767
activation_layer = {
5868
'index': len(layer_info),
5969
'name': f"activation_{layer_name}",
6070
'type': layer_activation,
61-
'weights': []
71+
'weights': [],
72+
'bias': []
6273
}
6374
layer_info.append(activation_layer)
6475

65-
# Сохранение данных в JSON файл
6676
with open(MODEL_DATA_PATH, 'w') as f:
6777
json.dump(layer_info, f, indent=2)
6878

69-
print(f"Model data saved to {MODEL_DATA_PATH}")
79+
print(f"Model data saved to {MODEL_DATA_PATH}")

app/Converters/reader_weights_sample.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ int main() {
1616

1717
try {
1818
Tensor tensor =
19-
create_tensor_from_json(layer_data["weights"], Type::kFloat);
19+
create_tensor_from_json(layer_data, Type::kFloat);
2020
// std::cout << tensor << std::endl;
2121
} catch (const std::exception& e) {
2222
std::cerr << "Error processing layer " << layer_name << ": " << e.what()

app/Graph/build.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ void build_graph(Tensor& input, Tensor& output, bool comments,
3636
std::cout << "Processing layer of type: " << layer_type << std::endl;
3737

3838
Tensor tensor =
39-
create_tensor_from_json(layer_data["weights"], Type::kFloat);
39+
create_tensor_from_json(layer_data, Type::kFloat);
4040

4141
if (layer_type.find("Conv") != std::string::npos) {
4242
Tensor tmp_tensor = tensor;

include/Weights_Reader/reader_weights.hpp

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ using json = nlohmann::json;
88
using namespace itlab_2023;
99

1010
json read_json(const std::string& filename);
11-
void extract_values_without_bias(const json& j, std::vector<float>& values);
1211
void extract_values_from_json(const json& j, std::vector<float>& values);
1312
void parse_json_shape(const json& j, std::vector<size_t>& shape, size_t dim);
1413
Tensor create_tensor_from_json(const json& j, Type type);
15-
void extract_bias_from_json(const json& j, std::vector<float>& bias);

include/Weights_Reader/reader_weights_onnx.hpp

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,3 @@ void extract_values_from_json_onnx(const json& j, std::vector<float>& values);
1212
void parse_json_shape_onnx(const json& j, std::vector<size_t>& shape,
1313
size_t dim);
1414
Tensor create_tensor_from_json_onnx(const json& j, Type type);
15-
16-
void parse_onnx_weights(const json& j, std::vector<float>& weights,
17-
std::vector<float>& bias);

src/Weights_Reader/reader_weights.cpp

Lines changed: 36 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,14 @@
99
using json = nlohmann::json;
1010

1111
json read_json(const std::string& filename) {
12-
std::ifstream ifs(filename, std::ifstream::binary);
12+
std::ifstream ifs(filename);
1313
if (!ifs.is_open()) {
1414
throw std::runtime_error("Failed to open JSON file: " + filename);
1515
}
1616

17-
ifs.seekg(0, std::ios::end);
18-
size_t size = ifs.tellg();
19-
ifs.seekg(0, std::ios::beg);
20-
21-
std::vector<char> buffer(size);
22-
ifs.read(buffer.data(), size);
23-
ifs.close();
24-
2517
json model_data;
2618
try {
27-
model_data = json::parse(buffer.begin(), buffer.end());
19+
ifs >> model_data;
2820
} catch (const json::parse_error& e) {
2921
throw std::runtime_error("JSON parse error: " + std::string(e.what()));
3022
}
@@ -42,74 +34,49 @@ void extract_values_from_json(const json& j, std::vector<float>& values) {
4234
}
4335
}
4436

45-
void extract_values_without_bias(const json& j, std::vector<float>& values) {
46-
std::vector<float> temp_values;
47-
extract_values_from_json(j, temp_values);
48-
size_t bias_size = 0;
49-
if (j.is_array() && !j.empty() && j.back().is_array()) {
50-
bias_size = j.back().size();
37+
void parse_json_shape(const json& j, std::vector<size_t>& shape,
38+
size_t dim = 0) {
39+
if (!j.is_array()) {
40+
if (dim == 0) shape.push_back(0);
41+
return;
5142
}
52-
// std::cout << "Bias size: " << bias_size << std::endl;
53-
if (temp_values.size() >= bias_size) {
54-
values.assign(temp_values.begin(), temp_values.end() - bias_size);
43+
44+
if (shape.size() <= dim) {
45+
shape.push_back(j.size());
5546
}
56-
}
5747

58-
void parse_json_shape(const json& j, std::vector<size_t>& shape, size_t dim) {
59-
if (dim == 0) {
60-
if (j.is_array()) {
61-
if (j.empty()) {
62-
shape.push_back(0);
63-
return;
64-
}
65-
parse_json_shape(j.front(), shape, dim + 1);
66-
} else {
67-
shape.push_back(0);
68-
}
69-
} else {
70-
if (j.is_array()) {
71-
if (shape.size() <= dim - 1) {
72-
shape.push_back(j.size());
73-
}
74-
if (!j.empty()) {
75-
parse_json_shape(j.front(), shape, dim + 1);
76-
}
77-
}
48+
if (!j.empty()) {
49+
parse_json_shape(j[0], shape, dim + 1);
7850
}
7951
}
8052

81-
void extract_bias_from_json(const json& j, std::vector<float>& bias) {
82-
if (j.is_array()) {
83-
if (!j.empty() && j.back().is_array()) {
84-
for (const auto& item : j.back()) {
85-
if (item.is_number()) {
86-
bias.push_back(item.get<float>());
87-
}
88-
}
89-
}
53+
Tensor create_tensor_from_json(const json& layer_data, Type type) {
54+
if (type != Type::kFloat) {
55+
throw std::invalid_argument("Only float type is supported");
9056
}
91-
}
9257

93-
Tensor create_tensor_from_json(const json& j, Type type) {
94-
if (type == Type::kFloat) {
95-
std::vector<float> vals;
96-
std::vector<size_t> shape;
97-
std::vector<float> bias;
98-
extract_values_without_bias(j, vals);
99-
// std::cout << "Extracted values size: " << vals.size() << std::endl;
58+
std::vector<float> weights;
59+
if (layer_data.contains("weights") && !layer_data["weights"].empty()) {
60+
extract_values_from_json(layer_data["weights"], weights);
61+
}
10062

101-
parse_json_shape(j, shape, 0);
102-
// std::cout << "Shape: ";
103-
/*for (size_t i = 0; i < shape.size() - 1; i++) {
104-
std::cout << shape[i] << ", ";
105-
}
106-
std::cout << shape[shape.size() - 1];
107-
std::cout << std::endl;*/
63+
// Извлекаем bias (если есть)
64+
std::vector<float> bias;
65+
if (layer_data.contains("bias") && !layer_data["bias"].empty()) {
66+
extract_values_from_json(layer_data["bias"], bias);
67+
}
10868

109-
extract_bias_from_json(j, bias);
110-
// std::cout << "Extracted bias size: " << bias.size() << std::endl;
111-
Shape sh(shape);
112-
return make_tensor<float>(vals, sh, bias);
69+
// Определяем shape
70+
std::vector<size_t> shape;
71+
if (layer_data.contains("weights")) {
72+
parse_json_shape(layer_data["weights"], shape);
11373
}
114-
throw std::invalid_argument("Unsupported type or invalid JSON format");
74+
75+
std::cout << "Extracted weights size: " << weights.size() << std::endl;
76+
std::cout << "Shape: ";
77+
for (auto dim : shape) std::cout << dim << " ";
78+
std::cout << std::endl;
79+
std::cout << "Extracted bias size: " << bias.size() << std::endl;
80+
81+
return make_tensor<float>(weights, Shape(shape), bias);
11582
}

src/Weights_Reader/reader_weights_onnx.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,11 @@ Tensor create_tensor_from_json_onnx(const json& layer_data, Type type) {
7272
parse_json_shape_onnx(layer_data["weights"], shape);
7373
}
7474

75-
std::cout << "Extracted weights size: " << weights.size() << std::endl;
75+
/*std::cout << "Extracted weights size: " << weights.size() << std::endl;
7676
std::cout << "Shape: ";
7777
for (auto dim : shape) std::cout << dim << " ";
7878
std::cout << std::endl;
79-
std::cout << "Extracted bias size: " << bias.size() << std::endl;
79+
std::cout << "Extracted bias size: " << bias.size() << std::endl;*/
8080

8181
return make_tensor<float>(weights, Shape(shape), bias);
8282
}

0 commit comments

Comments
 (0)