Skip to content

Commit 8a50673

Browse files
committed
Make Graph inherits from DisposableObject.
1 parent bad9aba commit 8a50673

8 files changed

Lines changed: 57 additions & 55 deletions

File tree

‎src/TensorFlowHub/TensorFlowHub.csproj‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<PropertyGroup>
33
<RootNamespace>Tensorflow.Hub</RootNamespace>
44
<TargetFramework>netstandard2.0</TargetFramework>
5-
<Version>0.0.1</Version>
5+
<Version>0.0.2</Version>
66
<Authors>Kerry Jiang</Authors>
77
<Company>SciSharp STACK</Company>
88
<Copyright>Apache 2.0</Copyright>
@@ -13,7 +13,7 @@
1313
<Description>TensorFlow Hub is a library to foster the publication, discovery, and consumption of reusable parts of machine learning models.</Description>
1414
<PackageId>SciSharp.TensorFlowHub</PackageId>
1515
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
16-
<PackageReleaseNotes>1. Add MNIST loader.</PackageReleaseNotes>
16+
<PackageReleaseNotes></PackageReleaseNotes>
1717
<PackageIconUrl>https://avatars3.githubusercontent.com/u/44989469?s=200&amp;v=4</PackageIconUrl>
1818
</PropertyGroup>
1919
<ItemGroup>

‎src/TensorFlowNET.Core/Graphs/DefaultGraphStack.cs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,17 @@ public void set_controller(Graph @default)
3434

3535
public Graph get_controller()
3636
{
37-
if (stack.Count == 0)
37+
if (stack.Count(x => x.IsDefault) == 0)
3838
stack.Add(new StackModel { Graph = tf.Graph(), IsDefault = true });
3939

40-
return stack.First(x => x.IsDefault).Graph;
40+
return stack.Last(x => x.IsDefault).Graph;
41+
}
42+
43+
public bool remove(Graph g)
44+
{
45+
var sm = stack.FirstOrDefault(x => x.Graph == g);
46+
if (sm == null) return false;
47+
return stack.Remove(sm);
4148
}
4249

4350
public void reset()

‎src/TensorFlowNET.Core/Graphs/Graph.cs‎

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,8 @@ that are identified by name. For convenience when building a large
7373
all variables that are created during the construction of a graph. The caller
7474
may define additional collections by specifying a new name.
7575
*/
76-
public partial class Graph : IPython, IDisposable, IEnumerable<Operation>
76+
public partial class Graph : DisposableObject, IEnumerable<Operation>
7777
{
78-
private IntPtr _handle;
7978
private Dictionary<int, ITensorOrOperation> _nodes_by_id;
8079
public Dictionary<string, ITensorOrOperation> _nodes_by_name;
8180
private Dictionary<string, int> _names_in_use;
@@ -121,10 +120,6 @@ public Graph(IntPtr handle)
121120
_graph_key = $"grap-key-{ops.uid()}/";
122121
}
123122

124-
public void __enter__()
125-
{
126-
}
127-
128123
public ITensorOrOperation as_graph_element(object obj, bool allow_tensor = true, bool allow_operation = true)
129124
{
130125
return _as_graph_element_locked(obj, allow_tensor, allow_operation);
@@ -443,14 +438,15 @@ public void prevent_fetching(Operation op)
443438
_unfetchable_ops.Add(op);
444439
}
445440

446-
public void Dispose()
447-
{
448-
/*if (_handle != IntPtr.Zero)
449-
c_api.TF_DeleteGraph(_handle);
450-
451-
_handle = IntPtr.Zero;
452-
453-
GC.SuppressFinalize(this);*/
441+
protected override void DisposeManagedState()
442+
{
443+
ops.default_graph_stack.remove(this);
444+
}
445+
446+
protected override void DisposeUnManagedState(IntPtr handle)
447+
{
448+
Console.WriteLine($"Destroy graph {handle}");
449+
c_api.TF_DeleteGraph(handle);
454450
}
455451

456452
/// <summary>
@@ -481,17 +477,19 @@ public TensorShape GetTensorShape(TF_Output output)
481477
return new TensorShape(dims.Select(x => (int)x).ToArray());
482478
}
483479

480+
string debugString = string.Empty;
484481
public override string ToString()
485482
{
486-
int len = 0;
487-
return c_api.TF_GraphDebugString(_handle, out len);
483+
return $"{graph_key}, ({_handle})";
484+
/*if (string.IsNullOrEmpty(debugString))
485+
{
486+
int len = 0;
487+
debugString = c_api.TF_GraphDebugString(_handle, out len);
488+
}
489+
490+
return debugString;*/
488491
}
489492

490-
public void __exit__()
491-
{
492-
493-
}
494-
495493
private IEnumerable<Operation> GetEnumerable()
496494
=> c_api_util.tf_operations(this);
497495

‎src/TensorFlowNET.Core/Operations/Operation.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public Operation(IntPtr handle, Graph g=null)
8484

8585
// Dict mapping op name to file and line information for op colocation
8686
// context managers.
87-
_control_flow_context = graph._get_control_flow_context();
87+
_control_flow_context = _graph._get_control_flow_context();
8888

8989
// Note: _control_flow_post_processing() must not be called here, the caller is responsible for calling it when using this constructor.
9090
}

‎src/TensorFlowNET.Core/Sessions/BaseSession.cs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ public class BaseSession : DisposableObject
3131
protected bool _closed;
3232
protected int _current_version;
3333
protected byte[] _target;
34-
protected IntPtr _session;
3534
public Graph graph => _graph;
3635

3736
public BaseSession(string target = "", Graph g = null, SessionOptions opts = null)
@@ -46,7 +45,7 @@ public BaseSession(string target = "", Graph g = null, SessionOptions opts = nul
4645

4746
var status = new Status();
4847

49-
_session = c_api.TF_NewSession(_graph, opts ?? newOpts, status);
48+
_handle = c_api.TF_NewSession(_graph, opts ?? newOpts, status);
5049

5150
status.Check(true);
5251
}
@@ -212,7 +211,7 @@ private unsafe NDArray[] _call_tf_sessionrun(KeyValuePair<TF_Output, Tensor>[] f
212211

213212
var output_values = fetch_list.Select(x => IntPtr.Zero).ToArray();
214213

215-
c_api.TF_SessionRun(_session,
214+
c_api.TF_SessionRun(_handle,
216215
run_options: null,
217216
inputs: feed_dict.Select(f => f.Key).ToArray(),
218217
input_values: feed_dict.Select(f => (IntPtr)f.Value).ToArray(),

‎src/TensorFlowNET.Core/Sessions/Session.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public Session(string target = "", Graph g = null)
3030
public Session(IntPtr handle, Graph g = null)
3131
: base("", g, null)
3232
{
33-
_session = handle;
33+
_handle = handle;
3434
}
3535

3636
public Session(Graph g, SessionOptions opts = null, Status s = null)
@@ -73,7 +73,7 @@ public static Session LoadFromSavedModel(string path)
7373
return new Session(sess, g: new Graph(graph).as_default());
7474
}
7575

76-
public static implicit operator IntPtr(Session session) => session._session;
76+
public static implicit operator IntPtr(Session session) => session._handle;
7777
public static implicit operator Session(IntPtr handle) => new Session(handle);
7878

7979
public void __enter__()

‎test/TensorFlowNET.Examples/ImageProcessing/RetrainImageClassifier.cs‎

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ public class RetrainImageClassifier : IExample
5252
// The location where variable checkpoints will be stored.
5353
string CHECKPOINT_NAME = Path.Join(data_dir, "_retrain_checkpoint");
5454
string tfhub_module = "https://tfhub.dev/google/imagenet/inception_v3/feature_vector/3";
55-
string final_tensor_name = "final_result";
55+
string input_tensor_name = "Placeholder";
56+
string final_tensor_name = "Score";
5657
float testing_percentage = 0.1f;
5758
float validation_percentage = 0.1f;
5859
float learning_rate = 0.01f;
@@ -81,13 +82,13 @@ public bool Run()
8182
PrepareData();
8283

8384
#region For debug purpose
84-
85+
8586
// predict images
8687
// Predict(null);
8788

8889
// load saved pb and test new images.
8990
// Test(null);
90-
91+
9192
#endregion
9293

9394
var graph = IsImportingGraph ? ImportGraph() : BuildGraph();
@@ -276,16 +277,13 @@ private void variable_summaries(RefVariable var)
276277
private (Graph, Tensor, Tensor, bool) create_module_graph()
277278
{
278279
var (height, width) = (299, 299);
279-
280-
return tf_with(tf.Graph().as_default(), graph =>
281-
{
282-
tf.train.import_meta_graph("graph/InceptionV3.meta");
283-
Tensor resized_input_tensor = graph.OperationByName("Placeholder"); //tf.placeholder(tf.float32, new TensorShape(-1, height, width, 3));
284-
// var m = hub.Module(module_spec);
285-
Tensor bottleneck_tensor = graph.OperationByName("module_apply_default/hub_output/feature_vector/SpatialSqueeze");// m(resized_input_tensor);
286-
var wants_quantization = false;
287-
return (graph, bottleneck_tensor, resized_input_tensor, wants_quantization);
288-
});
280+
var graph = tf.Graph().as_default();
281+
tf.train.import_meta_graph("graph/InceptionV3.meta");
282+
Tensor resized_input_tensor = graph.OperationByName(input_tensor_name); //tf.placeholder(tf.float32, new TensorShape(-1, height, width, 3));
283+
// var m = hub.Module(module_spec);
284+
Tensor bottleneck_tensor = graph.OperationByName("module_apply_default/hub_output/feature_vector/SpatialSqueeze");// m(resized_input_tensor);
285+
var wants_quantization = false;
286+
return (graph, bottleneck_tensor, resized_input_tensor, wants_quantization);
289287
}
290288

291289
private (NDArray, long[], string[]) get_random_cached_bottlenecks(Session sess, Dictionary<string, Dictionary<string, string[]>> image_lists,
@@ -594,13 +592,10 @@ public Graph ImportGraph()
594592
create_module_graph();
595593

596594
// Add the new layer that we'll be training.
597-
tf_with(graph.as_default(), delegate
598-
{
599-
(train_step, cross_entropy, bottleneck_input,
600-
ground_truth_input, final_tensor) = add_final_retrain_ops(
601-
class_count, final_tensor_name, bottleneck_tensor,
602-
wants_quantization, is_training: true);
603-
});
595+
(train_step, cross_entropy, bottleneck_input,
596+
ground_truth_input, final_tensor) = add_final_retrain_ops(
597+
class_count, final_tensor_name, bottleneck_tensor,
598+
wants_quantization, is_training: true);
604599

605600
return graph;
606601
}
@@ -734,15 +729,15 @@ public void Predict(Session sess_)
734729
var labels = File.ReadAllLines(output_labels);
735730

736731
// predict image
737-
var img_path = Path.Join(image_dir, "roses", "12240303_80d87f77a3_n.jpg");
732+
var img_path = Path.Join(image_dir, "daisy", "5547758_eea9edfd54_n.jpg");
738733
var fileBytes = ReadTensorFromImageFile(img_path);
739734

740735
// import graph and variables
741736
var graph = new Graph();
742737
graph.Import(output_graph, "");
743738

744-
Tensor input = graph.OperationByName("Placeholder");
745-
Tensor output = graph.OperationByName("final_result");
739+
Tensor input = graph.OperationByName(input_tensor_name);
740+
Tensor output = graph.OperationByName(final_tensor_name);
746741

747742
using (var sess = tf.Session(graph))
748743
{

‎test/TensorFlowNET.UnitTest/NameScopeTest.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ namespace TensorFlowNET.UnitTest
77
[TestClass]
88
public class NameScopeTest
99
{
10-
Graph g = ops.get_default_graph();
1110
string name = "";
1211

1312
[TestMethod]
1413
public void NestedNameScope()
1514
{
15+
Graph g = tf.Graph().as_default();
16+
1617
tf_with(new ops.NameScope("scope1"), scope1 =>
1718
{
1819
name = scope1;
@@ -37,6 +38,8 @@ public void NestedNameScope()
3738
Assert.AreEqual("scope1/Const_1:0", const3.name);
3839
});
3940

41+
g.Dispose();
42+
4043
Assert.AreEqual("", g._name_stack);
4144
}
4245
}

0 commit comments

Comments
 (0)