| 81 | |
| 82 | template <typename Context> |
| 83 | void ViewDtypeKernel(const Context& dev_ctx, |
| 84 | const DenseTensor& input, |
| 85 | DataType dtype, |
| 86 | DenseTensor* out) { |
| 87 | if (!FLAGS_use_stride_kernel) { |
| 88 | PADDLE_THROW(common::errors::Fatal( |
| 89 | "FLAGS_use_stride_kernel is closed. Strided kernel " |
| 90 | "be called, something wrong has happened!")); |
| 91 | } |
| 92 | size_t input_dtype_size = phi::SizeOf(input.dtype()); |
| 93 | size_t output_dtype_size = phi::SizeOf(dtype); |
| 94 | |
| 95 | if (input_dtype_size == output_dtype_size) { |
| 96 | auto meta = input.meta(); |
| 97 | meta.dtype = dtype; |
| 98 | out->set_meta(meta); |
| 99 | out->ResetHolder(input.Holder()); |
| 100 | out->ShareInplaceVersionCounterWith(input); |
| 101 | } else if (input_dtype_size == 0) { |
| 102 | PADDLE_THROW(common::errors::InvalidArgument( |
| 103 | "The Tensor's shape is [] can not be viewed.")); |
| 104 | } else if (input_dtype_size > output_dtype_size) { |
| 105 | PADDLE_ENFORCE_EQ( |
| 106 | input.strides()[input.strides().size() - 1], |
| 107 | 1, |
| 108 | common::errors::InvalidArgument( |
| 109 | "input.strides[-1] must be 1 to view %s as %s, but got %d", |
| 110 | input.dtype(), |
| 111 | dtype, |
| 112 | input.strides()[input.strides().size() - 1])); |
| 113 | size_t times = input_dtype_size / output_dtype_size; // NOLINT |
| 114 | |
| 115 | DDim output_dims = input.dims(); |
| 116 | output_dims[output_dims.size() - 1] = |
| 117 | output_dims[output_dims.size() - 1] * times; // NOLINT |
| 118 | |
| 119 | DDim output_stride = input.strides(); |
| 120 | for (int i = 0; i < output_stride.size(); i++) { |
| 121 | output_stride[i] = output_stride[i] * times; // NOLINT |
| 122 | } |
| 123 | output_stride[output_stride.size() - 1] = 1; |
| 124 | |
| 125 | auto meta = input.meta(); |
| 126 | meta.dtype = dtype; |
| 127 | meta.dims = output_dims; |
| 128 | meta.strides = output_stride; |
| 129 | meta.offset = input.offset() * times; |
| 130 | out->set_meta(meta); |
| 131 | out->ResetHolder(input.Holder()); |
| 132 | out->ShareInplaceVersionCounterWith(input); |
| 133 | } else { |
| 134 | PADDLE_ENFORCE_EQ( |
| 135 | input.strides()[input.strides().size() - 1], |
| 136 | 1, |
| 137 | common::errors::InvalidArgument( |
| 138 | "input.strides[%d] must be 1 to view %s as %s, but got %d", |
| 139 | input.strides().size() - 1, |
| 140 | input.dtype(), |