code
stringlengths
17
6.64M
class Resnet3dCSNiRMultiClass(Resnet3dChannelSeparated_ir): def __init__(self, tw=16, sample_size=112, e_dim=7, n_classes=2): super(Resnet3dCSNiRMultiClass, self).__init__(tw=tw, sample_size=sample_size, e_dim=e_dim, n_classes=n_classes, decoders=[DecoderMultiClass(n_classes=n_classes), DecoderEmbedding(...
def propagate3d(model, inputs, ref_mask, proposals): assert (inputs.shape[2] >= 2) e2 = model(inputs, ref_mask) return e2
def run_forward(model, inputs, ref_masks, proposals): return propagate3d(model, inputs, ref_masks, proposals)
def get_backbone_fn(backbone): '\n Returns a funtion that creates the required backbone\n :param backbone: name of the backbone function\n :return:\n ' backbones = inspect.getmembers(Resnet3d) _fn = [_f for (name, _f) in backbones if (name == backbone)] if (len(_fn) == 0): raise ValueError...
def get_module(module): backbones = inspect.getmembers(Modules) _cls = [_c for (name, _c) in backbones if (name == module)] return _cls[0]
class _NonLocalBlockND(nn.Module): def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True, return_sim=False): super(_NonLocalBlockND, self).__init__() assert (dimension in [1, 2, 3]) self.dimension = dimension self.sub_sample = sub_sample ...
class NONLocalBlock1D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): super(NONLocalBlock1D, self).__init__(in_channels, inter_channels=inter_channels, dimension=1, sub_sample=sub_sample, bn_layer=bn_layer)
class NONLocalBlock2D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): super(NONLocalBlock2D, self).__init__(in_channels, inter_channels=inter_channels, dimension=2, sub_sample=sub_sample, bn_layer=bn_layer)
class NONLocalBlock3D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True, return_sim=False): super(NONLocalBlock3D, self).__init__(in_channels, inter_channels=inter_channels, dimension=3, sub_sample=sub_sample, bn_layer=bn_layer, return_sim=return_sim)
def r2plus1d_34(num_classes, pretrained=False, progress=False, arch=None): model = VideoResNet(block=BasicBlock, conv_makers=([Conv2Plus1D] * 4), layers=[3, 4, 6, 3], stem=R2Plus1dStem) model.fc = nn.Linear(model.fc.in_features, out_features=num_classes) model.layer2[0].conv2[0] = Conv2Plus1D(128, 128, 28...
class Encoder(nn.Module): def __init__(self, n_classes=1): super(Encoder, self).__init__() self.conv1_p = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=True) resnet = models.resnet50(pretrained=True) self.conv1 = resnet.conv1 self.bn1 = resnet.bn1 self....
class Decoder(nn.Module): def __init__(self): super(Decoder, self).__init__() mdim = 256 self.GC = GC(4096, mdim) self.convG1 = nn.Conv2d(mdim, mdim, kernel_size=3, padding=1) self.convG2 = nn.Conv2d(mdim, mdim, kernel_size=3, padding=1) self.RF4 = Refine(1024, mdi...
class RGMP(BaseNetwork): def __init__(self): super(RGMP, self).__init__() self.encoder = Encoder() self.decoder = Decoder()
def conv3x3x3(in_planes, out_planes, stride=1): return nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def downsample_basic_block(x, planes, stride): out = F.avg_pool3d(x, kernel_size=1, stride=stride) zero_pads = torch.Tensor(out.size(0), (planes - out.size(1)), out.size(2), out.size(3), out.size(4)).zero_() if isinstance(out.data, torch.cuda.FloatTensor): zero_pads = zero_pads.cuda() out = Va...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm3d(planes) self.relu = nn.ReLU(inplace=True) self.conv...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm3d(planes) self.conv2 = nn.Conv...
class Bottleneck_depthwise_ip(Bottleneck): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck_depthwise_ip, self).__init__(inplanes, planes, stride, downsample, dilation) self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=Fals...
class Bottleneck_depthwise_ir(Bottleneck): def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck_depthwise_ir, self).__init__(inplanes, planes, stride, downsample) self.conv2 = nn.Conv3d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, g...
class ResNet(nn.Module): def __init__(self, block, layers, sample_size, sample_duration, shortcut_type='B', num_classes=400, last_fc=True): self.last_fc = last_fc self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv3d(3, 64, kernel_size=7, stride=(1, 2, 2), paddi...
class ResNetNoTS(ResNet): def __init__(self, block, layers, sample_size, sample_duration, shortcut_type='B', num_classes=400, last_fc=True): self.last_fc = last_fc self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv3d(3, 64, kernel_size=7, stride=(1, 2, 2), padd...
def get_fine_tuning_parameters(model, ft_begin_index): if (ft_begin_index == 0): return model.parameters() ft_module_names = [] for i in range(ft_begin_index, 5): ft_module_names.append('layer{}'.format(ft_begin_index)) ft_module_names.append('fc') parameters = [] for (k, v) in...
def resnet10(**kwargs): 'Constructs a ResNet-18 model.\n ' model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs) return model
def resnet18(**kwargs): 'Constructs a ResNet-18 model.\n ' model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) return model
def resnet34(**kwargs): 'Constructs a ResNet-34 model.\n ' model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) return model
def resnet50(**kwargs): 'Constructs a ResNet-50 model.\n ' model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) return model
def resnet50_no_ts(**kwargs): 'Constructs a ResNet-50 model.\n ' model = ResNetNoTS(Bottleneck, [3, 4, 6, 3], **kwargs) return model
def resnet50_csn_ir(**kwargs): 'Constructs a channel-separated ResNet-152 model with reduced interactions.\n ' model = ResNet(Bottleneck_depthwise_ir, [3, 4, 6, 3], **kwargs) model.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3), bias=False) return model
def resnet101(**kwargs): 'Constructs a ResNet-101 model.\n ' model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) return model
def resnet152(**kwargs): 'Constructs a ResNet-101 model.\n ' model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) return model
def resnet200(**kwargs): 'Constructs a ResNet-101 model.\n ' model = ResNet(Bottleneck, [3, 24, 36, 3], **kwargs) return model
def resnet152_csn_ip(**kwargs): 'Constructs a channel-separated ResNet-152 model with perserved interactions.\n ' model = ResNet(Bottleneck_depthwise_ip, [3, 8, 36, 3], **kwargs) model.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(3, 3, 3), bias=False) return model
def resnet152_csn_ir(**kwargs): 'Constructs a channel-separated ResNet-152 model with reduced interactions.\n ' model = ResNet(Bottleneck_depthwise_ir, [3, 8, 36, 3], **kwargs) model.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3), bias=False) return model
def biggerStem(): return nn.Sequential(nn.Conv3d(3, 45, kernel_size=(1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=False), nn.BatchNorm3d(45), nn.ReLU(inplace=True), nn.Conv3d(45, 64, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=(1, 0, 0), bias=False))
class Encoder3d(Encoder): def __init__(self, tw=16, sample_size=112, resnet=None): super(Encoder3d, self).__init__() self.conv1_p = nn.Conv3d(1, 64, kernel_size=7, stride=(1, 2, 2), padding=(3, 3, 3), bias=False) resnet = (resnet50(sample_size=sample_size, sample_duration=tw) if (resnet i...
class Encoder101(Encoder): def __init__(self): super(Encoder101, self).__init__() self.resnet = deeplabv3_resnet101(pretrained=True) self.conv1_p = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=True) resnet = fcn_resnet101(pretrained=True) self.conv1 = resnet.b...
class EncoderR2plus1d_34(Encoder3d): def __init__(self, tw=8, sample_size=112): super(EncoderR2plus1d_34, self).__init__(tw, sample_size) resnet = r2plus1d_34(num_classes=359, pretrained=True, arch='r2plus1d_34_32_ig65m') self.resnet = resnet self.conv1 = resnet.stem self....
class Encoder3d_csn_ip(Encoder3d): def __init__(self, tw=16, sample_size=112): super(Encoder3d_csn_ip, self).__init__(tw, sample_size) resnet = resnet152_csn_ip(sample_size=sample_size, sample_duration=tw) self.resnet = resnet self.conv1 = resnet.conv1 self.bn1 = resnet.bn...
class Encoder3d_csn_ir(Encoder3d): def __init__(self, tw=16, sample_size=112): super(Encoder3d_csn_ir, self).__init__(tw, sample_size) resnet = resnet152_csn_ir(sample_size=sample_size, sample_duration=tw) self.resnet = resnet self.conv1 = resnet.conv1 self.bn1 = resnet.bn...
class Decoder3d(nn.Module): def __init__(self, n_classes=2, pred_scale_factor=(1, 4, 4), inter_block=GC3d, refine_block=Refine3d): super(Decoder3d, self).__init__() mdim = 256 self.pred_scale_factor = pred_scale_factor self.GC = inter_block(2048, mdim) self.convG1 = nn.Con...
class Decoder3dNoGC(Decoder3d): def __init__(self, n_classes=2): super(Decoder3dNoGC, self).__init__(n_classes=n_classes) self.GC = nn.Conv3d(2048, 256, kernel_size=3, padding=1)
class Decoder3dNonLocal(Decoder3d): def __init__(self, n_classes=2): super(Decoder3dNonLocal, self).__init__(n_classes=n_classes) self.GC = nn.Sequential(nn.Conv3d(2048, 256, kernel_size=1), NONLocalBlock3D(256, sub_sample=True))
class DecoderR2plus1d(Decoder3d): def __init__(self, n_classes=2, inter_block=GC3d, refine_block=Refine3d): super(DecoderR2plus1d, self).__init__(n_classes=n_classes) mdim = 256 self.GC = inter_block(512, 256) self.RF4 = refine_block(256, mdim) self.RF3 = refine_block(128,...
class Resnet3d(BaseNetwork): def __init__(self, tw=16, sample_size=112): super(Resnet3d, self).__init__() self.encoder = Encoder3d(tw, sample_size) self.decoder = Decoder3d() def forward(self, x, ref): if ((ref is not None) and (len(ref.shape) == 4)): (r5, r4, r3,...
class Resnet3d101(Resnet3d): def __init__(self, tw=8, sample_size=112, e_dim=7, decoders=None, inter_block=GC3d, refine_block=Refine3d): super(Resnet3d101, self).__init__(tw=tw, sample_size=sample_size) resnet = resnet101(sample_size=sample_size, sample_duration=tw) self.encoder = Encoder...
class R2plus1d(Resnet3d101): def __init__(self, tw=8, sample_size=112, e_dim=7, decoders=None, inter_block=GC3d, refine_block=Refine3d): decoders = [DecoderR2plus1d(inter_block=inter_block, refine_block=refine_block)] super(R2plus1d, self).__init__(tw, sample_size, e_dim, decoders) self.e...
class ResnetCSN(Resnet3d101): def __init__(self, tw=8, sample_size=112, e_dim=7, decoders=None, inter_block=GC3d, refine_block=Refine3d): super(ResnetCSN, self).__init__(tw, sample_size, e_dim, decoders, inter_block=inter_block, refine_block=refine_block) self.encoder = Encoder3d_csn_ir(tw, sampl...
class ResnetCSNNoGC(Resnet3d101): def __init__(self, tw=8, sample_size=112, e_dim=7, decoders=None): decoders = ([Decoder3dNoGC()] if (decoders is None) else decoders) print('Creating decoders {}'.format(decoders)) super(ResnetCSNNoGC, self).__init__(tw, sample_size, e_dim, decoders) ...
class ResnetCSNNonLocal(ResnetCSNNoGC): def __init__(self, tw=8, sample_size=112, e_dim=7): decoders = [Decoder3dNonLocal()] super(ResnetCSNNonLocal, self).__init__(tw, sample_size, e_dim, decoders)
def csn_ip(pretrained=False, progress=False, **kwargs): model = resnet152_csn_ip(sample_size=224, sample_duration=32) num_classes = 400 model.fc = nn.Linear(model.fc.in_features, out_features=num_classes) for m in model.modules(): if isinstance(m, nn.BatchNorm3d): m.eps = 0.001 ...
def csn_ir(pretrained=False, progress=False, **kwargs): model = resnet152_csn_ir(sample_size=224, sample_duration=32) num_classes = 400 model.fc = nn.Linear(model.fc.in_features, out_features=num_classes) for m in model.modules(): if isinstance(m, nn.BatchNorm3d): m.eps = 0.001 ...
def blobs_from_pkl(path, num_classes=400): with path.open(mode='rb') as f: pkl = pickle.load(f, encoding='latin1') blobs = pkl['blobs'] assert ((('last_out_L' + str(num_classes)) + '_w') in blobs), 'Number of --classes argument doesnt matche the last linear layer in pkl' assert (((...
def copy_tensor(data, blobs, name): tensor = torch.from_numpy(blobs[name]) del blobs[name] assert (data.size() == tensor.size()), f'Torch tensor has size {data.size()}, while Caffe2 tensor has size {tensor.size()}' assert (data.dtype == tensor.dtype) data.copy_(tensor)
def copy_conv(module, blobs, prefix): assert isinstance(module, nn.Conv3d) assert (module.bias is None) copy_tensor(module.weight.data, blobs, (prefix + '_w'))
def copy_bn(module, blobs, prefix): assert isinstance(module, nn.BatchNorm3d) copy_tensor(module.weight.data, blobs, (prefix + '_s')) copy_tensor(module.running_mean.data, blobs, (prefix + '_rm')) copy_tensor(module.running_var.data, blobs, (prefix + '_riv')) copy_tensor(module.bias.data, blobs, (...
def copy_fc(module, blobs): assert isinstance(module, nn.Linear) n = module.out_features copy_tensor(module.bias.data, blobs, (('last_out_L' + str(n)) + '_b')) copy_tensor(module.weight.data, blobs, (('last_out_L' + str(n)) + '_w'))
def copy_stem(module, blobs): assert isinstance(module, nn.Sequential) assert (len(module) == 4) copy_conv(module[0], blobs, 'conv1_middle') copy_bn(module[1], blobs, 'conv1_middle_spatbn_relu') assert isinstance(module[2], nn.ReLU) copy_conv(module[3], blobs, 'conv1')
def copy_conv2plus1d(module, blobs, i, j): assert isinstance(module, Conv2Plus1D) assert (len(module) == 4) copy_conv(module[0], blobs, (((('comp_' + str(i)) + '_conv_') + str(j)) + '_middle')) copy_bn(module[1], blobs, (((('comp_' + str(i)) + '_spatbn_') + str(j)) + '_middle')) assert isinstance(...
def copy_basicblock(module, blobs, i): assert isinstance(module, BasicBlock) assert (len(module.conv1) == 3) assert isinstance(module.conv1[0], Conv2Plus1D) copy_conv2plus1d(module.conv1[0], blobs, i, 1) assert isinstance(module.conv1[1], nn.BatchNorm3d) copy_bn(module.conv1[1], blobs, ((('com...
def copy_bottleneck(module, blobs, i): assert isinstance(module, Bottleneck) copy_conv(module.conv1, blobs, ((('comp_' + str(i)) + '_conv_') + str(1))) copy_bn(module.bn1, blobs, ((('comp_' + str(i)) + '_spatbn_') + str(1))) copy_conv(module.conv2, blobs, ((('comp_' + str(i)) + '_conv_') + str(3))) ...
def copy_bottleneck_csn_ip(module, blobs, i): assert isinstance(module, Bottleneck) copy_conv(module.conv1, blobs, ((('comp_' + str(i)) + '_conv_') + str(1))) copy_bn(module.bn1, blobs, ((('comp_' + str(i)) + '_spatbn_') + str(1))) copy_conv(module.conv2, blobs, (((('comp_' + str(i)) + '_conv_') + str...
def init_canary(model): nan = float('nan') for m in model.modules(): if isinstance(m, nn.Conv3d): assert (m.bias is None) nn.init.constant_(m.weight, nan) elif isinstance(m, nn.BatchNorm3d): nn.init.constant_(m.weight, nan) nn.init.constant_(m.ru...
def check_canary(model): for m in model.modules(): if isinstance(m, nn.Conv3d): assert (m.bias is None) assert (not torch.isnan(m.weight).any()) elif isinstance(m, nn.BatchNorm3d): assert (not torch.isnan(m.weight).any()) assert (not torch.isnan(m.ru...
def main(args): blobs = blobs_from_pkl(args.pkl) if (args.model == 'csn_ip'): model = csn_ip() elif (args.model == 'csn_ir'): model = csn_ir() else: raise ValueError((args.model + ' is unknown')) init_canary(model) copy_conv(model.conv1, blobs, 'conv1') copy_bn(mode...
class NonLocalBlock3DWithDownsampling(nn.Module): def __init__(self, in_channels, intermediate_channels, downsampling_factor, out_channels=None): super(self.__class__, self).__init__() self.theta = nn.Conv3d(in_channels, intermediate_channels, kernel_size=1, stride=1, padding=0) self.phi ...
class NonlocalOffsetEmbeddingHead(nn.Module): def __init__(self, in_channels, nonlocal_inter_channels, embedding_size, downsampling_factor, add_spatial_coord=True): super(self.__class__, self).__init__() self.nonlocal_block = NonLocalBlock3DWithDownsampling(in_channels, nonlocal_inter_channels, d...
class BaseNetwork(nn.Module): def __init__(self, tw=5): super(BaseNetwork, self).__init__() self.tw = tw
class Encoder3d(nn.Module): def __init__(self, backbone, tw, pixel_mean, pixel_std): super(Encoder3d, self).__init__() self.conv1_p = nn.Conv3d(1, 64, kernel_size=7, stride=(1, 2, 2), padding=(3, 3, 3), bias=False) resnet = get_backbone_fn(backbone.NAME)(sample_size=112, sample_duration=t...
class Decoder3d(nn.Module): def __init__(self, n_classes, inter_block, refine_block, pred_scale_factor=(1, 4, 4)): super(Decoder3d, self).__init__() mdim = 256 self.pred_scale_factor = pred_scale_factor self.GC = get_module(inter_block)(2048, mdim) self.convG1 = nn.Conv3d(...
class SaliencyNetwork(BaseNetwork): def __init__(self, cfg): super(SaliencyNetwork, self).__init__() self.encoder = Encoder3d(cfg.MODEL.BACKBONE, cfg.INPUT.TW, cfg.MODEL.PIXEL_MEAN, cfg.MODEL.PIXEL_STD) decoders = [Decoder3d(cfg.MODEL.N_CLASSES, inter_block=cfg.MODEL.DECODER.INTER_BLOCK, ...
class MultiscaleCombinedHeadLongTemporalWindow(nn.Module): def __init__(self, in_channels, num_classes, variance_output, variance_per_axis, **kwargs): super().__init__() self.embedding_size = 3 self.variance_channels = ((self.embedding_size if variance_per_axis else 1) if variance_output ...
def str2bool(v): if isinstance(v, bool): return v if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
def parse_argsV2(): parser = argparse.ArgumentParser(description='SaliencySegmentation') parser.add_argument('--config', '-c', required=True, type=str) parser.add_argument('--num_workers', dest='num_workers', help='num_workers', default=4, type=int) parser.add_argument('--local_rank', type=int, defaul...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
class AverageMeterDict(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = {} self.avg = {} self.sum = None self.count = 0 def update(self, in_dict, n=1): self.val = in_dict ...
class font(): PURPLE = '\x1b[95m' CYAN = '\x1b[96m' DARKCYAN = '\x1b[36m' BLUE = '\x1b[94m' GREEN = '\x1b[92m' YELLOW = '\x1b[93m' RED = '\x1b[91m' BOLD = '\x1b[1m' UNDERLINE = '\x1b[4m' END = '\x1b[0m'
def findContours(*args, **kwargs): '\n Wraps cv2.findContours to maintain compatiblity between versions\n 3 and 4\n\n Returns:\n contours, hierarchy\n ' if cv2.__version__.startswith('4'): (contours, hierarchy) = cv2.findContours(*args, **kwargs) elif cv2.__version__.startswith(...
class AnalysisPipelineConfig(PipelineConfig): def __init__(self, d, layers, tensors): super().__init__(d) self.stage_to_model = {stage_id: self.realize_stage(layers, tensors, stage_id, device='cpu') for stage_id in range(self.n_stages)} try_jit = False if try_jit: for ...
def extra_communication_time_lower_bound(comp_time, comm_time): 'communication is completely parallel to computation ' if (comp_time >= comm_time): return 0 else: return (comm_time - comp_time)
def extra_communication_time_upper_bound(comp_time, comm_time): 'communication is completely not parallel to computation ' return comm_time
def upper_utilization_bound(comp_time, comm_time): 'communication is completely parallel to computation ' comm_time = extra_communication_time_lower_bound(comp_time, comm_time) return (comp_time / (comm_time + comp_time))
def lower_utilization_bound(comp_time, comm_time): 'communication is completely not parallel to computation ' comm_time = extra_communication_time_upper_bound(comp_time, comm_time) return (comp_time / (comm_time + comp_time))
def apply_ratio(upper, lower, ratio): return ((upper * (1 - ratio)) + (lower * ratio))
def convert_to_analysis_format(config: Dict, layers: Dict[(str, torch.nn.Module)], tensors: Dict[(str, Tensor)]) -> AnalysisPipelineConfig: 'convert a pipeline configuration to format used by the analysis module' return AnalysisPipelineConfig(config, layers, tensors)
def run_partitions(model_inputs, analysis_config: AnalysisPipelineConfig, device='cuda'): if (not torch.cuda.is_available()): device = 'cpu' if isinstance(model_inputs, dict): model_inputs = tuple([model_inputs[i] for i in analysis_config.model_inputs()]) if (not isinstance(model_inputs, t...
def add_dicts(d1, d2): assert (len(d1) == len(d2)) d = {} for ((i1, v1), (i2, v2)) in zip(d1.items(), d2.items()): assert (i1 == i2) d[i1] = (v1 + v2) return d
def add_stds_dicts(d1, d2): ' var(x+y) = var(x)+var(y) + cov(x,y)\n we assume for simplicity cov(x,y) is 0.\n ' assert (len(d1) == len(d2)) d = {} for ((i1, v1), (i2, v2)) in zip(d1.items(), d2.items()): assert (i1 == i2) d[i1] = math.sqrt(((v1 ** 2) + (v2 ** 2))) return ...
def get_tensor_req_grad(ts): def get_req_grad(t): if isinstance(t, Tensor): return t.requires_grad return False return nested_map(get_req_grad, ts)
def run_partitions_fwd(model_inputs, analysis_config: AnalysisPipelineConfig, device='cpu', return_info_for_bwd=False): if isinstance(model_inputs, dict): model_inputs = tuple([model_inputs[i] for i in analysis_config.model_inputs()]) n_partitions = analysis_config.n_stages if (not isinstance(mode...
def run_partitions_bwd(analysis_config: AnalysisPipelineConfig, activations, req_grad): n_partitions = analysis_config.n_stages for i in range(n_partitions): analysis_config.stage_to_model[i] = analysis_config.stage_to_model[i].to('cpu') parts = deque(range(n_partitions)) grads = {tensor: torc...
def run_analysis(sample, model, n_workers, bw_GBps=12, verbose=True, comm_comp_concurrency_ratio=0): ' Assuming bw_GBps is bw between worker and master.\n Assuming all samples are the same size.\n currently n_workers is not relevant, theoretically its linearly scaling.\n ' comp_time = cuda_co...
def theoretical_analysis(model, bw_GBps, comp_time, comm_comp_concurrency_ratio, n_workers): send_mb = (sum([(p.nelement() * p.element_size()) for p in model.parameters()]) / 1000000.0) single_send_time = (send_mb / bw_GBps) worker_to_master_sends = 1 master_to_worker_sends = 1 num_sends = (worker...
def asgd_anayslsis_speedup_vs_ratio_graph(all_ratios, sample, model, n_workers, bw_GBps=12, verbose=True): comp_time = cuda_computation_times(model, sample) speedups = [] ratios = all_ratios for ratio in ratios: (s, d) = theoretical_analysis(model, bw_GBps, comp_time, ratio, n_workers) ...
def theoretical_analysis(graph, recomputation=True, async_pipeline=False): " find execution time of partitions based on the model's graph using 2 a sequential assumption and parallel assumption\n the sequential assumption is that in the partition all operation are linear.\n the parallel assumption a...
def parallel_execution_analysis(node, part_idx, cache): if (node.scope in cache): return cache[node.scope] elif (node.stage_id != part_idx): cache[node.scope] = (0, 0) return (0, 0) (longest_f, longest_b) = (0, 0) for n in node.in_edges: (f, b) = parallel_execution_anal...
def extract_time(w, forward=False): if hasattr(w, 'weight'): w = w.weight if (not hasattr(w, 'forward_time')): return 0 if forward: return w.forward_time return w.backward_time
def maybe_do_theoretical_analysis(DO_THEORETICAL, PRINT_THEORETICAL, PRINT_MIN_MAX_BALANCE, async_pipeline, graph, recomputation): s = '' if ((graph is not None) and DO_THEORETICAL): (sequential_f, sequential_b, parallel_f, parallel_b) = theoretical_analysis(graph, recomputation=recomputation, async_p...
def edge_cut(graph): '\n find the cutting edges of the graph\n ' edges = [] for n in graph.nodes: stages = set() for o in n.out_edges: if ((n.stage_id != o.stage_id) and (o.stage_id not in stages)): stages.add(o.stage_id) edges.append((n, o...
def worst_balance(times): return (min(times.values()) / max(times.values()))
def pipedream_extimated_time(N, m, L=1): baseline_complexity = 709789824 baseline_seconds = 8 complexity = ((L * (N ** 3)) * (m ** 2)) estimated_time = (baseline_seconds * (complexity / baseline_complexity)) return estimated_time