更新:参考后面convert_xx方法,从而可以直接进行pack数据类型转换。
tflite中可能经常遇到cast不支持的情况,这应该主要是因为opencl中对cast支持不好。
opencl不支持pack数据类型直接cast,而只能逐个元素进行cast,例如不能这样cast:
int4 src = in[0];
half4 dst = src;
但是可以
int4 src = in[0];
half4 dst;
dst.s0=src.s0;
dst.s1=src.s1;
dst.s2=src.s2;
dst.s3=src.s3;
此外,即使这样,很多数据类型也无法直接转换,例如long或者bool无法直接cast到half,必须基于其他数据类型进行中转。有的opencl编译器支持使用一种通用的数据类型例如float进行中转cast,但是有的必须采用多种数据类型进行中转。
这里我的解决方案是分别对src和dst数据类型引入一种中间数据类型,首先建立一个中间数据类型映射map,内容为bool, char, long等整数类型中间数据类型为int,而对half, float, double浮点数据类型采用float作为中间数据类型。
然后,建立一个vector<dtype>,存入src_dtype, src_mid_dtype, dst_mid_dtype, dst_dtype四个元素。接着对这个数组移除相邻并且相同的元素,以避免冗余的转换。
根据这个vector来基于字符串操作自动code-gen中间转换的变量和赋值过程。
另外有两种数据类型转换方法可用:
convert_destType(sourceType)
destTypen convert_destTypen<_sat><_roundingMode>(sourceTypen)
uchar4 u;
int4 c = convert_int4(u);
Modifier | Rounding Mode Description |
| Round to nearest even |
| Round toward zero |
| Round toward positive infinity |
| Round toward negative infinity |
no modifier specified | Use the default rounding mode for this destination type, |
6.4.4.2. Reinterpreting Types Using as_type() and as_typen()
All data types described in Built-in Scalar Data Types and Built-in Vector Data Types (except bool
, void
, and half
[15]) may be also reinterpreted as another data type of the same size using the as_type() operator for scalar data types and the as_typen() operator [16] for vector data types. When the operand and result type contain the same number of elements, the bits in the operand shall be returned directly without modification as the new type. The usual type promotion for function arguments shall not be performed.
For example, as_float(0x3f800000)
returns 1.0f
, which is the value that the bit pattern 0x3f800000
has if viewed as an IEEE-754 single precision value.
opencl:kernel中两种向量类型转换(convert_T,as_typen)的主要区别-腾讯云开发者社区-腾讯云