Skip to content
class

AstypeBackward

extendskernel::IKernel
AstypeBackward

Autograd node for astype: casts the incoming gradient back to the source dtype so it can accumulate into the original Parameter or activation's gradient slot.

The forward cast is value-preserving — integer-to-float and float-to-integer paths route through the backend's astype kernel, which clamps / rounds as appropriate rather than reinterpreting bits. The backward applies the inverse cast (also value-preserving), so a no-op forward cast (matching dtypes) becomes a no-op backward. This is the hook that lets AMP-driven casts inside Linear / Conv / Matmul / BatchNorm participate in the autograd graph instead of silently dropping requires_grad at every boundary.

Math

\qquad \frac{\partial L}{\partial x} = \mathrm{cast}_{D_{\text{src}}}\!\Bigl(\frac{\partial L}{\partial y}\Bigr)$$

Attributes

schema_v1OpSchema
"astype", AmpPolicy::KeepInput — the AMP layer does not promote the input because astype itself is the dtype-control primitive that AMP composes with.
src_dtype_Dtype
Dtype of the original input; the gradient is cast back to this dtype during backward. Default Dtype::F32.
dtype_Dtype
Inherited from AutogradNode; carries the cast / output dtype.

Notes

Complex dtypes are not currently routed through this op; AMP and the public Tensor.astype API only target the real-floating and integer dtype families. Same-dtype calls short-circuit before reaching this node — see astype_op.

Methods

4
fn

apply

→std::vector<Storage>
int apply(int grad_out)

Eager-mode backward. Casts grad_out from dtype_ (the cast / output dtype) back to src_dtype_ so it can accumulate into the original input's gradient slot. If the two dtypes match (the forward cast was a no-op), passes the gradient through unchanged.

Parameters

grad_outStorage
Upstream gradient at the cast dtype.

Returns

std::vector<Storage>

Single-element vector holding the gradient cast back to src_dtype_.

fn

apply_for_graph

int apply_for_graph(const int & grad_out)

Graph-mode backward used when create_graph=True. Recursively calls astype_op so the inverse cast itself remains differentiable, enabling higher-order gradients through AMP boundaries.

fnconst

name

int name()

Schema-driven op name; participates in the profiler / op registry.

fnconst

node_name

int node_name()

Node-name override used by the autograd graph dumper.