id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
1,959
import torch from torch.nn import functional as F from torch import nn from detectron2.layers import cat from detectron2.modeling.poolers import ROIPooler from .utils import aligned_bilinear, compute_loss, compute_loss_softmax from fvcore.nn import sigmoid_focal_loss_jit from adet.utils.comm import reduce_sum from detectron2.utils.comm import get_world_size from detectron2.layers import ConvTranspose2d from detectron2.structures.instances import Instances import logging The provided code snippet includes necessary dependencies for implementing the `subnetworks_forward` function. Write a Python function `def subnetworks_forward(inputs, weights, biases, n_subnets)` to solve the following problem: :param inputs: a list of inputs :param weights: [w0, w1, ...] :param bias: [b0, b1, ...] :return: Here is the function: def subnetworks_forward(inputs, weights, biases, n_subnets): ''' :param inputs: a list of inputs :param weights: [w0, w1, ...] :param bias: [b0, b1, ...] :return: ''' assert inputs.dim() == 4 n_layer = len(weights) x = inputs for i, (w, b) in enumerate(zip(weights, biases)): x = F.conv2d( x, w, bias=b, stride=1, padding=0, groups=n_subnets ) if i < n_layer - 1: x = F.relu(x) return x
:param inputs: a list of inputs :param weights: [w0, w1, ...] :param bias: [b0, b1, ...] :return:
1,960
import torch.nn as nn from detectron2.layers.batch_norm import NaiveSyncBatchNorm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone import Backbone from .lpf import * The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, groups=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_planes, out_planes, stride=1, groups=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False)
3x3 convolution with padding
1,961
import torch.nn as nn from detectron2.layers.batch_norm import NaiveSyncBatchNorm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone import Backbone from .lpf import * The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_planes, out_planes, stride=1)` to solve the following problem: 1x1 convolution Here is the function: def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
1x1 convolution
1,962
import torch import torch.nn.parallel import numpy as np import torch.nn as nn import torch.nn.functional as F def get_pad_layer(pad_type): if(pad_type in ['refl','reflect']): PadLayer = nn.ReflectionPad2d elif(pad_type in ['repl','replicate']): PadLayer = nn.ReplicationPad2d elif(pad_type=='zero'): PadLayer = nn.ZeroPad2d else: print('Pad type [%s] not recognized'%pad_type) return PadLayer
null
1,963
import torch import torch.nn.parallel import numpy as np import torch.nn as nn import torch.nn.functional as F def get_pad_layer_1d(pad_type): if(pad_type in ['refl', 'reflect']): PadLayer = nn.ReflectionPad1d elif(pad_type in ['repl', 'replicate']): PadLayer = nn.ReplicationPad1d elif(pad_type == 'zero'): PadLayer = nn.ZeroPad1d else: print('Pad type [%s] not recognized' % pad_type) return PadLayer
null
1,964
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 WEB_ROOT = 'http://dl.yf.io/dla/models' def get_model_url(data, name): return join(WEB_ROOT, data.name, '{}-{}.pth'.format(name, data.model_hash[name]))
null
1,965
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
1,966
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class Bottleneck(nn.Module): expansion = 2 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(Bottleneck, self).__init__() expansion = Bottleneck.expansion bottle_planes = planes // expansion self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla46_c(cfg, pretrained=None, **kwargs): # DLA-46-C Bottleneck.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 2, 1], [16, 32, 64, 64, 128, 256], block=Bottleneck, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla46_c') return model
null
1,967
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class BottleneckX(nn.Module): def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): def forward(self, x, residual=None): class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): def _make_level(self, block, inplanes, planes, blocks, stride=1): def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): def forward(self, x): def dla46x_c(cfg, pretrained=None, **kwargs): # DLA-X-46-C BottleneckX.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 2, 1], [16, 32, 64, 64, 128, 256], block=BottleneckX, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla46x_c') return model
null
1,968
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class BottleneckX(nn.Module): expansion = 2 cardinality = 32 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(BottleneckX, self).__init__() cardinality = BottleneckX.cardinality # dim = int(math.floor(planes * (BottleneckV5.expansion / 64.0))) # bottle_planes = dim * cardinality bottle_planes = planes * cardinality // 32 self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation, groups=cardinality) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla60x_c(cfg, pretrained=None, **kwargs): # DLA-X-60-C BottleneckX.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 3, 1], [16, 32, 64, 64, 128, 256], block=BottleneckX, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla60x_c') return model
null
1,969
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class Bottleneck(nn.Module): expansion = 2 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(Bottleneck, self).__init__() expansion = Bottleneck.expansion bottle_planes = planes // expansion self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla60(cfg, pretrained=None, **kwargs): # DLA-60 Bottleneck.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 3, 1], [16, 32, 128, 256, 512, 1024], block=Bottleneck, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla60') return model
null
1,970
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class BottleneckX(nn.Module): expansion = 2 cardinality = 32 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(BottleneckX, self).__init__() cardinality = BottleneckX.cardinality # dim = int(math.floor(planes * (BottleneckV5.expansion / 64.0))) # bottle_planes = dim * cardinality bottle_planes = planes * cardinality // 32 self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation, groups=cardinality) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla60x(cfg, pretrained=None, **kwargs): # DLA-X-60 BottleneckX.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 3, 1], [16, 32, 128, 256, 512, 1024], block=BottleneckX, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla60x') return model
null
1,971
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class Bottleneck(nn.Module): expansion = 2 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(Bottleneck, self).__init__() expansion = Bottleneck.expansion bottle_planes = planes // expansion self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla102(cfg, pretrained=None, **kwargs): # DLA-102 Bottleneck.expansion = 2 model = DLA(cfg, [1, 1, 1, 3, 4, 1], [16, 32, 128, 256, 512, 1024], block=Bottleneck, residual_root=True, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla102') return model
null
1,972
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class BottleneckX(nn.Module): expansion = 2 cardinality = 32 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(BottleneckX, self).__init__() cardinality = BottleneckX.cardinality # dim = int(math.floor(planes * (BottleneckV5.expansion / 64.0))) # bottle_planes = dim * cardinality bottle_planes = planes * cardinality // 32 self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation, groups=cardinality) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla102x(cfg, pretrained=None, **kwargs): # DLA-X-102 BottleneckX.expansion = 2 model = DLA(cfg, [1, 1, 1, 3, 4, 1], [16, 32, 128, 256, 512, 1024], block=BottleneckX, residual_root=True, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla102x') return model
null
1,973
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class BottleneckX(nn.Module): expansion = 2 cardinality = 32 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(BottleneckX, self).__init__() cardinality = BottleneckX.cardinality # dim = int(math.floor(planes * (BottleneckV5.expansion / 64.0))) # bottle_planes = dim * cardinality bottle_planes = planes * cardinality // 32 self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation, groups=cardinality) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla102x2(cfg, pretrained=None, **kwargs): # DLA-X-102 64 BottleneckX.cardinality = 64 model = DLA(cfg, [1, 1, 1, 3, 4, 1], [16, 32, 128, 256, 512, 1024], block=BottleneckX, residual_root=True, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla102x2') return model
null
1,974
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class Bottleneck(nn.Module): def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): def forward(self, x, residual=None): class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): def _make_level(self, block, inplanes, planes, blocks, stride=1): def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): def forward(self, x): def dla169(cfg, pretrained=None, **kwargs): # DLA-169 Bottleneck.expansion = 2 model = DLA(cfg, [1, 1, 2, 3, 5, 1], [16, 32, 128, 256, 512, 1024], block=Bottleneck, residual_root=True, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla169') return model
null
1,975
import math from os.path import join import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone from .fpn import LastLevelP6, LastLevelP6P7 class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["level{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) # self.avgpool = nn.AvgPool2d(pool_size) # self.fc = nn.Conv2d(channels[-1], num_classes, kernel_size=1, # stride=1, padding=0, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) def _make_level(self, block, inplanes, planes, blocks, stride=1): downsample = None if stride != 1 or inplanes != planes: downsample = nn.Sequential( nn.MaxPool2d(stride, stride=stride), nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False), get_norm(self.cfg.MODEL.DLA.NORM, planes), ) layers = [] layers.append(block(inplanes, planes, stride, downsample=downsample)) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y[name] = x return y def dla34(cfg, pretrained=None, **kwargs): # DLA-34 model = DLA(cfg, [1, 1, 1, 2, 2, 1], [16, 32, 64, 128, 256, 512], block=BasicBlock, **kwargs) if pretrained is not None: model.load_pretrained_model(pretrained, 'dla34') return model class LastLevelP6P7(nn.Module): """ This module is used in RetinaNet and FCOS to generate extra layers, P6 and P7 from C5 or P5 feature. """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 2 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) p7 = self.p7(F.relu(p6)) return [p6, p7] class LastLevelP6(nn.Module): """ This module is used in FCOS to generate extra layers """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 1 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) for module in [self.p6]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) return [p6] The provided code snippet includes necessary dependencies for implementing the `build_fcos_dla_fpn_backbone` function. Write a Python function `def build_fcos_dla_fpn_backbone(cfg, input_shape: ShapeSpec)` to solve the following problem: Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. Here is the function: def build_fcos_dla_fpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ assert cfg.MODEL.BACKBONE.FREEZE_AT == -1, "Freezing layers does not be supported for DLA" depth_to_creator = {"DLA34": dla34} bottom_up = depth_to_creator[cfg.MODEL.DLA.CONV_BODY](cfg) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS top_levels = cfg.MODEL.FCOS.TOP_LEVELS in_channels_top = out_channels if top_levels == 2: top_block = LastLevelP6P7(in_channels_top, out_channels, "p5") elif top_levels == 1: top_block = LastLevelP6(in_channels_top, out_channels, "p5") elif top_levels == 0: top_block = None else: raise NotImplementedError() backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=top_block, fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
1,976
from torch import nn from torch.nn import BatchNorm2d from detectron2.layers import Conv2d from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone import Backbone def conv_bn(inp, oup, stride): return nn.Sequential( Conv2d(inp, oup, 3, stride, 1, bias=False), BatchNorm2d(oup), nn.ReLU6(inplace=True) )
null
1,977
from torch import nn from torch.nn import BatchNorm2d from detectron2.layers import Conv2d from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone import Backbone def conv_1x1_bn(inp, oup): return nn.Sequential( Conv2d(inp, oup, 1, 1, 0, bias=False), BatchNorm2d(oup), nn.ReLU6(inplace=True) )
null
1,978
from torch import nn import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN, build_resnet_backbone from detectron2.layers import ShapeSpec from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from .resnet_lpf import build_resnet_lpf_backbone from .resnet_interval import build_resnet_interval_backbone from .mobilenet import build_mnv2_backbone class LastLevelP6P7(nn.Module): """ This module is used in RetinaNet and FCOS to generate extra layers, P6 and P7 from C5 or P5 feature. """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 2 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) p7 = self.p7(F.relu(p6)) return [p6, p7] class LastLevelP6(nn.Module): """ This module is used in FCOS to generate extra layers """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 1 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) for module in [self.p6]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) return [p6] def build_resnet_lpf_backbone(cfg, input_shape): """ Create a ResNet instance from config. Returns: ResNet: a :class:`ResNet` instance. """ depth = cfg.MODEL.RESNETS.DEPTH out_features = cfg.MODEL.RESNETS.OUT_FEATURES num_blocks_per_stage = {50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3]}[depth] out_stage_idx = [{"res2": 0, "res3": 1, "res4": 2, "res5": 3}[f] for f in out_features] out_feature_channels = {"res2": 256, "res3": 512, "res4": 1024, "res5": 2048} out_feature_strides = {"res2": 4, "res3": 8, "res4": 16, "res5": 32} model = ResNetLPF(cfg, Bottleneck, num_blocks_per_stage, norm_layer=NaiveSyncBatchNorm, filter_size=3, pool_only=True, return_idx=out_stage_idx) model._out_features = out_features model._out_feature_channels = out_feature_channels model._out_feature_strides = out_feature_strides return model def build_resnet_interval_backbone(cfg, input_shape): """ Create a ResNet instance from config. Returns: ResNet: a :class:`ResNet` instance. """ # need registration of new blocks/stems? norm = cfg.MODEL.RESNETS.NORM stem = BasicStem( in_channels=input_shape.channels, out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS, norm=norm, ) freeze_at = cfg.MODEL.BACKBONE.FREEZE_AT if freeze_at >= 1: for p in stem.parameters(): p.requires_grad = False stem = FrozenBatchNorm2d.convert_frozen_batchnorm(stem) # fmt: off out_features = cfg.MODEL.RESNETS.OUT_FEATURES depth = cfg.MODEL.RESNETS.DEPTH num_groups = cfg.MODEL.RESNETS.NUM_GROUPS width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP bottleneck_channels = num_groups * width_per_group in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS stride_in_1x1 = cfg.MODEL.RESNETS.STRIDE_IN_1X1 res5_dilation = cfg.MODEL.RESNETS.RES5_DILATION deform_on_per_stage = cfg.MODEL.RESNETS.DEFORM_ON_PER_STAGE deform_modulated = cfg.MODEL.RESNETS.DEFORM_MODULATED deform_num_groups = cfg.MODEL.RESNETS.DEFORM_NUM_GROUPS deform_interval = cfg.MODEL.RESNETS.DEFORM_INTERVAL # fmt: on assert res5_dilation in {1, 2}, "res5_dilation cannot be {}.".format(res5_dilation) num_blocks_per_stage = {50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3]}[depth] stages = [] # Avoid creating variables without gradients # It consumes extra memory and may cause allreduce to fail out_stage_idx = [{"res2": 2, "res3": 3, "res4": 4, "res5": 5}[f] for f in out_features] max_stage_idx = max(out_stage_idx) for idx, stage_idx in enumerate(range(2, max_stage_idx + 1)): dilation = res5_dilation if stage_idx == 5 else 1 first_stride = 1 if idx == 0 or (stage_idx == 5 and dilation == 2) else 2 stage_kargs = { "num_blocks": num_blocks_per_stage[idx], "first_stride": first_stride, "in_channels": in_channels, "bottleneck_channels": bottleneck_channels, "out_channels": out_channels, "num_groups": num_groups, "norm": norm, "stride_in_1x1": stride_in_1x1, "dilation": dilation, } if deform_on_per_stage[idx]: stage_kargs["block_class"] = DeformBottleneckBlock stage_kargs["deform_modulated"] = deform_modulated stage_kargs["deform_num_groups"] = deform_num_groups stage_kargs["deform_interval"] = deform_interval else: stage_kargs["block_class"] = BottleneckBlock blocks = make_stage_intervals(**stage_kargs) in_channels = out_channels out_channels *= 2 bottleneck_channels *= 2 if freeze_at >= stage_idx: for block in blocks: block.freeze() stages.append(blocks) return ResNet(stem, stages, out_features=out_features) def build_mnv2_backbone(cfg, input_shape): """ Create a ResNet instance from config. Returns: ResNet: a :class:`ResNet` instance. """ out_features = cfg.MODEL.RESNETS.OUT_FEATURES out_feature_channels = {"res2": 24, "res3": 32, "res4": 96, "res5": 320} out_feature_strides = {"res2": 4, "res3": 8, "res4": 16, "res5": 32} model = MobileNetV2(cfg) model._out_features = out_features model._out_feature_channels = out_feature_channels model._out_feature_strides = out_feature_strides return model The provided code snippet includes necessary dependencies for implementing the `build_fcos_resnet_fpn_backbone` function. Write a Python function `def build_fcos_resnet_fpn_backbone(cfg, input_shape: ShapeSpec)` to solve the following problem: Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. Here is the function: def build_fcos_resnet_fpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ if cfg.MODEL.BACKBONE.ANTI_ALIAS: bottom_up = build_resnet_lpf_backbone(cfg, input_shape) elif cfg.MODEL.RESNETS.DEFORM_INTERVAL > 1: bottom_up = build_resnet_interval_backbone(cfg, input_shape) elif cfg.MODEL.MOBILENET: bottom_up = build_mnv2_backbone(cfg, input_shape) else: bottom_up = build_resnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS top_levels = cfg.MODEL.FCOS.TOP_LEVELS in_channels_top = out_channels if top_levels == 2: top_block = LastLevelP6P7(in_channels_top, out_channels, "p5") if top_levels == 1: top_block = LastLevelP6(in_channels_top, out_channels, "p5") elif top_levels == 0: top_block = None backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=top_block, fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
1,979
import torch import torch.nn.functional as F from torch import nn from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone import Backbone, build_resnet_backbone from detectron2.modeling import BACKBONE_REGISTRY from .mobilenet import build_mnv2_backbone def swish(x): return x * x.sigmoid()
null
1,980
import torch import torch.nn.functional as F from torch import nn from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone import Backbone, build_resnet_backbone from detectron2.modeling import BACKBONE_REGISTRY from .mobilenet import build_mnv2_backbone def split_name(name): for i, c in enumerate(name): if not c.isalpha(): return name[:i], int(name[i:]) raise ValueError()
null
1,981
import torch import torch.nn.functional as F from torch import nn from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone import Backbone, build_resnet_backbone from detectron2.modeling import BACKBONE_REGISTRY from .mobilenet import build_mnv2_backbone The provided code snippet includes necessary dependencies for implementing the `_assert_strides_are_log2_contiguous` function. Write a Python function `def _assert_strides_are_log2_contiguous(strides)` to solve the following problem: Assert that each stride is 2x times its preceding stride, i.e. "contiguous in log2". Here is the function: def _assert_strides_are_log2_contiguous(strides): """ Assert that each stride is 2x times its preceding stride, i.e. "contiguous in log2". """ for i, stride in enumerate(strides[1:], 1): assert stride == 2 * strides[i - 1], "Strides {} {} are not log2 contiguous".format( stride, strides[i - 1] )
Assert that each stride is 2x times its preceding stride, i.e. "contiguous in log2".
1,982
import torch import torch.nn.functional as F from torch import nn from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone import Backbone, build_resnet_backbone from detectron2.modeling import BACKBONE_REGISTRY from .mobilenet import build_mnv2_backbone class BiFPN(Backbone): """ This module implements Feature Pyramid Network. It creates pyramid features built on top of some input feature maps. """ def __init__( self, bottom_up, in_features, out_channels, num_top_levels, num_repeats, norm="" ): """ Args: bottom_up (Backbone): module representing the bottom up subnetwork. Must be a subclass of :class:`Backbone`. The multi-scale feature maps generated by the bottom up network, and listed in `in_features`, are used to generate FPN levels. in_features (list[str]): names of the input feature maps coming from the backbone to which FPN is attached. For example, if the backbone produces ["res2", "res3", "res4"], any *contiguous* sublist of these may be used; order must be from high to low resolution. out_channels (int): number of channels in the output feature maps. num_top_levels (int): the number of the top levels (p6 or p7). num_repeats (int): the number of repeats of BiFPN. norm (str): the normalization to use. """ super(BiFPN, self).__init__() assert isinstance(bottom_up, Backbone) # add extra feature levels (i.e., 6 and 7) self.bottom_up = BackboneWithTopLevels( bottom_up, out_channels, num_top_levels, norm ) bottom_up_output_shapes = self.bottom_up.output_shape() in_features = sorted(in_features, key=lambda x: split_name(x)[1]) self._size_divisibility = bottom_up_output_shapes[in_features[-1]].stride self.out_channels = out_channels self.min_level = split_name(in_features[0])[1] # add the names for top blocks prefix, last_suffix = split_name(in_features[-1]) for i in range(num_top_levels): in_features.append(prefix + str(last_suffix + i + 1)) self.in_features = in_features # generate output features self._out_features = ["p{}".format(split_name(name)[1]) for name in in_features] self._out_feature_strides = { out_name: bottom_up_output_shapes[in_name].stride for out_name, in_name in zip(self._out_features, in_features) } self._out_feature_channels = {k: out_channels for k in self._out_features} # build bifpn self.repeated_bifpn = nn.ModuleList() for i in range(num_repeats): if i == 0: in_channels_list = [ bottom_up_output_shapes[name].channels for name in in_features ] else: in_channels_list = [ self._out_feature_channels[name] for name in self._out_features ] self.repeated_bifpn.append(SingleBiFPN( in_channels_list, out_channels, norm )) def size_divisibility(self): return self._size_divisibility def forward(self, x): """ Args: input (dict[str->Tensor]): mapping feature map name (e.g., "p5") to feature map tensor for each feature level in high to low resolution order. Returns: dict[str->Tensor]: mapping from feature map name to FPN feature map tensor in high to low resolution order. Returned feature names follow the FPN paper convention: "p<stage>", where stage has stride = 2 ** stage e.g., ["n2", "n3", ..., "n6"]. """ bottom_up_features = self.bottom_up(x) feats = [bottom_up_features[f] for f in self.in_features] for bifpn in self.repeated_bifpn: feats = bifpn(feats) return dict(zip(self._out_features, feats)) def build_mnv2_backbone(cfg, input_shape): """ Create a ResNet instance from config. Returns: ResNet: a :class:`ResNet` instance. """ out_features = cfg.MODEL.RESNETS.OUT_FEATURES out_feature_channels = {"res2": 24, "res3": 32, "res4": 96, "res5": 320} out_feature_strides = {"res2": 4, "res3": 8, "res4": 16, "res5": 32} model = MobileNetV2(cfg) model._out_features = out_features model._out_feature_channels = out_feature_channels model._out_feature_strides = out_feature_strides return model The provided code snippet includes necessary dependencies for implementing the `build_fcos_resnet_bifpn_backbone` function. Write a Python function `def build_fcos_resnet_bifpn_backbone(cfg, input_shape: ShapeSpec)` to solve the following problem: Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. Here is the function: def build_fcos_resnet_bifpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ if cfg.MODEL.MOBILENET: bottom_up = build_mnv2_backbone(cfg, input_shape) else: bottom_up = build_resnet_backbone(cfg, input_shape) in_features = cfg.MODEL.BiFPN.IN_FEATURES out_channels = cfg.MODEL.BiFPN.OUT_CHANNELS num_repeats = cfg.MODEL.BiFPN.NUM_REPEATS top_levels = cfg.MODEL.FCOS.TOP_LEVELS backbone = BiFPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, num_top_levels=top_levels, num_repeats=num_repeats, norm=cfg.MODEL.BiFPN.NORM ) return backbone
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
1,983
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import Backbone from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.layers import ( Conv2d, DeformConv, FrozenBatchNorm2d, ShapeSpec, get_norm, ) from .fpn import LastLevelP6, LastLevelP6P7 _NORM = False The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=3, padding=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=3, padding=1): """3x3 convolution with padding""" return [ (f'{module_name}_{postfix}/conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False)), (f'{module_name}_{postfix}/norm', get_norm(_NORM, out_channels)), (f'{module_name}_{postfix}/relu', nn.ReLU(inplace=True)) ]
3x3 convolution with padding
1,984
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import Backbone from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.layers import ( Conv2d, DeformConv, FrozenBatchNorm2d, ShapeSpec, get_norm, ) from .fpn import LastLevelP6, LastLevelP6P7 _NORM = False The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=1, padding=0)` to solve the following problem: 1x1 convolution with padding Here is the function: def conv1x1(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=1, padding=0): """1x1 convolution with padding""" return [ (f'{module_name}_{postfix}/conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False)), (f'{module_name}_{postfix}/norm', get_norm(_NORM, out_channels)), (f'{module_name}_{postfix}/relu', nn.ReLU(inplace=True)) ]
1x1 convolution with padding
1,985
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import Backbone from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.layers import ( Conv2d, DeformConv, FrozenBatchNorm2d, ShapeSpec, get_norm, ) from .fpn import LastLevelP6, LastLevelP6P7 def build_vovnet_backbone(cfg, input_shape): """ Create a VoVNet instance from config. Returns: VoVNet: a :class:`VoVNet` instance. """ out_features = cfg.MODEL.VOVNET.OUT_FEATURES return VoVNet(cfg, input_shape.channels, out_features=out_features) The provided code snippet includes necessary dependencies for implementing the `build_vovnet_fpn_backbone` function. Write a Python function `def build_vovnet_fpn_backbone(cfg, input_shape: ShapeSpec)` to solve the following problem: Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. Here is the function: def build_vovnet_fpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_vovnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=LastLevelMaxPool(), fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
1,986
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import Backbone from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.layers import ( Conv2d, DeformConv, FrozenBatchNorm2d, ShapeSpec, get_norm, ) from .fpn import LastLevelP6, LastLevelP6P7 def build_vovnet_backbone(cfg, input_shape): """ Create a VoVNet instance from config. Returns: VoVNet: a :class:`VoVNet` instance. """ out_features = cfg.MODEL.VOVNET.OUT_FEATURES return VoVNet(cfg, input_shape.channels, out_features=out_features) class LastLevelP6P7(nn.Module): """ This module is used in RetinaNet and FCOS to generate extra layers, P6 and P7 from C5 or P5 feature. """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 2 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) p7 = self.p7(F.relu(p6)) return [p6, p7] class LastLevelP6(nn.Module): """ This module is used in FCOS to generate extra layers """ def __init__(self, in_channels, out_channels, in_features="res5"): super().__init__() self.num_levels = 1 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) for module in [self.p6]: weight_init.c2_xavier_fill(module) def forward(self, x): p6 = self.p6(x) return [p6] The provided code snippet includes necessary dependencies for implementing the `build_fcos_vovnet_fpn_backbone` function. Write a Python function `def build_fcos_vovnet_fpn_backbone(cfg, input_shape: ShapeSpec)` to solve the following problem: Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. Here is the function: def build_fcos_vovnet_fpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_vovnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS top_levels = cfg.MODEL.FCOS.TOP_LEVELS in_channels_top = out_channels if top_levels == 2: top_block = LastLevelP6P7(in_channels_top, out_channels, "p5") if top_levels == 1: top_block = LastLevelP6(in_channels_top, out_channels, "p5") elif top_levels == 0: top_block = None backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=top_block, fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
1,987
import sys import torch from torch import nn from detectron2.layers import cat from detectron2.modeling.poolers import ( ROIPooler, convert_boxes_to_pooler_format, assign_boxes_to_levels ) from adet.layers import BezierAlign from adet.structures import Beziers def _box_max_size(boxes): box = boxes.tensor max_size = torch.max(box[:, 2] - box[:, 0], box[:, 3] - box[:, 1]) return max_size def assign_boxes_to_levels_by_metric( box_lists, min_level, max_level, canonical_box_size, canonical_level, metric_fn=_box_max_size): """ Map each box in `box_lists` to a feature map level index and return the assignment vector. Args: box_lists (list[detectron2.structures.Boxes]): A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. min_level (int): Smallest feature map level index. The input is considered index 0, the output of stage 1 is index 1, and so. max_level (int): Largest feature map level index. canonical_box_size (int): A canonical box size in pixels (shorter side). canonical_level (int): The feature map level index on which a canonically-sized box should be placed. Returns: A tensor of length M, where M is the total number of boxes aggregated over all N batch images. The memory layout corresponds to the concatenation of boxes from all images. Each element is the feature map index, as an offset from `self.min_level`, for the corresponding box (so value i means the box is at `self.min_level + i`). """ eps = sys.float_info.epsilon box_sizes = cat([metric_fn(boxes) for boxes in box_lists]) # Eqn.(1) in FPN paper level_assignments = torch.floor( canonical_level + torch.log2(box_sizes / canonical_box_size + eps) ) level_assignments = torch.clamp(level_assignments, min=min_level, max=max_level) return level_assignments.to(torch.int64) - min_level def assign_boxes_to_levels_max( box_lists, min_level, max_level, canonical_box_size, canonical_level): return assign_boxes_to_levels_by_metric( box_lists, min_level, max_level, canonical_box_size, canonical_level, metric_fn=_box_max_size )
null
1,988
import sys import torch from torch import nn from detectron2.layers import cat from detectron2.modeling.poolers import ( ROIPooler, convert_boxes_to_pooler_format, assign_boxes_to_levels ) from adet.layers import BezierAlign from adet.structures import Beziers def _bezier_height(beziers): beziers = beziers.tensor # compute the distance between the first and last control point p1 = beziers[:, :2] p2 = beziers[:, 14:] height = ((p1 - p2) ** 2).sum(dim=1).sqrt() return height def assign_boxes_to_levels_by_metric( box_lists, min_level, max_level, canonical_box_size, canonical_level, metric_fn=_box_max_size): """ Map each box in `box_lists` to a feature map level index and return the assignment vector. Args: box_lists (list[detectron2.structures.Boxes]): A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. min_level (int): Smallest feature map level index. The input is considered index 0, the output of stage 1 is index 1, and so. max_level (int): Largest feature map level index. canonical_box_size (int): A canonical box size in pixels (shorter side). canonical_level (int): The feature map level index on which a canonically-sized box should be placed. Returns: A tensor of length M, where M is the total number of boxes aggregated over all N batch images. The memory layout corresponds to the concatenation of boxes from all images. Each element is the feature map index, as an offset from `self.min_level`, for the corresponding box (so value i means the box is at `self.min_level + i`). """ eps = sys.float_info.epsilon box_sizes = cat([metric_fn(boxes) for boxes in box_lists]) # Eqn.(1) in FPN paper level_assignments = torch.floor( canonical_level + torch.log2(box_sizes / canonical_box_size + eps) ) level_assignments = torch.clamp(level_assignments, min=min_level, max=max_level) return level_assignments.to(torch.int64) - min_level def assign_boxes_to_levels_bezier( box_lists, min_level, max_level, canonical_box_size, canonical_level): return assign_boxes_to_levels_by_metric( box_lists, min_level, max_level, canonical_box_size, canonical_level, metric_fn=_bezier_height )
null
1,989
import logging import torch import torch.nn.functional as F from detectron2.layers import cat from detectron2.structures import Instances, Boxes from adet.utils.comm import get_world_size from fvcore.nn import sigmoid_focal_loss_jit from adet.utils.comm import reduce_sum, compute_ious from adet.layers import ml_nms def compute_ctrness_targets(reg_targets): if len(reg_targets) == 0: return reg_targets.new_zeros(len(reg_targets)) left_right = reg_targets[:, [0, 2]] top_bottom = reg_targets[:, [1, 3]] ctrness = (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) * \ (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]) return torch.sqrt(ctrness) def reduce_sum(tensor): world_size = get_world_size() if world_size < 2: return tensor tensor = tensor.clone() dist.all_reduce(tensor, op=dist.ReduceOp.SUM) return tensor def compute_ious(pred, target): """ Args: pred: Nx4 predicted bounding boxes target: Nx4 target bounding boxes Both are in the form of FCOS prediction (l, t, r, b) """ pred_left = pred[:, 0] pred_top = pred[:, 1] pred_right = pred[:, 2] pred_bottom = pred[:, 3] target_left = target[:, 0] target_top = target[:, 1] target_right = target[:, 2] target_bottom = target[:, 3] target_aera = (target_left + target_right) * \ (target_top + target_bottom) pred_aera = (pred_left + pred_right) * \ (pred_top + pred_bottom) w_intersect = torch.min(pred_left, target_left) + \ torch.min(pred_right, target_right) h_intersect = torch.min(pred_bottom, target_bottom) + \ torch.min(pred_top, target_top) g_w_intersect = torch.max(pred_left, target_left) + \ torch.max(pred_right, target_right) g_h_intersect = torch.max(pred_bottom, target_bottom) + \ torch.max(pred_top, target_top) ac_uion = g_w_intersect * g_h_intersect area_intersect = w_intersect * h_intersect area_union = target_aera + pred_aera - area_intersect ious = (area_intersect + 1.0) / (area_union + 1.0) gious = ious - (ac_uion - area_union) / ac_uion return ious, gious def fcos_losses( labels, reg_targets, bezier_targets, logits_pred, reg_pred, bezier_pred, ctrness_pred, focal_loss_alpha, focal_loss_gamma, iou_loss, ): num_classes = logits_pred.size(1) labels = labels.flatten() pos_inds = torch.nonzero(labels != num_classes).squeeze(1) num_pos_local = pos_inds.numel() num_gpus = get_world_size() total_num_pos = reduce_sum(pos_inds.new_tensor([num_pos_local])).item() num_pos_avg = max(total_num_pos / num_gpus, 1.0) # prepare one_hot class_target = torch.zeros_like(logits_pred) class_target[pos_inds, labels[pos_inds]] = 1 class_loss = sigmoid_focal_loss_jit( logits_pred, class_target, alpha=focal_loss_alpha, gamma=focal_loss_gamma, reduction="sum", ) / num_pos_avg reg_pred = reg_pred[pos_inds] bezier_pred = bezier_pred[pos_inds] reg_targets = reg_targets[pos_inds] bezier_targets = bezier_targets[pos_inds] ctrness_pred = ctrness_pred[pos_inds] ious, gious = compute_ious(reg_pred, reg_targets) ctrness_targets = compute_ctrness_targets(reg_targets) ctrness_targets_sum = ctrness_targets.sum() loss_denorm = max(reduce_sum(ctrness_targets_sum).item() / num_gpus, 1e-6) if pos_inds.numel() > 0: reg_loss = iou_loss( ious, gious, ctrness_targets ) / loss_denorm ctrness_loss = F.binary_cross_entropy_with_logits( ctrness_pred, ctrness_targets, reduction="sum" ) / num_pos_avg else: reg_loss = reg_pred.sum() * 0 bezier_loss = bezier_pred.sum() * 0 ctrness_loss = ctrness_pred.sum() * 0 bezier_loss = F.smooth_l1_loss( bezier_pred, bezier_targets, reduction="none") bezier_loss = ((bezier_loss.mean(dim=-1) * ctrness_targets).sum() / loss_denorm) losses = { "loss_fcos_cls": class_loss, "loss_fcos_loc": reg_loss, "loss_fcos_ctr": ctrness_loss, "loss_fcos_bezier": bezier_loss, } return losses
null
1,990
import logging from typing import List import torch import torch.nn as nn import torch.nn.functional as F from detectron2.layers import cat from detectron2.structures import Instances, Boxes, pairwise_iou from detectron2.utils.comm import get_world_size from detectron2.modeling.matcher import Matcher from fvcore.nn import sigmoid_focal_loss_jit from adet.utils.comm import reduce_sum from adet.layers import ml_nms def compute_ctrness_targets(reg_targets): if len(reg_targets) == 0: return reg_targets.new_zeros(len(reg_targets)) left_right = reg_targets[:, [0, 2]] top_bottom = reg_targets[:, [1, 3]] ctrness = (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) * \ (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]) return torch.sqrt(ctrness)
null
1,991
import os import argparse import numpy as np from torch.utils.data import DataLoader from MaskLoader import MaskLoader from utils import ( IOUMetric, transform, inverse_transform, direct_sigmoid, inverse_sigmoid ) def parse_args(): parser = argparse.ArgumentParser(description='Evaluation for PCA Mask Encoding.') parser.add_argument('--root', default='datasets', type=str) parser.add_argument('--dataset', default='coco_2017_train', type=str) parser.add_argument('--matrix', default='coco/components/coco_2017_train' '_class_agnosticTrue_whitenTrue_sigmoidTrue_60.npz', type=str) # mask encoding params. parser.add_argument('--mask_size', default=28, type=int) parser.add_argument('--n_components', default=60, type=int) parser.add_argument('--class_agnostic', default=True, type=bool) parser.add_argument('--whiten', default=True, type=bool) parser.add_argument('--sigmoid', default=True, type=bool) parser.add_argument('--batch-size', default=1024, type=int) args = parser.parse_args() return args
null
1,992
import numpy as np The provided code snippet includes necessary dependencies for implementing the `direct_sigmoid` function. Write a Python function `def direct_sigmoid(x)` to solve the following problem: Apply the sigmoid operation. Here is the function: def direct_sigmoid(x): """Apply the sigmoid operation. """ y = 1./(1.+1./np.exp(x)) dy = y*(1-y) return y
Apply the sigmoid operation.
1,993
import numpy as np The provided code snippet includes necessary dependencies for implementing the `transform` function. Write a Python function `def transform(X, components_, explained_variance_, mean_=None, whiten=False)` to solve the following problem: Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X: array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_new : array-like, shape (n_samples, n_components) Here is the function: def transform(X, components_, explained_variance_, mean_=None, whiten=False): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X: array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_new : array-like, shape (n_samples, n_components) """ if mean_ is not None: X = X - mean_ X_transformed = np.dot(X, components_.T) if whiten: X_transformed /= np.sqrt(explained_variance_) return X_transformed
Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X: array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_new : array-like, shape (n_samples, n_components)
1,994
import numpy as np The provided code snippet includes necessary dependencies for implementing the `inverse_transform` function. Write a Python function `def inverse_transform(X, components_, explained_variance_, mean_=None, whiten=False)` to solve the following problem: Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_original array-like, shape (n_samples, n_features) Here is the function: def inverse_transform(X, components_, explained_variance_, mean_=None, whiten=False): """Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_original array-like, shape (n_samples, n_features) """ if whiten: X_transformed = np.dot(X, np.sqrt(explained_variance_[:, np.newaxis]) * components_) else: X_transformed = np.dot(X, components_) if mean_ is not None: X_transformed = X_transformed + mean_ return X_transformed
Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. components_: array-like, shape (n_components, n_features) mean_: array-like, shape (n_features,) explained_variance_: array-like, shape (n_components,) Variance explained by each of the selected components. whiten : bool, optional When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. Returns ------- X_original array-like, shape (n_samples, n_features)
1,995
import os import argparse import time import numpy as np import torch from torch.utils.data import DataLoader from sklearn.decomposition import IncrementalPCA from MaskLoader import MaskLoader from utils import inverse_sigmoid VALUE_MAX = 0.05 VALUE_MIN = 0.01 def inverse_sigmoid(x): """Apply the inverse sigmoid operation. y = -ln(1-x/x) """ y = -1 * np.log((1-x)/x) return y def mask_encoding(masks, n_components=60, class_agnostic=True, whiten=True, sigmoid=True, batch_size=1024): components_c = [] mean_c = [] ratio_c = [] explained_variance_c = [] if class_agnostic: if sigmoid: value_random = VALUE_MAX * np.random.rand(masks.shape[0], masks.shape[1]) value_random = np.maximum(value_random, VALUE_MIN) masks = np.where(masks > value_random, 1-value_random, value_random) masks = inverse_sigmoid(masks) pca = IncrementalPCA(n_components=n_components, copy=False, whiten=whiten, batch_size=batch_size) pca.fit(masks) components_c.append(pca.components_[np.newaxis, :, :]) mean_c.append(pca.mean_[np.newaxis, :]) ratio_c.append(pca.explained_variance_ratio_[np.newaxis, :]) explained_variance_c.append(pca.explained_variance_[np.newaxis, :]) ratio = pca.explained_variance_ratio_.sum() else: # TODO: We have not achieve the function in class-specific. raise NotImplemented return components_c, mean_c, ratio_c, explained_variance_c, ratio
null
1,996
import os import argparse import time import numpy as np import torch from torch.utils.data import DataLoader from sklearn.decomposition import IncrementalPCA from MaskLoader import MaskLoader from utils import inverse_sigmoid def parse_args(): parser = argparse.ArgumentParser(description='PCA Mask Encoding for local mask.') parser.add_argument('--root', default='datasets', type=str) parser.add_argument('--dataset', default='coco_2017_train', type=str) parser.add_argument('--output', default='coco/components', type=str) # mask encoding params. parser.add_argument('--mask_size', default=28, type=int) parser.add_argument('--n_components', default=60, type=int) parser.add_argument('--class_agnostic', default=True, type=bool) parser.add_argument('--whiten', default=True, type=bool) parser.add_argument('--sigmoid', default=True, type=bool) parser.add_argument('--batch-size', default=1024, type=int) args = parser.parse_args() return args
null
1,997
import math from typing import Dict, List import torch from torch import nn from torch.nn import functional as F from detectron2.layers import ShapeSpec, cat from detectron2.modeling import ROI_HEADS_REGISTRY from adet.layers import conv_with_kaiming_uniform from ..poolers import TopPooler from .attn_predictor import ATTPredictor class RNNPredictor(nn.Module): def __init__(self, cfg): super(RNNPredictor, self).__init__() # fmt: off self.voc_size = cfg.MODEL.BATEXT.VOC_SIZE conv_dim = cfg.MODEL.BATEXT.CONV_DIM roi_size = cfg.MODEL.BATEXT.POOLER_RESOLUTION # fmt: on self.convs = SeqConvs(conv_dim, roi_size) self.rnn = nn.LSTM(conv_dim, conv_dim, num_layers=1, bidirectional=True) self.clf = nn.Linear(conv_dim * 2, self.voc_size + 1) self.recognition_loss_fn = build_recognition_loss_fn() def forward(self, x, targets=None): # check empty if x.size(0) == 0: return x.new_zeros((x.size(2), 0, self.voc_size)) x = self.convs(x).squeeze(dim=2) # NxCxW x = x.permute(2, 0, 1) # WxNxC x, _ = self.rnn(x) preds = self.clf(x) if self.training: rec_loss = self.recognition_loss_fn(preds, targets, self.voc_size) return preds, rec_loss else: # (W, N, C) -> (N, W, C) _, preds = preds.permute(1, 0, 2).max(dim=-1) return preds, None class ATTPredictor(nn.Module): def __init__(self, cfg): super(ATTPredictor, self).__init__() in_channels = cfg.MODEL.BATEXT.CONV_DIM self.CRNN = CRNN(cfg, in_channels) self.criterion = torch.nn.NLLLoss() self.attention = Attention(cfg, in_channels) self.teach_prob = 0.5 def forward(self, rois, targets=None): rois = self.CRNN(rois) if self.training: target_variable = targets _init = torch.zeros((rois.size()[1], 1)).long() _init = torch.LongTensor(_init).to(rois.device) target_variable = torch.cat((_init, target_variable.long()), 1) target_variable = target_variable.to(rois.device) decoder_input = target_variable[:,0] # init decoder, from 0 decoder_hidden = self.attention.initHidden(rois.size()[1]).to(rois.device) # batch rois.size[1] loss = 0.0 for di in range(1, target_variable.shape[1]): decoder_output, decoder_hidden, decoder_attention = self.attention( # decoder_output (nbatch, ncls) decoder_input, decoder_hidden, rois) loss += self.criterion(decoder_output, target_variable[:,di]) teach_forcing = True if random.random() > self.teach_prob else False if teach_forcing: decoder_input = target_variable[:,di] # Teacher forcing else: topv, topi = decoder_output.data.topk(1) ni = topi.squeeze() decoder_input = ni return None, loss else: n = rois.size()[1] decodes = torch.zeros((n, self.attention.max_len)) prob = 1.0 decoder_input = torch.zeros(n).long().to(rois.device) decoder_hidden = self.attention.initHidden(n).to(rois.device) for di in range(self.attention.max_len): decoder_output, decoder_hidden, decoder_attention = self.attention( decoder_input, decoder_hidden, rois) probs = torch.exp(decoder_output) topv, topi = decoder_output.data.topk(1) ni = topi.squeeze() decoder_input = ni prob *= probs[:, ni] decodes[:, di] = decoder_input return decodes, None def build_recognizer(cfg, type): if type == 'rnn': return RNNPredictor(cfg) if type == 'attn': return ATTPredictor(cfg) else: raise NotImplementedError("{} is not a valid recognizer".format(type))
null
1,998
import math from typing import Dict, List import torch from torch import nn from torch.nn import functional as F from detectron2.layers import ShapeSpec, cat from detectron2.modeling import ROI_HEADS_REGISTRY from adet.layers import conv_with_kaiming_uniform from ..poolers import TopPooler from .attn_predictor import ATTPredictor def ctc_loss(preds, targets, voc_size): # prepare targets target_lengths = (targets != voc_size).long().sum(dim=-1) trimmed_targets = [t[:l] for t, l in zip(targets, target_lengths)] targets = torch.cat(trimmed_targets) x = F.log_softmax(preds, dim=-1) input_lengths = torch.full((x.size(1),), x.size(0), dtype=torch.long) return F.ctc_loss( x, targets, input_lengths, target_lengths, blank=voc_size, zero_infinity=True ) def build_recognition_loss_fn(rec_type="ctc"): if rec_type == "ctc": return ctc_loss else: raise NotImplementedError("{} is not a valid recognition loss".format(rec_type))
null
1,999
import logging from torch import nn from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling import ProposalNetwork, GeneralizedRCNN from detectron2.utils.events import get_event_storage from detectron2.utils.logger import log_first_n from detectron2.modeling.postprocessing import detector_postprocess as d2_postprocesss The provided code snippet includes necessary dependencies for implementing the `detector_postprocess` function. Write a Python function `def detector_postprocess(results, output_height, output_width, mask_threshold=0.5)` to solve the following problem: In addition to the post processing of detectron2, we add scalign for bezier control points. Here is the function: def detector_postprocess(results, output_height, output_width, mask_threshold=0.5): """ In addition to the post processing of detectron2, we add scalign for bezier control points. """ scale_x, scale_y = (output_width / results.image_size[1], output_height / results.image_size[0]) results = d2_postprocesss(results, output_height, output_width, mask_threshold) # scale bezier points if results.has("beziers"): beziers = results.beziers # scale and clip in place beziers[:, 0::2] *= scale_x beziers[:, 1::2] *= scale_y h, w = results.image_size beziers[:, 0].clamp_(min=0, max=w) beziers[:, 1].clamp_(min=0, max=h) beziers[:, 6].clamp_(min=0, max=w) beziers[:, 7].clamp_(min=0, max=h) beziers[:, 8].clamp_(min=0, max=w) beziers[:, 9].clamp_(min=0, max=h) beziers[:, 14].clamp_(min=0, max=w) beziers[:, 15].clamp_(min=0, max=h) return results
In addition to the post processing of detectron2, we add scalign for bezier control points.
2,000
import logging from torch import nn from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling import ProposalNetwork, GeneralizedRCNN from detectron2.utils.events import get_event_storage from detectron2.utils.logger import log_first_n from detectron2.modeling.postprocessing import detector_postprocess as d2_postprocesss def build_top_module(cfg): top_type = cfg.MODEL.TOP_MODULE.NAME if top_type == "conv": inp = cfg.MODEL.FPN.OUT_CHANNELS oup = cfg.MODEL.TOP_MODULE.DIM top_module = nn.Conv2d( inp, oup, kernel_size=3, stride=1, padding=1) else: top_module = None return top_module
null
2,001
import cv2 import torch import torch.nn.functional as F def imresize(img, size, return_scale=False, interpolation='bilinear', out=None): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple[int]): Target size (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanczos". out (ndarray): The output destination. Returns: tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`. """ h, w = img.shape[:2] resized_img = cv2.resize( img, size, dst=out, interpolation=interp_codes[interpolation]) if not return_scale: return resized_img else: w_scale = size[0] / w h_scale = size[1] / h return resized_img, w_scale, h_scale The provided code snippet includes necessary dependencies for implementing the `imresize_like` function. Write a Python function `def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear')` to solve the following problem: Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Same as :func:`resize`. Returns: tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`. Here is the function: def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'): """Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Same as :func:`resize`. Returns: tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`. """ h, w = dst_img.shape[:2] return imresize(img, (w, h), return_scale, interpolation)
Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Same as :func:`resize`. Returns: tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`.
2,002
import cv2 import torch import torch.nn.functional as F def imresize(img, size, return_scale=False, interpolation='bilinear', out=None): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple[int]): Target size (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanczos". out (ndarray): The output destination. Returns: tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`. """ h, w = img.shape[:2] resized_img = cv2.resize( img, size, dst=out, interpolation=interp_codes[interpolation]) if not return_scale: return resized_img else: w_scale = size[0] / w h_scale = size[1] / h return resized_img, w_scale, h_scale def rescale_size(old_size, scale, return_scale=False): """Calculate the new size to be rescaled to. Args: old_size (tuple[int]): The old size (w, h) of image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image size. Returns: tuple[int]: The new rescaled image size. """ w, h = old_size if isinstance(scale, (float, int)): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') scale_factor = scale elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w)) else: raise TypeError( f'Scale must be a number or tuple of int, but got {type(scale)}') new_size = _scale_size((w, h), scale_factor) if return_scale: return new_size, scale_factor else: return new_size The provided code snippet includes necessary dependencies for implementing the `imrescale` function. Write a Python function `def imrescale(img, scale, return_scale=False, interpolation='bilinear')` to solve the following problem: Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image. interpolation (str): Same as :func:`resize`. Returns: ndarray: The rescaled image. Here is the function: def imrescale(img, scale, return_scale=False, interpolation='bilinear'): """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image. interpolation (str): Same as :func:`resize`. Returns: ndarray: The rescaled image. """ h, w = img.shape[:2] new_size, scale_factor = rescale_size((w, h), scale, return_scale=True) rescaled_img = imresize(img, new_size, interpolation=interpolation) if return_scale: return rescaled_img, scale_factor else: return rescaled_img
Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image. interpolation (str): Same as :func:`resize`. Returns: ndarray: The rescaled image.
2,003
import cv2 import torch import torch.nn.functional as F def center_of_mass(bitmasks): _, h, w = bitmasks.size() ys = torch.arange(0, h, dtype=torch.float32, device=bitmasks.device) xs = torch.arange(0, w, dtype=torch.float32, device=bitmasks.device) m00 = bitmasks.sum(dim=-1).sum(dim=-1).clamp(min=1e-6) m10 = (bitmasks * xs).sum(dim=-1).sum(dim=-1) m01 = (bitmasks * ys[:, None]).sum(dim=-1).sum(dim=-1) center_x = m10 / m00 center_y = m01 / m00 return center_x, center_y
null
2,004
import cv2 import torch import torch.nn.functional as F def point_nms(heat, kernel=2): # kernel must be 2 hmax = F.max_pool2d(heat, (kernel, kernel), stride=1, padding=1) keep = (hmax[:, :, :-1, :-1] == heat).float() return heat * keep
null
2,005
import cv2 import torch import torch.nn.functional as F def matrix_nms(cate_labels, seg_masks, sum_masks, cate_scores, sigma=2.0, kernel='gaussian'): n_samples = len(cate_labels) if n_samples == 0: return [] seg_masks = seg_masks.reshape(n_samples, -1).float() # inter. inter_matrix = torch.mm(seg_masks, seg_masks.transpose(1, 0)) # union. sum_masks_x = sum_masks.expand(n_samples, n_samples) # iou. iou_matrix = (inter_matrix / (sum_masks_x + sum_masks_x.transpose(1, 0) - inter_matrix)).triu(diagonal=1) # label_specific matrix. cate_labels_x = cate_labels.expand(n_samples, n_samples) label_matrix = (cate_labels_x == cate_labels_x.transpose(1, 0)).float().triu(diagonal=1) # IoU compensation compensate_iou, _ = (iou_matrix * label_matrix).max(0) compensate_iou = compensate_iou.expand(n_samples, n_samples).transpose(1, 0) # IoU decay / soft nms delay_iou = iou_matrix * label_matrix # matrix nms if kernel == 'linear': delay_matrix = (1 - delay_iou) / (1 - compensate_iou) delay_coefficient, _ = delay_matrix.min(0) else: delay_matrix = torch.exp(-1 * sigma * (delay_iou ** 2)) compensate_matrix = torch.exp(-1 * sigma * (compensate_iou ** 2)) delay_coefficient, _ = (delay_matrix / compensate_matrix).min(0) # update the score. cate_scores_update = cate_scores * delay_coefficient return cate_scores_update
null
2,006
import cv2 import torch import torch.nn.functional as F def mask_nms(cate_labels, seg_masks, sum_masks, cate_scores, nms_thr=0.5): n_samples = len(cate_scores) if n_samples == 0: return [] keep = seg_masks.new_ones(cate_scores.shape) seg_masks = seg_masks.float() for i in range(n_samples - 1): if not keep[i]: continue mask_i = seg_masks[i] label_i = cate_labels[i] for j in range(i + 1, n_samples, 1): if not keep[j]: continue mask_j = seg_masks[j] label_j = cate_labels[j] if label_i != label_j: continue # overlaps inter = (mask_i * mask_j).sum() union = sum_masks[i] + sum_masks[j] - inter if union > 0: if inter / union > nms_thr: keep[j] = False else: keep[j] = False return keep
null
2,007
import torch from torch import nn import torch.nn.functional as F from fvcore.nn import sigmoid_focal_loss_jit def dice_loss(input, target): input = input.contiguous().view(input.size()[0], -1) target = target.contiguous().view(target.size()[0], -1).float() a = torch.sum(input * target, 1) b = torch.sum(input * input, 1) + 0.001 c = torch.sum(target * target, 1) + 0.001 d = (2 * a) / (b + c) return 1 - d
null
2,008
import torch from torch import nn import torch.nn.functional as F from fvcore.nn import sigmoid_focal_loss_jit def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Avarage factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ # if weight is specified, apply element-wise weight if weight is not None: loss = loss * weight # if avg_factor is not specified, just reduce the loss if avg_factor is None: loss = reduce_loss(loss, reduction) else: # if reduction is mean, then average the loss by avg_factor if reduction == 'mean': loss = loss.sum() / avg_factor # if reduction is 'none', then do nothing, otherwise raise an error elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None): # Function.apply does not accept keyword arguments, so the decorator # "weighted_loss" is not applicable loss = sigmoid_focal_loss_jit(pred, target, gamma=gamma, alpha=alpha) if weight is not None: if weight.shape != loss.shape: if weight.size(0) == loss.size(0): # For most cases, weight is of shape (num_priors, ), # which means it does not have the second axis num_class weight = weight.view(-1, 1) else: # Sometimes, weight per anchor per class is also needed. e.g. # in FSAF. But it may be flattened of shape # (num_priors x num_class, ), while loss is still of shape # (num_priors, num_class). assert weight.numel() == loss.numel() weight = weight.view(loss.size(0), -1) assert weight.ndim == loss.ndim loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss
null
2,009
import logging import torch from torch import nn import torch.nn.functional as F from detectron2.layers import cat from detectron2.structures import Instances, Boxes from detectron2.utils.comm import get_world_size from fvcore.nn import sigmoid_focal_loss_jit from adet.utils.comm import reduce_sum, reduce_mean, compute_ious from adet.layers import ml_nms, IOULoss def compute_ctrness_targets(reg_targets): if len(reg_targets) == 0: return reg_targets.new_zeros(len(reg_targets)) left_right = reg_targets[:, [0, 2]] top_bottom = reg_targets[:, [1, 3]] ctrness = (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) * \ (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]) return torch.sqrt(ctrness)
null
2,010
from typing import Dict import math import torch from torch import nn from fvcore.nn import sigmoid_focal_loss_jit from detectron2.layers import ShapeSpec from adet.layers import conv_with_kaiming_uniform from adet.utils.comm import aligned_bilinear class MaskBranch(nn.Module): def __init__(self, cfg, input_shape: Dict[str, ShapeSpec]): super().__init__() self.in_features = cfg.MODEL.CONDINST.MASK_BRANCH.IN_FEATURES self.sem_loss_on = cfg.MODEL.CONDINST.MASK_BRANCH.SEMANTIC_LOSS_ON self.num_outputs = cfg.MODEL.CONDINST.MASK_BRANCH.OUT_CHANNELS norm = cfg.MODEL.CONDINST.MASK_BRANCH.NORM num_convs = cfg.MODEL.CONDINST.MASK_BRANCH.NUM_CONVS channels = cfg.MODEL.CONDINST.MASK_BRANCH.CHANNELS self.out_stride = input_shape[self.in_features[0]].stride feature_channels = {k: v.channels for k, v in input_shape.items()} conv_block = conv_with_kaiming_uniform(norm, activation=True) self.refine = nn.ModuleList() for in_feature in self.in_features: self.refine.append(conv_block( feature_channels[in_feature], channels, 3, 1 )) tower = [] for i in range(num_convs): tower.append(conv_block( channels, channels, 3, 1 )) tower.append(nn.Conv2d( channels, max(self.num_outputs, 1), 1 )) self.add_module('tower', nn.Sequential(*tower)) if self.sem_loss_on: num_classes = cfg.MODEL.FCOS.NUM_CLASSES self.focal_loss_alpha = cfg.MODEL.FCOS.LOSS_ALPHA self.focal_loss_gamma = cfg.MODEL.FCOS.LOSS_GAMMA in_channels = feature_channels[self.in_features[0]] self.seg_head = nn.Sequential( conv_block(in_channels, channels, kernel_size=3, stride=1), conv_block(channels, channels, kernel_size=3, stride=1) ) self.logits = nn.Conv2d(channels, num_classes, kernel_size=1, stride=1) prior_prob = cfg.MODEL.FCOS.PRIOR_PROB bias_value = -math.log((1 - prior_prob) / prior_prob) torch.nn.init.constant_(self.logits.bias, bias_value) def forward(self, features, gt_instances=None): for i, f in enumerate(self.in_features): if i == 0: x = self.refine[i](features[f]) else: x_p = self.refine[i](features[f]) target_h, target_w = x.size()[2:] h, w = x_p.size()[2:] assert target_h % h == 0 assert target_w % w == 0 factor_h, factor_w = target_h // h, target_w // w assert factor_h == factor_w x_p = aligned_bilinear(x_p, factor_h) x = x + x_p mask_feats = self.tower(x) if self.num_outputs == 0: mask_feats = mask_feats[:, :self.num_outputs] losses = {} # auxiliary thing semantic loss if self.training and self.sem_loss_on: logits_pred = self.logits(self.seg_head( features[self.in_features[0]] )) # compute semantic targets semantic_targets = [] for per_im_gt in gt_instances: h, w = per_im_gt.gt_bitmasks_full.size()[-2:] areas = per_im_gt.gt_bitmasks_full.sum(dim=-1).sum(dim=-1) areas = areas[:, None, None].repeat(1, h, w) areas[per_im_gt.gt_bitmasks_full == 0] = INF areas = areas.permute(1, 2, 0).reshape(h * w, -1) min_areas, inds = areas.min(dim=1) per_im_sematic_targets = per_im_gt.gt_classes[inds] + 1 per_im_sematic_targets[min_areas == INF] = 0 per_im_sematic_targets = per_im_sematic_targets.reshape(h, w) semantic_targets.append(per_im_sematic_targets) semantic_targets = torch.stack(semantic_targets, dim=0) # resize target to reduce memory semantic_targets = semantic_targets[ :, None, self.out_stride // 2::self.out_stride, self.out_stride // 2::self.out_stride ] # prepare one-hot targets num_classes = logits_pred.size(1) class_range = torch.arange( num_classes, dtype=logits_pred.dtype, device=logits_pred.device )[:, None, None] class_range = class_range + 1 one_hot = (semantic_targets == class_range).float() num_pos = (one_hot > 0).sum().float().clamp(min=1.0) loss_sem = sigmoid_focal_loss_jit( logits_pred, one_hot, alpha=self.focal_loss_alpha, gamma=self.focal_loss_gamma, reduction="sum", ) / num_pos losses['loss_sem'] = loss_sem return mask_feats, losses def build_mask_branch(cfg, input_shape): return MaskBranch(cfg, input_shape)
null
2,011
import torch from torch.nn import functional as F from torch import nn from adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x, target): eps = 1e-5 n_inst = x.size(0) x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) intersection = (x * target).sum(dim=1) union = (x ** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) + eps loss = 1. - (2 * intersection / union) return loss def compute_project_term(mask_scores, gt_bitmasks): mask_losses_y = dice_coefficient( mask_scores.max(dim=2, keepdim=True)[0], gt_bitmasks.max(dim=2, keepdim=True)[0] ) mask_losses_x = dice_coefficient( mask_scores.max(dim=3, keepdim=True)[0], gt_bitmasks.max(dim=3, keepdim=True)[0] ) return (mask_losses_x + mask_losses_y).mean()
null
2,012
import torch from torch.nn import functional as F from torch import nn from adet.utils.comm import compute_locations, aligned_bilinear def unfold_wo_center(x, kernel_size, dilation): def compute_pairwise_term(mask_logits, pairwise_size, pairwise_dilation): assert mask_logits.dim() == 4 log_fg_prob = F.logsigmoid(mask_logits) log_bg_prob = F.logsigmoid(-mask_logits) from adet.modeling.condinst.condinst import unfold_wo_center log_fg_prob_unfold = unfold_wo_center( log_fg_prob, kernel_size=pairwise_size, dilation=pairwise_dilation ) log_bg_prob_unfold = unfold_wo_center( log_bg_prob, kernel_size=pairwise_size, dilation=pairwise_dilation ) # the probability of making the same prediction = p_i * p_j + (1 - p_i) * (1 - p_j) # we compute the the probability in log space to avoid numerical instability log_same_fg_prob = log_fg_prob[:, :, None] + log_fg_prob_unfold log_same_bg_prob = log_bg_prob[:, :, None] + log_bg_prob_unfold max_ = torch.max(log_same_fg_prob, log_same_bg_prob) log_same_prob = torch.log( torch.exp(log_same_fg_prob - max_) + torch.exp(log_same_bg_prob - max_) ) + max_ # loss = -log(prob) return -log_same_prob[:, 0]
null
2,013
import torch from torch.nn import functional as F from torch import nn from adet.utils.comm import compute_locations, aligned_bilinear def parse_dynamic_params(params, channels, weight_nums, bias_nums): assert params.dim() == 2 assert len(weight_nums) == len(bias_nums) assert params.size(1) == sum(weight_nums) + sum(bias_nums) num_insts = params.size(0) num_layers = len(weight_nums) params_splits = list(torch.split_with_sizes( params, weight_nums + bias_nums, dim=1 )) weight_splits = params_splits[:num_layers] bias_splits = params_splits[num_layers:] for l in range(num_layers): if l < num_layers - 1: # out_channels x in_channels x 1 x 1 weight_splits[l] = weight_splits[l].reshape(num_insts * channels, -1, 1, 1) bias_splits[l] = bias_splits[l].reshape(num_insts * channels) else: # out_channels x in_channels x 1 x 1 weight_splits[l] = weight_splits[l].reshape(num_insts * 1, -1, 1, 1) bias_splits[l] = bias_splits[l].reshape(num_insts) return weight_splits, bias_splits
null
2,014
import torch from torch.nn import functional as F from torch import nn from adet.utils.comm import compute_locations, aligned_bilinear class DynamicMaskHead(nn.Module): def __init__(self, cfg): def mask_heads_forward(self, features, weights, biases, num_insts): def mask_heads_forward_with_coords( self, mask_feats, mask_feat_stride, instances ): def __call__(self, mask_feats, mask_feat_stride, pred_instances, gt_instances=None): def build_dynamic_mask_head(cfg): return DynamicMaskHead(cfg)
null
2,015
import logging from skimage import color import torch from torch import nn import torch.nn.functional as F from detectron2.structures import ImageList from detectron2.modeling.proposal_generator import build_proposal_generator from detectron2.modeling.backbone import build_backbone from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.structures.instances import Instances from detectron2.structures.masks import PolygonMasks, polygons_to_bitmask from .dynamic_mask_head import build_dynamic_mask_head from .mask_branch import build_mask_branch from adet.utils.comm import aligned_bilinear def unfold_wo_center(x, kernel_size, dilation): assert x.dim() == 4 assert kernel_size % 2 == 1 # using SAME padding padding = (kernel_size + (dilation - 1) * (kernel_size - 1)) // 2 unfolded_x = F.unfold( x, kernel_size=kernel_size, padding=padding, dilation=dilation ) unfolded_x = unfolded_x.reshape( x.size(0), x.size(1), -1, x.size(2), x.size(3) ) # remove the center pixels size = kernel_size ** 2 unfolded_x = torch.cat(( unfolded_x[:, :, :size // 2], unfolded_x[:, :, size // 2 + 1:] ), dim=2) return unfolded_x def get_images_color_similarity(images, image_masks, kernel_size, dilation): assert images.dim() == 4 assert images.size(0) == 1 unfolded_images = unfold_wo_center( images, kernel_size=kernel_size, dilation=dilation ) diff = images[:, :, None] - unfolded_images similarity = torch.exp(-torch.norm(diff, dim=1) * 0.5) unfolded_weights = unfold_wo_center( image_masks[None, None], kernel_size=kernel_size, dilation=dilation ) unfolded_weights = torch.max(unfolded_weights, dim=1)[0] return similarity * unfolded_weights
null
2,016
from collections import namedtuple from adet.evaluation import rrc_evaluation_funcs_ic15 as rrc_evaluation_funcs import importlib import sys import math from rapidfuzz import string_metric WORD_SPOTTING =True def default_evaluation_params(): """ default_evaluation_params: Default parameters to use for the validation and evaluation. """ global WORD_SPOTTING return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :WORD_SPOTTING, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'res_img_([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. MAP and MAR will be calculated, 'SPECIAL_CHARACTERS':'!?.:,*"()·[]/\'', 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True } def validate_data(gtFilePath, submFilePath, evaluationParams): """ Method validate_data: validates that all files in the results folder are correct (have the correct name contents). Validates also that there are no missing files in the folder. If some error detected, the method raises the error """ gt = rrc_evaluation_funcs.load_zip_file(gtFilePath, evaluationParams['GT_SAMPLE_NAME_2_ID']) subm = rrc_evaluation_funcs.load_zip_file(submFilePath, evaluationParams['DET_SAMPLE_NAME_2_ID'], True) #Validate format of GroundTruth for k in gt: rrc_evaluation_funcs.validate_lines_in_file(k,gt[k],evaluationParams['CRLF'],evaluationParams['LTRB'],True) #Validate format of results for k in subm: if (k in gt) == False : raise Exception("The sample %s not present in GT" %k) rrc_evaluation_funcs.validate_lines_in_file(k,subm[k],evaluationParams['CRLF'],evaluationParams['LTRB'],True,evaluationParams['CONFIDENCES']) def evaluate_method(gtFilePath, submFilePath, evaluationParams): """ Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 } """ for module,alias in evaluation_imports().items(): globals()[alias] = importlib.import_module(module) def polygon_from_points(points,correctOffset=False): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ if correctOffset: #this will substract 1 from the coordinates that correspond to the xmax and ymax points[2] -= 1 points[4] -= 1 points[5] -= 1 points[7] -= 1 resBoxes=np.empty([1,8],dtype='int32') resBoxes[0,0]=int(points[0]) resBoxes[0,4]=int(points[1]) resBoxes[0,1]=int(points[2]) resBoxes[0,5]=int(points[3]) resBoxes[0,2]=int(points[4]) resBoxes[0,6]=int(points[5]) resBoxes[0,3]=int(points[6]) resBoxes[0,7]=int(points[7]) pointMat = resBoxes[0].reshape([2,4]).T return plg.Polygon( pointMat) def rectangle_to_polygon(rect): resBoxes=np.empty([1,8],dtype='int32') resBoxes[0,0]=int(rect.xmin) resBoxes[0,4]=int(rect.ymax) resBoxes[0,1]=int(rect.xmin) resBoxes[0,5]=int(rect.ymin) resBoxes[0,2]=int(rect.xmax) resBoxes[0,6]=int(rect.ymin) resBoxes[0,3]=int(rect.xmax) resBoxes[0,7]=int(rect.ymax) pointMat = resBoxes[0].reshape([2,4]).T return plg.Polygon( pointMat) def rectangle_to_points(rect): points = [int(rect.xmin), int(rect.ymax), int(rect.xmax), int(rect.ymax), int(rect.xmax), int(rect.ymin), int(rect.xmin), int(rect.ymin)] return points def get_union(pD,pG): areaA = pD.area(); areaB = pG.area(); return areaA + areaB - get_intersection(pD, pG); def get_intersection_over_union(pD,pG): try: return get_intersection(pD, pG) / get_union(pD, pG); except: return 0 def get_intersection(pD,pG): pInt = pD & pG if len(pInt) == 0: return 0 return pInt.area() def compute_ap(confList, matchList,numGtCare): correct = 0 AP = 0 if len(confList)>0: confList = np.array(confList) matchList = np.array(matchList) sorted_ind = np.argsort(-confList) confList = confList[sorted_ind] matchList = matchList[sorted_ind] for n in range(len(confList)): match = matchList[n] if match: correct += 1 AP += float(correct)/(n + 1) if numGtCare>0: AP /= numGtCare return AP def transcription_match(transGt,transDet,specialCharacters='!?.:,*"()·[]/\'',onlyRemoveFirstLastCharacterGT=True): if onlyRemoveFirstLastCharacterGT: #special characters in GT are allowed only at initial or final position if (transGt==transDet): return True if specialCharacters.find(transGt[0])>-1: if transGt[1:]==transDet: return True if specialCharacters.find(transGt[-1])>-1: if transGt[0:len(transGt)-1]==transDet: return True if specialCharacters.find(transGt[0])>-1 and specialCharacters.find(transGt[-1])>-1: if transGt[1:len(transGt)-1]==transDet: return True return False else: #Special characters are removed from the begining and the end of both Detection and GroundTruth while len(transGt)>0 and specialCharacters.find(transGt[0])>-1: transGt = transGt[1:] while len(transDet)>0 and specialCharacters.find(transDet[0])>-1: transDet = transDet[1:] while len(transGt)>0 and specialCharacters.find(transGt[-1])>-1 : transGt = transGt[0:len(transGt)-1] while len(transDet)>0 and specialCharacters.find(transDet[-1])>-1: transDet = transDet[0:len(transDet)-1] return transGt == transDet def include_in_dictionary(transcription): """ Function used in Word Spotting that finds if the Ground Truth transcription meets the rules to enter into the dictionary. If not, the transcription will be cared as don't care """ #special case 's at final if transcription[len(transcription)-2:]=="'s" or transcription[len(transcription)-2:]=="'S": transcription = transcription[0:len(transcription)-2] #hypens at init or final of the word transcription = transcription.strip('-'); specialCharacters = "'!?.:,*\"()·[]/"; for character in specialCharacters: transcription = transcription.replace(character,' ') transcription = transcription.strip() if len(transcription) != len(transcription.replace(" ","")) : return False; if len(transcription) < evaluationParams['MIN_LENGTH_CARE_WORD']: return False; notAllowed = "×÷·"; range1 = [ ord(u'a'), ord(u'z') ] range2 = [ ord(u'A'), ord(u'Z') ] range3 = [ ord(u'À'), ord(u'ƿ') ] range4 = [ ord(u'DŽ'), ord(u'ɿ') ] range5 = [ ord(u'Ά'), ord(u'Ͽ') ] range6 = [ ord(u'-'), ord(u'-') ] for char in transcription : charCode = ord(char) if(notAllowed.find(char) != -1): return False valid = ( charCode>=range1[0] and charCode<=range1[1] ) or ( charCode>=range2[0] and charCode<=range2[1] ) or ( charCode>=range3[0] and charCode<=range3[1] ) or ( charCode>=range4[0] and charCode<=range4[1] ) or ( charCode>=range5[0] and charCode<=range5[1] ) or ( charCode>=range6[0] and charCode<=range6[1] ) if valid == False: return False return True def include_in_dictionary_transcription(transcription): """ Function applied to the Ground Truth transcriptions used in Word Spotting. It removes special characters or terminations """ #special case 's at final if transcription[len(transcription)-2:]=="'s" or transcription[len(transcription)-2:]=="'S": transcription = transcription[0:len(transcription)-2] #hypens at init or final of the word transcription = transcription.strip('-'); specialCharacters = "'!?.:,*\"()·[]/"; for character in specialCharacters: transcription = transcription.replace(character,' ') transcription = transcription.strip() return transcription perSampleMetrics = {} matchedSum = 0 det_only_matchedSum = 0 Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax') gt = rrc_evaluation_funcs.load_zip_file(gtFilePath,evaluationParams['GT_SAMPLE_NAME_2_ID']) subm = rrc_evaluation_funcs.load_zip_file(submFilePath,evaluationParams['DET_SAMPLE_NAME_2_ID'],True) numGlobalCareGt = 0; numGlobalCareDet = 0; det_only_numGlobalCareGt = 0; det_only_numGlobalCareDet = 0; arrGlobalConfidences = []; arrGlobalMatches = []; for resFile in gt: gtFile = rrc_evaluation_funcs.decode_utf8(gt[resFile]) if (gtFile is None) : raise Exception("The file %s is not UTF-8" %resFile) recall = 0 precision = 0 hmean = 0 detCorrect = 0 detOnlyCorrect = 0 iouMat = np.empty([1,1]) gtPols = [] detPols = [] gtTrans = [] detTrans = [] gtPolPoints = [] detPolPoints = [] gtDontCarePolsNum = [] #Array of Ground Truth Polygons' keys marked as don't Care det_only_gtDontCarePolsNum = [] detDontCarePolsNum = [] #Array of Detected Polygons' matched with a don't Care GT det_only_detDontCarePolsNum = [] detMatchedNums = [] pairs = [] arrSampleConfidences = []; arrSampleMatch = []; sampleAP = 0; evaluationLog = "" pointsList,_,transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(gtFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,False) for n in range(len(pointsList)): points = pointsList[n] transcription = transcriptionsList[n] # dontCare = transcription == "###" det_only_dontCare = dontCare = transcription == "###" # ctw1500 and total_text gt have been modified to the same format. if evaluationParams['LTRB']: gtRect = Rectangle(*points) gtPol = rectangle_to_polygon(gtRect) else: gtPol = polygon_from_points(points) gtPols.append(gtPol) gtPolPoints.append(points) #On word spotting we will filter some transcriptions with special characters if evaluationParams['WORD_SPOTTING'] : if dontCare == False : if include_in_dictionary(transcription) == False : dontCare = True else: transcription = include_in_dictionary_transcription(transcription) gtTrans.append(transcription) if dontCare: gtDontCarePolsNum.append( len(gtPols)-1 ) if det_only_dontCare: det_only_gtDontCarePolsNum.append( len(gtPols)-1 ) evaluationLog += "GT polygons: " + str(len(gtPols)) + (" (" + str(len(gtDontCarePolsNum)) + " don't care)\n" if len(gtDontCarePolsNum)>0 else "\n") if resFile in subm: detFile = rrc_evaluation_funcs.decode_utf8(subm[resFile]) pointsList,confidencesList,transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(detFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,evaluationParams['CONFIDENCES']) for n in range(len(pointsList)): points = pointsList[n] transcription = transcriptionsList[n] if evaluationParams['LTRB']: detRect = Rectangle(*points) detPol = rectangle_to_polygon(detRect) else: detPol = polygon_from_points(points) detPols.append(detPol) detPolPoints.append(points) detTrans.append(transcription) if len(gtDontCarePolsNum)>0 : for dontCarePol in gtDontCarePolsNum: dontCarePol = gtPols[dontCarePol] intersected_area = get_intersection(dontCarePol,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT'] ): detDontCarePolsNum.append( len(detPols)-1 ) break if len(det_only_gtDontCarePolsNum)>0 : for dontCarePol in det_only_gtDontCarePolsNum: dontCarePol = gtPols[dontCarePol] intersected_area = get_intersection(dontCarePol,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT'] ): det_only_detDontCarePolsNum.append( len(detPols)-1 ) break evaluationLog += "DET polygons: " + str(len(detPols)) + (" (" + str(len(detDontCarePolsNum)) + " don't care)\n" if len(detDontCarePolsNum)>0 else "\n") if len(gtPols)>0 and len(detPols)>0: #Calculate IoU and precision matrixs outputShape=[len(gtPols),len(detPols)] iouMat = np.empty(outputShape) gtRectMat = np.zeros(len(gtPols),np.int8) detRectMat = np.zeros(len(detPols),np.int8) det_only_gtRectMat = np.zeros(len(gtPols),np.int8) det_only_detRectMat = np.zeros(len(detPols),np.int8) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): pG = gtPols[gtNum] pD = detPols[detNum] iouMat[gtNum,detNum] = get_intersection_over_union(pD,pG) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): if gtRectMat[gtNum] == 0 and detRectMat[detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum : if iouMat[gtNum,detNum]>evaluationParams['IOU_CONSTRAINT']: gtRectMat[gtNum] = 1 detRectMat[detNum] = 1 #detection matched only if transcription is equal if evaluationParams['WORD_SPOTTING']: correct = gtTrans[gtNum].upper() == detTrans[detNum].upper() else: correct = transcription_match(gtTrans[gtNum].upper(),detTrans[detNum].upper(),evaluationParams['SPECIAL_CHARACTERS'],evaluationParams['ONLY_REMOVE_FIRST_LAST_CHARACTER'])==True detCorrect += (1 if correct else 0) if correct: detMatchedNums.append(detNum) pairs.append({'gt':gtNum,'det':detNum,'correct':correct}) evaluationLog += "Match GT #" + str(gtNum) + " with Det #" + str(detNum) + " trans. correct: " + str(correct) + "\n" for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): if det_only_gtRectMat[gtNum] == 0 and det_only_detRectMat[detNum] == 0 and gtNum not in det_only_gtDontCarePolsNum and detNum not in det_only_detDontCarePolsNum: if iouMat[gtNum,detNum]>evaluationParams['IOU_CONSTRAINT']: det_only_gtRectMat[gtNum] = 1 det_only_detRectMat[detNum] = 1 #detection matched only if transcription is equal det_only_correct = True detOnlyCorrect += 1 if evaluationParams['CONFIDENCES']: for detNum in range(len(detPols)): if detNum not in detDontCarePolsNum : #we exclude the don't care detections match = detNum in detMatchedNums arrSampleConfidences.append(confidencesList[detNum]) arrSampleMatch.append(match) arrGlobalConfidences.append(confidencesList[detNum]); arrGlobalMatches.append(match); numGtCare = (len(gtPols) - len(gtDontCarePolsNum)) numDetCare = (len(detPols) - len(detDontCarePolsNum)) det_only_numGtCare = (len(gtPols) - len(det_only_gtDontCarePolsNum)) det_only_numDetCare = (len(detPols) - len(det_only_detDontCarePolsNum)) if numGtCare == 0: recall = float(1) precision = float(0) if numDetCare >0 else float(1) sampleAP = precision else: recall = float(detCorrect) / numGtCare precision = 0 if numDetCare==0 else float(detCorrect) / numDetCare if evaluationParams['CONFIDENCES']: sampleAP = compute_ap(arrSampleConfidences, arrSampleMatch, numGtCare ) if det_only_numGtCare == 0: det_only_recall = float(1) det_only_precision = float(0) if det_only_numDetCare >0 else float(1) else: det_only_recall = float(detOnlyCorrect) / det_only_numGtCare det_only_precision = 0 if det_only_numDetCare==0 else float(detOnlyCorrect) / det_only_numDetCare hmean = 0 if (precision + recall)==0 else 2.0 * precision * recall / (precision + recall) det_only_hmean = 0 if (det_only_precision + det_only_recall)==0 else 2.0 * det_only_precision * det_only_recall / (det_only_precision + det_only_recall) matchedSum += detCorrect det_only_matchedSum += detOnlyCorrect numGlobalCareGt += numGtCare numGlobalCareDet += numDetCare det_only_numGlobalCareGt += det_only_numGtCare det_only_numGlobalCareDet += det_only_numDetCare perSampleMetrics[resFile] = { 'precision':precision, 'recall':recall, 'hmean':hmean, 'pairs':pairs, 'AP':sampleAP, 'iouMat':[] if len(detPols)>100 else iouMat.tolist(), 'gtPolPoints':gtPolPoints, 'detPolPoints':detPolPoints, 'gtTrans':gtTrans, 'detTrans':detTrans, 'gtDontCare':gtDontCarePolsNum, 'detDontCare':detDontCarePolsNum, 'evaluationParams': evaluationParams, 'evaluationLog': evaluationLog } # Compute AP AP = 0 if evaluationParams['CONFIDENCES']: AP = compute_ap(arrGlobalConfidences, arrGlobalMatches, numGlobalCareGt) methodRecall = 0 if numGlobalCareGt == 0 else float(matchedSum)/numGlobalCareGt methodPrecision = 0 if numGlobalCareDet == 0 else float(matchedSum)/numGlobalCareDet methodHmean = 0 if methodRecall + methodPrecision==0 else 2* methodRecall * methodPrecision / (methodRecall + methodPrecision) det_only_methodRecall = 0 if det_only_numGlobalCareGt == 0 else float(det_only_matchedSum)/det_only_numGlobalCareGt det_only_methodPrecision = 0 if det_only_numGlobalCareDet == 0 else float(det_only_matchedSum)/det_only_numGlobalCareDet det_only_methodHmean = 0 if det_only_methodRecall + det_only_methodPrecision==0 else 2* det_only_methodRecall * det_only_methodPrecision / (det_only_methodRecall + det_only_methodPrecision) methodMetrics = r"E2E_RESULTS: precision: {}, recall: {}, hmean: {}".format(methodPrecision, methodRecall, methodHmean) det_only_methodMetrics = r"DETECTION_ONLY_RESULTS: precision: {}, recall: {}, hmean: {}".format(det_only_methodPrecision, det_only_methodRecall, det_only_methodHmean) resDict = {'calculated':True,'Message':'','e2e_method': methodMetrics, 'det_only_method': det_only_methodMetrics, 'per_sample': perSampleMetrics} return resDict; def text_eval_main_ic15(det_file, gt_file, is_word_spotting): global WORD_SPOTTING WORD_SPOTTING = is_word_spotting p = { 'g': gt_file, 's': det_file } return rrc_evaluation_funcs.main_evaluation(p,default_evaluation_params,validate_data,evaluate_method)
null
2,017
import contextlib import copy import io import itertools import json import logging import numpy as np import os import re import torch from collections import OrderedDict from fvcore.common.file_io import PathManager from pycocotools.coco import COCO from detectron2.utils import comm from detectron2.data import MetadataCatalog from detectron2.evaluation.evaluator import DatasetEvaluator import glob import shutil from shapely.geometry import Polygon, LinearRing from adet.evaluation import text_eval_script from adet.evaluation import text_eval_script_ic15 import zipfile import pickle import editdistance import cv2 def get_tight_rect(points, start_x, start_y, image_height, image_width, scale): points = list(points) ps = sorted(points, key=lambda x: x[0]) if ps[1][1] > ps[0][1]: px1 = ps[0][0] * scale + start_x py1 = ps[0][1] * scale + start_y px4 = ps[1][0] * scale + start_x py4 = ps[1][1] * scale + start_y else: px1 = ps[1][0] * scale + start_x py1 = ps[1][1] * scale + start_y px4 = ps[0][0] * scale + start_x py4 = ps[0][1] * scale + start_y if ps[3][1] > ps[2][1]: px2 = ps[2][0] * scale + start_x py2 = ps[2][1] * scale + start_y px3 = ps[3][0] * scale + start_x py3 = ps[3][1] * scale + start_y else: px2 = ps[3][0] * scale + start_x py2 = ps[3][1] * scale + start_y px3 = ps[2][0] * scale + start_x py3 = ps[2][1] * scale + start_y px1 = min(max(px1, 1), image_width - 1) px2 = min(max(px2, 1), image_width - 1) px3 = min(max(px3, 1), image_width - 1) px4 = min(max(px4, 1), image_width - 1) py1 = min(max(py1, 1), image_height - 1) py2 = min(max(py2, 1), image_height - 1) py3 = min(max(py3, 1), image_height - 1) py4 = min(max(py4, 1), image_height - 1) return [px1, py1, px2, py2, px3, py3, px4, py4] def polygon2rbox(polygon, image_height, image_width): poly = np.array(polygon).reshape((-1, 2)).astype(np.float32) rect = cv2.minAreaRect(poly) corners = cv2.boxPoints(rect) corners = np.array(corners, dtype="int") pts = get_tight_rect(corners, 0, 0, image_height, image_width, 1) pts = np.array(pts).reshape(-1,2) pts = pts.tolist() return pts
null
2,018
import json import sy import zipfile import re import sys import os import codecs import importlib The provided code snippet includes necessary dependencies for implementing the `load_zip_file_keys` function. Write a Python function `def load_zip_file_keys(file,fileNameRegExp='')` to solve the following problem: Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp Here is the function: def load_zip_file_keys(file,fileNameRegExp=''): """ Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp """ try: archive=zipfile.ZipFile(file, mode='r', allowZip64=True) except : raise Exception('Error loading the ZIP archive.') pairs = [] for name in archive.namelist(): addFile = True keyName = name if fileNameRegExp!="": m = re.match(fileNameRegExp,name) if m == None: addFile = False else: if len(m.groups())>0: keyName = m.group(1) if addFile: pairs.append( keyName ) return pairs
Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp
2,019
import json import sysys.path.append('./') import zipfile import re import sys import os import codecs import importlib The provided code snippet includes necessary dependencies for implementing the `main_validation` function. Write a Python function `def main_validation(default_evaluation_params_fn,validate_data_fn)` to solve the following problem: This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission Here is the function: def main_validation(default_evaluation_params_fn,validate_data_fn): """ This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission """ try: p = dict([s[1:].split('=') for s in sys.argv[1:]]) evalParams = default_evaluation_params_fn() if 'p' in p.keys(): evalParams.update( p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:-1]) ) validate_data_fn(p['g'], p['s'], evalParams) print('SUCCESS') sys.exit(0) except Exception as e: print(str(e)) sys.exit(101)
This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission
2,020
from collections import namedtuple from adet.evaluation import rrc_evaluation_funcs import importlib import sys import math from rapidfuzz import string_metric WORD_SPOTTING =True def default_evaluation_params(): """ default_evaluation_params: Default parameters to use for the validation and evaluation. """ global WORD_SPOTTING return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :WORD_SPOTTING, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. MAP and MAR will be calculated, 'SPECIAL_CHARACTERS':str('!?.:,*"()·[]/\''), 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True } def validate_data(gtFilePath, submFilePath, evaluationParams): """ Method validate_data: validates that all files in the results folder are correct (have the correct name contents). Validates also that there are no missing files in the folder. If some error detected, the method raises the error """ gt = rrc_evaluation_funcs.load_zip_file(gtFilePath, evaluationParams['GT_SAMPLE_NAME_2_ID']) subm = rrc_evaluation_funcs.load_zip_file(submFilePath, evaluationParams['DET_SAMPLE_NAME_2_ID'], True) #Validate format of GroundTruth for k in gt: rrc_evaluation_funcs.validate_lines_in_file_gt(k,gt[k],evaluationParams['CRLF'],evaluationParams['LTRB'],True) #Validate format of results for k in subm: if (k in gt) == False : raise Exception("The sample %s not present in GT" %k) rrc_evaluation_funcs.validate_lines_in_file(k,subm[k],evaluationParams['CRLF'],evaluationParams['LTRB'],True,evaluationParams['CONFIDENCES']) def evaluate_method(gtFilePath, submFilePath, evaluationParams): """ Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 } """ for module,alias in evaluation_imports().items(): globals()[alias] = importlib.import_module(module) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ num_points = len(points) # resBoxes=np.empty([1,num_points],dtype='int32') resBoxes=np.empty([1,num_points],dtype='float32') for inp in range(0, num_points, 2): resBoxes[0, int(inp/2)] = float(points[int(inp)]) resBoxes[0, int(inp/2+num_points/2)] = float(points[int(inp+1)]) pointMat = resBoxes[0].reshape([2,int(num_points/2)]).T return plg.Polygon(pointMat) def rectangle_to_polygon(rect): resBoxes=np.empty([1,8],dtype='int32') resBoxes[0,0]=int(rect.xmin) resBoxes[0,4]=int(rect.ymax) resBoxes[0,1]=int(rect.xmin) resBoxes[0,5]=int(rect.ymin) resBoxes[0,2]=int(rect.xmax) resBoxes[0,6]=int(rect.ymin) resBoxes[0,3]=int(rect.xmax) resBoxes[0,7]=int(rect.ymax) pointMat = resBoxes[0].reshape([2,4]).T return plg.Polygon( pointMat) def rectangle_to_points(rect): points = [int(rect.xmin), int(rect.ymax), int(rect.xmax), int(rect.ymax), int(rect.xmax), int(rect.ymin), int(rect.xmin), int(rect.ymin)] return points def get_union(pD,pG): areaA = pD.area(); areaB = pG.area(); return areaA + areaB - get_intersection(pD, pG); def get_intersection_over_union(pD,pG): try: return get_intersection(pD, pG) / get_union(pD, pG); except: return 0 def get_intersection(pD,pG): pInt = pD & pG if len(pInt) == 0: return 0 return pInt.area() def compute_ap(confList, matchList,numGtCare): correct = 0 AP = 0 if len(confList)>0: confList = np.array(confList) matchList = np.array(matchList) sorted_ind = np.argsort(-confList) confList = confList[sorted_ind] matchList = matchList[sorted_ind] for n in range(len(confList)): match = matchList[n] if match: correct += 1 AP += float(correct)/(n + 1) if numGtCare>0: AP /= numGtCare return AP def transcription_match(transGt,transDet,specialCharacters=str(r'!?.:,*"()·[]/\''),onlyRemoveFirstLastCharacterGT=True): if onlyRemoveFirstLastCharacterGT: #special characters in GT are allowed only at initial or final position if (transGt==transDet): return True if specialCharacters.find(transGt[0])>-1: if transGt[1:]==transDet: return True if specialCharacters.find(transGt[-1])>-1: if transGt[0:len(transGt)-1]==transDet: return True if specialCharacters.find(transGt[0])>-1 and specialCharacters.find(transGt[-1])>-1: if transGt[1:len(transGt)-1]==transDet: return True return False else: #Special characters are removed from the begining and the end of both Detection and GroundTruth while len(transGt)>0 and specialCharacters.find(transGt[0])>-1: transGt = transGt[1:] while len(transDet)>0 and specialCharacters.find(transDet[0])>-1: transDet = transDet[1:] while len(transGt)>0 and specialCharacters.find(transGt[-1])>-1 : transGt = transGt[0:len(transGt)-1] while len(transDet)>0 and specialCharacters.find(transDet[-1])>-1: transDet = transDet[0:len(transDet)-1] return transGt == transDet def include_in_dictionary(transcription): """ Function used in Word Spotting that finds if the Ground Truth transcription meets the rules to enter into the dictionary. If not, the transcription will be cared as don't care """ #special case 's at final if transcription[len(transcription)-2:]=="'s" or transcription[len(transcription)-2:]=="'S": transcription = transcription[0:len(transcription)-2] #hypens at init or final of the word transcription = transcription.strip('-'); specialCharacters = str("'!?.:,*\"()·[]/"); for character in specialCharacters: transcription = transcription.replace(character,' ') transcription = transcription.strip() if len(transcription) != len(transcription.replace(" ","")) : return False; if len(transcription) < evaluationParams['MIN_LENGTH_CARE_WORD']: return False; notAllowed = str("×÷·"); range1 = [ ord(u'a'), ord(u'z') ] range2 = [ ord(u'A'), ord(u'Z') ] range3 = [ ord(u'À'), ord(u'ƿ') ] range4 = [ ord(u'DŽ'), ord(u'ɿ') ] range5 = [ ord(u'Ά'), ord(u'Ͽ') ] range6 = [ ord(u'-'), ord(u'-') ] for char in transcription : charCode = ord(char) if(notAllowed.find(char) != -1): return False valid = ( charCode>=range1[0] and charCode<=range1[1] ) or ( charCode>=range2[0] and charCode<=range2[1] ) or ( charCode>=range3[0] and charCode<=range3[1] ) or ( charCode>=range4[0] and charCode<=range4[1] ) or ( charCode>=range5[0] and charCode<=range5[1] ) or ( charCode>=range6[0] and charCode<=range6[1] ) if valid == False: return False return True def include_in_dictionary_transcription(transcription): """ Function applied to the Ground Truth transcriptions used in Word Spotting. It removes special characters or terminations """ #special case 's at final if transcription[len(transcription)-2:]=="'s" or transcription[len(transcription)-2:]=="'S": transcription = transcription[0:len(transcription)-2] #hypens at init or final of the word transcription = transcription.strip('-'); specialCharacters = str("'!?.:,*\"()·[]/"); for character in specialCharacters: transcription = transcription.replace(character,' ') transcription = transcription.strip() return transcription perSampleMetrics = {} matchedSum = 0 det_only_matchedSum = 0 Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax') gt = rrc_evaluation_funcs.load_zip_file(gtFilePath,evaluationParams['GT_SAMPLE_NAME_2_ID']) subm = rrc_evaluation_funcs.load_zip_file(submFilePath,evaluationParams['DET_SAMPLE_NAME_2_ID'],True) numGlobalCareGt = 0; numGlobalCareDet = 0; det_only_numGlobalCareGt = 0; det_only_numGlobalCareDet = 0; arrGlobalConfidences = []; arrGlobalMatches = []; for resFile in gt: # print('resgt', resFile) gtFile = rrc_evaluation_funcs.decode_utf8(gt[resFile]) if (gtFile is None) : raise Exception("The file %s is not UTF-8" %resFile) recall = 0 precision = 0 hmean = 0 detCorrect = 0 detOnlyCorrect = 0 iouMat = np.empty([1,1]) gtPols = [] detPols = [] gtTrans = [] detTrans = [] gtPolPoints = [] detPolPoints = [] gtDontCarePolsNum = [] #Array of Ground Truth Polygons' keys marked as don't Care det_only_gtDontCarePolsNum = [] detDontCarePolsNum = [] #Array of Detected Polygons' matched with a don't Care GT det_only_detDontCarePolsNum = [] detMatchedNums = [] pairs = [] arrSampleConfidences = []; arrSampleMatch = []; sampleAP = 0; pointsList,_,transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(gtFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,False) for n in range(len(pointsList)): points = pointsList[n] transcription = transcriptionsList[n] det_only_dontCare = dontCare = transcription == "###" # ctw1500 and total_text gt have been modified to the same format. if evaluationParams['LTRB']: gtRect = Rectangle(*points) gtPol = rectangle_to_polygon(gtRect) else: gtPol = polygon_from_points(points) gtPols.append(gtPol) gtPolPoints.append(points) #On word spotting we will filter some transcriptions with special characters if evaluationParams['WORD_SPOTTING'] : if dontCare == False : if include_in_dictionary(transcription) == False : dontCare = True else: transcription = include_in_dictionary_transcription(transcription) gtTrans.append(transcription) if dontCare: gtDontCarePolsNum.append( len(gtPols)-1 ) if det_only_dontCare: det_only_gtDontCarePolsNum.append( len(gtPols)-1 ) if resFile in subm: detFile = rrc_evaluation_funcs.decode_utf8(subm[resFile]) pointsList,confidencesList,transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents_det(detFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,evaluationParams['CONFIDENCES']) for n in range(len(pointsList)): points = pointsList[n] transcription = transcriptionsList[n] if evaluationParams['LTRB']: detRect = Rectangle(*points) detPol = rectangle_to_polygon(detRect) else: detPol = polygon_from_points(points) detPols.append(detPol) detPolPoints.append(points) detTrans.append(transcription) if len(gtDontCarePolsNum)>0 : for dontCarePol in gtDontCarePolsNum: dontCarePol = gtPols[dontCarePol] intersected_area = get_intersection(dontCarePol,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT'] ): detDontCarePolsNum.append( len(detPols)-1 ) break if len(det_only_gtDontCarePolsNum)>0 : for dontCarePol in det_only_gtDontCarePolsNum: dontCarePol = gtPols[dontCarePol] intersected_area = get_intersection(dontCarePol,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT'] ): det_only_detDontCarePolsNum.append( len(detPols)-1 ) break if len(gtPols)>0 and len(detPols)>0: #Calculate IoU and precision matrixs outputShape=[len(gtPols),len(detPols)] iouMat = np.empty(outputShape) gtRectMat = np.zeros(len(gtPols),np.int8) detRectMat = np.zeros(len(detPols),np.int8) det_only_gtRectMat = np.zeros(len(gtPols),np.int8) det_only_detRectMat = np.zeros(len(detPols),np.int8) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): pG = gtPols[gtNum] pD = detPols[detNum] iouMat[gtNum,detNum] = get_intersection_over_union(pD,pG) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): if gtRectMat[gtNum] == 0 and detRectMat[detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum : if iouMat[gtNum,detNum]>evaluationParams['IOU_CONSTRAINT']: gtRectMat[gtNum] = 1 detRectMat[detNum] = 1 #detection matched only if transcription is equal # det_only_correct = True # detOnlyCorrect += 1 if evaluationParams['WORD_SPOTTING']: edd = string_metric.levenshtein(gtTrans[gtNum].upper(), detTrans[detNum].upper()) if edd<=0: correct = True else: correct = False # correct = gtTrans[gtNum].upper() == detTrans[detNum].upper() else: try: correct = transcription_match(gtTrans[gtNum].upper(),detTrans[detNum].upper(),evaluationParams['SPECIAL_CHARACTERS'],evaluationParams['ONLY_REMOVE_FIRST_LAST_CHARACTER'])==True except: # empty correct = False detCorrect += (1 if correct else 0) if correct: detMatchedNums.append(detNum) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): if det_only_gtRectMat[gtNum] == 0 and det_only_detRectMat[detNum] == 0 and gtNum not in det_only_gtDontCarePolsNum and detNum not in det_only_detDontCarePolsNum: if iouMat[gtNum,detNum]>evaluationParams['IOU_CONSTRAINT']: det_only_gtRectMat[gtNum] = 1 det_only_detRectMat[detNum] = 1 #detection matched only if transcription is equal det_only_correct = True detOnlyCorrect += 1 numGtCare = (len(gtPols) - len(gtDontCarePolsNum)) numDetCare = (len(detPols) - len(detDontCarePolsNum)) det_only_numGtCare = (len(gtPols) - len(det_only_gtDontCarePolsNum)) det_only_numDetCare = (len(detPols) - len(det_only_detDontCarePolsNum)) if numGtCare == 0: recall = float(1) precision = float(0) if numDetCare >0 else float(1) else: recall = float(detCorrect) / numGtCare precision = 0 if numDetCare==0 else float(detCorrect) / numDetCare if det_only_numGtCare == 0: det_only_recall = float(1) det_only_precision = float(0) if det_only_numDetCare >0 else float(1) else: det_only_recall = float(detOnlyCorrect) / det_only_numGtCare det_only_precision = 0 if det_only_numDetCare==0 else float(detOnlyCorrect) / det_only_numDetCare hmean = 0 if (precision + recall)==0 else 2.0 * precision * recall / (precision + recall) det_only_hmean = 0 if (det_only_precision + det_only_recall)==0 else 2.0 * det_only_precision * det_only_recall / (det_only_precision + det_only_recall) matchedSum += detCorrect det_only_matchedSum += detOnlyCorrect numGlobalCareGt += numGtCare numGlobalCareDet += numDetCare det_only_numGlobalCareGt += det_only_numGtCare det_only_numGlobalCareDet += det_only_numDetCare perSampleMetrics[resFile] = { 'precision':precision, 'recall':recall, 'hmean':hmean, 'iouMat':[] if len(detPols)>100 else iouMat.tolist(), 'gtPolPoints':gtPolPoints, 'detPolPoints':detPolPoints, 'gtTrans':gtTrans, 'detTrans':detTrans, 'gtDontCare':gtDontCarePolsNum, 'detDontCare':detDontCarePolsNum, 'evaluationParams': evaluationParams, } methodRecall = 0 if numGlobalCareGt == 0 else float(matchedSum)/numGlobalCareGt methodPrecision = 0 if numGlobalCareDet == 0 else float(matchedSum)/numGlobalCareDet methodHmean = 0 if methodRecall + methodPrecision==0 else 2* methodRecall * methodPrecision / (methodRecall + methodPrecision) det_only_methodRecall = 0 if det_only_numGlobalCareGt == 0 else float(det_only_matchedSum)/det_only_numGlobalCareGt det_only_methodPrecision = 0 if det_only_numGlobalCareDet == 0 else float(det_only_matchedSum)/det_only_numGlobalCareDet det_only_methodHmean = 0 if det_only_methodRecall + det_only_methodPrecision==0 else 2* det_only_methodRecall * det_only_methodPrecision / (det_only_methodRecall + det_only_methodPrecision) methodMetrics = r"E2E_RESULTS: precision: {}, recall: {}, hmean: {}".format(methodPrecision, methodRecall, methodHmean) det_only_methodMetrics = r"DETECTION_ONLY_RESULTS: precision: {}, recall: {}, hmean: {}".format(det_only_methodPrecision, det_only_methodRecall, det_only_methodHmean) resDict = {'calculated':True,'Message':'','e2e_method': methodMetrics,'det_only_method': det_only_methodMetrics,'per_sample': perSampleMetrics} return resDict; def text_eval_main(det_file, gt_file, is_word_spotting): global WORD_SPOTTING WORD_SPOTTING = is_word_spotting return rrc_evaluation_funcs.main_evaluation(None,det_file, gt_file, default_evaluation_params,validate_data,evaluate_method)
null
2,021
import json import sysys.path.append('./') import zipfile import re import sys import os import codecs import importlib from io import StringIO from shapely.geometry import * def print_help(): sys.stdout.write('Usage: python %s.py -g=<gtFile> -s=<submFile> [-o=<outputFolder> -p=<jsonParams>]' %sys.argv[0]) sys.exit(2)
null
2,022
import json import sy import zipfile import re import sys import os import codecs import importlib from io import StringIO from shapely.geometry import * The provided code snippet includes necessary dependencies for implementing the `load_zip_file_keys` function. Write a Python function `def load_zip_file_keys(file,fileNameRegExp='')` to solve the following problem: Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp Here is the function: def load_zip_file_keys(file,fileNameRegExp=''): """ Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp """ try: archive=zipfile.ZipFile(file, mode='r', allowZip64=True) except : raise Exception('Error loading the ZIP archive.') pairs = [] for name in archive.namelist(): addFile = True keyName = name if fileNameRegExp!="": m = re.match(fileNameRegExp,name) if m == None: addFile = False else: if len(m.groups())>0: keyName = m.group(1) if addFile: pairs.append( keyName ) return pairs
Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp
2,023
import json import sysys.path.append('./') import zipfile import re import sys import os import codecs import importlib from io import StringIO from shapely.geometry import * The provided code snippet includes necessary dependencies for implementing the `main_validation` function. Write a Python function `def main_validation(default_evaluation_params_fn,validate_data_fn)` to solve the following problem: This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission Here is the function: def main_validation(default_evaluation_params_fn,validate_data_fn): """ This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission """ try: p = dict([s[1:].split('=') for s in sys.argv[1:]]) evalParams = default_evaluation_params_fn() if 'p' in p.keys(): evalParams.update( p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:-1]) ) validate_data_fn(p['g'], p['s'], evalParams) print('SUCCESS') sys.exit(0) except Exception as e: print(str(e)) sys.exit(101)
This process validates a method Params: default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation validate_data_fn: points to a method that validates the corrct format of the submission
2,024
from detectron2.config import CfgNode _C.MODEL.MOBILENET = False _C.MODEL.BACKBONE.ANTI_ALIAS = False _C.MODEL.RESNETS.DEFORM_INTERVAL = 1 _C.INPUT.HFLIP_TRAIN = True _C.INPUT.CROP.CROP_INSTANCE = True _C.INPUT.IS_ROTATE = False _C.MODEL.FCOS = CN() _C.MODEL.FCOS.NUM_CLASSES = 80 _C.MODEL.FCOS.IN_FEATURES = ["p3", "p4", "p5", "p6", "p7"] _C.MODEL.FCOS.FPN_STRIDES = [8, 16, 32, 64, 128] _C.MODEL.FCOS.PRIOR_PROB = 0.01 _C.MODEL.FCOS.INFERENCE_TH_TRAIN = 0.05 _C.MODEL.FCOS.INFERENCE_TH_TEST = 0.05 _C.MODEL.FCOS.NMS_TH = 0.6 _C.MODEL.FCOS.PRE_NMS_TOPK_TRAIN = 1000 _C.MODEL.FCOS.PRE_NMS_TOPK_TEST = 1000 _C.MODEL.FCOS.POST_NMS_TOPK_TRAIN = 100 _C.MODEL.FCOS.POST_NMS_TOPK_TEST = 100 _C.MODEL.FCOS.TOP_LEVELS = 2 _C.MODEL.FCOS.NORM = "GN" _C.MODEL.FCOS.USE_SCALE = True _C.MODEL.FCOS.BOX_QUALITY = "ctrness" _C.MODEL.FCOS.THRESH_WITH_CTR = False _C.MODEL.FCOS.LOSS_ALPHA = 0.25 _C.MODEL.FCOS.LOSS_GAMMA = 2.0 _C.MODEL.FCOS.LOSS_NORMALIZER_CLS = "fg" _C.MODEL.FCOS.LOSS_WEIGHT_CLS = 1.0 _C.MODEL.FCOS.SIZES_OF_INTEREST = [64, 128, 256, 512] _C.MODEL.FCOS.USE_RELU = True _C.MODEL.FCOS.USE_DEFORMABLE = False _C.MODEL.FCOS.NUM_CLS_CONVS = 4 _C.MODEL.FCOS.NUM_BOX_CONVS = 4 _C.MODEL.FCOS.NUM_SHARE_CONVS = 0 _C.MODEL.FCOS.CENTER_SAMPLE = True _C.MODEL.FCOS.POS_RADIUS = 1.5 _C.MODEL.FCOS.LOC_LOSS_TYPE = 'giou' _C.MODEL.FCOS.YIELD_PROPOSAL = False _C.MODEL.FCOS.YIELD_BOX_FEATURES = False _C.MODEL.VOVNET = CN() _C.MODEL.VOVNET.CONV_BODY = "V-39-eSE" _C.MODEL.VOVNET.OUT_FEATURES = ["stage2", "stage3", "stage4", "stage5"] _C.MODEL.VOVNET.NORM = "FrozenBN" _C.MODEL.VOVNET.OUT_CHANNELS = 256 _C.MODEL.VOVNET.BACKBONE_OUT_CHANNELS = 256 _C.MODEL.DLA = CN() _C.MODEL.DLA.CONV_BODY = "DLA34" _C.MODEL.DLA.OUT_FEATURES = ["stage2", "stage3", "stage4", "stage5"] _C.MODEL.DLA.NORM = "FrozenBN" _C.MODEL.BATEXT = CN() _C.MODEL.BATEXT.VOC_SIZE = 96 _C.MODEL.BATEXT.NUM_CHARS = 25 _C.MODEL.BATEXT.POOLER_RESOLUTION = (8, 32) _C.MODEL.BATEXT.IN_FEATURES = ["p2", "p3", "p4"] _C.MODEL.BATEXT.POOLER_SCALES = (0.25, 0.125, 0.0625) _C.MODEL.BATEXT.SAMPLING_RATIO = 1 _C.MODEL.BATEXT.CONV_DIM = 256 _C.MODEL.BATEXT.NUM_CONV = 2 _C.MODEL.BATEXT.RECOGNITION_LOSS = "ctc" _C.MODEL.BATEXT.RECOGNIZER = "attn" _C.MODEL.BATEXT.CANONICAL_SIZE = 96 _C.MODEL.BATEXT.USE_COORDCONV = False _C.MODEL.BATEXT.USE_AET = False _C.MODEL.BATEXT.EVAL_TYPE = 3 _C.MODEL.BATEXT.CUSTOM_DICT = "" _C.MODEL.BLENDMASK = CN() _C.MODEL.BLENDMASK.ATTN_SIZE = 14 _C.MODEL.BLENDMASK.TOP_INTERP = "bilinear" _C.MODEL.BLENDMASK.BOTTOM_RESOLUTION = 56 _C.MODEL.BLENDMASK.POOLER_TYPE = "ROIAlignV2" _C.MODEL.BLENDMASK.POOLER_SAMPLING_RATIO = 1 _C.MODEL.BLENDMASK.POOLER_SCALES = (0.25,) _C.MODEL.BLENDMASK.INSTANCE_LOSS_WEIGHT = 1.0 _C.MODEL.BLENDMASK.VISUALIZE = False _C.MODEL.BASIS_MODULE = CN() _C.MODEL.BASIS_MODULE.NAME = "ProtoNet" _C.MODEL.BASIS_MODULE.NUM_BASES = 4 _C.MODEL.BASIS_MODULE.LOSS_ON = False _C.MODEL.BASIS_MODULE.ANN_SET = "coco" _C.MODEL.BASIS_MODULE.CONVS_DIM = 128 _C.MODEL.BASIS_MODULE.IN_FEATURES = ["p3", "p4", "p5"] _C.MODEL.BASIS_MODULE.NORM = "SyncBN" _C.MODEL.BASIS_MODULE.NUM_CONVS = 3 _C.MODEL.BASIS_MODULE.COMMON_STRIDE = 8 _C.MODEL.BASIS_MODULE.NUM_CLASSES = 80 _C.MODEL.BASIS_MODULE.LOSS_WEIGHT = 0.3 _C.MODEL.MEInst = CN() _C.MODEL.MEInst.NUM_CLASSES = 80 _C.MODEL.MEInst.IN_FEATURES = ["p3", "p4", "p5", "p6", "p7"] _C.MODEL.MEInst.FPN_STRIDES = [8, 16, 32, 64, 128] _C.MODEL.MEInst.PRIOR_PROB = 0.01 _C.MODEL.MEInst.INFERENCE_TH_TRAIN = 0.05 _C.MODEL.MEInst.INFERENCE_TH_TEST = 0.05 _C.MODEL.MEInst.NMS_TH = 0.6 _C.MODEL.MEInst.PRE_NMS_TOPK_TRAIN = 1000 _C.MODEL.MEInst.PRE_NMS_TOPK_TEST = 1000 _C.MODEL.MEInst.POST_NMS_TOPK_TRAIN = 100 _C.MODEL.MEInst.POST_NMS_TOPK_TEST = 100 _C.MODEL.MEInst.TOP_LEVELS = 2 _C.MODEL.MEInst.NORM = "GN" _C.MODEL.MEInst.USE_SCALE = True _C.MODEL.MEInst.THRESH_WITH_CTR = False _C.MODEL.MEInst.LOSS_ALPHA = 0.25 _C.MODEL.MEInst.LOSS_GAMMA = 2.0 _C.MODEL.MEInst.SIZES_OF_INTEREST = [64, 128, 256, 512] _C.MODEL.MEInst.USE_RELU = True _C.MODEL.MEInst.USE_DEFORMABLE = False _C.MODEL.MEInst.LAST_DEFORMABLE = False _C.MODEL.MEInst.TYPE_DEFORMABLE = "DCNv1" _C.MODEL.MEInst.NUM_CLS_CONVS = 4 _C.MODEL.MEInst.NUM_BOX_CONVS = 4 _C.MODEL.MEInst.NUM_SHARE_CONVS = 0 _C.MODEL.MEInst.CENTER_SAMPLE = True _C.MODEL.MEInst.POS_RADIUS = 1.5 _C.MODEL.MEInst.LOC_LOSS_TYPE = 'giou' _C.MODEL.MEInst.MASK_ON = True _C.MODEL.MEInst.IOU_THRESHOLDS = [0.5] _C.MODEL.MEInst.IOU_LABELS = [0, 1] _C.MODEL.MEInst.AGNOSTIC = True _C.MODEL.MEInst.WHITEN = True _C.MODEL.MEInst.SIGMOID = True _C.MODEL.MEInst.NUM_MASK_CONVS = 4 _C.MODEL.MEInst.DIM_MASK = 60 _C.MODEL.MEInst.MASK_SIZE = 28 _C.MODEL.MEInst.PATH_COMPONENTS = "datasets/coco/components/" \ "coco_2017_train_class_agnosticTrue_whitenTrue_sigmoidTrue_60.npz" _C.MODEL.MEInst.FLAG_PARAMETERS = False _C.MODEL.MEInst.MASK_LOSS_TYPE = "mse" _C.MODEL.MEInst.USE_GCN_IN_MASK = False _C.MODEL.MEInst.GCN_KERNEL_SIZE = 9 _C.MODEL.MEInst.LOSS_ON_MASK = False _C.MODEL.CONDINST = CN() _C.MODEL.CONDINST.MASK_OUT_STRIDE = 4 _C.MODEL.CONDINST.BOTTOM_PIXELS_REMOVED = -1 _C.MODEL.CONDINST.MAX_PROPOSALS = -1 _C.MODEL.CONDINST.TOPK_PROPOSALS_PER_IM = -1 _C.MODEL.CONDINST.MASK_HEAD = CN() _C.MODEL.CONDINST.MASK_HEAD.CHANNELS = 8 _C.MODEL.CONDINST.MASK_HEAD.NUM_LAYERS = 3 _C.MODEL.CONDINST.MASK_HEAD.USE_FP16 = False _C.MODEL.CONDINST.MASK_HEAD.DISABLE_REL_COORDS = False _C.MODEL.CONDINST.MASK_BRANCH = CN() _C.MODEL.CONDINST.MASK_BRANCH.OUT_CHANNELS = 8 _C.MODEL.CONDINST.MASK_BRANCH.IN_FEATURES = ["p3", "p4", "p5"] _C.MODEL.CONDINST.MASK_BRANCH.CHANNELS = 128 _C.MODEL.CONDINST.MASK_BRANCH.NORM = "BN" _C.MODEL.CONDINST.MASK_BRANCH.NUM_CONVS = 4 _C.MODEL.CONDINST.MASK_BRANCH.SEMANTIC_LOSS_ON = False _C.MODEL.BOXINST = CN() _C.MODEL.BOXINST.ENABLED = False _C.MODEL.BOXINST.BOTTOM_PIXELS_REMOVED = 10 _C.MODEL.BOXINST.PAIRWISE = CN() _C.MODEL.BOXINST.PAIRWISE.SIZE = 3 _C.MODEL.BOXINST.PAIRWISE.DILATION = 2 _C.MODEL.BOXINST.PAIRWISE.WARMUP_ITERS = 10000 _C.MODEL.BOXINST.PAIRWISE.COLOR_THRESH = 0.3 _C.MODEL.TOP_MODULE = CN() _C.MODEL.TOP_MODULE.NAME = "conv" _C.MODEL.TOP_MODULE.DIM = 16 _C.MODEL.BiFPN = CN() _C.MODEL.BiFPN.IN_FEATURES = ["res2", "res3", "res4", "res5"] _C.MODEL.BiFPN.OUT_CHANNELS = 160 _C.MODEL.BiFPN.NUM_REPEATS = 6 _C.MODEL.BiFPN.NORM = "" _C.MODEL.SOLOV2 = CN() _C.MODEL.SOLOV2.INSTANCE_IN_FEATURES = ["p2", "p3", "p4", "p5", "p6"] _C.MODEL.SOLOV2.FPN_INSTANCE_STRIDES = [8, 8, 16, 32, 32] _C.MODEL.SOLOV2.FPN_SCALE_RANGES = ((1, 96), (48, 192), (96, 384), (192, 768), (384, 2048)) _C.MODEL.SOLOV2.SIGMA = 0.2 _C.MODEL.SOLOV2.INSTANCE_IN_CHANNELS = 256 _C.MODEL.SOLOV2.INSTANCE_CHANNELS = 512 _C.MODEL.SOLOV2.NUM_INSTANCE_CONVS = 4 _C.MODEL.SOLOV2.USE_DCN_IN_INSTANCE = False _C.MODEL.SOLOV2.TYPE_DCN = 'DCN' _C.MODEL.SOLOV2.NUM_GRIDS = [40, 36, 24, 16, 12] _C.MODEL.SOLOV2.NUM_CLASSES = 80 _C.MODEL.SOLOV2.NUM_KERNELS = 256 _C.MODEL.SOLOV2.NORM = "GN" _C.MODEL.SOLOV2.USE_COORD_CONV = True _C.MODEL.SOLOV2.PRIOR_PROB = 0.01 _C.MODEL.SOLOV2.MASK_IN_FEATURES = ["p2", "p3", "p4", "p5"] _C.MODEL.SOLOV2.MASK_IN_CHANNELS = 256 _C.MODEL.SOLOV2.MASK_CHANNELS = 128 _C.MODEL.SOLOV2.NUM_MASKS = 256 _C.MODEL.SOLOV2.NMS_PRE = 500 _C.MODEL.SOLOV2.SCORE_THR = 0.1 _C.MODEL.SOLOV2.UPDATE_THR = 0.05 _C.MODEL.SOLOV2.MASK_THR = 0.5 _C.MODEL.SOLOV2.MAX_PER_IMG = 100 _C.MODEL.SOLOV2.NMS_TYPE = "matrix" _C.MODEL.SOLOV2.NMS_KERNEL = "gaussian" _C.MODEL.SOLOV2.NMS_SIGMA = 2 _C.MODEL.SOLOV2.LOSS = CN() _C.MODEL.SOLOV2.LOSS.FOCAL_USE_SIGMOID = True _C.MODEL.SOLOV2.LOSS.FOCAL_ALPHA = 0.25 _C.MODEL.SOLOV2.LOSS.FOCAL_GAMMA = 2.0 _C.MODEL.SOLOV2.LOSS.FOCAL_WEIGHT = 1.0 _C.MODEL.SOLOV2.LOSS.DICE_WEIGHT = 3.0 _C.MODEL.FCPOSE = CN() _C.MODEL.FCPOSE_ON = False _C.MODEL.FCPOSE.ATTN_LEN = 2737 _C.MODEL.FCPOSE.DYNAMIC_CHANNELS = 32 _C.MODEL.FCPOSE.MAX_PROPOSALS = 70 _C.MODEL.FCPOSE.PROPOSALS_PER_INST = 70 _C.MODEL.FCPOSE.LOSS_WEIGHT_KEYPOINT = 2.5 _C.MODEL.FCPOSE.FOCAL_LOSS_ALPHA = 0.25 _C.MODEL.FCPOSE.FOCAL_LOSS_GAMMA = 2.0 _C.MODEL.FCPOSE.GT_HEATMAP_STRIDE = 2 _C.MODEL.FCPOSE.SIGMA = 1 _C.MODEL.FCPOSE.HEATMAP_SIGMA = 1.8 _C.MODEL.FCPOSE.HEAD_HEATMAP_SIGMA = 0.01 _C.MODEL.FCPOSE.DISTANCE_NORM = 12.0 _C.MODEL.FCPOSE.LOSS_WEIGHT_DIRECTION = 9.0 _C.MODEL.FCPOSE.BASIS_MODULE = CN() _C.MODEL.FCPOSE.BASIS_MODULE.NUM_BASES = 32 _C.MODEL.FCPOSE.BASIS_MODULE.CONVS_DIM = 128 _C.MODEL.FCPOSE.BASIS_MODULE.COMMON_STRIDE = 8 _C.MODEL.FCPOSE.BASIS_MODULE.NUM_CLASSES = 17 _C.MODEL.FCPOSE.BASIS_MODULE.LOSS_WEIGHT = 0.2 _C.MODEL.FCPOSE.BASIS_MODULE.BN_TYPE = "SyncBN" The provided code snippet includes necessary dependencies for implementing the `get_cfg` function. Write a Python function `def get_cfg() -> CfgNode` to solve the following problem: Get a copy of the default config. Returns: a detectron2 CfgNode instance. Here is the function: def get_cfg() -> CfgNode: """ Get a copy of the default config. Returns: a detectron2 CfgNode instance. """ from .defaults import _C return _C.clone()
Get a copy of the default config. Returns: a detectron2 CfgNode instance.
2,025
import torch import torch.nn.functional as F import torch.distributed as dist from detectron2.utils.comm import get_world_size def reduce_sum(tensor): world_size = get_world_size() if world_size < 2: return tensor tensor = tensor.clone() dist.all_reduce(tensor, op=dist.ReduceOp.SUM) return tensor def reduce_mean(tensor): num_gpus = get_world_size() total = reduce_sum(tensor) return total.float() / num_gpus
null
2,026
import torch import torch.nn.functional as F import torch.distributed as dist from detectron2.utils.comm import get_world_size def aligned_bilinear(tensor, factor): assert tensor.dim() == 4 assert factor >= 1 assert int(factor) == factor if factor == 1: return tensor h, w = tensor.size()[2:] tensor = F.pad(tensor, pad=(0, 1, 0, 1), mode="replicate") oh = factor * h + 1 ow = factor * w + 1 tensor = F.interpolate( tensor, size=(oh, ow), mode='bilinear', align_corners=True ) tensor = F.pad( tensor, pad=(factor // 2, 0, factor // 2, 0), mode="replicate" ) return tensor[:, :, :oh - 1, :ow - 1]
null
2,027
import torch import torch.nn.functional as F import torch.distributed as dist from detectron2.utils.comm import get_world_size def compute_locations(h, w, stride, device): shifts_x = torch.arange( 0, w * stride, step=stride, dtype=torch.float32, device=device ) shifts_y = torch.arange( 0, h * stride, step=stride, dtype=torch.float32, device=device ) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) shift_x = shift_x.reshape(-1) shift_y = shift_y.reshape(-1) locations = torch.stack((shift_x, shift_y), dim=1) + stride // 2 return locations
null
2,028
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import operator from functools import reduce def is_pruned(layer): try: layer.mask return True except AttributeError: return False def is_leaf(model): return get_num_gen(model.children()) == 0 def measure_layer(layer, *args): global count_ops, count_params for x in args: delta_ops = 0 delta_params = 0 multi_add = 1 type_name = get_layer_info(layer) ### ops_conv if type_name in ['Conv2d']: out_h = int((x.size()[2] + 2 * layer.padding[0] / layer.dilation[0] - layer.kernel_size[0]) / layer.stride[0] + 1) out_w = int((x.size()[3] + 2 * layer.padding[1] / layer.dilation[1] - layer.kernel_size[1]) / layer.stride[1] + 1) delta_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = get_layer_param(layer) elif type_name in ['ConvTranspose2d']: _, _, in_h, in_w = x.size() out_h = int((in_h-1)*layer.stride[0] - 2 * layer.padding[0] + layer.kernel_size[0] + layer.output_padding[0]) out_w = int((in_w-1)*layer.stride[1] - 2 * layer.padding[1] + layer.kernel_size[1] + layer.output_padding[1]) delta_ops = layer.in_channels * layer.out_channels * layer.kernel_size[0] * \ layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = get_layer_param(layer) ### ops_learned_conv elif type_name in ['LearnedGroupConv']: measure_layer(layer.relu, x) measure_layer(layer.norm, x) conv = layer.conv out_h = int((x.size()[2] + 2 * conv.padding[0] - conv.kernel_size[0]) / conv.stride[0] + 1) out_w = int((x.size()[3] + 2 * conv.padding[1] - conv.kernel_size[1]) / conv.stride[1] + 1) delta_ops = conv.in_channels * conv.out_channels * conv.kernel_size[0] * conv.kernel_size[1] * out_h * out_w / layer.condense_factor * multi_add delta_params = get_layer_param(conv) / layer.condense_factor ### ops_nonlinearity elif type_name in ['ReLU', 'ReLU6']: delta_ops = x.numel() delta_params = get_layer_param(layer) ### ops_pooling elif type_name in ['AvgPool2d', 'MaxPool2d']: in_w = x.size()[2] kernel_ops = layer.kernel_size * layer.kernel_size out_w = int((in_w + 2 * layer.padding - layer.kernel_size) / layer.stride + 1) out_h = int((in_w + 2 * layer.padding - layer.kernel_size) / layer.stride + 1) delta_ops = x.size()[0] * x.size()[1] * out_w * out_h * kernel_ops delta_params = get_layer_param(layer) elif type_name in ['LastLevelMaxPool']: pass elif type_name in ['AdaptiveAvgPool2d']: delta_ops = x.size()[0] * x.size()[1] * x.size()[2] * x.size()[3] delta_params = get_layer_param(layer) elif type_name in ['ZeroPad2d', 'RetinaNetPostProcessor']: pass #delta_ops = x.size()[0] * x.size()[1] * x.size()[2] * x.size()[3] #delta_params = get_layer_param(layer) ### ops_linear elif type_name in ['Linear']: weight_ops = layer.weight.numel() * multi_add bias_ops = layer.bias.numel() delta_ops = x.size()[0] * (weight_ops + bias_ops) delta_params = get_layer_param(layer) ### ops_nothing elif type_name in ['BatchNorm2d', 'Dropout2d', 'DropChannel', 'Dropout', 'FrozenBatchNorm2d', 'GroupNorm']: delta_params = get_layer_param(layer) elif type_name in ['SumTwo']: delta_ops = x.numel() elif type_name in ['AggregateCell']: if not layer.pre_transform: delta_ops = 2 * x.numel() # twice for each input else: measure_layer(layer.branch_1, x) measure_layer(layer.branch_2, x) delta_params = get_layer_param(layer) elif type_name in ['Identity', 'Zero']: pass elif type_name in ['Scale']: delta_params = get_layer_param(layer) delta_ops = x.numel() elif type_name in ['FCOSPostProcessor', 'RPNPostProcessor', 'KeypointPostProcessor', 'ROIAlign', 'PostProcessor', 'KeypointRCNNPredictor', 'NaiveSyncBatchNorm', 'Upsample', 'Sequential']: pass elif type_name in ['DeformConv']: # don't count bilinear offset_conv = list(layer.parameters())[0] delta_ops = reduce(operator.mul, offset_conv.size(), x.size()[2] * x.size()[3]) out_h = int((x.size()[2] + 2 * layer.padding[0] / layer.dilation[0] - layer.kernel_size[0]) / layer.stride[0] + 1) out_w = int((x.size()[3] + 2 * layer.padding[1] / layer.dilation[1] - layer.kernel_size[1]) / layer.stride[1] + 1) delta_ops += layer.in_channels * layer.out_channels * layer.kernel_size[0] * layer.kernel_size[1] * out_h * out_w / layer.groups * multi_add delta_params = get_layer_param(layer) ### unknown layer type else: raise TypeError('unknown layer type: %s' % type_name) count_ops += delta_ops count_params += delta_params return def measure_model(model, x): global count_ops, count_params count_ops = 0 count_params = 0 def should_measure(x): return is_leaf(x) or is_pruned(x) def modify_forward(model): for child in model.children(): if should_measure(child): def new_forward(m): def lambda_forward(*args): measure_layer(m, *args) return m.old_forward(*args) return lambda_forward child.old_forward = child.forward child.forward = new_forward(child) else: modify_forward(child) def restore_forward(model): for child in model.children(): # leaf node if is_leaf(child) and hasattr(child, 'old_forward'): child.forward = child.old_forward child.old_forward = None else: restore_forward(child) modify_forward(model) out = model.forward(x) restore_forward(model) return out, count_ops, count_params
null
2,029
import argparse import glob import multiprocessing as mp import os import time import cv2 import tqdm from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from predictor import VisualizationDemo from adet.config import get_cfg def setup_cfg(args): # load config from file and command-line arguments cfg = get_cfg() cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) # Set score_threshold for builtin models cfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_threshold cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_threshold cfg.MODEL.FCOS.INFERENCE_TH_TEST = args.confidence_threshold cfg.MODEL.MEInst.INFERENCE_TH_TEST = args.confidence_threshold cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = args.confidence_threshold cfg.freeze() return cfg
null
2,030
import argparse import glob import multiprocessing as mp import os import time import cv2 import tqdm from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from predictor import VisualizationDemo from adet.config import get_cfg def get_parser(): parser = argparse.ArgumentParser(description="Detectron2 Demo") parser.add_argument( "--config-file", default="configs/quick_schedules/e2e_mask_rcnn_R_50_FPN_inference_acc_test.yaml", metavar="FILE", help="path to config file", ) parser.add_argument("--webcam", action="store_true", help="Take inputs from webcam.") parser.add_argument("--video-input", help="Path to video file.") parser.add_argument("--input", nargs="+", help="A list of space separated input images") parser.add_argument( "--output", help="A file or directory to save output visualizations. " "If not given, will show output in an OpenCV window.", ) parser.add_argument( "--confidence-threshold", type=float, default=0.3, help="Minimum score for instance predictions to be shown", ) parser.add_argument( "--opts", help="Modify config options using the command-line 'KEY VALUE' pairs", default=[], nargs=argparse.REMAINDER, ) return parser
null
2,031
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def patch_condinst(cfg, model, output_names): def forward(self, tensor): images = None gt_instances = None mask_feats = None proposals = None features = self.backbone(tensor) #return features proposals, proposal_losses = self.proposal_generator(images, features, gt_instances, self.controller) #return proposals mask_feats, sem_losses = self.mask_branch(features, gt_instances) #return mask_feats return mask_feats, proposals model.forward = types.MethodType(forward, model) #output tensor naming [optional]
null
2,032
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def patch_blendmask(cfg, model, output_names): def forward(self, tensor): images = None gt_instances = None basis_sem = None features = self.backbone(tensor) basis_out, basis_losses = self.basis_module(features, basis_sem) proposals, proposal_losses = self.proposal_generator(images, features, gt_instances, self.top_layer) return basis_out["bases"], proposals model.forward = types.MethodType(forward, model) #output tensor naming [optional] output_names.extend(["bases"]) for item in ["logits", "bbox_reg", "centerness", "top_feats"]: for l in range(len(cfg.MODEL.FCOS.FPN_STRIDES)): fpn_name = "P{}".format(3 + l) output_names.extend([fpn_name + item])
null
2,033
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def patch_ProposalNetwork(cfg, model, output_names): def forward(self, tensor): images = None gt_instances = None features = self.backbone(tensor) proposals, proposal_losses = self.proposal_generator(images, features, gt_instances) return proposals model.forward = types.MethodType(forward, model) #output tensor naming [optional] for item in ["logits", "bbox_reg", "centerness"]: for l in range(len(cfg.MODEL.FCOS.FPN_STRIDES)): fpn_name = "P{}".format(3 + l) output_names.extend([fpn_name + item])
null
2,034
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def patch_fcos(cfg, proposal_generator): def proposal_generator_forward(self, images, features, gt_instances=None, top_module=None): features = [features[f] for f in self.in_features] logits_pred, reg_pred, ctrness_pred, top_feats, bbox_towers = self.fcos_head(features, top_module, self.yield_proposal) return (logits_pred, reg_pred, ctrness_pred, top_feats, bbox_towers), None proposal_generator.forward = types.MethodType(proposal_generator_forward, proposal_generator)
null
2,035
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def patch_fcos_head(cfg, fcos_head): # step 1. config norm = None if cfg.MODEL.FCOS.NORM == "none" else cfg.MODEL.FCOS.NORM head_configs = {"cls": (cfg.MODEL.FCOS.NUM_CLS_CONVS, cfg.MODEL.FCOS.USE_DEFORMABLE), "bbox": (cfg.MODEL.FCOS.NUM_BOX_CONVS, cfg.MODEL.FCOS.USE_DEFORMABLE), "share": (cfg.MODEL.FCOS.NUM_SHARE_CONVS, False)} # step 2. separate module for l in range(fcos_head.num_levels): for head in head_configs: tower = [] num_convs, use_deformable = head_configs[head] for i in range(num_convs): tower.append(deepcopy(getattr(fcos_head, '{}_tower'.format(head))[i*3 + 0])) if norm in ["GN", "NaiveGN"]: tower.append(deepcopy(getattr(fcos_head, '{}_tower'.format(head))[i*3 + 1])) elif norm in ["BN", "SyncBN"]: tower.append(deepcopy(getattr(fcos_head, '{}_tower'.format(head))[i*3 + 1][l])) tower.append(deepcopy(getattr(fcos_head, '{}_tower'.format(head))[i*3 + 2])) fcos_head.add_module('{}_tower{}'.format(head, l), torch.nn.Sequential(*tower)) # step 3. override fcos_head forward def fcos_head_forward(self, x, top_module=None, yield_bbox_towers=False): logits = [] bbox_reg = [] ctrness = [] top_feats = [] bbox_towers = [] for l, feature in enumerate(x): feature = self.share_tower(feature) cls_tower = getattr(self, 'cls_tower{}'.format(l))(feature) bbox_tower = getattr(self, 'bbox_tower{}'.format(l))(feature) if yield_bbox_towers: bbox_towers.append(bbox_tower) logits.append(self.cls_logits(cls_tower)) ctrness.append(self.ctrness(bbox_tower)) reg = self.bbox_pred(bbox_tower) if self.scales is not None: reg = self.scales[l](reg) # Note that we use relu, as in the improved FCOS, instead of exp. bbox_reg.append(F.relu(reg)) if top_module is not None: top_feats.append(top_module(bbox_tower)) return logits, bbox_reg, ctrness, top_feats, bbox_towers fcos_head.forward = types.MethodType(fcos_head_forward, fcos_head)
null
2,036
import argparse import os import glob import multiprocessing as mp import os import time import cv2 import tqdm import types import torch from torch import nn from torch.nn import functional as F from copy import deepcopy from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from detectron2.data import MetadataCatalog from detectron2.modeling import build_model from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling import ProposalNetwork from adet.config import get_cfg from adet.modeling import FCOS, BlendMask, BAText, MEInst, condinst, SOLOv2 from adet.modeling.condinst.mask_branch import MaskBranch def upsample(tensor, factor): # aligned_bilinear in adet/utils/comm.py is not onnx-friendly assert tensor.dim() == 4 assert factor >= 1 assert int(factor) == factor if factor == 1: return tensor h, w = tensor.size()[2:] oh = factor * h ow = factor * w tensor = F.interpolate( tensor, size=(oh, ow), mode='nearest', ) return tensor def patch_mask_branch(cfg, mask_branch): def mask_branch_forward(self, features, gt_instances=None): for i, f in enumerate(self.in_features): if i == 0: x = self.refine[i](features[f]) else: x_p = self.refine[i](features[f]) target_h, target_w = x.size()[2:] h, w = x_p.size()[2:] assert target_h % h == 0 assert target_w % w == 0 factor_h, factor_w = target_h // h, target_w // w assert factor_h == factor_w x_p = upsample(x_p, factor_h) x = x + x_p mask_feats = self.tower(x) if self.num_outputs == 0: mask_feats = mask_feats[:, :self.num_outputs] losses = {} return mask_feats, losses mask_branch.forward = types.MethodType(mask_branch_forward, mask_branch)
null
2,037
import time import functools import multiprocessing as mp import numpy as np import os from lvis import LVIS from pycocotools import mask as maskUtils def _process_instance_to_semantic(anns, output_semantic, img): img_size = (img["height"], img["width"]) output = np.zeros(img_size, dtype=np.uint8) for ann in anns: mask = annToMask(ann, img_size) output[mask == 1] = ann["category_id"] // 5 # save as compressed npz np.savez_compressed(output_semantic, mask=output) # Image.fromarray(output).save(output_semantic) The provided code snippet includes necessary dependencies for implementing the `create_lvis_semantic_from_instance` function. Write a Python function `def create_lvis_semantic_from_instance(instance_json, sem_seg_root)` to solve the following problem: Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files Here is the function: def create_lvis_semantic_from_instance(instance_json, sem_seg_root): """ Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files """ os.makedirs(sem_seg_root, exist_ok=True) lvis_detection = LVIS(instance_json) def iter_annotations(): for img_id in lvis_detection.get_img_ids(): anns_ids = lvis_detection.get_ann_ids([img_id]) anns = lvis_detection.load_anns(anns_ids) img = lvis_detection.load_imgs([img_id])[0] file_name = os.path.splitext(img["file_name"])[0] output = os.path.join(sem_seg_root, file_name + '.npz') yield anns, output, img # # single process # print("Start writing to {} ...".format(sem_seg_root)) # start = time.time() # for anno, oup, img in iter_annotations(): # _process_instance_to_semantic( # anno, oup, img) # print("Finished. time: {:.2f}s".format(time.time() - start)) # return pool = mp.Pool(processes=max(mp.cpu_count() // 2, 4)) print("Start writing to {} ...".format(sem_seg_root)) start = time.time() pool.starmap( functools.partial( _process_instance_to_semantic), iter_annotations(), chunksize=100, ) print("Finished. time: {:.2f}s".format(time.time() - start))
Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files
2,038
import numpy as np import cv2 import os import json error_list = ['23382.png', '23441.png', '20714.png', '20727.png', '23300.png', '21200.png'] def mask2box(mask): def gen_coco(phase): result = { "info": {"description": "PIC2.0 dataset."}, "categories": [ {"supercategory": "none", "id": 1, "name": "person"} ] } out_json = phase +'_person.json' store_segmentation = True images_info = [] labels_info = [] img_id = 0 files = tuple(open("pic/list5/"+phase+'_id', 'r')) files = (_.strip() for _ in files) for index, image_name in enumerate(files): image_name = image_name+".png" print(index, image_name) if image_name in error_list: continue instance = cv2.imread(os.path.join('instance', phase, image_name), flags=cv2.IMREAD_GRAYSCALE) semantic = cv2.imread(os.path.join('semantic', phase, image_name), flags=cv2.IMREAD_GRAYSCALE) # print(instance.shape, semantic.shape) h = instance.shape[0] w = instance.shape[1] images_info.append( { "file_name": image_name[:-4]+'.jpg', "height": h, "width": w, "id": index } ) instance_max_num = instance.max() instance_ids = np.unique(instance) for instance_id in instance_ids: if instance_id == 0: continue instance_part = instance == instance_id object_pos = instance_part.nonzero() # category_id_ = int(semantic[object_pos[0][0], object_pos[1][0]]) category_id = int(np.max(semantic[object_pos[0], object_pos[1]])) # assert category_id_ == category_id, (category_id_, category_id) if category_id != 1: continue area = int(instance_part.sum()) x1, y1, x2, y2 = mask2box(instance_part) w = x2 - x1 + 1 h = y2 - y1 + 1 segmentation = [] if store_segmentation: contours, hierarchy = cv2.findContours((instance_part * 255).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: contour = contour.flatten().tolist() if len(contour) > 4: segmentation.append(contour) if len(segmentation) == 0: print('error') continue labels_info.append( { "segmentation": segmentation, # poly "area": area, # segmentation area "iscrowd": 0, "image_id": index, "bbox": [x1, y1, w, h], "category_id": category_id, "id": img_id }, ) img_id += 1 # break result["images"] = images_info result["annotations"] = labels_info with open('pic/annotations/' + out_json, 'w') as f: json.dump(result, f, indent=4)
null
2,039
import time import functools import multiprocessing as mp import numpy as np import os import argparse from pycocotools.coco import COCO from pycocotools import mask as maskUtils from detectron2.data.datasets.builtin_meta import _get_coco_instances_meta def _process_instance_to_semantic(anns, output_semantic, img, categories): img_size = (img["height"], img["width"]) output = np.zeros(img_size, dtype=np.uint8) for ann in anns: mask = annToMask(ann, img_size) output[mask == 1] = categories[ann["category_id"]] + 1 # save as compressed npz np.savez_compressed(output_semantic, mask=output) # Image.fromarray(output).save(output_semantic) The provided code snippet includes necessary dependencies for implementing the `create_coco_semantic_from_instance` function. Write a Python function `def create_coco_semantic_from_instance(instance_json, sem_seg_root, categories)` to solve the following problem: Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files categories (dict): category metadata. Each dict needs to have: "id": corresponds to the "category_id" in the json annotations "isthing": 0 or 1 Here is the function: def create_coco_semantic_from_instance(instance_json, sem_seg_root, categories): """ Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files categories (dict): category metadata. Each dict needs to have: "id": corresponds to the "category_id" in the json annotations "isthing": 0 or 1 """ os.makedirs(sem_seg_root, exist_ok=True) coco_detection = COCO(instance_json) def iter_annotations(): for img_id in coco_detection.getImgIds(): anns_ids = coco_detection.getAnnIds(img_id) anns = coco_detection.loadAnns(anns_ids) img = coco_detection.loadImgs(int(img_id))[0] file_name = os.path.splitext(img["file_name"])[0] output = os.path.join(sem_seg_root, file_name + '.npz') yield anns, output, img # single process # print("Start writing to {} ...".format(sem_seg_root)) # start = time.time() # for anno, oup, img in iter_annotations(): # _process_instance_to_semantic( # anno, oup, img, categories) # print("Finished. time: {:.2f}s".format(time.time() - start)) # return pool = mp.Pool(processes=max(mp.cpu_count() // 2, 4)) print("Start writing to {} ...".format(sem_seg_root)) start = time.time() pool.starmap( functools.partial( _process_instance_to_semantic, categories=categories), iter_annotations(), chunksize=100, ) print("Finished. time: {:.2f}s".format(time.time() - start))
Create semantic segmentation annotations from panoptic segmentation annotations, to be used by PanopticFPN. It maps all thing categories to contiguous ids starting from 1, and maps all unlabeled pixels to class 0 Args: instance_json (str): path to the instance json file, in COCO's format. sem_seg_root (str): a directory to output semantic annotation files categories (dict): category metadata. Each dict needs to have: "id": corresponds to the "category_id" in the json annotations "isthing": 0 or 1
2,040
import time import functools import multiprocessing as mp import numpy as np import os import argparse from pycocotools.coco import COCO from pycocotools import mask as maskUtils from detectron2.data.datasets.builtin_meta import _get_coco_instances_meta def get_parser(): parser = argparse.ArgumentParser(description="Keep only model in ckpt") parser.add_argument( "--dataset-name", default="coco", help="dataset to generate", ) return parser
null
2,041
import argparse import torch def get_parser(): parser = argparse.ArgumentParser(description="Keep only model in ckpt") parser.add_argument( "--path", default="output/person/blendmask/R_50_1x/", help="path to model weights", ) parser.add_argument( "--name", default="R_50_1x.pth", help="name of output file", ) return parser
null
2,042
import argparse from collections import OrderedDict import torch def get_parser(): parser = argparse.ArgumentParser(description="FCOS Detectron2 Converter") parser.add_argument( "--model", default="weights/blendmask/person/R_50_1x.pth", metavar="FILE", help="path to model weights", ) parser.add_argument( "--output", default="weights/blendmask/person/R_50_1x.pth", metavar="FILE", help="path to model weights", ) return parser
null
2,043
import argparse from collections import OrderedDict import torch def rename_resnet_param_names(ckpt_state_dict): converted_state_dict = OrderedDict() for key in ckpt_state_dict.keys(): value = ckpt_state_dict[key] key = key.replace("centerness", "ctrness") converted_state_dict[key] = value return converted_state_dict
null
2,044
import argparse import numpy as np import os from itertools import chain import cv2 import tqdm from PIL import Image from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader from detectron2.data import detection_utils as utils from detectron2.data.build import filter_images_with_few_keypoints from detectron2.utils.logger import setup_logger from detectron2.utils.visualizer import Visualizer from adet.config import get_cfg from adet.data.dataset_mapper import DatasetMapperWithBasis def setup(args): cfg = get_cfg() if args.config_file: cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() return cfg
null
2,045
import argparse import numpy as np import os from itertools import chain import cv2 import tqdm from PIL import Image from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader from detectron2.data import detection_utils as utils from detectron2.data.build import filter_images_with_few_keypoints from detectron2.utils.logger import setup_logger from detectron2.utils.visualizer import Visualizer from adet.config import get_cfg from adet.data.dataset_mapper import DatasetMapperWithBasis def parse_args(in_args=None): parser = argparse.ArgumentParser(description="Visualize ground-truth data") parser.add_argument( "--source", choices=["annotation", "dataloader"], required=True, help="visualize the annotations or the data loader (with pre-processing)", ) parser.add_argument("--config-file", metavar="FILE", help="path to config file") parser.add_argument("--output-dir", default="./", help="path to output directory") parser.add_argument("--show", action="store_true", help="show output in a window") parser.add_argument( "--opts", help="Modify config options using the command-line", default=[], nargs=argparse.REMAINDER, ) return parser.parse_args(in_args)
null
2,046
import argparse import numpy as np import os from itertools import chain import cv2 import tqdm from PIL import Image from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader from detectron2.data import detection_utils as utils from detectron2.data.build import filter_images_with_few_keypoints from detectron2.utils.logger import setup_logger from detectron2.utils.visualizer import Visualizer from adet.config import get_cfg from adet.data.dataset_mapper import DatasetMapperWithBasis def output(vis, fname): if args.show: print(fname) cv2.imshow("window", vis.get_image()[:, :, ::-1]) cv2.waitKey() else: filepath = os.path.join(dirname, fname) print("Saving to {} ...".format(filepath)) vis.save(filepath)
null
2,047
import logging import os from collections import OrderedDict import torch from torch.nn.parallel import DistributedDataParallel import detectron2.utils.comm as comm from detectron2.data import MetadataCatalog, build_detection_train_loader from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, hooks, launch from detectron2.utils.events import EventStorage from detectron2.evaluation import ( COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, PascalVOCDetectionEvaluator, SemSegEvaluator, verify_results, ) from detectron2.modeling import GeneralizedRCNNWithTTA from detectron2.utils.logger import setup_logger from adet.data.dataset_mapper import DatasetMapperWithBasis from adet.data.fcpose_dataset_mapper import FCPoseDatasetMapper from adet.config import get_cfg from adet.checkpoint import AdetCheckpointer from adet.evaluation import TextEvaluator The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python function `def setup(args)` to solve the following problem: Create configs and perform basic setups. Here is the function: def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() default_setup(cfg, args) rank = comm.get_rank() setup_logger(cfg.OUTPUT_DIR, distributed_rank=rank, name="adet") return cfg
Create configs and perform basic setups.
2,048
import argparse from collections import OrderedDict import torch def get_parser(): parser = argparse.ArgumentParser(description="FCOS Detectron2 Converter") parser.add_argument( "--model", default="weights/fcos_R_50_1x_official.pth", metavar="FILE", help="path to model weights", ) parser.add_argument( "--output", default="weights/fcos_R_50_1x_converted.pth", metavar="FILE", help="path to model weights", ) return parser
null
2,049
import argparse from collections import OrderedDict import torch def rename_resnet_param_names(ckpt_state_dict): converted_state_dict = OrderedDict() for key in ckpt_state_dict.keys(): value = ckpt_state_dict[key] key = key.replace("module.", "") key = key.replace("body", "bottom_up") # adding a . ahead to avoid renaming the fpn modules # this can happen after fpn renaming key = key.replace(".layer1", ".res2") key = key.replace(".layer2", ".res3") key = key.replace(".layer3", ".res4") key = key.replace(".layer4", ".res5") key = key.replace("downsample.0", "shortcut") key = key.replace("downsample.1", "shortcut.norm") key = key.replace("bn1", "conv1.norm") key = key.replace("bn2", "conv2.norm") key = key.replace("bn3", "conv3.norm") key = key.replace("fpn_inner2", "fpn_lateral3") key = key.replace("fpn_inner3", "fpn_lateral4") key = key.replace("fpn_inner4", "fpn_lateral5") key = key.replace("fpn_layer2", "fpn_output3") key = key.replace("fpn_layer3", "fpn_output4") key = key.replace("fpn_layer4", "fpn_output5") key = key.replace("top_blocks", "top_block") key = key.replace("fpn.", "") key = key.replace("rpn", "proposal_generator") key = key.replace("head", "fcos_head") converted_state_dict[key] = value return converted_state_dict
null
2,050
import collections.abc import os import os.path as osp from torch import nn import kornia.augmentation as K import pydiffvg import save_svg import cv2 from ttf import font_string_to_svgs, normalize_letter_size import torch import numpy as np def normalize_letter_size(dest_path, font, txt): fontname = os.path.splitext(os.path.basename(font))[0] for i, c in enumerate(txt): fname = f"{dest_path}/{fontname}_{c}.svg" fname = fname.replace(" ", "_") fix_single_svg(fname) fname = f"{dest_path}/{fontname}_{txt}.svg" fname = fname.replace(" ", "_") fix_single_svg(fname, all_word=True) def font_string_to_svgs(dest_path, font, txt, size=30, spacing=1.0, target_control=None, subdivision_thresh=None): fontname = os.path.splitext(os.path.basename(font))[0] glyph_beziers = font_string_to_beziers(font, txt, size, spacing, merge=False, target_control=target_control) if not os.path.isdir(dest_path): os.mkdir(dest_path) # Compute boundig box points = np.vstack(sum(glyph_beziers, [])) lt = np.min(points, axis=0) rb = np.max(points, axis=0) size = rb - lt sizestr = 'width="%.1f" height="%.1f"' % (size[0], size[1]) boxstr = ' viewBox="%.1f %.1f %.1f %.1f"' % (lt[0], lt[1], size[0], size[1]) header = '''<?xml version="1.0" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" ''' header += sizestr header += boxstr header += '>\n<defs/>\n' svg_all = header for i, (c, beziers) in enumerate(zip(txt, glyph_beziers)): print(f"==== {c} ====") fname, path = write_letter_svg(c, header, fontname, beziers, subdivision_thresh, dest_path) num_cp = count_cp(fname, fontname) print(num_cp) print(font, c) # Add to global svg svg_all += path + '</g>\n' # Save global svg svg_all += '</svg>\n' fname = f"{dest_path}/{fontname}_{txt}.svg" fname = fname.replace(" ", "_") f = open(fname, 'w') f.write(svg_all) f.close() def preprocess(font, word, letter, level_of_cc=1): if level_of_cc == 0: target_cp = None else: target_cp = {"A": 120, "B": 120, "C": 100, "D": 100, "E": 120, "F": 120, "G": 120, "H": 120, "I": 35, "J": 80, "K": 100, "L": 80, "M": 100, "N": 100, "O": 100, "P": 120, "Q": 120, "R": 130, "S": 110, "T": 90, "U": 100, "V": 100, "W": 100, "X": 130, "Y": 120, "Z": 120, "a": 120, "b": 120, "c": 100, "d": 100, "e": 120, "f": 120, "g": 120, "h": 120, "i": 35, "j": 80, "k": 100, "l": 80, "m": 100, "n": 100, "o": 100, "p": 120, "q": 120, "r": 130, "s": 110, "t": 90, "u": 100, "v": 100, "w": 100, "x": 130, "y": 120, "z": 120 } target_cp = {k: v * level_of_cc for k, v in target_cp.items()} print(f"======= {font} =======") font_path = f"code/data/fonts/{font}.ttf" init_path = f"code/data/init" subdivision_thresh = None font_string_to_svgs(init_path, font_path, word, target_control=target_cp, subdivision_thresh=subdivision_thresh) normalize_letter_size(init_path, font_path, word) # optimaize two adjacent letters if len(letter) > 1: subdivision_thresh = None font_string_to_svgs(init_path, font_path, letter, target_control=target_cp, subdivision_thresh=subdivision_thresh) normalize_letter_size(init_path, font_path, letter) print("Done preprocess")
null
2,051
import collections.abc import os import os.path as osp from torch import nn import kornia.augmentation as K import pydiffvg import save_svg import cv2 from ttf import font_string_to_svgs, normalize_letter_size import torch import numpy as np def get_data_augs(cut_size): augmentations = [] augmentations.append(K.RandomPerspective(distortion_scale=0.5, p=0.7)) augmentations.append(K.RandomCrop(size=(cut_size, cut_size), pad_if_needed=True, padding_mode='reflect', p=1.0)) return nn.Sequential(*augmentations)
null
2,052
import collections.abc import os import os.path as osp from torch import nn import kornia.augmentation as K import pydiffvg import save_svg import cv2 from ttf import font_string_to_svgs, normalize_letter_size import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `learning_rate_decay` function. Write a Python function `def learning_rate_decay(step, lr_init, lr_final, max_steps, lr_delay_steps=0, lr_delay_mult=1)` to solve the following problem: Continuous learning rate decay function. The returned rate is lr_init when step=0 and lr_final when step=max_steps, and is log-linearly interpolated elsewhere (equivalent to exponential decay). If lr_delay_steps>0 then the learning rate will be scaled by some smooth function of lr_delay_mult, such that the initial learning rate is lr_init*lr_delay_mult at the beginning of optimization but will be eased back to the normal learning rate when steps>lr_delay_steps. Args: step: int, the current optimization step. lr_init: float, the initial learning rate. lr_final: float, the final learning rate. max_steps: int, the number of steps during optimization. lr_delay_steps: int, the number of steps to delay the full learning rate. lr_delay_mult: float, the multiplier on the rate when delaying it. Returns: lr: the learning for current step 'step'. Here is the function: def learning_rate_decay(step, lr_init, lr_final, max_steps, lr_delay_steps=0, lr_delay_mult=1): """Continuous learning rate decay function. The returned rate is lr_init when step=0 and lr_final when step=max_steps, and is log-linearly interpolated elsewhere (equivalent to exponential decay). If lr_delay_steps>0 then the learning rate will be scaled by some smooth function of lr_delay_mult, such that the initial learning rate is lr_init*lr_delay_mult at the beginning of optimization but will be eased back to the normal learning rate when steps>lr_delay_steps. Args: step: int, the current optimization step. lr_init: float, the initial learning rate. lr_final: float, the final learning rate. max_steps: int, the number of steps during optimization. lr_delay_steps: int, the number of steps to delay the full learning rate. lr_delay_mult: float, the multiplier on the rate when delaying it. Returns: lr: the learning for current step 'step'. """ if lr_delay_steps > 0: # A kind of reverse cosine decay. delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin( 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)) else: delay_rate = 1. t = np.clip(step / max_steps, 0, 1) log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t) return delay_rate * log_lerp
Continuous learning rate decay function. The returned rate is lr_init when step=0 and lr_final when step=max_steps, and is log-linearly interpolated elsewhere (equivalent to exponential decay). If lr_delay_steps>0 then the learning rate will be scaled by some smooth function of lr_delay_mult, such that the initial learning rate is lr_init*lr_delay_mult at the beginning of optimization but will be eased back to the normal learning rate when steps>lr_delay_steps. Args: step: int, the current optimization step. lr_init: float, the initial learning rate. lr_final: float, the final learning rate. max_steps: int, the number of steps during optimization. lr_delay_steps: int, the number of steps to delay the full learning rate. lr_delay_mult: float, the multiplier on the rate when delaying it. Returns: lr: the learning for current step 'step'.
2,053
import collections.abc import os import os.path as osp from torch import nn import kornia.augmentation as K import pydiffvg import save_svg import cv2 from ttf import font_string_to_svgs, normalize_letter_size import torch import numpy as np def save_image(img, filename, gamma=1): check_and_create_dir(filename) imshow = img.detach().cpu() pydiffvg.imwrite(imshow, filename, gamma=gamma) def get_letter_ids(letter, word, shape_groups): for group, l in zip(shape_groups, word): if l == letter: return group.shape_ids def save_svg(filename, width, height, shapes, shape_groups, use_gamma = False, background=None): root = etree.Element('svg') root.set('version', '1.1') root.set('xmlns', 'http://www.w3.org/2000/svg') root.set('width', str(width)) root.set('height', str(height)) if background is not None: print(f"setting background to {background}") root.set('style', str(background)) defs = etree.SubElement(root, 'defs') g = etree.SubElement(root, 'g') if use_gamma: f = etree.SubElement(defs, 'filter') f.set('id', 'gamma') f.set('x', '0') f.set('y', '0') f.set('width', '100%') f.set('height', '100%') gamma = etree.SubElement(f, 'feComponentTransfer') gamma.set('color-interpolation-filters', 'sRGB') feFuncR = etree.SubElement(gamma, 'feFuncR') feFuncR.set('type', 'gamma') feFuncR.set('amplitude', str(1)) feFuncR.set('exponent', str(1/2.2)) feFuncG = etree.SubElement(gamma, 'feFuncG') feFuncG.set('type', 'gamma') feFuncG.set('amplitude', str(1)) feFuncG.set('exponent', str(1/2.2)) feFuncB = etree.SubElement(gamma, 'feFuncB') feFuncB.set('type', 'gamma') feFuncB.set('amplitude', str(1)) feFuncB.set('exponent', str(1/2.2)) feFuncA = etree.SubElement(gamma, 'feFuncA') feFuncA.set('type', 'gamma') feFuncA.set('amplitude', str(1)) feFuncA.set('exponent', str(1/2.2)) g.set('style', 'filter:url(#gamma)') # Store color for i, shape_group in enumerate(shape_groups): def add_color(shape_color, name): if isinstance(shape_color, pydiffvg.LinearGradient): lg = shape_color color = etree.SubElement(defs, 'linearGradient') color.set('id', name) color.set('x1', str(lg.begin[0].item()/width)) color.set('y1', str(lg.begin[1].item()/height)) color.set('x2', str(lg.end[0].item()/width)) color.set('y2', str(lg.end[1].item()/height)) offsets = lg.offsets.data.cpu().numpy() stop_colors = lg.stop_colors.data.cpu().numpy() for j in range(offsets.shape[0]): stop = etree.SubElement(color, 'stop') stop.set('offset', str(offsets[j])) c = lg.stop_colors[j, :] stop.set('stop-color', 'rgb({}, {}, {})'.format(\ int(255 * c[0]), int(255 * c[1]), int(255 * c[2]))) stop.set('stop-opacity', '{}'.format(c[3])) if isinstance(shape_color, pydiffvg.RadialGradient): lg = shape_color color = etree.SubElement(defs, 'radialGradient') color.set('id', name) color.set('cx', str(lg.center[0].item()/width)) color.set('cy', str(lg.center[1].item()/height)) # this only support width=height color.set('r', str(lg.radius[0].item()/width)) offsets = lg.offsets.data.cpu().numpy() stop_colors = lg.stop_colors.data.cpu().numpy() for j in range(offsets.shape[0]): stop = etree.SubElement(color, 'stop') stop.set('offset', str(offsets[j])) c = lg.stop_colors[j, :] stop.set('stop-color', 'rgb({}, {}, {})'.format(\ int(255 * c[0]), int(255 * c[1]), int(255 * c[2]))) stop.set('stop-opacity', '{}'.format(c[3])) if shape_group.fill_color is not None: add_color(shape_group.fill_color, 'shape_{}_fill'.format(i)) if shape_group.stroke_color is not None: add_color(shape_group.stroke_color, 'shape_{}_stroke'.format(i)) for i, shape_group in enumerate(shape_groups): # shape = shapes[shape_group.shape_ids[0]] for j,id in enumerate(shape_group.shape_ids): shape = shapes[id] if isinstance(shape, pydiffvg.Path): if j == 0: shape_node = etree.SubElement(g, 'path') path_str = '' # shape_node = etree.SubElement(g, 'path') num_segments = shape.num_control_points.shape[0] num_control_points = shape.num_control_points.data.cpu().numpy() points = shape.points.data.cpu().numpy() num_points = shape.points.shape[0] path_str += 'M {} {}'.format(points[0, 0], points[0, 1]) point_id = 1 for j in range(0, num_segments): if num_control_points[j] == 0: p = point_id % num_points path_str += ' L {} {}'.format(\ points[p, 0], points[p, 1]) point_id += 1 elif num_control_points[j] == 1: p1 = (point_id + 1) % num_points path_str += ' Q {} {} {} {}'.format(\ points[point_id, 0], points[point_id, 1], points[p1, 0], points[p1, 1]) point_id += 2 elif num_control_points[j] == 2: p2 = (point_id + 2) % num_points path_str += ' C {} {} {} {} {} {}'.format(\ points[point_id, 0], points[point_id, 1], points[point_id + 1, 0], points[point_id + 1, 1], points[p2, 0], points[p2, 1]) point_id += 3 else: assert(False) # shape_node.set('stroke-width', str(2 * shape.stroke_width.data.cpu().item())) shape_node.set('stroke-width', str(0)) # no strokes if shape_group.fill_color is not None: if isinstance(shape_group.fill_color, pydiffvg.LinearGradient): shape_node.set('fill', 'url(#shape_{}_fill)'.format(i)) elif isinstance(shape_group.fill_color, pydiffvg.RadialGradient): shape_node.set('fill', 'url(#shape_{}_fill)'.format(i)) else: c = shape_group.fill_color.data.cpu().numpy() shape_node.set('fill', 'rgb({}, {}, {})'.format(\ int(255 * c[0]), int(255 * c[1]), int(255 * c[2]))) shape_node.set('opacity', str(c[3])) else: shape_node.set('fill', 'none') if shape_group.stroke_color is not None: if isinstance(shape_group.stroke_color, pydiffvg.LinearGradient): shape_node.set('stroke', 'url(#shape_{}_stroke)'.format(i)) elif isinstance(shape_group.stroke_color, pydiffvg.LinearGradient): shape_node.set('stroke', 'url(#shape_{}_stroke)'.format(i)) else: c = shape_group.stroke_color.data.cpu().numpy() shape_node.set('stroke', 'rgb({}, {}, {})'.format(\ int(255 * c[0]), int(255 * c[1]), int(255 * c[2]))) shape_node.set('stroke-opacity', str(c[3])) shape_node.set('stroke-linecap', 'round') shape_node.set('stroke-linejoin', 'round') shape_node.set('d', path_str) with open(filename, "w") as f: f.write(prettify(root)) def combine_word(word, letter, font, experiment_dir): word_svg_scaled = f"./code/data/init/{font}_{word}_scaled.svg" canvas_width_word, canvas_height_word, shapes_word, shape_groups_word = pydiffvg.svg_to_scene(word_svg_scaled) letter_ids = [] for l in letter: letter_ids += get_letter_ids(l, word, shape_groups_word) w_min, w_max = min([torch.min(shapes_word[ids].points[:, 0]) for ids in letter_ids]), max( [torch.max(shapes_word[ids].points[:, 0]) for ids in letter_ids]) h_min, h_max = min([torch.min(shapes_word[ids].points[:, 1]) for ids in letter_ids]), max( [torch.max(shapes_word[ids].points[:, 1]) for ids in letter_ids]) c_w = (-w_min + w_max) / 2 c_h = (-h_min + h_max) / 2 svg_result = os.path.join(experiment_dir, "output-svg", "output.svg") canvas_width, canvas_height, shapes, shape_groups = pydiffvg.svg_to_scene(svg_result) out_w_min, out_w_max = min([torch.min(p.points[:, 0]) for p in shapes]), max( [torch.max(p.points[:, 0]) for p in shapes]) out_h_min, out_h_max = min([torch.min(p.points[:, 1]) for p in shapes]), max( [torch.max(p.points[:, 1]) for p in shapes]) out_c_w = (-out_w_min + out_w_max) / 2 out_c_h = (-out_h_min + out_h_max) / 2 scale_canvas_w = (w_max - w_min) / (out_w_max - out_w_min) scale_canvas_h = (h_max - h_min) / (out_h_max - out_h_min) if scale_canvas_h > scale_canvas_w: wsize = int((out_w_max - out_w_min) * scale_canvas_h) scale_canvas_w = wsize / (out_w_max - out_w_min) shift_w = -out_c_w * scale_canvas_w + c_w else: hsize = int((out_h_max - out_h_min) * scale_canvas_w) scale_canvas_h = hsize / (out_h_max - out_h_min) shift_h = -out_c_h * scale_canvas_h + c_h for num, p in enumerate(shapes): p.points[:, 0] = p.points[:, 0] * scale_canvas_w p.points[:, 1] = p.points[:, 1] * scale_canvas_h if scale_canvas_h > scale_canvas_w: p.points[:, 0] = p.points[:, 0] - out_w_min * scale_canvas_w + w_min + shift_w p.points[:, 1] = p.points[:, 1] - out_h_min * scale_canvas_h + h_min else: p.points[:, 0] = p.points[:, 0] - out_w_min * scale_canvas_w + w_min p.points[:, 1] = p.points[:, 1] - out_h_min * scale_canvas_h + h_min + shift_h for j, s in enumerate(letter_ids): shapes_word[s] = shapes[j] save_svg.save_svg( f"{experiment_dir}/{font}_{word}_{letter}.svg", canvas_width, canvas_height, shapes_word, shape_groups_word) render = pydiffvg.RenderFunction.apply scene_args = pydiffvg.RenderFunction.serialize_scene(canvas_width, canvas_height, shapes_word, shape_groups_word) img = render(canvas_width, canvas_height, 2, 2, 0, None, *scene_args) img = img[:, :, 3:4] * img[:, :, :3] + \ torch.ones(img.shape[0], img.shape[1], 3, device="cuda:0") * (1 - img[:, :, 3:4]) img = img[:, :, :3] save_image(img, f"{experiment_dir}/{font}_{word}_{letter}.png")
null
2,054
import collections.abc import os import os.path as osp from torch import nn import kornia.augmentation as K import pydiffvg import save_svg import cv2 from ttf import font_string_to_svgs, normalize_letter_size import torch import numpy as np def check_and_create_dir(path): pathdir = osp.split(path)[0] if osp.isdir(pathdir): pass else: os.makedirs(pathdir) def create_video(num_iter, experiment_dir, video_frame_freq): img_array = [] for ii in range(0, num_iter): if ii % video_frame_freq == 0 or ii == num_iter - 1: filename = os.path.join( experiment_dir, "video-png", f"iter{ii:04d}.png") img = cv2.imread(filename) img_array.append(img) video_name = os.path.join( experiment_dir, "video.mp4") check_and_create_dir(video_name) out = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'mp4v'), 30.0, (600, 600)) for iii in range(len(img_array)): out.write(img_array[iii]) out.release()
null
2,055
from typing import Mapping import os from tqdm import tqdm from easydict import EasyDict as edict import matplotlib.pyplot as plt import torch from torch.optim.lr_scheduler import LambdaLR import pydiffvg import save_svg from losses import SDSLoss, ToneLoss, ConformalLoss from config import set_config from utils import ( check_and_create_dir, get_data_augs, save_image, preprocess, learning_rate_decay, combine_word, create_video) import wandb import warnings pydiffvg.set_print_timing(False) def init_shapes(svg_path, trainable: Mapping[str, bool]): svg = f'{svg_path}.svg' canvas_width, canvas_height, shapes_init, shape_groups_init = pydiffvg.svg_to_scene(svg) parameters = edict() # path points if trainable.point: parameters.point = [] for path in shapes_init: path.points.requires_grad = True parameters.point.append(path.points) return shapes_init, shape_groups_init, parameters
null
2,056
import argparse import os.path as osp import yaml import random from easydict import EasyDict as edict import numpy.random as npr import torch from utils import ( edict_2_dict, check_and_create_dir, update) import wandb import warnings def parse_args(): def edict_2_dict(x): def check_and_create_dir(path): def update(d, u): def set_config(): cfg_arg = parse_args() with open(cfg_arg.config, 'r') as f: cfg_full = yaml.load(f, Loader=yaml.FullLoader) # recursively traverse parent_config pointers in the config dicts cfg_key = cfg_arg.experiment cfgs = [cfg_arg] while cfg_key: cfgs.append(cfg_full[cfg_key]) cfg_key = cfgs[-1].get('parent_config', 'baseline') # allowing children configs to override their parents cfg = edict() for options in reversed(cfgs): update(cfg, options) del cfgs # set experiment dir signature = f"{cfg.letter}_concept_{cfg.semantic_concept}_seed_{cfg.seed}" cfg.experiment_dir = \ osp.join(cfg.log_dir, cfg.font, signature) configfile = osp.join(cfg.experiment_dir, 'config.yaml') print('Config:', cfg) # create experiment dir and save config check_and_create_dir(configfile) with open(osp.join(configfile), 'w') as f: yaml.dump(edict_2_dict(cfg), f) if cfg.use_wandb: wandb.init(project="Word-As-Image", entity=cfg.wandb_user, config=cfg, name=f"{signature}", id=wandb.util.generate_id()) if cfg.seed is not None: random.seed(cfg.seed) npr.seed(cfg.seed) torch.manual_seed(cfg.seed) torch.backends.cudnn.benchmark = False else: assert False return cfg
null
2,057
import numpy as np import matplotlib.pyplot as plt from scipy.special import binom from numpy.linalg import norm def cubic_bezier(P, t): return (1.0-t)**3*P[0] + 3*(1.0-t)**2*t*P[1] + 3*(1.0-t)*t**2*P[2] + t**3*P[3]
null
2,058
import numpy as np import matplotlib.pyplot as plt from scipy.special import binom from numpy.linalg import norm def bezier_piecewise(Cp, subd=100, degree=3, d=0): ''' sample a piecewise Bezier curve given a sequence of control points''' num = num_bezier(Cp.shape[0], degree) X = [] for i in range(num): P = Cp[i*degree:i*degree+degree+1, :] t = np.linspace(0, 1., subd)[:-1] Y = bezier(P, t, d) X += [Y] X.append(Cp[-1]) X = np.vstack(X) return X def beziers_to_chain(beziers): ''' Convert list of Bezier curve segments to a piecewise bezier chain (shares vertices)''' n = len(beziers) chain = [] for i in range(n): chain.append(list(beziers[i][:-1])) chain.append([beziers[-1][-1]]) return np.array(sum(chain, [])) def compute_beziers(beziers, subd=100, degree=3): chain = beziers_to_chain(beziers) return bezier_piecewise(chain, subd, degree)
null