(
original_forward: Any, weak_self: Any, offload_to_cpu: bool, *args: Any, **kwargs: Any
)
| 327 | |
| 328 | |
| 329 | def _checkpointed_forward( |
| 330 | original_forward: Any, weak_self: Any, offload_to_cpu: bool, *args: Any, **kwargs: Any |
| 331 | ) -> Any: |
| 332 | module = weak_self() |
| 333 | |
| 334 | # If gradients are disabled, just use original `.forward()` method directly. |
| 335 | if not torch.is_grad_enabled() or thread_local.is_checkpointing_disabled: |
| 336 | return original_forward(module, *args, **kwargs) |
| 337 | |
| 338 | # Autograd Functions in PyTorch work best with positional args, since |
| 339 | # the backward must return gradients (or None) for every input argument. |
| 340 | # We can flatten keyword arguments to make this easier. |
| 341 | args = (module,) + args |
| 342 | kwarg_keys, flat_args = pack_kwargs(*args, **kwargs) |
| 343 | parent_ctx_dict: Dict[str, Any] = { |
| 344 | "offload": offload_to_cpu, |
| 345 | } |
| 346 | # Dummy tensor with grad is used to ensure the backward pass is called. This is needed |
| 347 | # when original_forward's input are non-tensor (i.e. a tuple). Using this dummy tensor |
| 348 | # avoids requiring users to set their input tensors's requires_grad flag. In the case |
| 349 | # of tuple type inputs, setting the flag won't even trigger the backward pass. |
| 350 | # |
| 351 | # One implication of this is that since we always feed in a dummy tensor |
| 352 | # needing grad, then the output will always require grad, even if it originally |
| 353 | # wouldn't, such as if the module and original input both do not require grad. |
| 354 | # We get around this by saving the desired requires_grad value in output and |
| 355 | # detaching the output if needed. |
| 356 | output = CheckpointFunction.apply( |
| 357 | torch.tensor([], requires_grad=True), original_forward, parent_ctx_dict, kwarg_keys, *flat_args |
| 358 | ) |
| 359 | output_requires_grad = parent_ctx_dict["output_requires_grad"] |
| 360 | if not isinstance(output, torch.Tensor): |
| 361 | # If output should not require grad, then detach it, since otherwise it will |
| 362 | # always have requires_grad = True due to our dummy tensor input above that |
| 363 | # requires_grad |
| 364 | output = [x.detach() if not output_requires_grad else x for x in output] |
| 365 | |
| 366 | packed_non_tensor_outputs = parent_ctx_dict["packed_non_tensor_outputs"] |
| 367 | if packed_non_tensor_outputs: |
| 368 | output = unpack_non_tensors(output, packed_non_tensor_outputs) |
| 369 | |
| 370 | else: |
| 371 | # If output should not require grad, then detach it, since otherwise it will |
| 372 | # always have requires_grad = True due to our dummy tensor input above that |
| 373 | # requires_grad |
| 374 | if not output_requires_grad: |
| 375 | output = output.detach() |
| 376 | |
| 377 | return output |
| 378 | |
| 379 | |
| 380 | def get_rng_state() -> Dict[str, Any]: |
nothing calls this directly
no test coverage detected