Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable torch.nn.init when counting parmeters in initializing PipelineModule #5258

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions deepspeed/runtime/pipe/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# DeepSpeed Team

import contextlib
import os
import glob

Expand Down Expand Up @@ -83,6 +84,24 @@ def __init__(self, key, typename, *module_args, forward_fn=None, tied_weight_att
self.tied_weight_attr = [tied_weight_attr] if type(tied_weight_attr) == str else tied_weight_attr


if hasattr(torch.overrides, "TorchFunctionMode"):

class _DisableInit(torch.overrides.TorchFunctionMode):

def __torch_function__(self, func, types, args=(), kwargs=None):
kwargs = kwargs or {}
if getattr(func, '__module__', None) == 'torch.nn.init':
if 'tensor' in kwargs:
return kwargs['tensor']
else:
return args[0]
else:
return func(*args, **kwargs)

else:
_DisableInit = contextlib.suppress


class PipelineModule(nn.Module):
"""Modules to be parallelized with pipeline parallelism.

Expand Down Expand Up @@ -269,7 +288,8 @@ def _get_frozen_parameter_names(self, layer):
A list of frozen parameter names
"""
if isinstance(layer, LayerSpec):
l = layer.build()
with _DisableInit():
l = layer.build()
return [n for n, p in l.named_parameters() if not p.requires_grad]
elif isinstance(layer, nn.Module):
return [n for n, p in layer.named_parameters() if not p.requires_grad]
Expand All @@ -287,7 +307,8 @@ def _count_layer_params(self):
param_counts = [0] * len(self._layer_specs)
for idx, layer in enumerate(self._layer_specs):
if isinstance(layer, LayerSpec):
l = layer.build()
with _DisableInit():
l = layer.build()
params = filter(lambda p: p.requires_grad, l.parameters())
param_counts[idx] = sum(p.numel() for p in params)
elif isinstance(layer, nn.Module):
Expand Down
Loading