为什么在常量张量的创建过程中使用 "CopyFrom"?

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

常量Tensor的创建过程中有如下line:

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

CopyFrom 创建新创建的 Tensor 原型的副本。然而,这看起来像是浪费资源来应对,因为根据文档,make_tensor_proto 创建了一个新对象。是不是更够了,就做下一步:

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

这不应创建新对象,而且它也是 OneOf protobuf 字段的有效用法。

您不能将原型分配给原型的字段,如本文档中所述: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.

如果删除 CopyFrom,将出现以下错误:

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