Agnes-Video-H3-MoE / deploy /diffsynth /core /gradient /gradient_checkpoint.py
Agnes-AI's picture
Release E8T1 shared MoE model and reference inference code
2594d73 verified
Raw History Blame Contribute Delete
2.4 kB
import torch
from contextlib import contextmanager
from contextvars import ContextVar
_route_replay = ContextVar('taskcal_route_replay', default=None)
def current_route_replay():
return _route_replay.get()
def route_contexts():
holder = {}
@contextmanager
def phase(name):
token = _route_replay.set((name, holder))
try:
yield
finally:
_route_replay.reset(token)
return phase('record'), phase('replay')
try:
import deepspeed
_HAS_DEEPSPEED = True
except ModuleNotFoundError:
_HAS_DEEPSPEED = False
def create_custom_forward(module):
def custom_forward(*inputs, **kwargs):
return module(*inputs, **kwargs)
return custom_forward
def create_custom_forward_use_reentrant(module):
def custom_forward(*inputs):
return module(*inputs)
return custom_forward
def judge_args_requires_grad(*args):
for arg in args:
if isinstance(arg, torch.Tensor) and arg.requires_grad:
return True
return False
def gradient_checkpoint_forward(
model,
use_gradient_checkpointing,
use_gradient_checkpointing_offload,
*args,
**kwargs,
):
if use_gradient_checkpointing and _HAS_DEEPSPEED and deepspeed.checkpointing.is_configured():
all_args = args + tuple(kwargs.values())
if not judge_args_requires_grad(*all_args):
# get the first grad_enabled tensor from un_checkpointed forward
model_output = model(*args, **kwargs)
else:
model_output = deepspeed.checkpointing.checkpoint(
create_custom_forward_use_reentrant(model),
*all_args,
)
return model_output
if use_gradient_checkpointing_offload:
with torch.autograd.graph.save_on_cpu():
model_output = torch.utils.checkpoint.checkpoint(
create_custom_forward(model),
*args,
**kwargs,
use_reentrant=False,
context_fn=route_contexts,
)
elif use_gradient_checkpointing:
model_output = torch.utils.checkpoint.checkpoint(
create_custom_forward(model),
*args,
**kwargs,
use_reentrant=False,
context_fn=route_contexts,
)
else:
model_output = model(*args, **kwargs)
return model_output