reinterpret_cast_to
功能说明
以用户指定的数据类型,读取Tensor数据。
该接口会以用户指定的数据类型读取Tensor的内存数据,并对内存中的字节重新解释,并不具有数据精度转化功能,如需进行数据精度转化请参考数据精度转换接口vec_conv。
例如:128个float16,则可以使用reinterpret_cast_to指定以float32的方式读取该段数据,会获得64个float32,因此reinterpret_cast_to并非真正将每一个float16数据转化成对应float32数据。
函数原型
reinterpret_cast_to(dtype)
参数说明
参数名称 |
输入/输出 |
含义 |
|---|---|---|
dtype |
输入 |
指定读取Tensor对象的数据类型,取值: uint8、int8、uint16、int16、float16、uint32、int32、float32、uint64、int64 |
支持的型号
注意事项
- reinterpret_cast_to的使用存在一些需要注意的限制,为了方便叙述,我们从用户的角度定义一个factor的概念:原本的数据类型的bit数除以指定类型数据的bit数,例如,原本用户申请tensor时申明内存上的数据是128个float16,但是现在期望指定以float32方式读取该段数据,则factor = 16/32 = 0.5。reinterpret_cast_to()的使用,仅局限于以下情形:
- factor必须大于零。
- 若factor大于1,factor必须是个整数。
- 若factor小于1,则用户需要注意数据的shape,shape的最后一维shape[-1]必须满足shape[-1] * factor为整数。对于原本的数据是128个float16,指定以float32方式读取的情形,若用户在这里将shape设置为(128, 1),则shape的最后一维为1,而此时factor是0.5,shape[-1] * factor = 1*0.5 = 0.5,非整数,说明我们无法将单个的float16以float32的形式读入,因此会报错“Error: Last dimension can't be divided." 正确的调用方式是将shape直接设置为128。
返回值
新的Tensor。
调用示例
示例1:
from tbe import tik
tik_instance = tik.Tik()
data_A = tik_instance.Tensor("float16", (16,), name="data_A", scope=tik.scope_gm)
data_B = data_A.reinterpret_cast_to("uint32")
data_C = data_B.reinterpret_cast_to("float16")
"""实际例子如下:
输入数据:
data_A:
[ 4.812e+00 1.870e-04 -5.692e-02 2.528e-02 -9.225e+02 -1.431e+02
-1.541e+01 -2.018e-03 1.653e-03 -4.090e+00 2.016e+01 -5.846e+04
-8.072e-03 2.627e+00 -3.174e-02 -3.088e-01]
输出数据:
data_B:
[ 169952464 645507913 3631866677 2552417204 3289847493 4213394698
1094819874 3035736080]
data_C:
[ 4.812e+00 1.870e-04 -5.692e-02 2.528e-02 -9.225e+02 -1.431e+02
-1.541e+01 -2.018e-03 1.653e-03 -4.090e+00 2.016e+01 -5.846e+04
-8.072e-03 2.627e+00 -3.174e-02 -3.088e-01]
"""
示例2:
from tbe import tik
tik_instance = tik.Tik()
data_A = tik_instance.Tensor("float16", (16,), name="data_A", scope=tik.scope_gm)
data_B = data_A.reinterpret_cast_to("uint16")
data_C = data_B.reinterpret_cast_to("float16")
"""实际例子如下:
输入数据:
data_A:
[ 4.566e+01 -7.880e+02 1.414e-04 -1.300e-02 -1.893e+03 -1.622e-01
-1.289e+00 2.478e+02 -3.107e+00 -2.072e+01 7.192e-01 -1.805e+00
3.259e+01 -3.181e-03 -3.248e-05 4.086e+04]
输出数据:
data_B:
[20917 57896 2210 41640 59237 45361 48424 23486 49719 52526 14785 48952
20499 39556 33313 30973]
data_C:
[ 4.566e+01 -7.880e+02 1.414e-04 -1.300e-02 -1.893e+03 -1.622e-01
-1.289e+00 2.478e+02 -3.107e+00 -2.072e+01 7.192e-01 -1.805e+00
3.259e+01 -3.181e-03 -3.248e-05 4.086e+04]
"""
父主题: Tensor管理