Search code examples
pythontensorflowprotocol-buffers

Tensorflow: create tf.NodeDef() and set attributes


I'm trying to create a new node and set its attributes.

For example printing one of the graph nodes I see that its attributes are:

attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

I can create a node like:

node = tf.NodeDef(name='MyConstTensor', op='Const',
                   attr={'value': tf.AttrValue(tensor=tensor_proto),
                         'dtype': tf.AttrValue(type=dt)})

but how to add key: "T" atribute? i.e. what should be inside tf.AttrValue in this case?

Looking at attr_value.proto I have tried:

node = tf.NodeDef()
node.name = 'MySub'
node.op = 'Sub'
node.input.extend(['MyConstTensor', 'conv2'])
node.attr["key"].s = 'T' # TypeError: 'T' has type str, but expected one of: bytes

UPDATE:

I figured out that in Tensorflow it should be written like:

node.attr["T"].type = b'float32'

But this gives an error:

TypeError: b'float32' has type bytes, but expected one of: int, long

And I'm not sure which int value corresponds to float32.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L23

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L35


Solution

  • By trial and error I fugire out that it's just:

    node.attr["T"].type = 1 # to set type to float32