paddle.fluid.layers.cast(x, dtype)[source]

This OP takes in the Variable x with x.dtype and casts it to the output with dtype. It’s meaningless if the output dtype equals the input dtype, but it’s fine if you do so.

  • x (Variable) – An input N-D Tensor with data type bool, float16, float32, float64, int32, int64, uint8.

  • dtype (np.dtype|core.VarDesc.VarType|str) – Data type of the output: bool, float16, float32, float64, int8, int32, int64, uint8.


A Tensor with the same shape as input’s.

Return type



import paddle.fluid as fluid
import numpy as np

place = fluid.core.CPUPlace()

x_lod ="x", shape=[2,2], lod_level=0)
cast_res1 = fluid.layers.cast(x=x_lod, dtype="uint8")
cast_res2 = fluid.layers.cast(x=x_lod, dtype=np.int32)

exe = fluid.Executor(place)

x_i_lod = fluid.core.LoDTensor()
x_i_lod.set(np.array([[1.3,-2.4],[0,4]]).astype("float32"), place)
res1 =, feed={'x':x_i_lod}, fetch_list=[cast_res1], return_numpy=False)
res2 =, feed={'x':x_i_lod}, fetch_list=[cast_res2], return_numpy=False)
print(np.array(res1[0]), np.array(res1[0]).dtype)
# [[  1 254]
#  [  0   4]] uint8
print(np.array(res2[0]), np.array(res2[0]).dtype)
# [[ 1 -2]
#  [ 0  4]] int32