repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
s2anet | s2anet-master/mmdet/ops/box_iou_rotated_diff/box_iou_rotated_diff.py | """
Differentiable IoU calculation for rotated boxes
Most of the code is adapted from https://github.com/lilanxiao/Rotated_IoU
"""
import torch
from .box_intersection_2d import oriented_box_intersection_2d
def rotated_box_to_poly(rotated_boxes: torch.Tensor):
""" Transform rotated boxes to polygons
Args:
... | 2,207 | 32.454545 | 102 | py |
s2anet | s2anet-master/mmdet/ops/box_iou_rotated_diff/box_intersection_2d.py | '''
torch implementation of 2d oriented box intersection
author: lanxiao li
Modified by csuhan:
Remove the `batch` indice in a tensor.
This setting is more suitable for mmdet.
'''
import torch
from .sort_vertices_cuda import sort_vertices_forward
EPSILON = 1e-8
def get_intersection_points(polys1: torch.Te... | 6,963 | 35.460733 | 103 | py |
s2anet | s2anet-master/mmdet/ops/roi_pool/roi_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_pool_cuda
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
... | 2,544 | 32.486842 | 78 | py |
s2anet | s2anet-master/mmdet/ops/roi_pool/gradcheck.py | import os.path as osp
import sys
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_pool import RoIPool # noqa: E402, isort:skip
feat = torch.randn(4, 16, 15, 15, requires_grad=True).cuda()
rois = torch.Tensor([[0, 0, 0, 50, 50], [0, 10, 30, 43, 55]... | 513 | 29.235294 | 66 | py |
s2anet | s2anet-master/mmdet/ops/roi_align_rotated/roi_align_rotated.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from .roi_align_rotated_cuda import roi_align_rotated_forward, roi_align_rotated_backward
class _RO... | 3,281 | 33.914894 | 90 | py |
s2anet | s2anet-master/mmdet/ops/nms/nms_wrapper.py | import numpy as np
import torch
from . import nms_cpu, nms_cuda
from .soft_nms_cpu import soft_nms_cpu
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or... | 2,580 | 31.670886 | 79 | py |
taming-transformers | taming-transformers-master/main.py | import argparse, os, sys, datetime, glob, importlib
from omegaconf import OmegaConf
import numpy as np
from PIL import Image
import torch
import torchvision
from torch.utils.data import random_split, DataLoader, Dataset
import pytorch_lightning as pl
from pytorch_lightning import seed_everything
from pytorch_lightning.... | 21,251 | 35.266212 | 138 | py |
taming-transformers | taming-transformers-master/setup.py | from setuptools import setup, find_packages
setup(
name='taming-transformers',
version='0.0.1',
description='Taming Transformers for High-Resolution Image Synthesis',
packages=find_packages(),
install_requires=[
'torch',
'numpy',
'tqdm',
],
)
| 292 | 19.928571 | 74 | py |
taming-transformers | taming-transformers-master/scripts/extract_segmentation.py | import sys, os
import numpy as np
import scipy
import torch
import torch.nn as nn
from scipy import ndimage
from tqdm import tqdm, trange
from PIL import Image
import torch.hub
import torchvision
import torch.nn.functional as F
# download deeplabv2_resnet101_msc-cocostuff164k-100000.pth from
# https://github.com/kazut... | 3,753 | 27.656489 | 119 | py |
taming-transformers | taming-transformers-master/scripts/sample_conditional.py | import argparse, os, sys, glob, math, time
import torch
import numpy as np
from omegaconf import OmegaConf
import streamlit as st
from streamlit import caching
from PIL import Image
from main import instantiate_from_config, DataModuleFromConfig
from torch.utils.data import DataLoader
from torch.utils.data.dataloader im... | 12,535 | 34.213483 | 122 | py |
taming-transformers | taming-transformers-master/scripts/sample_fast.py | import argparse, os, sys, glob
import torch
import time
import numpy as np
from omegaconf import OmegaConf
from PIL import Image
from tqdm import tqdm, trange
from einops import repeat
from main import instantiate_from_config
from taming.modules.transformer.mingpt import sample_with_past
rescale = lambda x: (x + 1.)... | 9,191 | 34.218391 | 115 | py |
taming-transformers | taming-transformers-master/scripts/make_scene_samples.py | import glob
import os
import sys
from itertools import product
from pathlib import Path
from typing import Literal, List, Optional, Tuple
import numpy as np
import torch
from omegaconf import OmegaConf
from pytorch_lightning import seed_everything
from torch import Tensor
from torchvision.utils import save_image
from ... | 8,092 | 39.668342 | 120 | py |
taming-transformers | taming-transformers-master/scripts/extract_depth.py | import os
import torch
import numpy as np
from tqdm import trange
from PIL import Image
def get_state(gpu):
import torch
midas = torch.hub.load("intel-isl/MiDaS", "MiDaS")
if gpu:
midas.cuda()
midas.eval()
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
transform = ... | 3,121 | 26.628319 | 91 | py |
taming-transformers | taming-transformers-master/scripts/extract_submodel.py | import torch
import sys
if __name__ == "__main__":
inpath = sys.argv[1]
outpath = sys.argv[2]
submodel = "cond_stage_model"
if len(sys.argv) > 3:
submodel = sys.argv[3]
print("Extracting {} from {} to {}.".format(submodel, inpath, outpath))
sd = torch.load(inpath, map_location="cpu")
... | 549 | 29.555556 | 75 | py |
taming-transformers | taming-transformers-master/scripts/make_samples.py | import argparse, os, sys, glob, math, time
import torch
import numpy as np
from omegaconf import OmegaConf
from PIL import Image
from main import instantiate_from_config, DataModuleFromConfig
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from tqdm import trange
def sa... | 10,146 | 33.631399 | 102 | py |
taming-transformers | taming-transformers-master/taming/modules/util.py | import torch
import torch.nn as nn
def count_params(model):
total_params = sum(p.numel() for p in model.parameters())
return total_params
class ActNorm(nn.Module):
def __init__(self, num_features, logdet=False, affine=True,
allow_reverse_init=False):
assert affine
super(... | 3,847 | 28.374046 | 85 | py |
taming-transformers | taming-transformers-master/taming/modules/vqvae/quantize.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch import einsum
from einops import rearrange
class VectorQuantizer(nn.Module):
"""
see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
_____________________... | 18,182 | 39.769058 | 110 | py |
taming-transformers | taming-transformers-master/taming/modules/discriminator/model.py | import functools
import torch.nn as nn
from taming.modules.util import ActNorm
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02... | 2,550 | 36.514706 | 116 | py |
taming-transformers | taming-transformers-master/taming/modules/misc/coord.py | import torch
class CoordStage(object):
def __init__(self, n_embed, down_factor):
self.n_embed = n_embed
self.down_factor = down_factor
def eval(self):
return self
def encode(self, c):
"""fake vqmodel interface"""
assert 0.0 <= c.min() and c.max() <= 1.0
b,c... | 904 | 27.28125 | 79 | py |
taming-transformers | taming-transformers-master/taming/modules/diffusionmodules/model.py | # pytorch_diffusion + derived encoder decoder
import math
import torch
import torch.nn as nn
import numpy as np
def get_timestep_embedding(timesteps, embedding_dim):
"""
This matches the implementation in Denoising Diffusion Probabilistic Models:
From Fairseq.
Build sinusoidal embeddings.
This mat... | 30,221 | 37.895753 | 121 | py |
taming-transformers | taming-transformers-master/taming/modules/transformer/mingpt.py | """
taken from: https://github.com/karpathy/minGPT/
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block... | 16,836 | 39.473558 | 140 | py |
taming-transformers | taming-transformers-master/taming/modules/transformer/permuter.py | import torch
import torch.nn as nn
import numpy as np
class AbstractPermuter(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x, reverse=False):
raise NotImplementedError
class Identity(AbstractPermuter):
def __init__(self):
super().__init__()... | 7,093 | 27.48996 | 83 | py |
taming-transformers | taming-transformers-master/taming/modules/losses/lpips.py | """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
import torch
import torch.nn as nn
from torchvision import models
from collections import namedtuple
from taming.util import get_ckpt_path
class LPIPS(nn.Module):
# Learned perceptual metric
def __init__(self, use... | 4,832 | 37.975806 | 104 | py |
taming-transformers | taming-transformers-master/taming/modules/losses/segmentation.py | import torch.nn as nn
import torch.nn.functional as F
class BCELoss(nn.Module):
def forward(self, prediction, target):
loss = F.binary_cross_entropy_with_logits(prediction,target)
return loss, {}
class BCELossWithQuant(nn.Module):
def __init__(self, codebook_weight=1.):
super().__ini... | 816 | 34.521739 | 82 | py |
taming-transformers | taming-transformers-master/taming/modules/losses/vqperceptual.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from taming.modules.losses.lpips import LPIPS
from taming.modules.discriminator.model import NLayerDiscriminator, weights_init
class DummyLoss(nn.Module):
def __init__(self):
super().__init__()
def adopt_weight(weight, global_step, thre... | 6,179 | 44.109489 | 113 | py |
taming-transformers | taming-transformers-master/taming/models/dummy_cond_stage.py | from torch import Tensor
class DummyCondStage:
def __init__(self, conditional_key):
self.conditional_key = conditional_key
self.train = None
def eval(self):
return self
@staticmethod
def encode(c: Tensor):
return c, None, (None, None, c)
@staticmethod
def dec... | 416 | 17.130435 | 46 | py |
taming-transformers | taming-transformers-master/taming/models/vqgan.py | import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from main import instantiate_from_config
from taming.modules.diffusionmodules.model import Encoder, Decoder
from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
from taming.modules.vqvae.quantize import GumbelQuantize... | 16,760 | 40.487624 | 120 | py |
taming-transformers | taming-transformers-master/taming/models/cond_transformer.py | import os, math
import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from main import instantiate_from_config
from taming.modules.util import SOSProvider
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change anymor... | 15,648 | 43.331445 | 127 | py |
taming-transformers | taming-transformers-master/taming/data/custom.py | import os
import numpy as np
import albumentations
from torch.utils.data import Dataset
from taming.data.base import ImagePaths, NumpyPaths, ConcatDatasetWithIndex
class CustomBase(Dataset):
def __init__(self, *args, **kwargs):
super().__init__()
self.data = None
def __len__(self):
r... | 998 | 24.615385 | 75 | py |
taming-transformers | taming-transformers-master/taming/data/base.py | import bisect
import numpy as np
import albumentations
from PIL import Image
from torch.utils.data import Dataset, ConcatDataset
class ConcatDatasetWithIndex(ConcatDataset):
"""Modified from original pytorch code to return dataset idx"""
def __getitem__(self, idx):
if idx < 0:
if -idx > le... | 2,609 | 35.760563 | 92 | py |
taming-transformers | taming-transformers-master/taming/data/helper_types.py | from typing import Dict, Tuple, Optional, NamedTuple, Union
from PIL.Image import Image as pil_image
from torch import Tensor
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
Image = Union[Tensor, pil_image]
BoundingBox = Tuple[float, float, float, float] # x0, y0, w, h
C... | 1,350 | 26.02 | 65 | py |
taming-transformers | taming-transformers-master/taming/data/ade20k.py | import os
import numpy as np
import cv2
import albumentations
from PIL import Image
from torch.utils.data import Dataset
from taming.data.sflckr import SegmentationBase # for examples included in repo
class Examples(SegmentationBase):
def __init__(self, size=256, random_crop=False, interpolation="bicubic"):
... | 5,378 | 42.032 | 107 | py |
taming-transformers | taming-transformers-master/taming/data/utils.py | import collections
import os
import tarfile
import urllib
import zipfile
from pathlib import Path
import numpy as np
import torch
from taming.data.helper_types import Annotation
from torch._six import string_classes
from torch.utils.data._utils.collate import np_str_obj_array_pattern, default_collate_err_msg_format
fr... | 5,903 | 33.729412 | 100 | py |
taming-transformers | taming-transformers-master/taming/data/faceshq.py | import os
import numpy as np
import albumentations
from torch.utils.data import Dataset
from taming.data.base import ImagePaths, NumpyPaths, ConcatDatasetWithIndex
class FacesBase(Dataset):
def __init__(self, *args, **kwargs):
super().__init__()
self.data = None
self.keys = None
def ... | 4,640 | 33.377778 | 92 | py |
taming-transformers | taming-transformers-master/taming/data/annotated_objects_dataset.py | from pathlib import Path
from typing import Optional, List, Callable, Dict, Any, Union
import warnings
import PIL.Image as pil_image
from torch import Tensor
from torch.utils.data import Dataset
from torchvision import transforms
from taming.data.conditional_builder.objects_bbox import ObjectsBoundingBoxConditionalBu... | 10,226 | 45.69863 | 122 | py |
taming-transformers | taming-transformers-master/taming/data/sflckr.py | import os
import numpy as np
import cv2
import albumentations
from PIL import Image
from torch.utils.data import Dataset
class SegmentationBase(Dataset):
def __init__(self,
data_csv, data_root, segmentation_root,
size=None, random_crop=False, interpolation="bicubic",
... | 4,097 | 43.543478 | 104 | py |
taming-transformers | taming-transformers-master/taming/data/imagenet.py | import os, tarfile, glob, shutil
import yaml
import numpy as np
from tqdm import tqdm
from PIL import Image
import albumentations
from omegaconf import OmegaConf
from torch.utils.data import Dataset
from taming.data.base import ImagePaths
from taming.util import download, retrieve
import taming.data.utils as bdu
def... | 20,815 | 36.237925 | 112 | py |
taming-transformers | taming-transformers-master/taming/data/coco.py | import os
import json
import albumentations
import numpy as np
from PIL import Image
from tqdm import tqdm
from torch.utils.data import Dataset
from taming.data.sflckr import SegmentationBase # for examples included in repo
class Examples(SegmentationBase):
def __init__(self, size=256, random_crop=False, interpo... | 8,121 | 44.887006 | 115 | py |
taming-transformers | taming-transformers-master/taming/data/image_transforms.py | import random
import warnings
from typing import Union
import torch
from torch import Tensor
from torchvision.transforms import RandomCrop, functional as F, CenterCrop, RandomHorizontalFlip, PILToTensor
from torchvision.transforms.functional import _get_image_size as get_image_size
from taming.data.helper_types impor... | 4,511 | 32.924812 | 109 | py |
taming-transformers | taming-transformers-master/taming/data/conditional_builder/objects_center_points.py | import math
import random
import warnings
from itertools import cycle
from typing import List, Optional, Tuple, Callable
from PIL import Image as pil_image, ImageDraw as pil_img_draw, ImageFont
from more_itertools.recipes import grouper
from taming.data.conditional_builder.utils import COLOR_PALETTE, WHITE, GRAY_75, B... | 8,165 | 47.319527 | 120 | py |
taming-transformers | taming-transformers-master/taming/data/conditional_builder/objects_bbox.py | from itertools import cycle
from typing import List, Tuple, Callable, Optional
from PIL import Image as pil_image, ImageDraw as pil_img_draw, ImageFont
from more_itertools.recipes import grouper
from taming.data.image_transforms import convert_pil_to_tensor
from torch import LongTensor, Tensor
from taming.data.helper... | 3,223 | 51.852459 | 120 | py |
ppgn | ppgn-master/settings.py | # Set this to the path to Caffe installation on your system
caffe_root = "/path/to/your/caffe/python"
gpu = True
# -------------------------------------
# The following are hard-coded and hardly change unless we change to use a different generator.
# -------------------------------------
# Generator G
generator_weigh... | 777 | 32.826087 | 95 | py |
ppgn | ppgn-master/sampling_caption.py | #!/usr/bin/env python
'''
Anh Nguyen <anh.ng8@gmail.com>
2016
'''
import os, sys
os.environ['GLOG_minloglevel'] = '2' # suprress Caffe verbose prints
import settings
sys.path.insert(0, settings.caffe_root)
import caffe
import numpy as np
from numpy.linalg import norm
import scipy.misc, scipy.io
import argparse
i... | 9,371 | 41.6 | 157 | py |
ppgn | ppgn-master/sampler.py | #!/usr/bin/env python
'''
Anh Nguyen <anh.ng8@gmail.com>
2017
'''
import os, sys
os.environ['GLOG_minloglevel'] = '2' # suprress Caffe verbose prints
import settings
sys.path.insert(0, settings.caffe_root)
import caffe
import numpy as np
from numpy.linalg import norm
import scipy.misc, scipy.io
import util
class... | 8,319 | 41.020202 | 174 | py |
ppgn | ppgn-master/sampling_class.py | #!/usr/bin/env python
'''
Anh Nguyen <anh.ng8@gmail.com>
2016
'''
import os, sys
os.environ['GLOG_minloglevel'] = '2' # suprress Caffe verbose prints
import settings
sys.path.insert(0, settings.caffe_root)
import caffe
import numpy as np
from numpy.linalg import norm
import scipy.misc, scipy.io
import argparse
i... | 11,251 | 40.216117 | 165 | py |
gcnn-survey-paper | gcnn-survey-paper-master/third_party/gcn/gcn/layers.py | from gcn.inits import *
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
# global unique layer ID dictionary for layer name assignment
_LAYER_UIDS = {}
def get_layer_uid(layer_name=''):
"""Helper function, assigns unique layer IDs."""
if layer_name not in _LAYER_UIDS:
_LAYER_UIDS[lay... | 5,886 | 30.148148 | 92 | py |
STTS | STTS-main/MViT/setup.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from setuptools import find_packages, setup
setup(
name="slowfast",
version="1.0",
author="FAIR",
url="unknown",
description="SlowFast Video Understanding",
install_requires=[
"yacs>=0.1.6",
... | 794 | 23.090909 | 71 | py |
STTS | STTS-main/MViT/tools/visualization.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import pickle
import torch
import tqdm
import slowfast.datasets.utils as data_utils
import slowfast.utils.checkpoint as cu
import slowfast.utils.distributed as du
import slowfast.utils.logging as logging
... | 14,000 | 39.465318 | 126 | py |
STTS | STTS-main/MViT/tools/test_net.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Multi-view test a video classification model."""
import numpy as np
import os
import pickle
import torch
import torch.nn.functional as F
from einops import rearrange
import slowfast.utils.checkpoint as cu
import slowfast... | 7,234 | 34.816832 | 84 | py |
STTS | STTS-main/MViT/tools/demo_net.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import time
import torch
import tqdm
from slowfast.utils import logging
from slowfast.visualization.async_predictor import AsyncDemo, AsyncVis
from slowfast.visualization.ava_demo_precomputed_boxes import... | 3,683 | 29.7 | 93 | py |
STTS | STTS-main/MViT/tools/submit.py | import argparse
import os
from pathlib import Path
import submitit
import torch
from slowfast.utils.misc import launch_job
from slowfast.utils.parser import load_config
from run_net import get_func
def parse_args():
parser = argparse.ArgumentParser(
"Submitit for onestage training", add_help=False
)... | 6,114 | 30.040609 | 102 | py |
STTS | STTS-main/MViT/tools/train_net.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Train a video classification model."""
import numpy as np
import torch
from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats
import copy
import slowfast.models.losses as losses
import slowfast.models.optimize... | 21,443 | 34.562189 | 116 | py |
STTS | STTS-main/MViT/slowfast/config/defaults.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Configs."""
from fvcore.common.config import CfgNode
from . import custom_config
# -----------------------------------------------------------------------------
# Config definition
# ------------------------------------... | 31,843 | 31.230769 | 115 | py |
STTS | STTS-main/MViT/slowfast/models/operators.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Custom operators."""
import torch
import torch.nn as nn
class Swish(nn.Module):
"""Swish activation function: x * sigmoid(x)."""
def __init__(self):
super(Swish, self).__init__()
def forward(self,... | 2,552 | 29.759036 | 86 | py |
STTS | STTS-main/MViT/slowfast/models/losses.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Loss functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from slowfast.models.topk import batched_index_select
class SoftTargetCrossEntropy(nn.Module):
"""
Cross entropy loss with so... | 2,960 | 28.61 | 110 | py |
STTS | STTS-main/MViT/slowfast/models/batchnorm_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""BatchNorm (BN) utility functions and custom batch-size BN implementations"""
from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.autograd.function import Function
... | 7,424 | 32.90411 | 82 | py |
STTS | STTS-main/MViT/slowfast/models/mvit.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Video models."""
import math
from functools import partial
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
from einops import rearrange
from math import sqrt
import slowfast.utils.weight_init_helper as init_helper
f... | 14,098 | 35.058824 | 111 | py |
STTS | STTS-main/MViT/slowfast/models/ptv_model_builder.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Video models using PyTorchVideo model builder."""
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.vi... | 26,986 | 33.777062 | 89 | py |
STTS | STTS-main/MViT/slowfast/models/topk.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import einops
from einops import rearrange
from math import sqrt
import time
class PredictorLG(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, embed_dim=384):
super().__init__()
self.in_con... | 8,512 | 32.916335 | 101 | py |
STTS | STTS-main/MViT/slowfast/models/utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from logging import NOTSET
import slowfast.utils.logging as logging
import numpy as np
import torch.nn.functional as F
from einops import rearrange
logger = logging.get_logger(__name__)
def round_width(width, multiplier, min_width=1, divisor=1,... | 1,017 | 28.941176 | 77 | py |
STTS | STTS-main/MViT/slowfast/models/nonlocal_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Non-local helper"""
import torch
import torch.nn as nn
class Nonlocal(nn.Module):
"""
Builds Non-local Neural Networks as a generic family of building
blocks for capturing long-range dependencies. Non-local... | 5,418 | 35.369128 | 80 | py |
STTS | STTS-main/MViT/slowfast/models/video_model_builder.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Video models."""
import math
from functools import partial
import torch
import torch.nn as nn
from torch.nn.init import trunc_normal_
import slowfast.utils.weight_init_helper as init_helper
from slowfast.models.attention import MultiScaleBlo... | 28,931 | 36.044814 | 96 | py |
STTS | STTS-main/MViT/slowfast/models/common.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop_rate=0.0,
):
super().__init__()
self.dr... | 1,900 | 25.774648 | 99 | py |
STTS | STTS-main/MViT/slowfast/models/head_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""ResNe(X)t Head helper."""
import torch
import torch.nn as nn
from detectron2.layers import ROIAlign
class ResNetRoIHead(nn.Module):
"""
ResNe(X)t RoI head.
"""
def __init__(
self,
dim_i... | 14,978 | 35.623472 | 81 | py |
STTS | STTS-main/MViT/slowfast/models/stem_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""ResNe(X)t 3D stem helper."""
import torch.nn as nn
def get_stem_func(name):
"""
Retrieves the stem module by name.
"""
trans_funcs = {"x3d_stem": X3DStem, "basic_stem": ResNetBasicStem}
assert (
... | 10,775 | 32.362229 | 102 | py |
STTS | STTS-main/MViT/slowfast/models/resnet_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Video models."""
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
def get_trans_func(... | 24,795 | 33.15427 | 83 | py |
STTS | STTS-main/MViT/slowfast/models/attention.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy
import torch
import torch.nn as nn
from einops import rearrange
from slowfast.models.common import DropPath, Mlp
def attention_pool(tensor, pool, thw_shape, has_cls_embed=True, norm=None):
if pool is None... | 8,875 | 29.712803 | 80 | py |
STTS | STTS-main/MViT/slowfast/models/build.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Model construction functions."""
import torch
from fvcore.common.registry import Registry
MODEL_REGISTRY = Registry("MODEL")
MODEL_REGISTRY.__doc__ = """
Registry for video model.
The registered object will be called w... | 1,725 | 30.962963 | 80 | py |
STTS | STTS-main/MViT/slowfast/models/optimizer.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Optimizer."""
import torch
import slowfast.utils.lr_policy as lr_policy
def construct_optimizer(model, cfg):
"""
Construct a stochastic gradient descent or ADAM optimizer with momentum.
Details can be found in:
Herbert Robbi... | 4,155 | 30.484848 | 101 | py |
STTS | STTS-main/MViT/slowfast/datasets/video_container.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import av
def get_video_container(path_to_vid, multi_thread_decode=False, backend="pyav"):
"""
Given the path to the video, return the pyav video container.
Args:
path_to_vid (str): path to the video.
... | 1,033 | 33.466667 | 80 | py |
STTS | STTS-main/MViT/slowfast/datasets/transform.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import numpy as np
# import cv2
import random
import torch
import torchvision.transforms.functional as F
from PIL import Image
from torchvision import transforms
from .rand_augment import rand_augment_transform... | 30,520 | 33.101676 | 90 | py |
STTS | STTS-main/MViT/slowfast/datasets/utils.py | #!/usr/bin/env python3
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 slowfast.utils.env import pathmgr
from . import transform as transform
logger = logging.getLogger(... | 11,739 | 32.638968 | 90 | py |
STTS | STTS-main/MViT/slowfast/datasets/mixup.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This implementation is based on
https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/mixup.py,
published under an Apache License 2.0.
COMMENT FROM ORIGINAL:
Mixup and Cutmix
Papers:
mixup: Beyond Empirical Risk Minimization... | 6,659 | 34.052632 | 127 | py |
STTS | STTS-main/MViT/slowfast/datasets/ava_dataset.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import numpy as np
import torch
from . import ava_helper as ava_helper
from . import cv2_transform as cv2_transform
from . import transform as transform
from . import utils as utils
from .build import DATASET... | 14,963 | 33.881119 | 82 | py |
STTS | STTS-main/MViT/slowfast/datasets/ptv_datasets.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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._tran... | 19,371 | 31.557983 | 84 | py |
STTS | STTS-main/MViT/slowfast/datasets/charades.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import random
from itertools import chain as chain
import torch
import torch.utils.data
import slowfast.utils.logging as logging
from slowfast.utils.env import pathmgr
from . import utils as utils
from .build imp... | 9,677 | 36.366795 | 82 | py |
STTS | STTS-main/MViT/slowfast/datasets/multigrid_helper.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Helper functions for multigrid training."""
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
TORCH_MAJOR = int(torch.__version__.split(".")[0])
TORCH_MINOR = int(torch.__version__.split(".")[... | 2,753 | 30.295455 | 78 | py |
STTS | STTS-main/MViT/slowfast/datasets/decoder.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import numpy as np
import random
import torch
import torchvision.io as io
def temporal_sampling(frames, start_idx, end_idx, num_samples):
"""
Given the start and end frame index, sample num_samples fram... | 15,165 | 37.787724 | 80 | py |
STTS | STTS-main/MViT/slowfast/datasets/ssv2.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import json
import numpy as np
import os
import random
from itertools import chain as chain
import torch
import torch.utils.data
import slowfast.utils.logging as logging
from slowfast.utils.env import pathmgr
from . import... | 10,293 | 35.246479 | 82 | py |
STTS | STTS-main/MViT/slowfast/datasets/random_erasing.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This implementation is based on
https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/random_erasing.py
pulished under an Apache License 2.0.
COMMENT FROM ORIGINAL:
Originally inspired by impl at https://github.com/zhunzhong... | 6,887 | 37.055249 | 95 | py |
STTS | STTS-main/MViT/slowfast/datasets/kinetics.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import random
import torch
import torch.utils.data
import numpy as np
from torchvision import transforms
import slowfast.utils.logging as logging
from slowfast.utils.env import pathmgr
from . import decoder as de... | 16,469 | 37.661972 | 87 | py |
STTS | STTS-main/MViT/slowfast/datasets/loader.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Data loader."""
import itertools
import numpy as np
from functools import partial
import torch
from torch.utils.data._utils.collate import default_collate
from torch.utils.data.distributed import DistributedSampler
from ... | 7,067 | 34.878173 | 79 | py |
STTS | STTS-main/MViT/slowfast/datasets/imagenet.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import numpy as np
import os
import random
import re
import torch
import torch.utils.data
from PIL import Image
from torchvision import transforms as transforms_tv
import slowfast.datasets.transform as transform
import slowfast.utils.logging as logging
#... | 7,414 | 35.348039 | 84 | py |
STTS | STTS-main/MViT/slowfast/datasets/rand_augment.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This implementation is based on
https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/auto_augment.py
pulished under an Apache License 2.0.
COMMENT FROM ORIGINAL:
AutoAugment, RandAugment, and AugMix for PyTorch
This code im... | 16,199 | 29.337079 | 119 | py |
STTS | STTS-main/MViT/slowfast/datasets/build.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from fvcore.common.registry import Registry
DATASET_REGISTRY = Registry("DATASET")
DATASET_REGISTRY.__doc__ = """
Registry for dataset.
The registered object will be called with `obj(cfg, split)`.
The call should return a ... | 1,120 | 34.03125 | 80 | py |
STTS | STTS-main/MViT/slowfast/visualization/async_predictor.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import atexit
import numpy as np
import queue
import torch
import torch.multiprocessing as mp
import slowfast.utils.logging as logging
from slowfast.datasets import cv2_transform
from slowfast.visualization.predictor import... | 9,808 | 29.653125 | 98 | py |
STTS | STTS-main/MViT/slowfast/visualization/predictor.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import queue
import cv2
import torch
from detectron2 import model_zoo
from detectron2.config import get_cfg
from detectron2.engine import DefaultPredictor
import slowfast.utils.checkpoint as cu
from slowfast.datasets import... | 6,847 | 31.923077 | 85 | py |
STTS | STTS-main/MViT/slowfast/visualization/gradcam_utils.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
import slowfast.datasets.utils as data_utils
from slowfast.visualization.utils import get_layer
class GradCAM:
"""
GradCAM class helps c... | 6,958 | 37.877095 | 92 | py |
STTS | STTS-main/MViT/slowfast/visualization/utils.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import numpy as np
import matplotlib.pyplot as plt
import torch
from sklearn.metrics import confusion_matrix
import slowfast.utils.logging as logging
from slowfast.datasets.utils import pack_pathway_output,... | 12,593 | 32.494681 | 101 | py |
STTS | STTS-main/MViT/slowfast/visualization/prediction_vis.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import torch
import slowfast.datasets.utils as data_utils
import slowfast.utils.logging as logging
import slowfast.visualization.tensorboard_vis as tb
from slowfast.utils.misc import get_class_names
from ... | 5,296 | 37.948529 | 108 | py |
STTS | STTS-main/MViT/slowfast/visualization/ava_demo_precomputed_boxes.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.datas... | 17,969 | 37.397436 | 98 | py |
STTS | STTS-main/MViT/slowfast/visualization/tensorboard_vis.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging as log
import math
import os
import matplotlib.pyplot as plt
import torch
from torch.utils.tensorboard import SummaryWriter
from torchvision.utils import make_grid
import slowfast.utils.logging as logging
imp... | 16,010 | 36.234884 | 102 | py |
STTS | STTS-main/MViT/slowfast/visualization/video_visualizer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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 imp... | 27,400 | 39.414454 | 143 | py |
STTS | STTS-main/MViT/slowfast/utils/c2_model_loading.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Caffe2 to PyTorch checkpoint name converting utility."""
import re
def get_name_convert_func():
"""
Get the function to convert Caffe2 layer names to PyTorch layer names.
Returns:
(func): function t... | 5,005 | 40.371901 | 80 | py |
STTS | STTS-main/MViT/slowfast/utils/parser.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Argument parser functions."""
import argparse
import sys
import slowfast.utils.checkpoint as cu
from slowfast.config.defaults import get_cfg
def parse_args():
"""
Parse the following arguments for a default pa... | 3,021 | 30.810526 | 80 | py |
STTS | STTS-main/MViT/slowfast/utils/checkpoint.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Functions that handle saving and loading of checkpoints."""
import copy
import numpy as np
import os
import pickle
from collections import OrderedDict
import torch
import slowfast.utils.distributed as du
import slowfast... | 19,869 | 36.775665 | 102 | py |
STTS | STTS-main/MViT/slowfast/utils/benchmark.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Functions for benchmarks.
"""
import numpy as np
import pprint
import torch
import tqdm
from fvcore.common.timer import Timer
import slowfast.utils.logging as logging
import slowfast.utils.misc as misc
from slowfast.datasets import loader
from... | 3,290 | 30.644231 | 81 | py |
STTS | STTS-main/MViT/slowfast/utils/misc.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import json
import logging
import math
import numpy as np
import os
from datetime import datetime
import psutil
import torch
from fvcore.nn.activation_count import activation_count
from fvcore.nn.flop_count import flop_count... | 12,587 | 31.78125 | 84 | py |
STTS | STTS-main/MViT/slowfast/utils/distributed.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Distributed helpers."""
import functools
import logging
import pickle
import torch
import torch.distributed as dist
_LOCAL_PROCESS_GROUP = None
def all_gather(tensors):
"""
All gathers the provided tensors fro... | 8,879 | 27.645161 | 85 | py |
STTS | STTS-main/MViT/slowfast/utils/metrics.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Functions for computing metrics."""
import torch
def topks_correct(preds, labels, ks):
"""
Given the predictions, labels, and a list of top-k values, compute the
number of correct predictions for each top-k... | 2,381 | 35.646154 | 76 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.