id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
141,418
import logging from dataclasses import dataclass, field from typing import Optional import torch import torch.nn as nn from omegaconf import II from metaseq.dataclass import ChoiceEnum, MetaseqDataclass from metaseq.dataclass.constants import ATTN_CHOICES, UNSPECIFIED_DOC_SEP from metaseq.models import ( BaseModel,...
null
141,419
import logging from dataclasses import dataclass, field from typing import Optional import torch import torch.nn as nn from omegaconf import II from metaseq.dataclass import ChoiceEnum, MetaseqDataclass from metaseq.dataclass.constants import ATTN_CHOICES, UNSPECIFIED_DOC_SEP from metaseq.models import ( BaseModel,...
null
141,420
import logging from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from omegaconf import DictConfig from torch import Tensor from metaseq.dataclass.utils import gen_parser_from_dataclass from metaseq.models import BaseDecoder def check_type(module, expected...
null
141,422
import os import sys import glob import numpy as np import hashlib SEED_SIZE = 16*1024*1024 def xor_files(input_path, output_path): # Check if output file exists if os.path.exists(output_path): print('Skipping already decrypted file: ' + output_path) return print('Decrypting: ', input_path,...
null
141,423
import gradio as gr import subprocess import sys from pathlib import Path async def generate(prompt, model_name, seed=0, temperature=0.5, num_tokens=256): # stream stout base = ""#"../model/" tokenizer_name = "tokenizer.bin" if model_name == "tl-chat.bin": tokenizer_name = 'tok_tl-chat.bin' ...
null
141,424
import argparse import multiprocessing import os import torch import transformers from accelerate import PartialState from datasets import load_dataset from peft import LoraConfig from transformers import ( AutoModelForCausalLM, BitsAndBytesConfig, logging, set_seed, ) from trl import SFTTrainer def ge...
null
141,425
import argparse import multiprocessing import os import torch import transformers from accelerate import PartialState from datasets import load_dataset from peft import LoraConfig from transformers import ( AutoModelForCausalLM, BitsAndBytesConfig, logging, set_seed, ) from trl import SFTTrainer The pr...
Prints the number of trainable parameters in the model.
141,426
import torch.optim as optim import os from ltr.dataset import Lasot, Got10k, TrackingNet from ltr.data import processing, sampler, LTRLoader import ltr.models.tracking.kysnet as kysnet_models import ltr.models.loss as ltr_losses from ltr import actors from ltr.trainers import LTRTrainer from ltr.models.kys.utils import...
null
141,427
import torch.nn as nn import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses from ltr import actors from ltr.trainers import LTRTrainer import ltr.data.tran...
null
141,428
import torch.nn as nn import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses from ltr import actors from ltr.trainers import LTRTrainer import ltr.data.tran...
null
141,429
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses import ltr.models.loss.kl_regression as klreg_losses import ltr.actors.tracking as tracking_actors fr...
null
141,430
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses import ltr.models.loss.kl_regression as klreg_losses import ltr.actors.tracking as tracking_actors fr...
null
141,431
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses import ltr.models.loss.kl_regression as klreg_losses import ltr.actors.tracking as tracking_actors fr...
null
141,432
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import dimpnet import ltr.models.loss as ltr_losses import ltr.models.loss.kl_regression as klreg_losses import ltr.actors.tracking as tracking_actors fr...
null
141,433
import torch.optim as optim from ltr.dataset import YouTubeVOS, Davis, Got10k, Got10kVOS, LasotVOS from ltr.data import processing, sampler, LTRLoader import ltr.models.rts.rts_net as rts_networks import ltr.actors.segmentation as segm_actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm from lt...
null
141,434
import torch.nn as nn import torch.optim as optim from ltr.dataset import Lasot, TrackingNet, MSCOCOSeq, Got10k from ltr.data import processing, sampler, LTRLoader import ltr.models.bbreg.atom as atom_models from ltr import actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm def run(settings):...
null
141,435
import torch.nn as nn import torch.optim as optim from ltr.dataset import Lasot, TrackingNet, MSCOCOSeq, Got10k from ltr.data import processing, sampler, LTRLoader import ltr.models.bbreg.atom as atom_models from ltr import actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm def run(settings):...
null
141,436
import torch.optim as optim from ltr.dataset import Lasot, TrackingNet, MSCOCOSeq, Got10k from ltr.data import processing, sampler, LTRLoader import ltr.models.bbreg.atom as atom_models import ltr.models.loss.kl_regression as klreg_losses import ltr.actors.bbreg as bbreg_actors from ltr.trainers import LTRTrainer impor...
null
141,437
import torch.nn as nn import torch.optim as optim from ltr.dataset import Lasot, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader import ltr.models.bbreg.atom as atom_models from ltr import actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm def run(settings): # M...
null
141,438
import os import torch.optim as optim from ltr.dataset import LasotCandidateMatching from ltr.data import processing, sampler, LTRLoader from ltr.models.target_candidate_matching import target_candidate_matching as tcm import ltr.models.loss.target_candidate_matching_loss as tcm_loss import ltr.actors.tracking as tcm...
null
141,439
import torch import torch.optim as optim from ltr.data.loader import MultiEpochLTRLoader from ltr.dataset import Got10k, Lasot, TrackingNet, MSCOCOMOTSeq, YouTubeVOS, ImagenetVIDMOT, TAOBURST from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import tamosnet import ltr.models.loss as ltr_losse...
null
141,440
import torch import torch.optim as optim from ltr.data.loader import MultiEpochLTRLoader from ltr.dataset import Got10k, Lasot, TrackingNet, MSCOCOMOTSeq, YouTubeVOS, TAOBURST, ImagenetVIDMOT from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import tamosnet import ltr.models.loss as ltr_losse...
null
141,441
import torch.optim as optim from ltr.dataset import YouTubeVOS, Davis from ltr.data import processing, sampler, LTRLoader import ltr.models.lwl.lwl_net as lwl_networks import ltr.actors.segmentation as segm_actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm from ltr import MultiGPU from ltr.mo...
null
141,442
import torch.optim as optim from ltr.dataset import YouTubeVOS, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader import ltr.models.lwl.lwl_box_net as lwt_box_networks import ltr.actors.segmentation as lwtl_actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm from ltr import MultiGPU...
null
141,443
import torch import os import torch.optim as optim from ltr.dataset import YouTubeVOS, Davis from ltr.data import processing, sampler, LTRLoader import ltr.models.lwl.lwl_net as lwl_networks import ltr.actors.segmentation as segm_actors from ltr.trainers import LTRTrainer import ltr.data.transforms as tfm from ltr impo...
null
141,444
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import tompnet import ltr.models.loss as ltr_losses import ltr.actors.tracking as actors from ltr.trainers import LTRTrainer import ltr.data.transforms a...
null
141,445
import torch.optim as optim from ltr.dataset import Lasot, Got10k, TrackingNet, MSCOCOSeq from ltr.data import processing, sampler, LTRLoader from ltr.models.tracking import tompnet import ltr.models.loss as ltr_losses import ltr.actors.tracking as actors from ltr.trainers import LTRTrainer import ltr.data.transforms a...
null
141,446
import random import torch.utils.data from pytracking import TensorDict def no_processing(data): return data
null
141,447
import torch import torch.utils.data.dataloader import importlib import collections from pytracking import TensorDict, TensorList string_classes = (str, bytes) def _check_use_shared_memory(): if hasattr(torch.utils.data.dataloader, '_use_shared_memory'): return getattr(torch.utils.data.dataloader, '_use_sha...
Puts each data field into a tensor with outer dimension batch size
141,448
import torch import torch.utils.data.dataloader import importlib import collections from pytracking import TensorDict, TensorList string_classes = (str, bytes) def _check_use_shared_memory(): if hasattr(torch.utils.data.dataloader, '_use_shared_memory'): return getattr(torch.utils.data.dataloader, '_use_sha...
Puts each data field into a tensor. The tensors are stacked at dim=1 to form the batch
141,449
import torch import math import numpy as np import cv2 as cv import torchvision.transforms as transforms from pytracking import TensorDict import ltr.data.processing_utils as prutils def stack_tensors(x): if isinstance(x, (list, tuple)) and isinstance(x[0], torch.Tensor): return torch.stack(x) return x
null
141,455
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def sample_target(im, target_bb, search_area_factor, output_sz=None, mask=None): """ Extracts a square crop centered at target_bb box, of...
For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2 times box_extract area. The extracted crops are then resized to output_sz. Further, the co-ordinates of the box box_gt are transformed to the image crop co-ordinates args: frames - list of frames box_extract - list of...
141,456
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList The provided code snippet includes necessary dependencies for implementing the `sample_target_from_crop_region` function. Write a Python fun...
Extracts a crop of the image according to the crop box with the specified output size. args: im - Input numpy image to crop. crop_box - crop box [x, y, w, h] output_sz - Size to which the extracted crop is resized (always square) or tuple. returns: numpy image - Extracted crop.
141,457
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def crop_and_resize(im, box, crop_bb, output_sz, mask=None): if isinstance(output_sz, (float, int)): output_sz = (output_sz, out...
null
141,458
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def sample_target_adaptive(im, target_bb, search_area_factor, output_sz, mode: str = 'replicate', max_scale_change...
For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2 times box_extract area. If the crop area contains regions outside the image, it is shifted / shrunk so that it completely fits inside the image. The extracted crops are then resized to output_sz. Further, the co-ordin...
141,459
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def iou(reference, proposals): """Compute the IoU between a reference box with multiple proposal boxes. args: reference - Ten...
Perturb the input box by adding gaussian noise to the co-ordinates args: box - input box min_iou - minimum IoU overlap between input box and the perturbed box sigma_factor - amount of perturbation, relative to the box size. Can be either a single element, or a list of sigma_factors, in which case one of them will be un...
141,460
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def gauss_2d(sz, sigma, center, end_pad=(0, 0), density=False): if isinstance(sigma, (float, int)): sigma = (sigma, sigma) re...
Construct Gaussian label function.
141,461
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def gmm_density_centered(x, std): """Evaluate the probability density of a GMM centered at zero. args: x - Samples. Assumes d...
Sample from a GMM distribution: args: mean - a single mean vector std - Tensor of standard deviations num_samples - number of samples
141,462
import torch import math import cv2 as cv import random import torch.nn.functional as F from .bounding_box_utils import rect_to_rel, rel_to_rect from pytracking import TensorList def gauss_density_centered(x, std): """Evaluate the probability density of a Gaussian centered at zero. args: x - Samples. ...
Sample boxes from a Gaussian mixture model. args: mean_box - Center (or mean) bounding box proposal_sigma - List of standard deviations for each Gaussian gt_sigma - Standard deviation of the ground truth distribution num_samples - Number of sampled boxes add_mean_box - Also add mean box as first element returns: propos...
141,463
import os import sys import argparse import importlib import multiprocessing import cv2 as cv import torch.backends.cudnn import ltr.admin.settings as ws_settings The provided code snippet includes necessary dependencies for implementing the `run_training` function. Write a Python function `def run_training(train_modu...
Run a train scripts in train_settings. args: train_module: Name of module in the "train_settings/" folder. train_name: Name of the train settings file. cudnn_benchmark: Use cudnn benchmark or not (default is True).
141,464
from functools import wraps import importlib class NetConstructor: """ Class to construct networks. Takes as input the function name (e.g. atom_resnet18), the name of the module which contains the network function (e.g. ltr.models.bbreg.atom) and the arguments for the network function. The class object can ...
Wraps the function 'f' which returns the network. An extra field 'constructor' is added to the network returned by 'f'. This field contains an instance of the 'NetConstructor' class, which contains the information needed to re-construct the network, such as the name of the function 'f', the function arguments etc. Thus...
141,465
import torch import os import sys from pathlib import Path import importlib import inspect import ltr.admin.settings as ws_settings def load_weights(net, path, strict=True): checkpoint_dict = torch.load(path) weight_dict = checkpoint_dict['net'] net.load_state_dict(weight_dict, strict=strict) return ne...
null
141,467
import importlib import os from collections import OrderedDict def create_default_local_file(): path = os.path.join(os.path.dirname(__file__), 'local.py') empty_str = '\'\'' default_settings = OrderedDict({ 'workspace_dir': empty_str, 'tensorboard_dir': 'self.workspace_dir + \'/tensorboard/\...
null
141,468
import torch.nn as nn class MultiGPU(nn.DataParallel): """Wraps a network to allow simple multi-GPU training.""" def __getattr__(self, item): try: return super().__getattr__(item) except: pass return getattr(self.module, item) def is_multi_gpu(net): return is...
null
141,469
import os from .base_video_dataset import BaseVideoDataset from ltr.data.image_loader import default_image_loader import xml.etree.ElementTree as ET import json import torch import random from collections import OrderedDict from ltr.admin.environment import env_settings def get_target_to_image_ratio(seq): anno = t...
null
141,470
import torch import os import os.path import numpy as np import pandas import random from collections import OrderedDict from ltr.data.image_loader import jpeg4py_loader from .base_video_dataset import BaseVideoDataset from ltr.admin.environment import env_settings The provided code snippet includes necessary dependen...
Lists all the videos in the input set_ids. Returns a list of tuples (set_id, video_name) args: root: Root directory to TrackingNet set_ids: Sets (0-11) which are to be used returns: list - list of tuples (set_id, video_name) containing the set_id and video_name for each sequence
141,471
import os import pandas from .base_video_dataset import BaseVideoDataset from ltr.data.image_loader import jpeg4py_loader import json import torch from collections import OrderedDict from ltr.admin.environment import env_settings def get_target_to_image_ratio(seq): anno = torch.Tensor(seq['anno']) img_sz = tor...
null
141,472
import os from collections import OrderedDict from ltr.trainers import BaseTrainer from ltr.admin.stats import AverageMeter, StatValue from ltr.admin.tensorboard import TensorboardWriter import torch import torch.nn as nn import time def freeze_batchnorm_layers(net): for module in net.modules(): if isinsta...
null
141,473
import torch import torch.nn as nn import torch.nn.functional as F def shift_features(feat, relative_translation_vector): T_mat = torch.eye(2).repeat(feat.shape[0], 1, 1).to(feat.device) T_mat = torch.cat((T_mat, relative_translation_vector.view(-1, 2, 1)), dim=2) grid = F.affine_grid(T_mat, feat.shape) ...
null
141,474
import torch import torch.nn as nn import numpy as np from spatial_correlation_sampler import SpatialCorrelationSampler The provided code snippet includes necessary dependencies for implementing the `remap_cost_volume` function. Write a Python function `def remap_cost_volume(cost_volume)` to solve the following proble...
:param cost_volume: cost volume of shape (batch, (2*md-1)*(2*md-1), rows, cols), where md is the maximum displacement allowed when computing the cost volume. :return: cost_volume_remapped: The input cost volume is remapped to shape (batch, rows, cols, rows, cols)
141,475
import math import torch.nn as nn import os import torch from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls import ltr.admin.settings as ws_settings from .base import Backbone The provided code snippet includes necessary dependencies for imple...
3x3 convolution with padding
141,476
import math import torch.nn as nn import os import torch from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls import ltr.admin.settings as ws_settings from .base import Backbone class Bottleneck(nn.Module): expansion = 4 def __init__(self...
Constructs a ResNet-50 model.
141,477
import os from collections import OrderedDict import functools import torch import torch.nn.functional as F from torch import nn import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import ltr.admin.settings as env_settings from .base import Ba...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
141,478
import os from collections import OrderedDict import functools import torch import torch.nn.functional as F from torch import nn import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import ltr.admin.settings as env_settings from .base import Ba...
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
141,479
import os from collections import OrderedDict import functools import torch import torch.nn.functional as F from torch import nn import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import ltr.admin.settings as env_settings from .base import Ba...
null
141,480
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict def get_model_parameters(model): total_parameters = 0 for layer in list(model.parameters()): layer_parameter = 1 for l in list(layer.size()): layer_parameter *= l total_par...
null
141,481
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict def _weights_init(m): if isinstance(m, nn.Conv2d): torch.nn.init.xavier_uniform_(m.weight) if m.bias is not None: torch.nn.init.zeros_(m.bias) elif isinstance(m, nn.BatchNorm2d): ...
null
141,482
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict def _make_divisible(v, divisor=8, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not ...
null
141,483
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict class MobileNetV3(nn.Module): def __init__(self, model_mode="LARGE", num_classes=1000, multiplier=1.0, dropout_rate=0.0, output_layers=['default']): super(MobileNetV3, self).__init__() self.num_cla...
Constructs a ResNet-18 model with first-layer VGGm features.
141,484
import math import torch import torch.nn as nn from collections import OrderedDict from torchvision.models.resnet import BasicBlock from .base import Backbone class ResNetVGGm1(Backbone): def __init__(self, block, layers, output_layers, num_classes=1000, frozen_layers=()): self.inplanes = 64 super(R...
Constructs a ResNet-18 model with first-layer VGGm features.
141,485
import math import torch.nn as nn from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from .base import Backbone The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def con...
3x3 convolution with padding
141,486
import math import torch.nn as nn from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from .base import Backbone class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1, use_b...
Constructs a ResNet-18 model.
141,487
import math import torch.nn as nn from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from .base import Backbone class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1, use_b...
Constructs a ResNet-18 model.
141,488
import math import torch.nn as nn from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from .base import Backbone class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): ...
Constructs a ResNet-50 model.
141,489
import math import torch.nn as nn from collections import OrderedDict import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from .base import Backbone class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): ...
Constructs a ResNet-101 model.
141,490
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `_apply_feat_transpose_v1` function. Write a Python function `def _apply_feat_transpose_v1(feat, input, filter_ksz)` to solve the following problem: This one is slow as hell!!!! Here is the func...
This one is slow as hell!!!!
141,491
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `_apply_feat_transpose_v4` function. Write a Python function `def _apply_feat_transpose_v4(feat, input, filter_ksz)` to solve the following problem: Slow forward fast backward Here is the functi...
Slow forward fast backward
141,492
import torch import torch.nn.functional as F def apply_filter(feat, filter, dilation_factors=None): """Applies the filter on the input features (feat). The number of groups is automatically calculated. args: feat: These are the input features. Must have dimensions (images_in_sequence, sequences, feat_di...
Computes gradient of the filter when applied on the input features and ground truth label. args: feat: These are the input features. Must have dimensions (images_in_sequence, sequences, feat_dim, H, W) filter: The filter to apply. Must have dimensions (sequences, feat_dim, fH, fW) label: Ground truth label in the L2 lo...
141,493
import math import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `softmax_reg` function. Write a Python function `def softmax_reg(x: torch.Tensor, dim, reg=None)` to solve the following problem: Softmax with optional denominat...
Softmax with optional denominator regularization.
141,494
from torch import nn def conv_block(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, bias=True, batch_norm=True, relu=True, padding_mode='zeros'): layers = [] assert padding_mode == 'zeros' or padding_mode == 'replicate' if padding_mode == 'replicate' and padding > 0: ...
null
141,495
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `interpolate` function. Write a Python function `def interpolate(x, sz)` to solve the following problem: Interpolate 4D tensor x to size ...
Interpolate 4D tensor x to size sz.
141,496
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def MLP(channels, do_bn=True): n = len(channels) layers = [] for i in range(1, n): layers.append( nn.Conv1d(channels[i - 1], channels[i], kernel_size=1...
null
141,497
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def normalize_keypoints(kpts, shape_or_size): if isinstance(shape_or_size, (tuple, list)): # it's a shape h, w = shape_or_size[-2:] size = kpts.new_tensor(...
null
141,498
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def attention(query, key, value): dim = query.shape[1] scores = torch.einsum('bdhn,bdhm->bhnm', query, key) / dim**.5 prob = torch.nn.functional.softmax(scores, dim=-1) ...
null
141,499
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def log_sinkhorn_iterations(Z, log_mu, log_nu, iters): def log_optimal_transport(scores, alpha, iters): b, m, n = scores.shape one = scores.new_tensor(1) ms, ns = (m*one)....
null
141,500
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def log_double_softmax(scores, bin_score): b, m, n = scores.shape bin_ = bin_score[None, None, None] scores0 = torch.cat([scores, bin_.expand(b, m, 1)], 2) scores1 = t...
null
141,501
import torch import torch.utils.checkpoint from torch import nn from copy import deepcopy, copy from abc import ABCMeta, abstractmethod def arange_like(x, dim): return x.new_ones(x.shape[dim]).cumsum(0) - 1 # traceable in 1.1
null
141,502
import torch from torch import nn import torch.nn.functional as F from torchvision.models.resnet import BasicBlock, Bottleneck from ltr.models.layers.normalization import InstanceL2Norm from ltr.models.layers.transform import InterpCat class InstanceL2Norm(nn.Module): """Instance L2 normalization. """ def ...
Construct a network block based on the BasicBlock used in ResNet.
141,503
import torch import torch.nn.functional as F def interpolate(t, sz, mode='bilinear'): sz = sz.tolist() if torch.is_tensor(sz) else sz align = {} if mode == 'nearest' else dict(align_corners=False) return F.interpolate(t, sz, mode=mode, **align) if t.shape[-2:] != sz else t def adaptive_cat(seq, dim=0, ref_...
null
141,504
import math import torch import torch.nn as nn from collections import OrderedDict import ltr.models.rts.linear_filter as target_clf import ltr.models.target_classifier.features as clf_features import ltr.models.target_classifier.linear_filter as clf_target_clf import ltr.models.target_classifier.initializer as clf_ini...
null
141,505
import math import torch import torch.nn as nn from collections import OrderedDict import ltr.models.rts.linear_filter as target_clf import ltr.models.target_classifier.features as clf_features import ltr.models.target_classifier.linear_filter as clf_target_clf import ltr.models.target_classifier.initializer as clf_ini...
null
141,506
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from ltr.models.rts.utils import adaptive_cat, interpolate from collections import OrderedDict def conv(ic, oc, ksize, bias=True, dilation=1, stride=1): return nn.Conv2d(ic, oc, ksize, padding=ksize // 2, bias=bias, ...
null
141,507
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from ltr.models.rts.utils import adaptive_cat, interpolate from collections import OrderedDict def relu(negative_slope=0.0, inplace=False): return nn.LeakyReLU(negative_slope, inplace=inplace)
null
141,508
import torch.nn as nn import ltr.models.backbone as backbones import ltr.models.bbreg as bbmodels from ltr import model_constructor class ATOMnet(nn.Module): """ ATOM network module""" def __init__(self, feature_extractor, bb_regressor, bb_regressor_layer, extractor_grad=True): """ args: ...
null
141,509
import torch.nn as nn import torch from ltr.models.layers.blocks import LinearBlock from ltr.external.PreciseRoIPooling.pytorch.prroi_pool import PrRoIPool2D def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_si...
null
141,510
import math import torch import torch.nn as nn from collections import OrderedDict from ltr.models.meta import steepestdescent import ltr.models.target_classifier.linear_filter as target_clf import ltr.models.target_classifier.features as clf_features import ltr.models.target_classifier.initializer as clf_initializer i...
null
141,512
import math import torch import torch.nn as nn from collections import OrderedDict import ltr.models.lwl.linear_filter as target_clf import ltr.models.target_classifier.features as clf_features import ltr.models.lwl.initializer as seg_initializer import ltr.models.lwl.label_encoder as seg_label_encoder import ltr.model...
null
141,513
import math import torch import torch.nn as nn from collections import OrderedDict import ltr.models.lwl.label_encoder as seg_label_encoder from ltr import model_constructor import ltr.models.lwl.linear_filter as target_clf import ltr.models.target_classifier.features as clf_features import ltr.models.lwl.initializer a...
null
141,514
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from ltr.models.lwl.utils import adaptive_cat, interpolate from collections import OrderedDict def conv(ic, oc, ksize, bias=True, dilation=1, stride=1): return nn.Conv2d(ic, oc, ksize, padding=ksize // 2, bias=bias, ...
null
141,515
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from ltr.models.lwl.utils import adaptive_cat, interpolate from collections import OrderedDict def relu(negative_slope=0.0, inplace=False): return nn.LeakyReLU(negative_slope, inplace=inplace)
null
141,516
from __future__ import print_function, division import torch from torch.autograd import Variable import torch.nn.functional as F import numpy as np import torch.nn as nn def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False): """ Array of IoU for each (non ignored) class """ if not per_image:...
IoU for foreground class binary: 1 foreground, 0 background
141,517
from __future__ import print_function, division import torch from torch.autograd import Variable import torch.nn.functional as F import numpy as np import torch.nn as nn def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and...
Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id
141,518
from __future__ import print_function, division import torch from torch.autograd import Variable import torch.nn.functional as F import numpy as np import torch.nn as nn def flatten_binary_scores(scores, labels, ignore=None): """ Flattens predictions in the batch (binary case) Remove labels equal to 'ignore...
Binary Cross entropy loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) ignore: void class id
141,519
from __future__ import print_function, division import torch from torch.autograd import Variable import torch.nn.functional as F import numpy as np import torch.nn as nn def lovasz_softmax_flat(probas, labels, classes='present'): """ Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabili...
Multi-class Lovasz-Softmax loss probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1). Interpreted as binary (sigmoid) output with outputs of size [B, H, W]. labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) classes: 'all' for all, 'present' for classes present in lab...
141,520
from __future__ import print_function, division import torch from torch.autograd import Variable import torch.nn.functional as F import numpy as np import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `xloss` function. Write a Python function `def xloss(logits, labels, i...
Cross entropy loss
141,521
import math import torch import torch.nn as nn from torch.nn import functional as F import ltr.models.loss.lovasz_loss as lovasz_loss The provided code snippet includes necessary dependencies for implementing the `one_hot` function. Write a Python function `def one_hot(labels: torch.Tensor, num_classes: in...
r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor. Args: labels (torch.Tensor) : tensor with labels of shape :math:`(N, *)`, where N is batch size. Each value is an integer representing correct classification. num_classes (int): number of classes in labels. device (Optional[torch.device]): the desire...
141,522
import torch import torch.nn as nn def recall(m, gt_m): mask = (gt_m > -1).float() return ((m == gt_m) * mask).sum(1) / mask.sum(1)
null
141,523
import torch import torch.nn as nn def precision(m, gt_m): mask = ((m > -1) & (gt_m >= -1)).float() prec = ((m == gt_m) * mask).sum(1) / torch.max(mask.sum(1), torch.ones_like(mask.sum(1))) no_match_mask = (gt_m > -1).sum(1) == 0 prec[no_match_mask] = float('NaN') return prec
null
141,524
import copy import torch import torch.nn.functional as F from torch import nn def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
null
141,525
import copy import torch import torch.nn.functional as F from torch import nn class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec...
null