-
Notifications
You must be signed in to change notification settings - Fork 541
Expand file tree
/
Copy pathTrackableView.cs
More file actions
82 lines (75 loc) · 2.84 KB
/
Copy pathTrackableView.cs
File metadata and controls
82 lines (75 loc) · 2.84 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
using System;
using Tensorflow.Train;
using System.Collections.Generic;
using System.IO;
using Tensorflow.Keras.Saving.SavedModel;
namespace Tensorflow.Checkpoint;
public class TrackableView
{
protected WeakReference<Trackable> _root_ref;
public TrackableView(Trackable obj)
{
_root_ref = new WeakReference<Trackable>(obj);
}
public TrackableView(WeakReference<Trackable> obj)
{
_root_ref = obj;
}
public virtual IDictionary<string, Trackable> children(Trackable obj, SaveType save_type = SaveType.CHECKPOINT, IDictionary<string, IDictionary<Trackable, ISerializedAttributes>>? cache = null)
{
obj._maybe_initialize_trackable();
Dictionary<string, Trackable> children = new();
// Note: in python the return type of `Trackable._trackable_children` is not fixed.
// Therefore it uses `convert_to_trackable` to have an extra process.
foreach (var pair in obj._trackable_children(save_type, cache))
{
children[pair.Key] = pair.Value;
}
return children;
}
public Trackable Root
{
get
{
if (_root_ref.TryGetTarget(out Trackable res))
{
return res;
}
else
{
throw new InvalidDataException(
"Cannot get the object from the weak reference. Please consider if a null reference is passed to the constructor.");
}
}
}
/// <summary>
/// Returns a list of all nodes and its paths from self.root using a breadth first traversal.
/// Corresponding to tensorflow/python/checkpoint/trackable_view.Trackable._descendants_with_paths
/// </summary>
protected (IList<Trackable>, IDictionary<Trackable, IEnumerable<TrackableReference>>) _descendants_with_paths()
{
List<Trackable> bfs_sorted = new();
Queue<Trackable> to_visit = new();
to_visit.Enqueue(Root);
Dictionary<Trackable, IEnumerable<TrackableReference>> node_paths = new();
node_paths[this.Root] = new List<TrackableReference>();
while (!to_visit.empty())
{
var current_trackable = to_visit.Dequeue();
bfs_sorted.Add(current_trackable);
var children_dict = this.children(current_trackable);
foreach (var name in children_dict.Keys)
{
var dependency = children_dict[name];
if (!node_paths.ContainsKey(dependency))
{
var list = new List<TrackableReference>(node_paths[current_trackable]);
list.Add(new TrackableReference(name, dependency));
node_paths[dependency] = list;
to_visit.Enqueue(dependency);
}
}
}
return (bfs_sorted, node_paths);
}
}