Skip to content
class

BroadcastBackward

BroadcastBackward

Autograd node for broadcasting a tensor to a larger shape.

Forward replicates a along all broadcast dimensions so that its shape matches the requested output shape, following NumPy broadcasting rules (left-pad with size-1 dims, then allow size-1 dims to broadcast). Backward inverts that replication by summing the incoming gradient over every axis that was broadcast — either a newly prepended axis or a size-1 dimension that was expanded — via Dispatcher::reduce_broadcast.

Math

Forward expands each size-1 broadcast axis kk by replication: y[…,ik,…]=x[…,0,…]for all ik.y_{[\ldots, i_k, \ldots]} = x_{[\ldots, 0, \ldots]} \quad \text{for all } i_k. Backward reduces over those axes:

= \sum_{i_k} \frac{\partial L}{\partial y_{[\ldots, i_k, \ldots]}}. $$ **Shape** Output rank == `output_shape_.size()`. For each axis from the right, either `input_shape_[d] == output_shape_[d]` or `input_shape_[d] == 1` (broadcast). Newly prepended axes are implicitly summed in backward. **See Also** `broadcast_to_op`, `expand_op`.

Parameters

input_shape_Shape
The original tensor shape before broadcasting.
output_shape_Shape
The fully broadcast target shape.

Attributes

schema_v1OpSchema
"broadcast_to", AmpPolicy::KeepInput, requires_grad=true.

Instance methods

2
fn

apply

int apply(int grad_out)

Backward — sums grad_out across broadcast axes back to the input shape.

fn

apply_for_graph

int apply_for_graph(const int & grad_out)

Graph-mode twin: the same sum, written in ops so the result can be differentiated again.