torch.while_loop is a structured control flow operator that runs a body function while a condition is true.
It can logically be seen as implemented as follows:
cond_fn (Callable) – A callable function that returns a boolean Scalar tensor or a python boolean.
body_fn (Callable) – A callable function that takes the same inputs as cond_fn and returns a tuple of tensors or ints
carried_inputs (Tuple of possibly nested dict/list/tuple of tensors or ints) – A tuple of inputs to cond_fn and body_fn.
It’s also the initial value of states that are carried across iterations. Note that when pass an integer as carry,
the corresponding return of while_loop will be another int with unknown values because we don’t know how many
iterations while_loop will run.
body_fn must return tensors or int with the same metadata (e.g.shape, dtype) as inputs.
body_fn and cond_fn must not in-place mutate the carried_inputs. A clone before the mutation is required.
body_fn and cond_fn must not mutate python variables (e.g. list/dict) created outside of the body_fn.
body_fn and cond_fn’s output cannot alias any of the inputs. A clone is required.
During inference, body_fn and cond_fn can in-place mutate tensors that are not
carried_inputs, such as module buffers and captured tensors from the enclosing scope.