Tensor .shape 函数疑惑

代码里是这样写的,为什么要这么设计呀
@property
def shape(self):
r""“Return an int tuple that is the shape/layout of the tensor.
Could be invalid in static graph mode.
“””
from …jit import trace

    if trace._active_instance:  # pylint: disable=protected-access
        # NOTE: this is an hack
        shape = mgb.opr.get_var_shape(self._symvar)
        return tuple(Tensor(shape[i]) for i in range(self.ndim))
    return self._symvar.imm_shape

没懂你想表达什么?

这里是为了做动静结合,在动态模式下返回 tuple of int 做为 shape,在静态 trace 模式下,返回 symbolic shape(这样是为了让网络在有大量 y.reshape(x.shape) 时,仍然能对于不同的 shape 输入能正确推导计算图用的)

谢谢您的回答。
我是在看 Models.official/vision/detection/layers/basic/functional.py 这个地方感觉有点奇怪
def get_padded_tensor(
array: Tensor, multiple_number: int = 32, pad_value: float = 0
) -> Tensor:
“”" pad the nd-array to multiple stride of th e

Args:
    array (Tensor):
        the tensor with the shape of [batch, channel, height, width]
    multiple_number (int):
        make the height and width can be divided by multiple_number
    pad_value (int): the value to be padded

Returns:
    padded_array (Tensor)
"""
batch, chl, t_height, t_width = array.shape
padded_height = (
    (t_height + multiple_number - 1) // multiple_number * multiple_number
)
padded_width = (t_width + multiple_number - 1) // multiple_number * multiple_number

padded_array = (
    mge.ones(
        F.concat([batch, chl, padded_height, padded_width], axis=0),
        dtype=np.float32,
    )
    * pad_value
)

ndim = array.ndim
if ndim == 4:
    padded_array = padded_array.set_subtensor(array)[:, :, :t_height, :t_width]
elif ndim == 3:
    padded_array = padded_array.set_subtensor(array)[:, :t_height, :t_width]
else:
    raise Exception("Not supported tensor dim: %d" % ndim)
return padded_array

这里动态图和静态图时array.shape返回的类型不同,一个得到的是tensor一个得到的int,因为之前没用过静态图所以觉得这个地方有问题。如果不用静态图的话 F.concat([batch, chl, padded_height, padded_width], axis=0) 这里会报错。

现在已经搞明白了,谢谢您