id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
22,319
import numpy as np import os import cv2 import torch import tqdm import slowfast.utils.checkpoint as cu import slowfast.utils.logging as logging from slowfast.datasets.ava_helper import parse_bboxes_file from slowfast.datasets.cv2_transform import scale, scale_boxes from slowfast.datasets.utils import get_sequence from...
Loading boxes and labels from AVA bounding boxes csv files. Args: cfg (CfgNode): config. video_name (str): name of the given video. fps (int or float): frames per second of the input video/images folder. img_width (int): width of images in input video/images folder. img_height (int): height of images in input video/ima...
22,320
import itertools import logging as log import numpy as np import matplotlib.pyplot as plt import torch from detectron2.utils.visualizer import Visualizer import slowfast.utils.logging as logging from slowfast.utils.misc import get_class_names logger = logging.get_logger(__name__) The provided code snippet includes nec...
Create text labels. Args: classes (list[int]): a list of class ids for each example. scores (list[float] or None): list of scores for each example. class_names (list[str]): a list of class names, ordered by their ids. ground_truth (bool): whether the labels are ground truth. Returns: labels (list[str]): formatted text ...
22,321
import math from fvcore.common.config import CfgNode from . import custom_config def assert_and_infer_cfg(cfg): # BN assertions. if cfg.BN.USE_PRECISE_STATS: assert cfg.BN.NUM_BATCHES_PRECISE >= 0 # TRAIN assertions. assert cfg.TRAIN.CHECKPOINT_TYPE in ["pytorch", "caffe2"] assert cfg.NUM_G...
null
22,322
def add_custom_config(_C): # Add your own customized configs. pass
null
22,323
import logging import os from collections import defaultdict from slowfast.utils.env import pathmgr logger = logging.getLogger(__name__) pathmgr = PathManagerFactory.get(key="pyslowfast") The provided code snippet includes necessary dependencies for implementing the `load_image_lists` function. Write a Python functio...
Loading image paths from corresponding files. Args: cfg (CfgNode): config. is_train (bool): if it is training dataset or not. Returns: image_paths (list[list]): a list of items. Each item (also a list) corresponds to one video and contains the paths of images for this video. video_idx_to_name (list): a list which store...
22,324
import logging import os from collections import defaultdict from slowfast.utils.env import pathmgr logger = logging.getLogger(__name__) def parse_bboxes_file( ann_filenames, ann_is_gt_box, detect_thresh, boxes_sample_rate=1 ): """ Parse AVA bounding boxes files. Args: ann_filenames (list of str...
Loading boxes and labels from csv files. Args: cfg (CfgNode): config. mode (str): 'train', 'val', or 'test' mode. Returns: all_boxes (dict): a dict which maps from `video_name` and `frame_sec` to a list of `box`. Each `box` is a [`box_coord`, `box_labels`] where `box_coord` is the coordinates of box and 'box_labels` ar...
22,325
import logging import os from collections import defaultdict from slowfast.utils.env import pathmgr logger = logging.getLogger(__name__) FPS = 30 AVA_VALID_FRAMES = range(902, 1799) The provided code snippet includes necessary dependencies for implementing the `get_keyframe_data` function. Write a Python function `def...
Getting keyframe indices, boxes and labels in the dataset. Args: boxes_and_labels (list[dict]): a list which maps from video_idx to a dict. Each dict `frame_sec` to a list of boxes and corresponding labels. Returns: keyframe_indices (list): a list of indices of the keyframes. keyframe_boxes_and_labels (list[list[list]]...
22,326
import logging import os from collections import defaultdict from slowfast.utils.env import pathmgr The provided code snippet includes necessary dependencies for implementing the `get_num_boxes_used` function. Write a Python function `def get_num_boxes_used(keyframe_indices, keyframe_boxes_and_labels)` to solve the fo...
Get total number of used boxes. Args: keyframe_indices (list): a list of indices of the keyframes. keyframe_boxes_and_labels (list[list[list]]): a list of list which maps from video_idx and sec_idx to a list of boxes and corresponding labels. Returns: count (int): total number of used boxes.
22,327
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
This function is to load images with support of retrying for failed load. Args: image_paths (list): paths of images needed to be loaded. retry (int, optional): maximum time of loading retrying. Defaults to 10. backend (str): `pytorch` or `cv2`. Returns: imgs (list): list of loaded images.
22,328
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
Sample frames among the corresponding clip. Args: center_idx (int): center frame idx for current clip half_len (int): half of the clip length sample_rate (int): sampling rate for sampling frames inside of the clip num_frames (int): number of expected sampled frames Returns: seq (list): list of indexes of sampled frames...
22,329
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
Aggregate annotations from all frames of a video to form video-level labels. Args: labels (list): The input label list. Returns: labels (list): Same as input, but with each label replaced by a video-level one.
22,330
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
Load image paths and labels from a "frame list". Each line of the frame list contains: `original_vido_id video_id frame_id path labels` Args: frame_list_file (string): path to the frame list. prefix (str): the prefix for the path. return_list (bool): if True, return a list. If False, return a dict. Returns: image_paths...
22,331
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
When multigrid training uses a fewer number of frames, we randomly increase the sampling rate so that some clips cover the original span.
22,332
import logging import numpy as np import os import random import time from collections import defaultdict import cv2 import torch from torch.utils.data.distributed import DistributedSampler from torchvision import transforms from slowfast.utils.env import pathmgr from . import transform as transform from .random_erasin...
Perform augmentations on the given video frames, including random augmentation, normalization, spatial sampling and optional random erasing. Args: cfg (CfgNode): configs. mode (string): Options includes `train`, `val`, or `test` mode. rand_erase (bool): if performing random erasing. frames (tensor): frames of images sa...
22,333
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _interpolation(kwargs) def shear_x(img, factor, **kwargs): _check_...
null
22,334
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _interpolation(kwargs) def shear_y(img, factor, **kwargs): _check_...
null
22,335
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _interpolation(kwargs) def translate_x_rel(img, pct, **kwargs): pi...
null
22,336
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _interpolation(kwargs) def translate_y_rel(img, pct, **kwargs): pi...
null
22,337
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): def translate_x_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform( img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs )
null
22,338
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _interpolation(kwargs) def translate_y_abs(img, pixels, **kwargs): ...
null
22,339
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _PIL_VER = tuple([int(x) for x in PIL.__version__.split(".")[:2]]) def _check_args_tf(kwargs): if "fillcolor" in kwargs and _PIL_VER < (5, 0): kwargs.pop("fillcolor") kwargs["resample"] = _int...
null
22,340
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def auto_contrast(img, **__): return ImageOps.autocontrast(img)
null
22,341
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def invert(img, **__): return ImageOps.invert(img)
null
22,342
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def equalize(img, **__): return ImageOps.equalize(img)
null
22,343
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def solarize(img, thresh, **__): return ImageOps.solarize(img, thresh)
null
22,344
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def solarize_add(img, add, thresh=128, **__): lut = [] for i in range(256): if i < thresh: lut.append(min(255, i + add)) else: lut.append(i) if img.mode in...
null
22,345
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def posterize(img, bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep)
null
22,346
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor)
null
22,347
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor)
null
22,348
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
null
22,349
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
null
22,350
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _randomly_negate(v): def _rotate_level_to_arg(level, _hparams): # range [-30, 30] level = (level / _MAX_LEVEL) * 30.0 level = _randomly_negate(level) return (level,)
null
22,351
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _enhance_level_to_arg(level, _hparams): # range [0.1, 1.9] return ((level / _MAX_LEVEL) * 1.8 + 0.1,)
null
22,352
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _enhance_increasing_level_to_arg(level, _hparams): # the 'no change'...
null
22,353
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _shear_level_to_arg(level, _hparams): # range [-0.3, 0.3] level ...
null
22,354
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _randomly_negate(v): def _translate_abs_level_to_arg(level, hparams): translate_const = hparams["translate_const"] level = (level / _MAX_LEVEL) * float(translate_const) leve...
null
22,355
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _randomly_negate(v): def _translate_rel_level_to_arg(level, hparams): # default range [-0.45, 0.45] translate_pct = hparams.get("translate_pct", 0.45) level = (level / _MAX_...
null
22,356
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _posterize_level_to_arg(level, _hparams): # As per Tensorflow TPU EfficientNet impl # range [0, 4], 'keep 0 up to 4 MSB of original image' # intensity/severity of augmentation decreases with l...
null
22,357
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _posterize_original_level_to_arg(level, _hparams): # As per original AutoAugment paper description # range [4, 8], 'keep 4 up to 8 MSB of image' # intensity/severity of augm...
null
22,358
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps def _solarize_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation decreases with level return (int((level / _MAX_LEVEL) * 256),) def _solarize_increasing_level_to...
null
22,359
import math import numpy as np import random import re import PIL from PIL import Image, ImageEnhance, ImageOps _MAX_LEVEL = 10.0 def _solarize_add_level_to_arg(level, _hparams): # range [0, 110] return (int((level / _MAX_LEVEL) * 110),)
null
22,360
import av The provided code snippet includes necessary dependencies for implementing the `get_video_container` function. Write a Python function `def get_video_container(path_to_vid, multi_thread_decode=False, backend="pyav")` to solve the following problem: Given the path to the video, return the pyav video container...
Given the path to the video, return the pyav video container. Args: path_to_vid (str): path to the video. multi_thread_decode (bool): if True, perform multi-thread decoding. backend (str): decoder backend, options include `pyav` and `torchvision`, default is `pyav`. Returns: container (container): video container.
22,361
import numpy as np import torch def convert_to_one_hot(targets, num_classes, on_value=1.0, off_value=0.0): """ This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (loader): Class labels. num_classes (int): Total number of classes. ...
This function converts target class indices to one-hot vectors, given the number of classes. Args: targets (loader): Class labels. num_classes (int): Total number of classes. lam (float): lamba value for mixup/cutmix. smoothing (float): Label smoothing value.
22,362
import numpy as np import torch def rand_bbox(img_shape, lam, margin=0.0, count=None): """ Generates a random square bbox based on lambda value. Args: img_shape (tuple): Image shape as tuple lam (float): Cutmix lambda value margin (float): Percentage of bbox dimension to enforce as m...
Generates the box coordinates for cutmix. Args: img_shape (tuple): Image shape as tuple lam (float): Cutmix lambda value correct_lam (bool): Apply lambda correction when cutmix bbox clipped by image borders. count (int): Number of bbox to generate
22,363
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `clip_boxes_to_image` function. Write a Python function `def clip_boxes_to_image(boxes, height, width)` to solve the following problem: Clip the boxes with the height and width of the image size. Ar...
Clip the boxes with the height and width of the image size. Args: boxes (ndarray): bounding boxes to peform crop. The dimension is `num boxes` x 4. height (int): the height of the image. width (int): the width of the image. Returns: boxes (ndarray): cropped bounding boxes.
22,364
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `random_short_side_scale_jitter_list` function. Write a Python function `def random_short_side_scale_jitter_list(images, min_size, max_size, boxes=None)` to solve the following problem: Perform a sp...
Perform a spatial short scale jittering on the given images and corresponding boxes. Args: images (list): list of images to perform scale jitter. Dimension is `height` x `width` x `channel`. min_size (int): the minimal size to scale the frames. max_size (int): the maximal size to scale the frames. boxes (list): optiona...
22,365
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `scale_boxes` function. Write a Python function `def scale_boxes(size, boxes, height, width)` to solve the following problem: Scale the short side of the box to size. Args: size (int): size to scale...
Scale the short side of the box to size. Args: size (int): size to scale the image. boxes (ndarray): bounding boxes to peform scale. The dimension is `num boxes` x 4. height (int): the height of the image. width (int): the width of the image. Returns: boxes (ndarray): scaled bounding boxes.
22,366
import math import numpy as np import cv2 def flip_boxes(boxes, im_width): """ Horizontally flip the boxes. Args: boxes (array): box to flip. im_width (int): width of the image. Returns: boxes_flipped (array): flipped box. """ boxes_flipped = boxes.copy() boxes_flippe...
Horizontally flip the list of image and optional boxes. Args: prob (float): probability to flip. image (list): ilist of images to perform short side scale. Dimension is `height` x `width` x `channel` or `channel` x `height` x `width`. order (str): order of the `height`, `channel` and `width`. boxes (list): optional. Co...
22,367
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `spatial_shift_crop_list` function. Write a Python function `def spatial_shift_crop_list(size, images, spatial_shift_pos, boxes=None)` to solve the following problem: Perform left, center, or right ...
Perform left, center, or right crop of the given list of images. Args: size (int): size to crop. image (list): ilist of images to perform short side scale. Dimension is `height` x `width` x `channel` or `channel` x `height` x `width`. spatial_shift_pos (int): option includes 0 (left), 1 (middle), and 2 (right) crop. bo...
22,368
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `CHW2HWC` function. Write a Python function `def CHW2HWC(image)` to solve the following problem: Transpose the dimension from `channel` x `height` x `width` to `height` x `width` x `channel`. Args: ...
Transpose the dimension from `channel` x `height` x `width` to `height` x `width` x `channel`. Args: image (array): image to transpose. Returns (array): transposed image.
22,369
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `HWC2CHW` function. Write a Python function `def HWC2CHW(image)` to solve the following problem: Transpose the dimension from `height` x `width` x `channel` to `channel` x `height` x `width`. Args: ...
Transpose the dimension from `height` x `width` x `channel` to `channel` x `height` x `width`. Args: image (array): image to transpose. Returns (array): transposed image.
22,370
import math import numpy as np import cv2 def saturation_list(var, images): """ Perform color saturation on the list of given images. Args: var (float): variance. images (list): list of images to perform color saturation. Returns: (list): list of images that performed color satur...
Perform color jitter on the list of images. Args: images (list): list of images to perform color jitter. img_brightness (float): jitter ratio for brightness. img_contrast (float): jitter ratio for contrast. img_saturation (float): jitter ratio for saturation. Returns: images (list): the jittered list of images.
22,371
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `lighting_list` function. Write a Python function `def lighting_list(imgs, alphastd, eigval, eigvec, alpha=None)` to solve the following problem: Perform AlexNet-style PCA jitter on the given list o...
Perform AlexNet-style PCA jitter on the given list of images. Args: images (list): list of images to perform lighting jitter. alphastd (float): jitter ratio for PCA jitter. eigval (list): eigenvalues for PCA jitter. eigvec (list[list]): eigenvectors for PCA jitter. Returns: out_images (list): the list of jittered image...
22,372
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `color_normalization` function. Write a Python function `def color_normalization(image, mean, stddev)` to solve the following problem: Perform color normalization on the image with the given mean an...
Perform color normalization on the image with the given mean and stddev. Args: image (array): image to perform color normalization. mean (float): mean value to subtract. stddev (float): stddev to devide.
22,373
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `horizontal_flip` function. Write a Python function `def horizontal_flip(prob, image, order="CHW")` to solve the following problem: Horizontally flip the image. Args: prob (float): probability to fl...
Horizontally flip the image. Args: prob (float): probability to flip. image (array): image to pad. order (str): order of the `height`, `channel` and `width`. Returns: img (array): flipped image.
22,374
import math import numpy as np import cv2 def pad_image(image, pad_size, order="CHW"): """ Pad the given image with the size of pad_size. Args: image (array): image to pad. pad_size (int): size to pad. order (str): order of the `height`, `channel` and `width`. Returns: im...
Perform random crop on a list of images. Args: images (list): list of images to perform random crop. size (int): size to crop. pad_size (int): padding size. order (str): order of the `height`, `channel` and `width`. boxes (list): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. Returns: cropped (n...
22,375
import math import numpy as np import cv2 def scale(size, image): """ Scale the short side of the image to size. Args: size (int): size to scale the image. image (array): image to perform short side scale. Dimension is `height` x `width` x `channel`. Returns: (ndarray...
Perform ResNet style random scale jittering: randomly select the scale from [1/max_size, 1/min_size]. Args: image (array): image to perform random scale. min_size (int): min size to scale. max_size (int) max size to scale. Returns: image (array): scaled image.
22,376
import math import numpy as np import cv2 def scale(size, image): """ Scale the short side of the image to size. Args: size (int): size to scale the image. image (array): image to perform short side scale. Dimension is `height` x `width` x `channel`. Returns: (ndarray...
Perform ResNet style random scale jittering on a list of image: randomly select the scale from [1/max_size, 1/min_size]. Note that all the image will share the same scale. Args: images (list): list of images to perform random scale. min_size (int): min size to scale. max_size (int) max size to scale. Returns: images (l...
22,377
import math import numpy as np import cv2 def scale(size, image): """ Scale the short side of the image to size. Args: size (int): size to scale the image. image (array): image to perform short side scale. Dimension is `height` x `width` x `channel`. Returns: (ndarray...
Perform random sized cropping on the given image. Random crop with size 8% - 100% image area and aspect ratio in [3/4, 4/3]. Args: image (array): image to crop. size (int): size to crop. area_frac (float): area of fraction. Returns: (array): cropped image.
22,378
import math import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `lighting` function. Write a Python function `def lighting(img, alphastd, eigval, eigvec)` to solve the following problem: Perform AlexNet-style PCA jitter on the given image. Args: image (array): l...
Perform AlexNet-style PCA jitter on the given image. Args: image (array): list of images to perform lighting jitter. alphastd (float): jitter ratio for PCA jitter. eigval (array): eigenvalues for PCA jitter. eigvec (list): eigenvectors for PCA jitter. Returns: img (tensor): the jittered image.
22,379
import math import numpy as np import cv2 def scale(size, image): """ Scale the short side of the image to size. Args: size (int): size to scale the image. image (array): image to perform short side scale. Dimension is `height` x `width` x `channel`. Returns: (ndarray...
Perform random sized cropping on the given list of images. Random crop with size 8% - 100% image area and aspect ratio in [3/4, 4/3]. Args: images (list): image to crop. size (int): size to crop. area_frac (float): area of fraction. Returns: (list): list of cropped image.
22,380
import math import numpy as np import cv2 def saturation(var, image): """ Perform color saturation on the given image. Args: var (float): variance. image (array): image to perform color saturation. Returns: (array): image that performed color saturation. """ img_gray = gr...
Perform color jitter on the given image. Args: image (array): image to perform color jitter. img_brightness (float): jitter ratio for brightness. img_contrast (float): jitter ratio for contrast. img_saturation (float): jitter ratio for saturation. Returns: image (array): the jittered image.
22,381
import math import random import torch def _get_pixels( per_pixel, rand_color, patch_size, dtype=torch.float32, device="cuda" ): # NOTE I've seen CUDA illegal memory access errors being caused by the normal_() # paths, flip the order so normal is run on CPU if this becomes a problem # Issue has been fi...
null
22,382
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
Clip an array of boxes to an image with the given height and width. Args: boxes (ndarray): bounding boxes to perform clipping. Dimension is `num boxes` x 4. height (int): given image height. width (int): given image width. Returns: clipped_boxes (ndarray): the clipped boxes with dimension of `num boxes` x 4.
22,383
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
Perform AlexNet-style PCA jitter on the given images. Args: images (tensor): images to perform lighting jitter. Dimension is `num frames` x `channel` x `height` x `width`. alphastd (float): jitter ratio for PCA jitter. eigval (list): eigenvalues for PCA jitter. eigvec (list[list]): eigenvectors for PCA jitter. Returns:...
22,384
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
Perform color nomration on the given images. Args: images (tensor): images to perform color normalization. Dimension is `num frames` x `channel` x `height` x `width`. mean (list): mean values for normalization. stddev (list): standard deviations for normalization. Returns: out_images (tensor): the noramlized images, th...
22,385
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
Performs Inception-style cropping (used for training).
22,386
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
If separate==True, the transforms are returned as a tuple of 3 separate transforms for use in a mixing dataset that passes * all data through the first (primary) transform, called the 'clean' data * a portion of the data through the secondary transform * normalizes and converts the branches above with the third, final ...
22,387
import logging import math import numpy as np import random import torch import torchvision as tv import torchvision.transforms.functional as F from PIL import Image, ImageFilter from scipy.ndimage import gaussian_filter from torchvision import transforms from .rand_augment import rand_augment_transform from .random_er...
null
22,388
import functools import os from typing import Dict import torch from torch.utils.data import ( DistributedSampler, RandomSampler, SequentialSampler, ) from torchvision.transforms import Compose, Lambda from torchvision.transforms._transforms_video import ( NormalizeVideo, RandomCropVideo, Random...
Construct the Kinetics video loader with a given csv file. The format of the csv file is: ``` path_to_video_1 label_1 path_to_video_2 label_2 ... path_to_video_N label_N ``` For `train` and `val` mode, a single clip is randomly sampled from every video with random cropping, scaling, and flipping. For `test` mode, multi...
22,389
import functools import os from typing import Dict import torch from torch.utils.data import ( DistributedSampler, RandomSampler, SequentialSampler, ) from torchvision.transforms import Compose, Lambda from torchvision.transforms._transforms_video import ( NormalizeVideo, RandomCropVideo, Random...
Construct PyTorchVideo Charades video loader. Load Charades data (frame paths, labels, etc. ) to Charades Dataset object. The dataset could be downloaded from Chrades official website (https://allenai.org/plato/charades/). Please see datasets/DATASET.md for more information about the data format. For `train` and `val` ...
22,390
import functools import os from typing import Dict import torch from torch.utils.data import ( DistributedSampler, RandomSampler, SequentialSampler, ) from torchvision.transforms import Compose, Lambda from torchvision.transforms._transforms_video import ( NormalizeVideo, RandomCropVideo, Random...
Construct PyTorchVideo Something-Something v2 SSv2 video loader. Load SSv2 data (frame paths, labels, etc. ) to SSv2 Dataset object. The dataset could be downloaded from Chrades official website (https://20bn.com/datasets/something-something). Please see datasets/DATASET.md for more information about the data format. F...
22,391
import torch import torch.nn as nn class ResNetBasicStem(nn.Module): """ ResNe(X)t 3D stem module. Performs spatiotemporal Convolution, BN, and Relu following by a spatiotemporal pooling. """ def __init__( self, dim_in, dim_out, kernel, stride, ...
Retrieves the stem module by name.
22,392
import numpy as np import torch import slowfast.utils.logging as logging logger = logging.get_logger(__name__) def round_width(width, multiplier, min_width=1, divisor=1, verbose=False): if not multiplier: return width width *= multiplier min_width = min_width or divisor if verbose: logg...
null
22,393
import numpy as np import torch import slowfast.utils.logging as logging The provided code snippet includes necessary dependencies for implementing the `validate_checkpoint_wrapper_import` function. Write a Python function `def validate_checkpoint_wrapper_import(checkpoint_wrapper)` to solve the following problem: Che...
Check if checkpoint_wrapper is imported.
22,394
import numpy as np import torch import slowfast.utils.logging as logging The provided code snippet includes necessary dependencies for implementing the `get_gkern` function. Write a Python function `def get_gkern(kernlen, std)` to solve the following problem: Returns a 2D Gaussian kernel array. Here is the function: ...
Returns a 2D Gaussian kernel array.
22,395
import numpy as np import torch import slowfast.utils.logging as logging def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0 # use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid( embed_dim // 2, grid[0] ) # (H*W, D/2) emb_w = get_...
grid_size: int of the grid height and width t_size: int of the temporal size return: pos_embed: [t_size*grid_size*grid_size, embed_dim] or [1+t_size*grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
22,396
import numpy as np import torch import slowfast.utils.logging as logging def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0 # use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid( embed_dim // 2, grid[0] ) # (H*W, D/2) emb_w = get_...
grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
22,397
import numpy as np import torch import slowfast.utils.logging as logging def interpolate_pos_embed(model, checkpoint_model): if "pos_embed" in checkpoint_model: pos_embed_checkpoint = checkpoint_model["pos_embed"] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_emb...
null
22,398
import numpy as np import torch import slowfast.utils.logging as logging def calc_mvit_feature_geometry(cfg): feat_size = [ [ cfg.DATA.NUM_FRAMES // cfg.MVIT.PATCH_STRIDE[0] if len(cfg.MVIT.PATCH_STRIDE) > 2 else 1, cfg.DATA.TRAIN_CROP_SIZE // cfg.MVIT.PATCH_...
null
22,399
import numpy import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import trunc_normal_ from slowfast.models.common import DropPath, Mlp def attention_pool(tensor, pool, thw_shape, has_cls_embed=True, norm=None): if pool is None: return tensor, thw_shape tensor_dim = ten...
null
22,400
import numpy import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import trunc_normal_ from slowfast.models.common import DropPath, Mlp def get_rel_pos(rel_pos, d): if isinstance(d, int): ori_d = rel_pos.shape[0] if ori_d == d: return rel_pos else...
Decomposed Spatial Relative Positional Embeddings.
22,401
import numpy import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import trunc_normal_ from slowfast.models.common import DropPath, Mlp def get_rel_pos(rel_pos, d): if isinstance(d, int): ori_d = rel_pos.shape[0] if ori_d == d: return rel_pos else...
Temporal Relative Positional Embeddings.
22,402
from functools import partial import torch.nn as nn from detectron2.layers import ROIAlign from slowfast.models.batchnorm_helper import get_norm from slowfast.models.video_model_builder import _POOL1, _TEMPORAL_KERNEL_BASIS from pytorchvideo.models.csn import create_csn from pytorchvideo.models.head import ( create...
Return the actual head activation function given the activation fucntion name. Args: act_func (string): activation function to use. 'softmax': applies softmax on the output. 'sigmoid': applies sigmoid on the output. Returns: nn.Module: the activation layer.
22,403
from functools import partial import torch import torch.nn as nn from pytorchvideo.layers.batch_norm import ( NaiveSyncBatchNorm1d, NaiveSyncBatchNorm3d, ) class SubBatchNorm3d(nn.Module): """ The standard BN layer computes stats across all examples in a GPU. In some cases it is desirable to comput...
Args: cfg (CfgNode): model building configs, details are in the comments of the config file. Returns: nn.Module: the normalization layer.
22,404
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import slowfast.models.losses as losses import slowfast.utils.distributed as du import slowfast.utils.logging as logging from slowfast.models.video_model_builder import X3D, MViT, ResNet, SlowFast from .build import MODEL_...
null
22,405
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def drop_path(x, drop_prob: float = 0.0, training: bool = False)` to solve the following problem: Stochastic Depth per sample. Here is the function: def dro...
Stochastic Depth per sample.
22,406
import torch import torch.nn as nn from slowfast.models.common import drop_path from slowfast.models.nonlocal_helper import Nonlocal from slowfast.models.operators import SE, Swish class BasicTransform(nn.Module): """ Basic transformation: Tx3x3, 1x3x3, where T is the size of temporal kernel. """ def __...
Retrieves the transformation module by name.
22,407
import torch from fvcore.common.registry import Registry from torch.distributed.algorithms.ddp_comm_hooks import ( default as comm_hooks_default, ) import slowfast.utils.logging as logging logger = logging.get_logger(__name__) MODEL_REGISTRY = Registry("MODEL") MODEL_REGISTRY.__doc__ = """ Registry for video model....
Builds the video model. Args: cfg (configs): configs that contains the hyper-parameters to build the backbone. Details can be seen in slowfast/config/defaults.py. gpu_id (Optional[int]): specify the gpu index to build model.
22,408
import atexit import builtins import decimal import functools import logging import os import sys import simplejson import slowfast.utils.distributed as du from slowfast.utils.env import pathmgr def get_logger(name): """ Retrieve the logger with the specified name or, if name is None, return a logger which ...
Logs json stats. Args: stats (dict): a dictionary of statistical information to log.
22,409
import argparse import sys import slowfast.utils.checkpoint as cu from slowfast.config.defaults import get_cfg The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args()` to solve the following problem: Parse the following arguments f...
Parse the following arguments for a default parser for PySlowFast users. Args: shard_id (int): shard id for the current machine. Starts from 0 to num_shards - 1. If single machine is used, then set shard id to 0. num_shards (int): number of shards using by the job. init_method (str): initialization method to launch the...
22,410
import argparse import sys import slowfast.utils.checkpoint as cu from slowfast.config.defaults import get_cfg def get_cfg(): """ Get a copy of the default config. """ return _C.clone() The provided code snippet includes necessary dependencies for implementing the `load_config` function. Write a Pytho...
Given the arguemnts, load and initialize the configs. Args: args (argument): arguments includes `shard_id`, `num_shards`, `init_method`, `cfg_file`, and `opts`.
22,411
import numpy as np import slowfast.utils.logging as logging logger = logging.get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `print_schedule` function. Write a Python function `def print_schedule(schedule)` to solve the following problem: Log schedule. Here is the f...
Log schedule.
22,412
import numpy as np import slowfast.utils.logging as logging The provided code snippet includes necessary dependencies for implementing the `get_current_long_cycle_shape` function. Write a Python function `def get_current_long_cycle_shape(schedule, epoch)` to solve the following problem: Given a schedule and epoch inde...
Given a schedule and epoch index, return the long cycle base shape. Args: schedule (configs): configs that contains training and multigrid specific hyperparameters. Details can be seen in slowfast/config/defaults.py. cur_epoch (int): current epoch index. Returns: shapes (list): A list describing the base shape in a lon...
22,413
from __future__ import absolute_import, division, print_function, unicode_literals import csv import logging import pprint import time from collections import defaultdict import numpy as np import slowfast.utils.distributed as du from ava_evaluation import object_detection_evaluation, standard_fields from slowfast.util...
Run AVA evaluation given annotation/prediction files.
22,414
from __future__ import absolute_import, division, print_function, unicode_literals import csv import logging import pprint import time from collections import defaultdict import numpy as np import slowfast.utils.distributed as du from ava_evaluation import object_detection_evaluation, standard_fields from slowfast.util...
Run AVA evaluation given numpy arrays.
22,415
import copy import math import numpy as np import os import pickle from collections import OrderedDict import torch import slowfast.utils.distributed as du import slowfast.utils.logging as logging from slowfast.utils.c2_model_loading import get_name_convert_func from slowfast.utils.env import checkpoint_pathmgr as path...
Loading checkpoint logic for training.
22,416
import itertools import torch The provided code snippet includes necessary dependencies for implementing the `compute_and_update_bn_stats` function. Write a Python function `def compute_and_update_bn_stats(model, data_loader, num_batches=200)` to solve the following problem: Compute and update the batch norm stats to ...
Compute and update the batch norm stats to make it more precise. During training both bn stats and the weight are changing after every iteration, so the bn can not precisely reflect the latest stats of the current model. Here the bn stats is recomputed without change of weights, to make the running mean and running var...
22,417
import json import logging import math import numpy as np import os from datetime import datetime import psutil import torch import torchvision.io as io from fvcore.nn.activation_count import activation_count from fvcore.nn.flop_count import flop_count from matplotlib import pyplot as plt from torch import nn from torc...
Plot the input tensor with the optional bounding box and save it to disk. Args: tensor (tensor): a tensor with shape of `NxCxHxW`. bboxes (tuple): bounding boxes with format of [[x, y, h, w]]. texts (tuple): a tuple of string to plot. path (str): path to the image to save to.
22,418
import json import logging import math import numpy as np import os from datetime import datetime import psutil import torch import torchvision.io as io from fvcore.nn.activation_count import activation_count from fvcore.nn.flop_count import flop_count from matplotlib import pyplot as plt from torch import nn from torc...
Plot the input tensor with the optional bounding box and save it to disk. Args: tensor (tensor): a tensor with shape of `NxCxHxW`. bboxes (tuple): bounding boxes with format of [[x, y, h, w]]. texts (tuple): a tuple of string to plot. path (str): path to the image to save to.