Skip to content
class

BinaryKernel

extendsAutogradNode<Derived, 2>kernel::IKernel
BinaryKernel

CRTP base for two-input, single-output op kernels — pairs forward output computation with the two-input saved-tensor bookkeeping every binary op needs.

Inherits AutogradNode\<Derived, 2\> (two saved input slots) and kernel::IKernel. forward owns all validation, broadcast inference, dispatch, and graph wiring; apply calls Derived::grad_formula and broadcast-reduces each gradient back to its original input shape.

Concrete ops declare themselves as class FooBackward : public BinaryKernel<FooBackward> and provide:

  • static constexpr OpSchema schema_v1 — op name + AMP policy.
    • static cpu_kernel(a, b, out_shape, dtype) -> CpuStorage and/or static gpu_kernel(a, b, out_shape, dtype) -> GpuStorage, or static dispatch(IBackend&, a, b, out_shape, dtype) -> Storage.
    • grad_formula(grad_out) -> std::tuple<Storage, Storage> for the local Jacobian product.
    • Optional grad_formula_impl(grad_out, a_impl, b_impl) -> std::pair<TensorImplPtr, TensorImplPtr> for create_graph higher-order differentiation.

Template Parameters

Derived : class The concrete CRTP self-type.

See Also

UnaryKernel, NaryKernel, VariadicKernel. IKernel — the abstract base above the CRTP layer.

Attributes

kSavesInputsstatic constexpr bool
Whether forward() snapshots both input storages into saved_inputs_. Defaults to true; set false for ops whose backward does not consult the original inputs (e.g. Add whose backward is identity).

Notes

Slot count is 2 (one per input). Mixed-dtype binary ops are not implicitly promoted — callers must cast. Cross-device operands are never silently moved — callers must migrate. Both checks throw DtypeMismatch / DeviceMismatch from forward.

Static methods

5
static

backend_for

backend::IBackend & backend_for(Device d)

Convenience accessor for the backend matching a device.

static

compute_storage

int compute_storage(const int & a_ptr, const int & b_ptr, const int & out_shape, Dtype eff_dt)

The result's storage at out_shape and eff_dt for operands already cast to eff_dt: the backend's dispatch, or the Derived CPU / GPU kernel. A phantom under phantom mode — no kernel runs then, and no operand's storage is read. Outside the mode a phantom operand refuses where its storage is read (TensorImpl::storage).

static

cpu_operand

const CpuStorage & cpu_operand(const int & t, const int & out_shape, Dtype dt, CpuStorage & buf)

t's CPU storage at out_shape: its own when it has that shape, else a broadcast copy made into buf.

static

forward

→std::shared_ptr<TensorImpl>
int forward(const int & a, const int & b)

Typed forward trampoline for a two-input op.

Parameters

a, bconst std::shared_ptr<TensorImpl>&
The two input tensors. Must share dtype and device.

Returns

std::shared_ptr<TensorImpl>

The output tensor. If grad mode is on and either input requires a gradient the result carries a fresh Derived grad_fn with two outbound edges.

Raises

DtypeMismatch
If a->dtype() != b->dtype().
DeviceMismatch
If a->device() != b->device().
ShapeMismatch
If the shapes are not NumPy-broadcast-compatible.
static

reduce_impl_to_shape

→TensorImplPtr
int reduce_impl_to_shape(const int & grad, const int & grad_shape, const int & target_shape)

Reduce a traced gradient tensor back to a target input shape.

Parameters

gradconst TensorImplPtr&
The traced gradient with shape grad_shape.
grad_shapeconst Shape&
The current shape of grad.
target_shapeconst Shape&
The desired output shape (typically an original input shape).

Returns

TensorImplPtr

A new tensor whose shape equals target_shape. Sums over leading broadcast axes and over any axis where target_shape is unit but grad_shape is not, then reshapes to target_shape exactly.

Notes

Used inside apply_for_graph implementations and mirrors the Storage-level helper reduce_grad_to_shape.

Methods

7
fn

apply

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

Backward implementation invoked by the autograd engine.

Parameters

grad_outStorage
The upstream gradient with respect to this op's output.

Returns

std::vector<Storage>

{grad_a, grad_b} each reduced back to its original input shape via reduce_grad_to_shape.

Notes

Reduction is needed because forward() may have broadcast either operand to a larger output shape.

fn

apply_for_graph

→std::vector<TensorImplPtr>
int apply_for_graph(const int & grad_out)

Graph-mode backward — supports create_graph=True.

Parameters

grad_outconst TensorImplPtr&
The upstream gradient retained as a TensorImpl with grad_fn.

Returns

std::vector<TensorImplPtr>

{grad_a, grad_b} as fully-traced TensorImpl pointers, each reduced to its original input shape via sum_op / reshape_op.

Raises

:runtime_error
If the saved input pointers were not captured, or if Derived did not override grad_formula_impl.
fnconst

broadcast_graph_input

int broadcast_graph_input(int i)

Return saved input i broadcast to out_shape_ for graph-mode backward when needed, or nullptr when no needed gradient reads it.

fn

grad_formula_impl

→std::pair<TensorImplPtr, TensorImplPtr>
int grad_formula_impl(const int &, const int &, const int &)

Default graph-mode gradient formula — concrete ops override.

Parameters

grad_outconst TensorImplPtr&
The upstream gradient.
a, bconst TensorImplPtr&
The saved forward inputs already broadcast to out_shape_.

Returns

std::pair<TensorImplPtr, TensorImplPtr>

(grad_a, grad_b) as fully-traced tensors.

Raises

:runtime_error
The default implementation always throws. Concrete ops must override to support create_graph=True.
fnconst

name

int name()

Return the canonical schema name of the concrete op.

fnconst

node_name

int node_name()

Return the autograd node label (same string as name).

fnconst

saved_input_broadcasted

→Storage
int saved_input_broadcasted(int k)

Return the saved input k ready for element-wise arithmetic at out_shape_.

Parameters

kstd::size_t
Index into saved_inputs_ (0 or 1).

Returns

Storage

The saved storage when input_shapes_[k] == out_shape_ or on GPU (where MLX binary primitives broadcast natively without materialising an expanded buffer), otherwise a freshly materialised CPU broadcast copy via detail::broadcast_cpu.