I explore how is variable represented in graph. I create a variable, initialize it and make graph snapshots after every action:
import tensorflow as tf
def dump_graph(g, filename):
with open(filename, 'w') as f:
print(g.as_graph_def(), file=f)
g = tf.get_default_graph()
var = tf.Variable(2)
dump_graph(g, 'data/after_var_creation.graph')
init = tf.global_variables_initializer()
dump_graph(g, 'data/after_initializer_creation.graph')
with tf.Session() as sess:
sess.run(init)
dump_graph(g, 'data/after_initializer_run.graph')
Graph after variable creation looks like
node {
name: "Variable/initial_value"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 2
}
}
}
}
node {
name: "Variable"
op: "VariableV2"
attr {
key: "container"
value {
s: ""
}
}
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "shape"
value {
shape {
}
}
}
attr {
key: "shared_name"
value {
s: ""
}
}
}
node {
name: "Variable/Assign"
op: "Assign"
input: "Variable"
input: "Variable/initial_value"
attr {
key: "T"
value {
type: DT_INT32
}
}
attr {
key: "_class"
value {
list {
s: "loc:@Variable"
}
}
}
attr {
key: "use_locking"
value {
b: true
}
}
attr {
key: "validate_shape"
value {
b: true
}
}
}
node {
name: "Variable/read"
op: "Identity"
input: "Variable"
attr {
key: "T"
value {
type: DT_INT32
}
}
attr {
key: "_class"
value {
list {
s: "loc:@Variable"
}
}
}
}
versions {
producer: 21
}
There are several nodes: Variable/initial_value
, Variable
,
Variable/Assign
, Variable/read
.
After running init operation, another node is added:
node {
name: "init"
op: "NoOp"
input: "^Variable/Assign"
}
I do not have tight grasp of what happens here.
- Could anybody explain what is the precise meaning of these nodes?
- What is the purpose of implicit variables initialization in tensorflow Python API? Why can't we automatically initialize a variable after variable object creation, or initialize uninitialized variables inside Session.run()?
- What is the meaning of "loc:@" syntax inside
Variable/read
node and^Variable/Assign
insideinit
node? - How does retrieving of a variable value work? I suppose that the value is
stored inside a session, and that
session.run()
substitue somewhere for this value, but do not know the gory details.