forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhdf5_format.cs
More file actions
347 lines (306 loc) · 13.3 KB
/
hdf5_format.cs
File metadata and controls
347 lines (306 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
using System;
using System.Collections.Generic;
using System.Text;
using HDF.PInvoke;
using Tensorflow.NumPy;
using HDF5CSharp;
using static Tensorflow.Binding;
using static Tensorflow.KerasApi;
using System.Linq;
namespace Tensorflow.Keras.Saving
{
public class hdf5_format
{
private static int HDF5_OBJECT_HEADER_LIMIT = 64512;
public static void load_model_from_hdf5(string filepath = "", Dictionary<string, object> custom_objects = null, bool compile = false)
{
long root = Hdf5.OpenFile(filepath,true);
load_model_from_hdf5(root, custom_objects, compile);
}
public static void load_model_from_hdf5(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
//long fileId = filepath;
//try
//{
// groupId = H5G.open(fileId, "/");
// (bool success, string[] attrId) = Hdf5.ReadStringAttributes(groupId, "model_config", "");
// H5G.close(groupId);
// if (success == true) {
// Console.WriteLine(attrId[0]);
// }
//}
//catch (Exception ex)
//{
// if (filepath != -1) {
// Hdf5.CloseFile(filepath);
// }
// if (groupId != -1) {
// H5G.close(groupId);
// }
// throw new Exception(ex.ToString());
//}
}
public static void save_model_to_hdf5(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
/// <summary>
/// Preprocess layer weights between different Keras formats.
/// </summary>
/// <param name="layer"></param>
/// <param name="weights"></param>
/// <param name="original_keras_version"></param>
/// <param name="original_backend"></param>
public static List<NDArray> preprocess_weights_for_loading(ILayer layer, List<NDArray> weights, string original_keras_version = null, string original_backend = null)
{
// convert CuDNN layers
return _convert_rnn_weights(layer, weights);
}
/// <summary>
/// Converts weights for RNN layers between native and CuDNN format.
/// </summary>
/// <param name="layer"></param>
/// <param name="weights"></param>
static List<NDArray> _convert_rnn_weights(ILayer layer, List<NDArray> weights)
{
var target_class = layer.GetType().Name;
return weights;
}
public static void save_optimizer_weights_to_hdf5_group(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
public static void load_optimizer_weights_from_hdf5_group(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
public static void load_weights_from_hdf5_group(long f, List<ILayer> layers)
{
string original_keras_version = "2.5.0";
string original_backend = null;
var (success, attr) = Hdf5.ReadStringAttributes(f, "keras_version", "", true);
if (success)
original_keras_version = attr.First();
// keras version should be 2.5.0+
var ver_major = int.Parse(original_keras_version.Split('.')[0]);
var ver_minor = int.Parse(original_keras_version.Split('.')[1]);
if (ver_major < 2 || (ver_major == 2 && ver_minor < 5))
throw new ValueError("keras version should be 2.5.0 or later.");
(success, attr) = Hdf5.ReadStringAttributes(f, "backend", "", true);
if (success)
original_backend = attr.First();
var filtered_layers = new List<ILayer>();
foreach (var layer in layers)
{
var weights = _legacy_weights(layer);
if (weights.Count > 0)
filtered_layers.append(layer);
}
string[] layer_names = load_attributes_from_hdf5_group(f, "layer_names");
var filtered_layer_names = new List<string>();
foreach(var name in layer_names)
{
if (!filtered_layers.Select(x => x.Name).Contains(name))
continue;
long g = H5G.open(f, name);
var weight_names = load_attributes_from_hdf5_group(g, "weight_names");
if (weight_names.Count() > 0)
filtered_layer_names.Add(name);
H5G.close(g);
}
layer_names = filtered_layer_names.ToArray();
if (layer_names.Length != filtered_layers.Count())
throw new ValueError("You are trying to load a weight file " +
$"containing {layer_names}" +
$" layers into a model with {filtered_layers.Count} layers.");
var weight_value_tuples = new List<(IVariableV1, NDArray)>();
foreach (var (k, name) in enumerate(layer_names))
{
var weight_values = new List<NDArray>();
long g = H5G.open(f, name);
var weight_names = load_attributes_from_hdf5_group(g, "weight_names");
foreach (var i_ in weight_names)
{
(success, Array result) = Hdf5.ReadDataset<float>(g, i_);
if (success)
weight_values.Add(np.array(result));
}
H5G.close(g);
var layer = filtered_layers[k];
var symbolic_weights = _legacy_weights(layer);
preprocess_weights_for_loading(layer, weight_values, original_keras_version, original_backend);
if (weight_values.Count() != symbolic_weights.Count())
throw new ValueError($"Layer #{k} (named {layer.Name}" +
"in the current model) was found to " +
$"correspond to layer {name} in the save file." +
$"However the new layer {layer.Name} expects " +
$"{symbolic_weights.Count()} weights, but the saved weights have " +
$"{weight_values.Count()} elements.");
weight_value_tuples.AddRange(zip(symbolic_weights, weight_values));
}
keras.backend.batch_set_value(weight_value_tuples);
}
public static void toarrayf4(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
public static void load_weights_from_hdf5_group_by_name(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
public static void save_weights_to_hdf5_group(long f, List<ILayer> layers)
{
List<string> layerName=new List<string>();
foreach (var layer in layers)
{
layerName.Add(layer.Name);
}
save_attributes_to_hdf5_group(f, "layer_names", layerName.ToArray());
Hdf5.WriteAttribute(f, "backend", "tensorflow");
Hdf5.WriteAttribute(f, "keras_version", "2.5.0");
foreach (var layer in layers)
{
var weights = _legacy_weights(layer);
if (weights.Count == 0)
continue;
var weight_names = new List<string>();
// weight_values= keras.backend.batch_get_value(weights);
foreach (var weight in weights)
weight_names.Add(weight.Name);
var g = Hdf5.CreateOrOpenGroup(f, Hdf5Utils.NormalizedName(layer.Name));
save_attributes_to_hdf5_group(g, "weight_names", weight_names.ToArray());
foreach (var (name, val) in zip(weight_names, weights))
{
var tensor = val.AsTensor();
if (name.IndexOf("/") > 1)
{
var crDataGroup = Hdf5.CreateOrOpenGroup(g, Hdf5Utils.NormalizedName(name.Split('/')[0]));
WriteDataset(crDataGroup, name.Split('/')[1], tensor);
Hdf5.CloseGroup(crDataGroup);
}
else
{
WriteDataset(g, name, tensor);
}
}
Hdf5.CloseGroup(g);
}
}
private static void save_attributes_to_hdf5_group(long f, string name, Array data)
{
int num_chunks = 1;
var chunked_data = Split(data, num_chunks);
int getSize = 0;
string getType = data.Length > 0 ? data.GetValue(0).GetType().Name.ToLower() : "string";
switch (getType)
{
case "single":
getSize = sizeof(float);
break;
case "double":
getSize = sizeof(double);
break;
case "string":
getSize = -1;
break;
case "int32":
getSize = sizeof(int);
break;
case "int64":
getSize = sizeof(long);
break;
default:
getSize = -1;
break;
}
int getCount = chunked_data.Count;
if (getSize != -1)
{
num_chunks = (int)Math.Ceiling((double)(getCount * getSize) / HDF5_OBJECT_HEADER_LIMIT);
if (num_chunks > 1) chunked_data = Split(data, num_chunks);
}
if (num_chunks > 1)
{
foreach (var (chunk_id, chunk_data) in enumerate(chunked_data))
WriteAttrs(f, getType, $"{name}{chunk_id}", chunk_data.ToArray());
}
else
{
WriteAttrs(f, getType, name, data);
}
}
private static void WriteDataset(long f, string name, Tensor data)
{
switch (data.dtype)
{
case TF_DataType.TF_FLOAT:
Hdf5.WriteDatasetFromArray<float>(f, name, data.numpy().ToMultiDimArray<float>());
break;
case TF_DataType.TF_DOUBLE:
Hdf5.WriteDatasetFromArray<double>(f, name, data.numpy().ToMultiDimArray<double>());
break;
case TF_DataType.TF_INT32:
Hdf5.WriteDatasetFromArray<int>(f, name, data.numpy().ToMultiDimArray<int>());
break;
case TF_DataType.TF_INT64:
Hdf5.WriteDatasetFromArray<long>(f, name, data.numpy().ToMultiDimArray<long>());
break;
default:
Hdf5.WriteDatasetFromArray<float>(f, name, data.numpy().ToMultiDimArray<float>());
break;
}
}
private static void WriteAttrs(long f,string typename, string name, Array data)
{
switch (typename)
{
case "single":
Hdf5.WriteAttributes<float>(f, name, data);
break;
case "double":
Hdf5.WriteAttributes<double>(f, name, data);
break;
case "string":
Hdf5.WriteAttributes<string>(f, name, data);
break;
case "int32":
Hdf5.WriteAttributes<int>(f, name, data);
break;
case "int64":
Hdf5.WriteAttributes<long>(f, name, data);
break;
default:
Hdf5.WriteAttributes<string>(f, name,data);
break;
}
}
private static List<List<object>> Split(Array list, int chunkSize)
{
var splitList = new List<List<object>>();
var chunkCount = (int)Math.Ceiling((double)list.Length / (double)chunkSize);
for (int c = 0; c < chunkCount; c++)
{
var skip = c * chunkSize;
var take = skip + chunkSize;
var chunk = new List<object>(chunkSize);
for (int e = skip; e < take && e < list.Length; e++)
{
chunk.Add(list.GetValue(e));
}
splitList.Add(chunk);
}
return splitList;
}
public static string[] load_attributes_from_hdf5_group(long group, string name)
{
var (success, attr) = Hdf5.ReadStringAttributes(group, name, "", true);
if (success)
return attr.ToArray();
return null;
}
public static void load_attributes_from_hdf5_group(long filepath = -1, Dictionary<string, object> custom_objects = null, bool compile = false)
{
}
public static List<IVariableV1> _legacy_weights(ILayer layer)
{
var weights = layer.TrainableWeights.Select(x => x).ToList();
weights.AddRange(layer.NonTrainableWeights);
return weights;
}
}
}