Example

Example: Differentiating a Function with Dynamic Control Flow

To illustrate automatic differentiation with dynamic control flow, consider a contrived function where a while loop scales an input vector a\mathbf{a} until its norm exceeds a threshold, followed by an if statement that returns different multiples of the vector based on the sum of its elements. Even though the number of loop iterations and the final scaling factor depend entirely on the specific values of the input, the deep learning framework constructs a concrete computational graph during the forward pass. Because the resulting function f(a)f(\mathbf{a}) is linear with a piecewise defined scale, its gradient with respect to a\mathbf{a} can be logically verified to match the element-wise division f(a)/af(\mathbf{a}) / \mathbf{a}.

0

1

Updated 2026-05-02

Contributors are:

Who are from:

Tags

D2L

Dive into Deep Learning @ D2L