Clip grad norm support for dtensors - #4219
Conversation
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
There was a problem hiding this comment.
Thanks ! This was kind of tackled in transformers trainer but happy to have it here also ! Can you just check the impl differences and maybe align if necessary ? huggingface/transformers#48208
| if not any(isinstance(p.grad, DTensor) for p in parameters if p.grad is not None): | ||
| return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) | ||
|
|
||
| dtensor_params = [p for p in parameters if p.grad is not None and isinstance(p.grad, DTensor)] | ||
| plain_params = [p for p in parameters if p.grad is not None and not isinstance(p.grad, DTensor)] |
There was a problem hiding this comment.
maybe create the dtensor_params once and check for it ?
| parameters = list(parameters) | ||
|
|
||
| is_dtensor_available = torch.distributed.is_available() and is_torch_version(">=", DTENSOR_PYTORCH_VERSION) | ||
| if not is_dtensor_available: | ||
| return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) | ||
|
|
||
| from torch.distributed.tensor import DTensor | ||
|
|
||
| if not any(isinstance(p.grad, DTensor) for p in parameters if p.grad is not None): | ||
| return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) | ||
|
|
||
| dtensor_params = [p for p in parameters if p.grad is not None and isinstance(p.grad, DTensor)] | ||
| plain_params = [p for p in parameters if p.grad is not None and not isinstance(p.grad, DTensor)] | ||
| group_norms = [ | ||
| torch.nn.utils.get_total_norm([p.grad for p in group], norm_type) | ||
| for group in (dtensor_params, plain_params) | ||
| if group | ||
| ] |
There was a problem hiding this comment.
this is a specific case when we have mixed dtensors as we have here no ? huggingface/transformers#48208. maybe have a check for mixed grad + a seperate function to calculate the correct grad. otherwise return torch.nn.utils.clip_grads_with_norm_
| if len(mesh_groups) + bool(plain_params) <= 1: | ||
| return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) |
Co-authored-by: Marc Sun <57196510+SunMarc@users.noreply.github.com>
What does this PR do?
Seperate the plain tensors from the dtensors, otherwise the foreach op in
torch.nn.utils.clip_grad_norm_fails.