The operator casts the elements of a given input tensor to a data type specified by the 'to' argument and returns an output tensor of the same size in the converted type.
| 4673 | |
| 4674 | |
| 4675 | class Cast(Operator): |
| 4676 | """ |
| 4677 | The operator casts the elements of a given input tensor to a data type |
| 4678 | specified by the 'to' argument and returns an output tensor of the same |
| 4679 | size in the converted type. |
| 4680 | """ |
| 4681 | |
| 4682 | def __init__(self, to): |
| 4683 | """ |
| 4684 | Args: |
| 4685 | to (int): data type, float32 = 0; int = 2. |
| 4686 | """ |
| 4687 | super(Cast, self).__init__() |
| 4688 | self.to = to |
| 4689 | |
| 4690 | def forward(self, x): |
| 4691 | """ |
| 4692 | forward of Cast |
| 4693 | Args: |
| 4694 | x (CTensor): input tensor. |
| 4695 | Returns: |
| 4696 | the output CTensor. |
| 4697 | """ |
| 4698 | if x.data_type() != self.to: |
| 4699 | x = x.AsType(self.to) |
| 4700 | return x |
| 4701 | |
| 4702 | def backward(self, dy): |
| 4703 | """ |
| 4704 | backward of Cast |
| 4705 | Args: |
| 4706 | dy (CTensor), gradient tensor. |
| 4707 | Raises: |
| 4708 | AssertionError: no backward function for this operator |
| 4709 | """ |
| 4710 | assert False, ('no gradient for backward function') |
| 4711 | |
| 4712 | |
| 4713 | def cast(x, to): |