Viacheslav V Kovalevskyi Viacheslav V Kovalevskyi - 18 days ago 6
Python Question

Why "CopyFrom" is used during the creation of the constant Tensor?

During the creation process of the constant Tensor there is the following line:

tensor_value.tensor.CopyFrom(
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))


CopyFrom
creates a copy of a newly created Tensor proto. However this looks like waste of resource for coping since
make_tensor_proto
, according to the doc, creates a new object. Would it be more sufficient, just to do next:

tensor_value.tensor =
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape)


This should not create a new object, plus it is also a valid usage of the OneOf protobuf fields.

Answer

You cannot assign a proto to a field of a proto as explained in this doc: https://developers.google.com/protocol-buffers/docs/reference/python-generated

You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent.

If you remove the CopyFrom, you will get the following error:

AttributeError: Assignment not allowed to field "tensor" in protocol message object.
Comments