code stringlengths 17 6.64M |
|---|
class GoogLeNet(nn.Module):
def __init__(self, num_classes=1000):
super(GoogLeNet, self).__init__()
self.pre_layers = nn.Sequential(nn.Conv2d(3, 192, kernel_size=3, padding=1), nn.BatchNorm2d(192), nn.ReLU(True))
self.a3 = Inception(192, 64, 96, 128, 16, 32, 32)
self.b3 = Inceptio... |
class LeNet(nn.Module):
def __init__(self, num_classes=1000):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(((16 * 5) * 5), 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = n... |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
|
def conv1x1(in_planes, out_planes, stride=1):
'1x1 convolution'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
if ((groups != 1) or (b... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
width = (int((planes * ... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
self._n... |
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
from torchvision.models.utils import load_state_dict_from_url
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_... |
def resnet18(pretrained=False, progress=True, **kwargs):
'ResNet-18 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progr... |
def resnet34(pretrained=False, progress=True, **kwargs):
'ResNet-34 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progr... |
def resnet50(pretrained=False, progress=True, **kwargs):
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progr... |
def resnet101(pretrained=False, progress=True, **kwargs):
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a pro... |
def resnet152(pretrained=False, progress=True, **kwargs):
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a pro... |
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
'ResNeXt-50 32x4d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (boo... |
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
'ResNeXt-101 32x8d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (b... |
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
'Wide ResNet-50-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channels... |
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
'Wide ResNet-101-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channe... |
class Fire(nn.Module):
def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes):
super(Fire, self).__init__()
self.inplanes = inplanes
self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)
self.squeeze_activation = nn.ReLU(inplace=True)
... |
class SqueezeNet(nn.Module):
def __init__(self, version=1.0, num_classes=1000):
super(SqueezeNet, self).__init__()
if (version not in [1.0, 1.1]):
raise ValueError('Unsupported SqueezeNet version {version}:1.0 or 1.1 expected'.format(version=version))
self.num_classes = num_cl... |
def squeezenet1_0(pretrained=False, **kwargs):
'SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level\n accuracy with 50x fewer parameters and <0.5MB model size"\n <https://arxiv.org/abs/1602.07360>`_ paper.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageN... |
def squeezenet1_1(pretrained=False, **kwargs):
'SqueezeNet 1.1 model from the `official SqueezeNet repo\n <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_.\n SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters\n than SqueezeNet 1.0, without sacrificing accuracy.\... |
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__init__()
self.features = features
self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
self.classifier = nn.Sequential(nn.Linear(((512 * 7) * 7), 4096), nn.ReLU(True), nn.Dropout(), ... |
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers +=... |
def vgg11(pretrained=False, **kwargs):
'VGG 11-layer model (configuration "A")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A']), **kwargs)
if pretrained:
mode... |
def vgg11_bn(pretrained=False, **kwargs):
'VGG 11-layer model (configuration "A") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A'], batch_norm=Tru... |
def vgg13(pretrained=False, **kwargs):
'VGG 13-layer model (configuration "B")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['B']), **kwargs)
if pretrained:
mode... |
def vgg13_bn(pretrained=False, **kwargs):
'VGG 13-layer model (configuration "B") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['B'], batch_norm=Tru... |
def vgg16(pretrained=False, **kwargs):
'VGG 16-layer model (configuration "D")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['D']), **kwargs)
if pretrained:
mode... |
def vgg16_bn(pretrained=False, **kwargs):
'VGG 16-layer model (configuration "D") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['D'], batch_norm=Tru... |
def vgg19(pretrained=False, **kwargs):
'VGG 19-layer model (configuration "E")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
mode... |
def vgg19_bn(pretrained=False, **kwargs):
"VGG 19-layer model (configuration 'E') with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n "
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E'], batch_norm=Tru... |
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, drop_rate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, pad... |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
@staticmethod
def _make_layer(block, in_planes, ... |
class WideResNet(nn.Module):
def __init__(self, depth=10, num_classes=1000, widen_factor=1, drop_rate=0.0):
super(WideResNet, self).__init__()
n_channels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = int(((depth - 4) / 6)... |
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, drop_rate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.GroupNorm((in_planes // 16), in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, s... |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
@staticmethod
def _make_layer(block, in_planes, ... |
class WideResNet(nn.Module):
def __init__(self, depth=10, num_classes=1000, widen_factor=1, drop_rate=0.0):
super(WideResNet, self).__init__()
n_channels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = int(((depth - 4) / 6)... |
def relu_conv_bn(in_channels: int, out_channels: int, kernel_size: int=1, stride: int=1, padding: int=0) -> nn.Module:
return nn.Sequential(nn.ReLU(inplace=False), nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False), nn.BatchNorm2d(out_channels))
|
class Classify(nn.Module):
def __init__(self, channels_prev: int, num_classes: int):
super().__init__()
self.pool = nn.AvgPool2d(7)
self.flat = nn.Flatten()
self.fc = nn.Linear(channels_prev, num_classes)
def forward(self, states: Tuple[(Tensor, Tensor)]) -> Tensor:
(... |
class Stem(nn.Sequential):
def __init__(self, channels: int):
super().__init__(nn.ReLU(inplace=False), nn.Conv2d(3, channels, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(channels))
|
class Cell(nn.Module):
def __init__(self, channels_prev_prev: int, channels_prev: int, channels: int, reduction: bool, reduction_prev: bool):
super().__init__()
self.reduce1 = relu_conv_bn(in_channels=channels_prev, out_channels=channels)
self.reduce2: nn.Module = nn.Identity()
if... |
def amoebanetd(num_classes: int=10, num_layers: int=4, num_filters: int=512) -> nn.Sequential:
'Builds an AmoebaNet-D model for ImageNet.'
layers = OrderedDict()
repeat_normal_cells = (num_layers // 3)
channels = (num_filters // 4)
channels_prev_prev = channels_prev = channels
reduction_prev =... |
def create_pipeline_configuration(DEBUG=False, batch_size=4):
config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (Softmax, Linear, Tanh, Gelu, Embedding, LayerNorm, Dropout), 'model_inputs': {'attention_mask': {'shape': torch.Size([4, 384]), 'dtype': torch.int64, 'is_batched': True, 'used_by': [0]}, 'input... |
class Partition0(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[word_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[position_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/... |
class Partition1(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertAttention[attention]/BertSelfAttention[self]/Dropout[dropout]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertAttention[attention]/BertSelfOutput[output]/L... |
def traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[Type[nn.Module]]=(), full: bool=False) -> Iterator[Tuple[(nn.Module, str, nn.Module, Optional[bool])]]:
'\n iterate over model layers yielding the layer,layer_scope,encasing_module\n Parameters:\n ----------... |
def layerDict(model: nn.Module, depth=1000, basic_blocks=()) -> Dict[(str, nn.Module)]:
return {s: l for (l, s, _) in traverse_model(model, depth, basic_blocks=basic_blocks)}
|
def traverse_params_buffs(module: nn.Module, prefix: Optional[str]=None) -> Iterator[Tuple[(torch.tensor, str)]]:
"\n iterate over model's buffers and parameters yielding obj,obj_scope\n\n Parameters:\n -----------\n model:\n the model to iterate over\n "
if (prefix is None):
pre... |
def tensorDict(model: nn.Module) -> OrderedDict[(str, Tensor)]:
return collections.OrderedDict(((s, t) for (t, s) in traverse_params_buffs(model)))
|
def move_tensors(ts, device):
def move(t):
if isinstance(t, (nn.Module, Tensor)):
return t.to(device)
return t
return nested_map(move, ts)
|
def nested_map(func, ts, full=False):
if isinstance(ts, torch.Size):
return func(ts)
elif isinstance(ts, (list, tuple, set)):
return type(ts)((nested_map(func, t, full=full) for t in ts))
elif isinstance(ts, dict):
return {k: nested_map(func, v, full=full) for (k, v) in ts.items()}... |
def flatten(ts):
if isinstance(ts, torch.Size):
(yield ts)
elif isinstance(ts, (list, tuple, set)):
(yield from chain(*[flatten(t) for t in ts]))
elif isinstance(ts, dict):
(yield from chain(*[flatten(t) for (k, t) in sorted(ts.items(), key=(lambda t: t[0]))]))
else:
(y... |
def unflatten(xs, structure):
return _unflatten(xs, structure)[0]
|
def _unflatten(xs, structure):
if isinstance(structure, torch.Size):
return (xs[0], 1)
if (not isinstance(structure, (list, tuple, set, dict))):
return (xs[0], 1)
if isinstance(structure, (list, tuple, set)):
offset = 0
elements = []
for s in structure:
... |
def state_dict(partition, *args, **kwargs):
state = nn.Module.state_dict(partition, *args, **kwargs)
lookup = partition.lookup
result = dict()
for (k, v) in state.items():
if (k in lookup):
result[lookup[k]] = v
else:
assert ('.' in k)
split_idx = k.... |
def load_state_dict(partition, state_dict, strict=True):
reverse_lookup = {v: k for (k, v) in partition.lookup.items()}
device = partition.device
keys = list(partition.state_dict(None).keys())
new_state = dict()
for k in keys:
if (k in reverse_lookup):
new_state[reverse_lookup[... |
def named_buffers(partition, prefix='', recurse=True):
params = nn.Module.named_buffers(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx ... |
def named_parameters(partition, prefix='', recurse=True):
params = nn.Module.named_parameters(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
spli... |
def cpu(partition):
partition.device = torch.device('cpu')
return nn.Module.cpu(partition)
|
def cuda(partition, device=None):
if (device is None):
device = torch.cuda.current_device()
partition.device = torch.device(device)
return nn.Module.cuda(partition, partition.device)
|
def to(partition, *args, **kwargs):
device = None
if ('device' in kwargs):
device = kwargs['device']
elif ('tensor' in kwargs):
device = kwargs['tensor'].device
if args:
if isinstance(args[0], (torch.device, int, str)):
device = args[0]
if torch.is_tensor(ar... |
def create_pipeline_configuration(DEBUG=False, batch_size=4):
config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (Softmax, LayerNorm, Dropout, Linear, Embedding, Gelu, Tanh), 'model_inputs': {'attention_mask': {'shape': torch.Size([4, 384]), 'dtype': torch.int64, 'is_batched': True, 'used_by': [0]}, 'input... |
class Partition0(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[word_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[position_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/... |
class Partition1(nn.Module):
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertOutput[output]/Dropout[dropout]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[5]/BertOutput[output]/LayerNorm[LayerNorm]', 'BertForQuestionAnswering/BertModel[b... |
def traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[Type[nn.Module]]=(), full: bool=False) -> Iterator[Tuple[(nn.Module, str, nn.Module, Optional[bool])]]:
'\n iterate over model layers yielding the layer,layer_scope,encasing_module\n Parameters:\n ----------... |
def layerDict(model: nn.Module, depth=1000, basic_blocks=()) -> Dict[(str, nn.Module)]:
return {s: l for (l, s, _) in traverse_model(model, depth, basic_blocks=basic_blocks)}
|
def traverse_params_buffs(module: nn.Module, prefix: Optional[str]=None) -> Iterator[Tuple[(torch.tensor, str)]]:
"\n iterate over model's buffers and parameters yielding obj,obj_scope\n\n Parameters:\n -----------\n model:\n the model to iterate over\n "
if (prefix is None):
pre... |
def tensorDict(model: nn.Module) -> OrderedDict[(str, Tensor)]:
return collections.OrderedDict(((s, t) for (t, s) in traverse_params_buffs(model)))
|
def move_tensors(ts, device):
def move(t):
if isinstance(t, (nn.Module, Tensor)):
return t.to(device)
return t
return nested_map(move, ts)
|
def nested_map(func, ts, full=False):
if isinstance(ts, torch.Size):
return func(ts)
elif isinstance(ts, (list, tuple, set)):
return type(ts)((nested_map(func, t, full=full) for t in ts))
elif isinstance(ts, dict):
return {k: nested_map(func, v, full=full) for (k, v) in ts.items()}... |
def flatten(ts):
if isinstance(ts, torch.Size):
(yield ts)
elif isinstance(ts, (list, tuple, set)):
(yield from chain(*[flatten(t) for t in ts]))
elif isinstance(ts, dict):
(yield from chain(*[flatten(t) for (k, t) in sorted(ts.items(), key=(lambda t: t[0]))]))
else:
(y... |
def unflatten(xs, structure):
return _unflatten(xs, structure)[0]
|
def _unflatten(xs, structure):
if isinstance(structure, torch.Size):
return (xs[0], 1)
if (not isinstance(structure, (list, tuple, set, dict))):
return (xs[0], 1)
if isinstance(structure, (list, tuple, set)):
offset = 0
elements = []
for s in structure:
... |
def state_dict(partition, *args, **kwargs):
state = nn.Module.state_dict(partition, *args, **kwargs)
lookup = partition.lookup
result = dict()
for (k, v) in state.items():
if (k in lookup):
result[lookup[k]] = v
else:
assert ('.' in k)
split_idx = k.... |
def load_state_dict(partition, state_dict, strict=True):
reverse_lookup = {v: k for (k, v) in partition.lookup.items()}
device = partition.device
keys = list(partition.state_dict(None).keys())
new_state = dict()
for k in keys:
if (k in reverse_lookup):
new_state[reverse_lookup[... |
def named_buffers(partition, prefix='', recurse=True):
params = nn.Module.named_buffers(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx ... |
def named_parameters(partition, prefix='', recurse=True):
params = nn.Module.named_parameters(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
spli... |
def cpu(partition):
partition.device = torch.device('cpu')
return nn.Module.cpu(partition)
|
def cuda(partition, device=None):
if (device is None):
device = torch.cuda.current_device()
partition.device = torch.device(device)
return nn.Module.cuda(partition, partition.device)
|
def to(partition, *args, **kwargs):
device = None
if ('device' in kwargs):
device = kwargs['device']
elif ('tensor' in kwargs):
device = kwargs['tensor'].device
if args:
if isinstance(args[0], (torch.device, int, str)):
device = args[0]
if torch.is_tensor(ar... |
def create_pipeline_configuration(DEBUG=False):
depth = 10000
basic_blocks = (Tanh, Dropout, BertSelfAttention, LayerNorm, Embedding, Gelu, Linear)
blocks_path = ['torch.nn.modules.activation.Tanh', 'torch.nn.modules.dropout.Dropout', 'models.normal.NLP_models.modeling_bert_old.BertSelfAttention', 'torch.... |
class Partition0(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Embedding, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[word_embeddings]', 'BertForQuestionAnswering/BertModel[bert]/BertEmbeddings[embeddings]/Embedding[position... |
class Partition1(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[2]/BertOutput[output]/LayerNorm[LayerNorm]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[3]/Be... |
class Partition2(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[6]/BertAttention[attention]/BertSelfAttention[self]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLa... |
class Partition3(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[9]/BertAttention[attention]/BertSelfAttention[self]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLa... |
class Partition4(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[12]/BertAttention[attention]/BertSelfAttention[self]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertL... |
class Partition5(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[15]/BertAttention[attention]/BertSelfAttention[self]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertL... |
class Partition6(nn.Module):
BASIC_BLOCKS = (LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[17]/BertOutput[output]/LayerNorm[LayerNorm]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[18]/... |
class Partition7(nn.Module):
BASIC_BLOCKS = (Tanh, LayerNorm, Linear, Gelu, BertSelfAttention, Dropout)
LAYER_SCOPES = ['BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]/BertLayer[21]/BertAttention[attention]/BertSelfAttention[self]', 'BertForQuestionAnswering/BertModel[bert]/BertEncoder[encoder]... |
def traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[nn.Module]=(), full: bool=False) -> Iterator[Tuple[(nn.Module, str, nn.Module)]]:
'\n iterate over model layers yielding the layer,layer_scope,encasing_module\n Parameters:\n -----------\n model:\n ... |
def layerDict(model: nn.Module, depth=1000, basic_blocks=()) -> Dict[(str, nn.Module)]:
return {s: l for (l, s, _) in traverse_model(model, depth, basic_blocks=basic_blocks)}
|
def traverse_params_buffs(module: nn.Module, prefix: Optional[str]=None) -> Iterator[Tuple[(torch.tensor, str)]]:
"\n iterate over model's buffers and parameters yielding obj,obj_scope\n\n Parameters:\n -----------\n model:\n the model to iterate over\n "
if (prefix is None):
pre... |
def tensorDict(model: nn.Module) -> OrderedDict[(str, Tensor)]:
return collections.OrderedDict(((s, t) for (t, s) in traverse_params_buffs(model)))
|
def move_tensors(ts, device):
def move(t):
if isinstance(t, (nn.Module, Tensor)):
return t.to(device)
return t
return nested_map(move, ts)
|
def nested_map(func, ts):
if isinstance(ts, torch.Size):
return func(ts)
elif isinstance(ts, (list, tuple, set)):
return type(ts)((nested_map(func, t) for t in ts))
elif isinstance(ts, dict):
return {k: nested_map(func, v) for (k, v) in ts.items()}
elif isinstance(ts, slice):
... |
def state_dict(partition, device=None):
state = nn.Module.state_dict(partition)
lookup = partition.lookup
result = dict()
for (k, v) in state.items():
if (k in lookup):
result[lookup[k]] = (v if (device is None) else v.to(device))
else:
assert ('.' in k)
... |
def load_state_dict(partition, state):
reverse_lookup = {v: k for (k, v) in partition.lookup.items()}
device = partition.device
keys = list(partition.state_dict(None).keys())
new_state = dict()
for k in keys:
if (k in reverse_lookup):
new_state[reverse_lookup[k]] = state[k].to(... |
def named_buffers(partition, recurse=True):
params = nn.Module.named_buffers(partition, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx = k.find('.')
... |
def named_parameters(partition, recurse=True):
params = nn.Module.named_parameters(partition, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx = k.find('.')
... |
def cpu(partition):
partition.device = torch.device('cpu')
return nn.Module.cpu(partition)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.