code stringlengths 17 6.64M |
|---|
def countless_generalized(data, factor):
assert (len(data.shape) == len(factor))
sections = []
mode_of = reduce((lambda x, y: (x * y)), factor)
majority = int(math.ceil((float(mode_of) / 2)))
data += 1
for offset in np.ndindex(factor):
part = data[tuple((np.s_[o::f] for (o, f) in zip(o... |
def dynamic_countless_generalized(data, factor):
assert (len(data.shape) == len(factor))
sections = []
mode_of = reduce((lambda x, y: (x * y)), factor)
majority = int(math.ceil((float(mode_of) / 2)))
data += 1
for offset in np.ndindex(factor):
part = data[tuple((np.s_[o::f] for (o, f) ... |
def downsample_with_averaging(array):
'\n Downsample x by factor using averaging.\n\n @return: The downsampled array, of the same type as x.\n '
factor = (2, 2, 2)
if np.array_equal(factor[:3], np.array([1, 1, 1])):
return array
output_shape = tuple((int(math.ceil((s / f))) for (s, f) in zi... |
def downsample_with_max_pooling(array):
factor = (2, 2, 2)
sections = []
for offset in np.ndindex(factor):
part = array[tuple((np.s_[o::f] for (o, f) in zip(offset, factor)))]
sections.append(part)
output = sections[0].copy()
for section in sections[1:]:
np.maximum(output, ... |
def striding(array):
'Downsample x by factor using striding.\n\n @return: The downsampled array, of the same type as x.\n '
factor = (2, 2, 2)
if np.all((np.array(factor, int) == 1)):
return array
return array[tuple((np.s_[::f] for f in factor))]
|
def benchmark():
def countless3d_generalized(img):
return countless_generalized(img, (2, 8, 1))
def countless3d_dynamic_generalized(img):
return dynamic_countless_generalized(img, (8, 8, 1))
methods = [countless3d_generalized]
data = (np.zeros(shape=((16 ** 2), (16 ** 2), (16 ** 2)),... |
def test_countless2d():
def test_all_cases(fn, test_zero):
case1 = np.array([[1, 2], [3, 4]]).reshape((2, 2, 1, 1))
case2 = np.array([[1, 1], [2, 3]]).reshape((2, 2, 1, 1))
case1z = np.array([[0, 1], [2, 3]]).reshape((2, 2, 1, 1))
case2z = np.array([[0, 0], [2, 3]]).reshape((2, 2,... |
def test_stippled_countless2d():
a = np.array([[1, 2], [3, 4]]).reshape((2, 2, 1, 1))
b = np.array([[0, 2], [3, 4]]).reshape((2, 2, 1, 1))
c = np.array([[1, 0], [3, 4]]).reshape((2, 2, 1, 1))
d = np.array([[1, 2], [0, 4]]).reshape((2, 2, 1, 1))
e = np.array([[1, 2], [3, 0]]).reshape((2, 2, 1, 1))
... |
def test_countless3d():
def test_all_cases(fn):
alldifferent = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
allsame = [[[1, 1], [1, 1]], [[1, 1], [1, 1]]]
assert (fn(np.array(alldifferent)) == [[[8]]])
assert (fn(np.array(allsame)) == [[[1]]])
twosame = deepcopy(alldifferent)
... |
def load_yaml(path):
with open(path, 'r') as f:
return edict(yaml.safe_load(f))
|
def move_to_device(obj, device):
if isinstance(obj, nn.Module):
return obj.to(device)
if torch.is_tensor(obj):
return obj.to(device)
if isinstance(obj, (tuple, list)):
return [move_to_device(el, device) for el in obj]
if isinstance(obj, dict):
return {name: move_to_devi... |
class SmallMode(Enum):
DROP = 'drop'
UPSCALE = 'upscale'
|
def save_item_for_vis(item, out_file):
mask = (item['mask'] > 0.5)
if (mask.ndim == 3):
mask = mask[0]
img = mark_boundaries(np.transpose(item['image'], (1, 2, 0)), mask, color=(1.0, 0.0, 0.0), outline_color=(1.0, 1.0, 1.0), mode='thick')
if ('inpainted' in item):
inp_img = mark_bounda... |
def save_mask_for_sidebyside(item, out_file):
mask = item['mask']
if (mask.ndim == 3):
mask = mask[0]
mask = np.clip((mask * 255), 0, 255).astype('uint8')
io.imsave(out_file, mask)
|
def save_img_for_sidebyside(item, out_file):
img = np.transpose(item['image'], (1, 2, 0))
img = np.clip((img * 255), 0, 255).astype('uint8')
io.imsave(out_file, img)
|
class IAAAffine2(DualIAATransform):
'Place a regular grid of points on the input and randomly move the neighbourhood of these point around\n via affine transformations.\n\n Note: This class introduce interpolation artifacts to mask if it has values other than {0;1}\n\n Args:\n p (float): probabili... |
class IAAPerspective2(DualIAATransform):
"Perform a random four point perspective transform of the input.\n\n Note: This class introduce interpolation artifacts to mask if it has values other than {0;1}\n\n Args:\n scale ((float, float): standard deviation of the normal distributions. These are used ... |
class InpaintingTrainDataset(Dataset):
def __init__(self, indir, mask_generator, transform):
self.in_files = list(glob.glob(os.path.join(indir, '**', '*.jpg'), recursive=True))
self.mask_generator = mask_generator
self.transform = transform
self.iter_i = 0
def __len__(self):
... |
class InpaintingTrainWebDataset(IterableDataset):
def __init__(self, indir, mask_generator, transform, shuffle_buffer=200):
self.impl = webdataset.Dataset(indir).shuffle(shuffle_buffer).decode('rgb').to_tuple('jpg')
self.mask_generator = mask_generator
self.transform = transform
def ... |
class ImgSegmentationDataset(Dataset):
def __init__(self, indir, mask_generator, transform, out_size, segm_indir, semantic_seg_n_classes):
self.indir = indir
self.segm_indir = segm_indir
self.mask_generator = mask_generator
self.transform = transform
self.out_size = out_si... |
def get_transforms(transform_variant, out_size):
if (transform_variant == 'default'):
transform = A.Compose([A.RandomScale(scale_limit=0.2), A.PadIfNeeded(min_height=out_size, min_width=out_size), A.RandomCrop(height=out_size, width=out_size), A.HorizontalFlip(), A.CLAHE(), A.RandomBrightnessContrast(brig... |
def make_default_train_dataloader(indir, kind='default', out_size=512, mask_gen_kwargs=None, transform_variant='default', mask_generator_kind='mixed', dataloader_kwargs=None, ddp_kwargs=None, **kwargs):
LOGGER.info(f'Make train dataloader {kind} from {indir}. Using mask generator={mask_generator_kind}')
mask_... |
def make_default_val_dataset(indir, kind='default', out_size=512, transform_variant='default', **kwargs):
if (OmegaConf.is_list(indir) or isinstance(indir, (tuple, list))):
return ConcatDataset([make_default_val_dataset(idir, kind=kind, out_size=out_size, transform_variant=transform_variant, **kwargs) for... |
def make_default_val_dataloader(*args, dataloader_kwargs=None, **kwargs):
dataset = make_default_val_dataset(*args, **kwargs)
if (dataloader_kwargs is None):
dataloader_kwargs = {}
dataloader = DataLoader(dataset, **dataloader_kwargs)
return dataloader
|
def make_constant_area_crop_params(img_height, img_width, min_size=128, max_size=512, area=(256 * 256), round_to_mod=16):
min_size = min(img_height, img_width, min_size)
max_size = min(img_height, img_width, max_size)
if (random.random() < 0.5):
out_height = min(max_size, ceil_modulo(random.randin... |
class BaseAdversarialLoss():
def pre_generator_step(self, real_batch: torch.Tensor, fake_batch: torch.Tensor, generator: nn.Module, discriminator: nn.Module):
'\n Prepare for generator step\n :param real_batch: Tensor, a batch of real samples\n :param fake_batch: Tensor, a batch of s... |
def make_r1_gp(discr_real_pred, real_batch):
if torch.is_grad_enabled():
grad_real = torch.autograd.grad(outputs=discr_real_pred.sum(), inputs=real_batch, create_graph=True)[0]
grad_penalty = (grad_real.view(grad_real.shape[0], (- 1)).norm(2, dim=1) ** 2).mean()
else:
grad_penalty = 0
... |
class NonSaturatingWithR1(BaseAdversarialLoss):
def __init__(self, gp_coef=5, weight=1, mask_as_fake_target=False, allow_scale_mask=False, mask_scale_mode='nearest', extra_mask_weight_for_gen=0, use_unmasked_for_gen=True, use_unmasked_for_discr=True):
self.gp_coef = gp_coef
self.weight = weight
... |
class BCELoss(BaseAdversarialLoss):
def __init__(self, weight):
self.weight = weight
self.bce_loss = nn.BCEWithLogitsLoss()
def generator_loss(self, discr_fake_pred: torch.Tensor) -> Tuple[(torch.Tensor, Dict[(str, torch.Tensor)])]:
real_mask_gt = torch.zeros(discr_fake_pred.shape).t... |
def make_discrim_loss(kind, **kwargs):
if (kind == 'r1'):
return NonSaturatingWithR1(**kwargs)
elif (kind == 'bce'):
return BCELoss(**kwargs)
raise ValueError(f'Unknown adversarial loss kind {kind}')
|
def masked_l2_loss(pred, target, mask, weight_known, weight_missing):
per_pixel_l2 = F.mse_loss(pred, target, reduction='none')
pixel_weights = ((mask * weight_missing) + ((1 - mask) * weight_known))
return (pixel_weights * per_pixel_l2).mean()
|
def masked_l1_loss(pred, target, mask, weight_known, weight_missing):
per_pixel_l1 = F.l1_loss(pred, target, reduction='none')
pixel_weights = ((mask * weight_missing) + ((1 - mask) * weight_known))
return (pixel_weights * per_pixel_l1).mean()
|
def feature_matching_loss(fake_features: List[torch.Tensor], target_features: List[torch.Tensor], mask=None):
if (mask is None):
res = torch.stack([F.mse_loss(fake_feat, target_feat) for (fake_feat, target_feat) in zip(fake_features, target_features)]).mean()
else:
res = 0
norm = 0
... |
class CrossEntropy2d(nn.Module):
def __init__(self, reduction='mean', ignore_label=255, weights=None, *args, **kwargs):
'\n weight (Tensor, optional): a manual rescaling weight given to each class.\n If given, has to be a Tensor of size "nclasses"\n '
super(CrossEntropy2d... |
class PerceptualLoss(nn.Module):
'\n Perceptual loss, VGG-based\n https://arxiv.org/abs/1603.08155\n https://github.com/dxyang/StyleTransfer/blob/master/utils.py\n '
def __init__(self, weights=[1.0, 1.0, 1.0, 1.0, 1.0]):
super(PerceptualLoss, self).__init__()
self.add_module('vgg'... |
class VGG19(torch.nn.Module):
def __init__(self):
super(VGG19, self).__init__()
features = models.vgg19(pretrained=True).features
self.relu1_1 = torch.nn.Sequential()
self.relu1_2 = torch.nn.Sequential()
self.relu2_1 = torch.nn.Sequential()
self.relu2_2 = torch.nn.... |
def make_generator(config, kind, **kwargs):
logging.info(f'Make generator {kind}')
if (kind == 'pix2pixhd_multidilated'):
return MultiDilatedGlobalGenerator(**kwargs)
if (kind == 'pix2pixhd_global'):
return GlobalGenerator(**kwargs)
if (kind == 'ffc_resnet'):
return FFCResNetGe... |
def make_discriminator(kind, **kwargs):
logging.info(f'Make discriminator {kind}')
if (kind == 'pix2pixhd_nlayer_multidilated'):
return MultidilatedNLayerDiscriminator(**kwargs)
if (kind == 'pix2pixhd_nlayer'):
return NLayerDiscriminator(**kwargs)
raise ValueError(f'Unknown discriminat... |
class BaseDiscriminator(nn.Module):
@abc.abstractmethod
def forward(self, x: torch.Tensor) -> Tuple[(torch.Tensor, List[torch.Tensor])]:
'\n Predict scores and get intermediate activations. Useful for feature matching loss\n :return tuple (scores, list of intermediate activations)\n ... |
def get_conv_block_ctor(kind='default'):
if (not isinstance(kind, str)):
return kind
if (kind == 'default'):
return nn.Conv2d
if (kind == 'depthwise'):
return DepthWiseSeperableConv
if (kind == 'multidilated'):
return MultidilatedConv
raise ValueError(f'Unknown conv... |
def get_norm_layer(kind='bn'):
if (not isinstance(kind, str)):
return kind
if (kind == 'bn'):
return nn.BatchNorm2d
if (kind == 'in'):
return nn.InstanceNorm2d
raise ValueError(f'Unknown norm block kind {kind}')
|
def get_activation(kind='tanh'):
if (kind == 'tanh'):
return nn.Tanh()
if (kind == 'sigmoid'):
return nn.Sigmoid()
if (kind is False):
return nn.Identity()
raise ValueError(f'Unknown activation kind {kind}')
|
class SimpleMultiStepGenerator(nn.Module):
def __init__(self, steps: List[nn.Module]):
super().__init__()
self.steps = nn.ModuleList(steps)
def forward(self, x):
cur_in = x
outs = []
for step in self.steps:
cur_out = step(cur_in)
outs.append(cu... |
def deconv_factory(kind, ngf, mult, norm_layer, activation, max_features):
if (kind == 'convtranspose'):
return [nn.ConvTranspose2d(min(max_features, (ngf * mult)), min(max_features, int(((ngf * mult) / 2))), kernel_size=3, stride=2, padding=1, output_padding=1), norm_layer(min(max_features, int(((ngf * m... |
class DepthWiseSeperableConv(nn.Module):
def __init__(self, in_dim, out_dim, *args, **kwargs):
super().__init__()
if ('groups' in kwargs):
del kwargs['groups']
self.depthwise = nn.Conv2d(in_dim, in_dim, *args, groups=in_dim, **kwargs)
self.pointwise = nn.Conv2d(in_dim,... |
class ResNetHead(nn.Module):
def __init__(self, input_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', activation=nn.ReLU(True)):
assert (n_blocks >= 0)
super(ResNetHead, self).__init__()
conv_layer = get_conv_block_ctor(con... |
class ResNetTail(nn.Module):
def __init__(self, output_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', activation=nn.ReLU(True), up_norm_layer=nn.BatchNorm2d, up_activation=nn.ReLU(True), add_out_act=False, out_extra_layers_n=0, add_in_proj=None):... |
class MultiscaleResNet(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=2, n_blocks_head=2, n_blocks_tail=6, n_scales=3, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', activation=nn.ReLU(True), up_norm_layer=nn.BatchNorm2d, up_activation=nn.ReLU(True), add_out_a... |
class MultiscaleDiscriminatorSimple(nn.Module):
def __init__(self, ms_impl):
super().__init__()
self.ms_impl = nn.ModuleList(ms_impl)
@property
def num_scales(self):
return len(self.ms_impl)
def forward(self, ms_inputs: List[torch.Tensor], smallest_scales_num: Optional[int]=... |
class SingleToMultiScaleInputMixin():
def forward(self, x: torch.Tensor) -> List:
(orig_height, orig_width) = x.shape[2:]
factors = [(2 ** i) for i in range(self.num_scales)]
ms_inputs = [F.interpolate(x, size=((orig_height // f), (orig_width // f)), mode='bilinear', align_corners=False) ... |
class GeneratorMultiToSingleOutputMixin():
def forward(self, x):
return super().forward(x)[0]
|
class DiscriminatorMultiToSingleOutputMixin():
def forward(self, x):
out_feat_tuples = super().forward(x)
return (out_feat_tuples[0][0], [f for (_, flist) in out_feat_tuples for f in flist])
|
class DiscriminatorMultiToSingleOutputStackedMixin():
def __init__(self, *args, return_feats_only_levels=None, **kwargs):
super().__init__(*args, **kwargs)
self.return_feats_only_levels = return_feats_only_levels
def forward(self, x):
out_feat_tuples = super().forward(x)
outs... |
class MultiscaleDiscrSingleInput(SingleToMultiScaleInputMixin, DiscriminatorMultiToSingleOutputStackedMixin, MultiscaleDiscriminatorSimple):
pass
|
class MultiscaleResNetSingle(GeneratorMultiToSingleOutputMixin, SingleToMultiScaleInputMixin, MultiscaleResNet):
pass
|
class DotDict(defaultdict):
'dot.notation access to dictionary attributes'
__getattr__ = defaultdict.get
__setattr__ = defaultdict.__setitem__
__delattr__ = defaultdict.__delitem__
|
class Identity(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x
|
class ResnetBlock(nn.Module):
def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False, conv_kind='default', dilation=1, in_dim=None, groups=1, second_dilation=None):
super(ResnetBlock, self).__init__()
self.in_dim = in_dim
self.dim = dim
if (s... |
class ResnetBlock5x5(nn.Module):
def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False, conv_kind='default', dilation=1, in_dim=None, groups=1, second_dilation=None):
super(ResnetBlock5x5, self).__init__()
self.in_dim = in_dim
self.dim = dim
... |
class MultidilatedResnetBlock(nn.Module):
def __init__(self, dim, padding_type, conv_layer, norm_layer, activation=nn.ReLU(True), use_dropout=False):
super().__init__()
self.conv_block = self.build_conv_block(dim, padding_type, conv_layer, norm_layer, activation, use_dropout)
def build_conv_... |
class MultiDilatedGlobalGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=3, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', deconv_kind='convtranspose', activation=nn.ReLU(True), up_norm_layer=nn.BatchNorm2d, affine=None, up_activation=nn.Re... |
class ConfigGlobalGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=3, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', deconv_kind='convtranspose', activation=nn.ReLU(True), up_norm_layer=nn.BatchNorm2d, affine=None, up_activation=nn.ReLU(Tru... |
def make_dil_blocks(dilated_blocks_n, dilation_block_kind, dilated_block_kwargs):
blocks = []
for i in range(dilated_blocks_n):
if (dilation_block_kind == 'simple'):
blocks.append(ResnetBlock(**dilated_block_kwargs, dilation=(2 ** (i + 1))))
elif (dilation_block_kind == 'multi'):
... |
class GlobalGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d, padding_type='reflect', conv_kind='default', activation=nn.ReLU(True), up_norm_layer=nn.BatchNorm2d, affine=None, up_activation=nn.ReLU(True), dilated_blocks_n=0, dilated_blo... |
class GlobalGeneratorGated(GlobalGenerator):
def __init__(self, *args, **kwargs):
real_kwargs = dict(conv_kind='gated_bn_relu', activation=nn.Identity(), norm_layer=nn.Identity)
real_kwargs.update(kwargs)
super().__init__(*args, **real_kwargs)
|
class GlobalGeneratorFromSuperChannels(nn.Module):
def __init__(self, input_nc, output_nc, n_downsampling, n_blocks, super_channels, norm_layer='bn', padding_type='reflect', add_out_act=True):
super().__init__()
self.n_downsampling = n_downsampling
norm_layer = get_norm_layer(norm_layer)
... |
class NLayerDiscriminator(BaseDiscriminator):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
super().__init__()
self.n_layers = n_layers
kw = 4
padw = int(np.ceil(((kw - 1.0) / 2)))
sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=... |
class MultidilatedNLayerDiscriminator(BaseDiscriminator):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, multidilation_kwargs={}):
super().__init__()
self.n_layers = n_layers
kw = 4
padw = int(np.ceil(((kw - 1.0) / 2)))
sequence = [[nn.Conv2d(i... |
class NLayerDiscriminatorAsGen(NLayerDiscriminator):
def forward(self, x):
return super().forward(x)[0]
|
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(nn.Linear(channel, (channel // reduction), bias=False), nn.ReLU(inplace=True), nn.Linear((channel // reduction), channel, bi... |
def get_training_model_class(kind):
if (kind == 'default'):
return DefaultInpaintingTrainingModule
raise ValueError(f'Unknown trainer module {kind}')
|
def make_training_model(config):
kind = config.training_model.kind
kwargs = dict(config.training_model)
kwargs.pop('kind')
kwargs['use_ddp'] = (config.trainer.kwargs.get('accelerator', None) == 'ddp')
logging.info(f'Make training model {kind}')
cls = get_training_model_class(kind)
return c... |
def load_checkpoint(train_config, path, map_location='cuda', strict=True):
model: torch.nn.Module = make_training_model(train_config)
state = torch.load(path, map_location=map_location)
model.load_state_dict(state['state_dict'], strict=strict)
model.on_load_checkpoint(state)
return model
|
def make_optimizer(parameters, kind='adamw', **kwargs):
if (kind == 'adam'):
optimizer_class = torch.optim.Adam
elif (kind == 'adamw'):
optimizer_class = torch.optim.AdamW
else:
raise ValueError(f'Unknown optimizer kind {kind}')
return optimizer_class(parameters, **kwargs)
|
def update_running_average(result: nn.Module, new_iterate_model: nn.Module, decay=0.999):
with torch.no_grad():
res_params = dict(result.named_parameters())
new_params = dict(new_iterate_model.named_parameters())
for k in res_params.keys():
res_params[k].data.mul_(decay).add_(n... |
def make_multiscale_noise(base_tensor, scales=6, scale_mode='bilinear'):
(batch_size, _, height, width) = base_tensor.shape
(cur_height, cur_width) = (height, width)
result = []
align_corners = (False if (scale_mode in ('bilinear', 'bicubic')) else None)
for _ in range(scales):
cur_sample ... |
class BaseInpaintingTrainingModule(ptl.LightningModule):
def __init__(self, config, use_ddp, *args, predict_only=False, visualize_each_iters=100, average_generator=False, generator_avg_beta=0.999, average_generator_start_step=30000, average_generator_period=10, store_discr_outputs_for_vis=False, **kwargs):
... |
def make_visualizer(kind, **kwargs):
logging.info(f'Make visualizer {kind}')
if (kind == 'directory'):
return DirectoryVisualizer(**kwargs)
if (kind == 'noop'):
return NoopVisualizer()
raise ValueError(f'Unknown visualizer kind {kind}')
|
class BaseVisualizer():
@abc.abstractmethod
def __call__(self, epoch_i, batch_i, batch, suffix='', rank=None):
'\n Take a batch, make an image from it and visualize\n '
raise NotImplementedError()
|
def visualize_mask_and_images(images_dict: Dict[(str, np.ndarray)], keys: List[str], last_without_mask=True, rescale_keys=None, mask_only_first=None, black_mask=False) -> np.ndarray:
mask = (images_dict['mask'] > 0.5)
result = []
for (i, k) in enumerate(keys):
img = images_dict[k]
img = np... |
def visualize_mask_and_images_batch(batch: Dict[(str, torch.Tensor)], keys: List[str], max_items=10, last_without_mask=True, rescale_keys=None) -> np.ndarray:
batch = {k: tens.detach().cpu().numpy() for (k, tens) in batch.items() if ((k in keys) or (k == 'mask'))}
batch_size = next(iter(batch.values())).shape... |
def generate_colors(nlabels, type='bright', first_color_black=False, last_color_black=True, verbose=False):
"\n Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks\n :param nlabels: Number of labels (size of colormap)\n :param type: 'bright' for strong colors, 'so... |
class DirectoryVisualizer(BaseVisualizer):
DEFAULT_KEY_ORDER = 'image predicted_image inpainted'.split(' ')
def __init__(self, outdir, key_order=DEFAULT_KEY_ORDER, max_items_in_batch=10, last_without_mask=True, rescale_keys=None):
self.outdir = outdir
os.makedirs(self.outdir, exist_ok=True)
... |
class NoopVisualizer(BaseVisualizer):
def __init__(self, *args, **kwargs):
pass
def __call__(self, epoch_i, batch_i, batch, suffix='', rank=None):
pass
|
def check_and_warn_input_range(tensor, min_value, max_value, name):
actual_min = tensor.min()
actual_max = tensor.max()
if ((actual_min < min_value) or (actual_max > max_value)):
warnings.warn(f'{name} must be in {min_value}..{max_value} range, but it ranges {actual_min}..{actual_max}')
|
def sum_dict_with_prefix(target, cur_dict, prefix, default=0):
for (k, v) in cur_dict.items():
target_key = (prefix + k)
target[target_key] = (target.get(target_key, default) + v)
|
def average_dicts(dict_list):
result = {}
norm = 0.001
for dct in dict_list:
sum_dict_with_prefix(result, dct, '')
norm += 1
for k in list(result):
result[k] /= norm
return result
|
def add_prefix_to_keys(dct, prefix):
return {(prefix + k): v for (k, v) in dct.items()}
|
def set_requires_grad(module, value):
for param in module.parameters():
param.requires_grad = value
|
def flatten_dict(dct):
result = {}
for (k, v) in dct.items():
if isinstance(k, tuple):
k = '_'.join(k)
if isinstance(v, dict):
for (sub_k, sub_v) in flatten_dict(v).items():
result[f'{k}_{sub_k}'] = sub_v
else:
result[k] = v
retur... |
class LinearRamp():
def __init__(self, start_value=0, end_value=1, start_iter=(- 1), end_iter=0):
self.start_value = start_value
self.end_value = end_value
self.start_iter = start_iter
self.end_iter = end_iter
def __call__(self, i):
if (i < self.start_iter):
... |
class LadderRamp():
def __init__(self, start_iters, values):
self.start_iters = start_iters
self.values = values
assert (len(values) == (len(start_iters) + 1)), (len(values), len(start_iters))
def __call__(self, i):
segment_i = bisect.bisect_right(self.start_iters, i)
... |
def get_ramp(kind='ladder', **kwargs):
if (kind == 'linear'):
return LinearRamp(**kwargs)
if (kind == 'ladder'):
return LadderRamp(**kwargs)
raise ValueError(f'Unexpected ramp kind: {kind}')
|
def print_traceback_handler(sig, frame):
LOGGER.warning(f'Received signal {sig}')
bt = ''.join(traceback.format_stack())
LOGGER.warning(f'''Requested stack trace:
{bt}''')
|
def register_debug_signal_handlers(sig=signal.SIGUSR1, handler=print_traceback_handler):
LOGGER.warning(f'Setting signal {sig} handler {handler}')
signal.signal(sig, handler)
|
def handle_deterministic_config(config):
seed = dict(config).get('seed', None)
if (seed is None):
return False
seed_everything(seed)
return True
|
def get_shape(t):
if torch.is_tensor(t):
return tuple(t.shape)
elif isinstance(t, dict):
return {n: get_shape(q) for (n, q) in t.items()}
elif isinstance(t, (list, tuple)):
return [get_shape(q) for q in t]
elif isinstance(t, numbers.Number):
return type(t)
else:
... |
def get_has_ddp_rank():
master_port = os.environ.get('MASTER_PORT', None)
node_rank = os.environ.get('NODE_RANK', None)
local_rank = os.environ.get('LOCAL_RANK', None)
world_size = os.environ.get('WORLD_SIZE', None)
has_rank = ((master_port is not None) or (node_rank is not None) or (local_rank is... |
def handle_ddp_subprocess():
def main_decorator(main_func):
@functools.wraps(main_func)
def new_main(*args, **kwargs):
parent_cwd = os.environ.get('TRAINING_PARENT_WORK_DIR', None)
has_parent = (parent_cwd is not None)
has_rank = get_has_ddp_rank()
... |
def handle_ddp_parent_process():
parent_cwd = os.environ.get('TRAINING_PARENT_WORK_DIR', None)
has_parent = (parent_cwd is not None)
has_rank = get_has_ddp_rank()
assert (has_parent == has_rank), f'Inconsistent state: has_parent={has_parent}, has_rank={has_rank}'
if (parent_cwd is None):
o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.