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
STR
STR-master/utils/conv_type.py
from torch.nn import init import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import math from args import args as parser_args import numpy as np DenseConv = nn.Conv2d def sparseFunction(x, s, activation=torch.relu, f=torch.sigmoid): return torch.sign(x)*activati...
3,471
30.853211
154
py
STR
STR-master/utils/logging.py
import abc import tqdm from torch.utils.tensorboard import SummaryWriter class ProgressMeter(object): def __init__(self, num_batches, meters, prefix=""): self.batch_fmtstr = self._get_batch_fmtstr(num_batches) self.meters = meters self.prefix = prefix def display(self, batch, tqdm_wr...
3,167
25.621849
78
py
STR
STR-master/utils/builder.py
from args import args import math import torch import torch.nn as nn import utils.conv_type import utils.bn_type class Builder(object): def __init__(self, conv_layer, bn_layer, first_layer=None): self.conv_layer = conv_layer self.bn_layer = bn_layer self.first_layer = first_layer or conv...
5,356
30.327485
88
py
STR
STR-master/utils/eval_utils.py
import torch def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() corr...
563
28.684211
88
py
STR
STR-master/utils/net_utils.py
from functools import partial import os import pathlib import shutil import math import torch import torch.nn as nn def save_checkpoint(state, is_best, filename="checkpoint.pth", save=False): filename = pathlib.Path(filename) if not filename.parent.exists(): os.makedirs(filename.parent) torch.s...
1,847
21.536585
75
py
STR
STR-master/data/utils.py
import torch from torch.utils.data.dataset import Dataset def one_batch_dataset(dataset, batch_size): print("==> Grabbing a single batch") perm = torch.randperm(len(dataset)) one_batch = [dataset[idx.item()] for idx in perm[:batch_size]] class _OneBatchWrapper(Dataset): def __init__(self): ...
525
21.869565
66
py
STR
STR-master/data/imagenet.py
import os import torch from torchvision import datasets, transforms import torch.multiprocessing import h5py import os import numpy as np torch.multiprocessing.set_sharing_strategy("file_system") class ImageNet: def __init__(self, args): super(ImageNet, self).__init__() data_root = os.path.join(...
4,309
30.691176
89
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/severity_scan.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
4,768
33.810219
100
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/test_cifar10.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
1,308
25.18
65
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/train_imagenet.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
3,301
29.859813
87
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/closest_augs.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
6,088
41.284722
149
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/severity_scan_imagenet.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
4,942
34.307143
100
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/train_imagenet_jsd.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net_jsd import train_net from overlap.test_net import test_...
3,398
30.183486
87
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/feature_corrupt_error.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
4,670
40.336283
115
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/train_cifar10_jsd.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net_jsd import train_net from overlap.test_net import test_...
1,841
27.338462
65
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/train_cifar10.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
1,744
26.698413
65
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/test_imagenet.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from hydra.utils import instantiate import logging from overlap.train_net import train_net from overlap.test_net import test_net ...
2,623
27.835165
73
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/train_net_jsd.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import logging import os import time import datetime import torch.nn as nn import torch.nn.functional as F log = logging.getLogg...
6,417
37.202381
135
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/feature_extractor.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import numpy as np from hydra.utils import instantiate from .train_net import train_net class Network(object): def __in...
2,017
32.081967
99
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/test_net.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import logging from .utils import logging as lu log = logging.getLogger(__name__) def test_net(model, test_dataset, batch_size,...
1,338
30.880952
99
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/extract_features.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import logging from .utils import logging as lu import numpy as np import os log = logging.getLogger(__name__) def distributed_...
4,564
43.320388
165
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/test_corrupt_net.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import logging from .utils import logging as lu from omegaconf import open_dict from .augmentations.utils import aug_finder from...
4,659
37.196721
169
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/datasets.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import augmentations as aug from .augmentations.utils.converters import NumpyToTensor, PilToNumpy from .augmentations.utils.aug_finder ...
33,803
45.117326
157
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/models.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn as nn import torch.nn.functional as F class ResHead(nn.Module): """ResNet head.""" def __in...
8,640
35.459916
103
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/train_net.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import logging import os import time import datetime log = logging.getLogger(__name__) def eta_str(eta_td): """Converts an ...
5,251
35.727273
135
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/wideresnet.py
# This source code is adapted from code licensed under the MIT license # found in third_party/wideresnet_license from the root directory of # this source tree. """WideResNet implementation (https://arxiv.org/abs/1605.07146).""" import math import torch import torch.nn as nn import torch.nn.functional as F class Bas...
4,461
29.986111
79
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/augmentations/imagenetc.py
# This source code is adapted from code licensed under the license at # third_party/imagenetc_license from the root directory of the repository # Originally available: github.com/hendrycks/robustness # Modifications Copyright (c) Facebook, Inc. and its affiliates, # licensed under the MIT license found in the LICENSE...
25,528
31.940645
143
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/experiments/overlap/augmentations/utils/converters.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from PIL import Image import torch class PilToNumpy(object): def __init__(self, as_float=False, scaled_to_one=False): ...
1,351
29.044444
68
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/imagenet_c_bar/test_c_bar.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from transform_finder import build_transform import torch import torchvision as tv from utils.converters import PilToNumpy, NumpyToTensor CIF...
4,285
36.596491
105
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/imagenet_c_bar/make_cifar10_c_bar.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import torchvision as tv from transform_finder import build_transform from utils.converters import PilToNumpy, NumpyToPil impo...
3,650
37.840426
105
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/imagenet_c_bar/make_imagenet_c_bar.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import torchvision as tv from transform_finder import build_transform from utils.converters import PilToNumpy, NumpyToPil impo...
4,256
36.342105
87
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/imagenet_c_bar/utils/converters.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from PIL import Image import torch class PilToNumpy(object): def __init__(self, as_float=False, scaled_to_one=False): ...
1,351
29.044444
68
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/notebook_utils/training_loop.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def train_model(model, dataset, num_workers...
1,811
27.3125
95
py
augmentation-corruption-fbr_main
augmentation-corruption-fbr_main/notebook_utils/wideresnet.py
# This source code is adapted from code licensed under the MIT license # found in third_party/wideresnet_license from the root directory of # this source tree. """WideResNet implementation (https://arxiv.org/abs/1605.07146).""" import math import torch import torch.nn as nn import torch.nn.functional as F import nump...
4,479
30.111111
79
py
jupyter-book
jupyter-book-master/tests/test_config.py
# from pathlib import Path import jsonschema import pytest import sphinx as sphinx_build from jupyter_book.cli.main import sphinx from jupyter_book.config import get_final_config, validate_yaml pytest_plugins = "pytester" SPHINX_VERSION = f".sphinx{sphinx_build.version_info[0]}" @pytest.mark.parametrize( "user...
9,373
32.359431
123
py
jupyter-book
jupyter-book-master/jupyter_book/config.py
"""A small sphinx extension to let you configure a site with YAML metadata.""" import json import sys from functools import lru_cache from pathlib import Path from typing import Optional, Union import docutils import jsonschema import sphinx import yaml from sphinx.util import logging from .utils import _message_box ...
18,195
38.04721
135
py
jupyter-book
jupyter-book-master/jupyter_book/pdf.py
"""Commands to facilitate conversion to PDF.""" import asyncio import os from copy import copy from pathlib import Path from .utils import _error, _message_box # LaTeX Documents Tuple Spec LATEX_DOCUMENTS = ( "startdocname", "targetname", "title", "author", "theme", "toctree_only", ) def htm...
5,554
30.5625
86
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/trainer/trainer.py
from typing import Any, List, Tuple import torch from torch import nn, optim from torch.utils.data import DataLoader class Trainer: def __init__( self, net: nn.Module, optimizer: optim.Optimizer, critetion: nn.Module, lr_scheduler: Any, device: torch.device, ) ...
3,588
30.482456
82
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/models/nn/bert.py
import torch from torch import nn from transformers import BertModel class DarkpatternClassifierBert(nn.Module): def __init__( self, pretrained: str = "bert-base-uncased", dropout_rate: float = 0.1, output_layer: nn.Linear = nn.Linear(in_features=768, out_features=2), ): ...
801
31.08
77
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/experiments/train.py
from os.path import join from typing import List import hydra import numpy as np import pandas as pd import torch from const.path import CONFIG_PATH, DATASET_TSV_PATH, NN_MODEL_PICKLES_PATH from omegaconf import DictConfig from sklearn import metrics from sklearn.model_selection import StratifiedKFold from torch impor...
6,125
30.415385
88
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/utils/dataset.py
from typing import Callable, List, Tuple import torch from torch.utils.data import Dataset class DarkpatternDataset(Dataset): def __init__( self, texts: List[str], labels: List[int], text_to_tensor: Callable[[str], torch.Tensor], ) -> None: self.texts: List[str] = text...
723
26.846154
74
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/utils/random_seed.py
import os import random import numpy as np import torch def set_random_seed(random_seed: int = 42) -> None: random.seed(random_seed) os.environ["PYTHONHASHSEED"] = str(random_seed) np.random.seed(random_seed) torch.manual_seed(random_seed) torch.cuda.manual_seed(random_seed) torch.backends.cu...
341
21.8
51
py
ec-darkpattern
ec-darkpattern-master/darkpattern-auto-detection-deeplearning/utils/text.py
import torch from transformers import PreTrainedTokenizer def tensor_to_text(tensor: torch.Tensor, tokenizer: PreTrainedTokenizer) -> str: """ Convert tensor to text. """ return tokenizer.decode(tensor) def text_to_tensor( text: str, tokenizer: PreTrainedTokenizer, max_length: int ) -> torch.Ten...
493
22.52381
80
py
dolphin
dolphin-main/video_utils.py
import imageio import torch import numpy as np import decord import torchvision from einops import rearrange from torchvision.transforms import Resize, InterpolationMode from utils import get_new_video_name def prepare_video( video_path: str, resolution: int, device, dtype=torch.float16, normaliz...
2,467
28.73494
87
py
dolphin
dolphin-main/utils.py
import os, sys, uuid import importlib import numpy as np import torch import random def instantiate_from_config(config, **kwargs): if not "target" in config: raise KeyError("Expected key `target` to instantiate.") return get_obj_from_str(config["target"])(**config.get("params", dict()), **kwargs) d...
1,588
25.932203
87
py
dolphin
dolphin-main/modules/text2video_zero/utils.py
import os import cv2 import numpy as np import torch import torchvision from torchvision.transforms import Resize, InterpolationMode import imageio from einops import rearrange from PIL import Image import decord def create_gif(frames, fps, rescale=False, path=None): if path is None: dir = "temporal" ...
3,963
32.880342
87
py
dolphin
dolphin-main/modules/text2video_zero/model.py
import os from enum import Enum import numpy as np import tomesd import torch from diffusers import ( StableDiffusionInstructPix2PixPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UNet2DConditionModel, ) from diffusers.schedulers import EulerAncestralDiscreteScheduler, DDIMScheduler from ...
17,263
33.528
193
py
dolphin
dolphin-main/modules/text2video_zero/__init__.py
import torch from .model import ( CannyText2VideoModel, PoseText2VideoModel, DepthText2VideoModel, VideoPix2PixModel, Text2VideoModel, ) from utils import generate_video_name_mp4, get_new_video_name class CannyText2Video: def __init__(self, device): self.device = device self....
3,031
28.153846
80
py
dolphin
dolphin-main/modules/text2video_zero/text_to_video_pipeline.py
from diffusers import StableDiffusionPipeline import torch from dataclasses import dataclass from typing import Callable, List, Optional, Union import numpy as np from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange, repeat from torch.nn.functional import grid_sample import torchvisio...
24,513
33.72238
143
py
dolphin
dolphin-main/modules/blip/__init__.py
import torch import numpy as np from transformers import AutoProcessor, Blip2ForConditionalGeneration from PIL import Image from video_utils import prepare_video class ImageCaptioning: def __init__(self, device): print("Initializing BLIP2 for ImageCaptioning") self.device = device self.pr...
1,840
37.354167
83
py
dolphin
dolphin-main/modules/modelscope_t2v/__init__.py
from __future__ import annotations import random import tempfile import imageio import numpy as np import torch from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler from utils import generate_video_name_mp4 def to_video(frames: list[np.ndarray], fps: int, out_file=None) -> str: if out_file is N...
1,838
26.863636
87
py
dolphin
dolphin-main/modules/annotator/__init__.py
import cv2 import torch import numpy as np from einops import rearrange from torchvision.transforms import Resize, InterpolationMode from .util import HWC3 from .openpose import OpenposeDetector from .midas import MidasDetector from utils import get_new_video_name from video_utils import prepare_video, create_video ...
4,607
36.770492
84
py
dolphin
dolphin-main/modules/annotator/midas/utils.py
"""Utils for monoDepth.""" import sys import re import numpy as np import cv2 import torch def read_pfm(path): """Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale) """ with open(path, "rb") as file: color = None width = None heig...
4,582
23.121053
88
py
dolphin
dolphin-main/modules/annotator/midas/api.py
# based on https://github.com/isl-org/MiDaS import cv2 import os import torch import torch.nn as nn from torchvision.transforms import Compose from .midas.dpt_depth import DPTDepthModel from .midas.midas_net import MidasNet from .midas.midas_net_custom import MidasNet_small from .midas.transforms import Resize, Norma...
5,309
28.831461
124
py
dolphin
dolphin-main/modules/annotator/midas/__init__.py
import cv2 import numpy as np import torch from einops import rearrange from .api import MiDaSInference class MidasDetector: def __init__(self, device=None): self.device = device or torch.device( "cuda" if torch.cuda.is_available() else "cpu" ) self.model = MiDaSInference(mode...
1,544
35.785714
81
py
dolphin
dolphin-main/modules/annotator/midas/midas/base_model.py
import torch class BaseModel(torch.nn.Module): def load(self, path): """Load model from file. Args: path (str): file path """ parameters = torch.load(path, map_location=torch.device('cpu')) if "optimizer" in parameters: parameters = parameters["mod...
367
20.647059
71
py
dolphin
dolphin-main/modules/annotator/midas/midas/midas_net.py
"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. This file contains code that is adapted from https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py """ import torch import torch.nn as nn from .base_model import BaseModel f...
2,709
34.194805
130
py
dolphin
dolphin-main/modules/annotator/midas/midas/vit.py
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F class Slice(nn.Module): def __init__(self, start_index=1): super(Slice, self).__init__() self.start_index = start_index def forward(self, x): return x[:, self.start_index :] class...
14,625
28.727642
96
py
dolphin
dolphin-main/modules/annotator/midas/midas/dpt_depth.py
import torch import torch.nn as nn import torch.nn.functional as F from .base_model import BaseModel from .blocks import ( FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder, forward_vit, ) def _make_fusion_block(features, use_bn): return FeatureFusionBlock_custom( ...
3,154
27.681818
89
py
dolphin
dolphin-main/modules/annotator/midas/midas/midas_net_custom.py
"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. This file contains code that is adapted from https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py """ import torch import torch.nn as nn from .base_model import BaseModel f...
5,207
39.6875
168
py
dolphin
dolphin-main/modules/annotator/midas/midas/blocks.py
import torch import torch.nn as nn from .vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ign...
9,242
25.947522
150
py
dolphin
dolphin-main/modules/annotator/openpose/hand.py
import cv2 import json import numpy as np import math import time from scipy.ndimage.filters import gaussian_filter import matplotlib.pyplot as plt import matplotlib import torch from skimage.measure import label from .model import handpose_model from . import util class Hand(object): def __init__(self, model_pa...
3,588
32.542056
85
py
dolphin
dolphin-main/modules/annotator/openpose/model.py
import torch from collections import OrderedDict import torch import torch.nn as nn def make_layers(block, no_relu_layers): layers = [] for layer_name, v in block.items(): if "pool" in layer_name: layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1], padding=v[2]) layers.append(...
8,853
34.416
87
py
dolphin
dolphin-main/modules/annotator/openpose/util.py
import math import numpy as np import matplotlib import cv2 def padRightDownCorner(img, stride, padValue): h = img.shape[0] w = img.shape[1] pad = 4 * [None] pad[0] = 0 # up pad[1] = 0 # left pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down pad[3] = 0 if (w % stride ==...
8,372
32.626506
121
py
dolphin
dolphin-main/modules/annotator/openpose/__init__.py
import os os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" import torch import numpy as np from . import util from .body import Body from .hand import Hand from ..util import annotator_ckpts_path body_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/body_pose_model.pth" hand_model_...
2,170
40.75
113
py
dolphin
dolphin-main/modules/annotator/openpose/body.py
import cv2 import numpy as np import math from scipy.ndimage.filters import gaussian_filter import torch from torchvision import transforms from . import util from .model import bodypose_model class Body(object): def __init__(self, model_path, device=None): self.device = device or torch.device( ...
13,127
38.18806
123
py
dolphin
dolphin-main/modules/mplug/get_video_caption.py
import ruamel.yaml as yaml import numpy as np import torch import torch.nn as nn from .models.model_caption_mplug_vatex import MPLUG from .models.vit import interpolate_pos_embed, resize_pos_embed from .models.tokenization_bert import BertTokenizer from decord import VideoReader import decord import os config_path = ...
3,736
31.495652
162
py
dolphin
dolphin-main/modules/mplug/models/model_caption_mplug_vatex.py
from functools import partial from .vit import VisionTransformer from .modeling_mplug import BertConfig, BertModel, BertPrefixModel, FusionModel from .visual_transformers import initialize_clip from .predictor import TextGenerator import torch from torch import nn import torch.nn.functional as F import numpy as np ...
9,712
35.242537
135
py
dolphin
dolphin-main/modules/mplug/models/predictor.py
#!/usr/bin/env python """ Translator Class and builder """ from __future__ import print_function import torch.nn as nn import torch.nn.functional as F import os import math import json import torch def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0, device='cuda:0'...
21,697
40.726923
149
py
dolphin
dolphin-main/modules/mplug/models/vit.py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import math import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.vision_transformer import _cfg, PatchEmbed from timm.models.registry import register_model from timm.models.layers import tru...
9,634
41.822222
132
py
dolphin
dolphin-main/modules/mplug/models/visual_transformers.py
import copy import json import logging import math import os import shutil import tarfile import tempfile import sys from io import open import torch.nn.functional as F import torch from torch import nn from torch.nn import CrossEntropyLoss, SmoothL1Loss import numpy as np from .clip import clip def resize_pos_embed...
3,991
35.290909
132
py
dolphin
dolphin-main/modules/mplug/models/modeling_mplug.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
112,740
43.526461
213
py
dolphin
dolphin-main/modules/mplug/models/clip/clip.py
import hashlib import os import urllib import warnings from typing import Union, List import torch from PIL import Image from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize from tqdm import tqdm from .model import build_model from .simple_tokenizer import SimpleTokenizer as _Tokenizer ...
6,098
37.601266
142
py
dolphin
dolphin-main/modules/mplug/models/clip/model.py
from collections import OrderedDict from typing import Tuple, Union import torch import torch.nn.functional as F from torch import nn class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1): super().__init__() # all conv layers have stride 1. an avgpool is ...
18,310
39.511062
178
py
jericho
jericho-master/jericho/game_info.py
# Copyright (C) 2018 Microsoft Corporation # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # This program is distribut...
417,373
752.382671
16,184
py
BBA_measures_classification
BBA_measures_classification-main/grad_opt.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: olympio """ import matplotlib.pyplot as plt import numpy as np import data_gen as dg from aux_functions import * import train_classifier as tc from numpy.random import default_rng rng = default_rng() import tensorflow as tf N1=500 #Number of points in class ...
3,182
32.505263
113
py
scicite
scicite-master/scicite/training/multitask_trainer_two_tasks.py
""" This module is an extended trainer based on the allennlp's default trainer to handle multitask training for two auxiliary tasks A :class:`~allennlp.training.trainer.Trainer` is responsible for training a :class:`~allennlp.models.model.Model`. Typically you might create a configuration file specifying the mode...
58,023
48.977606
119
py
scicite
scicite-master/scicite/training/train_multitask_two_tasks.py
""" The `train_multitask` subcommand that can be used to train the model in the multitask fashion It requires a configuration file and a directory in which to write the results. .. code-block:: bash $ allennlp train --help usage: allennlp train [-h] -s SERIALIZATION_DIR [-r] [-o OVERRIDES] ...
23,845
46.692
143
py
scicite
scicite-master/scicite/training/multitask_trainer.py
""" This module is an extended trainer based on the allennlp's default trainer to handle multitask training A :class:`~allennlp.training.trainer.Trainer` is responsible for training a :class:`~allennlp.models.model.Model`. Typically you might create a configuration file specifying the model and training parameters an...
55,632
48.407638
114
py
scicite
scicite-master/scicite/training/train_multitask.py
""" The ``train`` subcommand can be used to train a model. It requires a configuration file and a directory in which to write the results. .. code-block:: bash $ allennlp train --help usage: allennlp train [-h] -s SERIALIZATION_DIR [-r] [-o OVERRIDES] [--file-friendly-logging] ...
20,414
45.083521
113
py
scicite
scicite-master/scicite/models/scaffold_bilstm_attention_classifier.py
import operator from copy import deepcopy from distutils.version import StrictVersion from typing import Dict, Optional import allennlp import numpy as np import torch import torch.nn.functional as F from allennlp.common import Params from allennlp.data import Instance from allennlp.data import Vocabulary from allennl...
15,619
47.8125
125
py
scicite
scicite-master/scicite/dataset_readers/citation_data_reader_aclarc.py
""" Data reader for AllenNLP """ from typing import Dict, List import json import jsonlines import logging import torch from allennlp.data import Field from overrides import overrides from allennlp.common import Params from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_read...
6,739
44.234899
109
py
scicite
scicite-master/scicite/dataset_readers/citation_data_reader_scicite.py
""" Data reader for AllenNLP """ from typing import Dict, List import json import logging import torch from allennlp.data import Field from overrides import overrides from allennlp.common import Params from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import Dataset...
7,766
45.232143
109
py
sharpDARTS
sharpDARTS-master/cnn/warmup_scheduler.py
# https://github.com/ildoonet/pytorch-gradual-warmup-lr # License: MIT from torch.optim.lr_scheduler import _LRScheduler class GradualWarmupScheduler(_LRScheduler): """ Gradually warm-up(increasing) learning rate in optimizer. Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'. Args...
1,749
41.682927
122
py
sharpDARTS
sharpDARTS-master/cnn/costar_baseline_model.py
import math import torch import torch.nn as nn from torch.nn import functional as F # from . import operations # from . import genotypes # from .operations import ReLUConvBN # from .operations import ConvBNReLU # from .operations import FactorizedReduce # from .operations import Identity from torch.autograd import Vari...
7,916
35.652778
146
py
sharpDARTS
sharpDARTS-master/cnn/test.py
import os import sys import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import NetworkCIFAR as Network ...
3,599
33.285714
102
py
sharpDARTS
sharpDARTS-master/cnn/train_costar.py
# source: https://github.com/NVIDIA/apex/tree/master/examples/imagenet # license: BSD 3-Clause # # to install apex: # pip3 install --user --upgrade -e . --global-option="build_ext" --global-option="--cpp_ext" --global-option="--cuda_ext" # # ### Multi-process training with FP16_Optimizer, dynamic loss scaling # $ p...
37,252
47.192755
315
py
sharpDARTS
sharpDARTS-master/cnn/main_fp16_optimizer.py
# source: https://github.com/NVIDIA/apex/tree/master/examples/imagenet # license: BSD 3-Clause # # to install apex: # pip3 install --user --upgrade -e . --global-option="build_ext" --global-option="--cpp_ext" --global-option="--cuda_ext" # # ### Multi-process training with FP16_Optimizer, dynamic loss scaling # $ p...
34,031
42.352866
365
py
sharpDARTS
sharpDARTS-master/cnn/cifar10_1.py
# Source: https://github.com/kharvd/cifar-10.1-pytorch # License: MIT import io import os import os.path import pickle import numpy as np from PIL import Image import torch.utils.data as data from torchvision.datasets.utils import download_url, check_integrity def load_new_test_data(root, version='default'): d...
4,555
31.542857
105
py
sharpDARTS
sharpDARTS-master/cnn/architect.py
import torch import numpy as np import torch.nn as nn from torch.autograd import Variable def _concat(xs): return torch.cat([x.view(-1) for x in xs]) class Architect(object): def __init__(self, model, args): self.network_momentum = args.momentum self.network_weight_decay = args.weight_decay self.mo...
3,429
35.88172
130
py
sharpDARTS
sharpDARTS-master/cnn/train_imagenet.py
import os import sys import numpy as np import time import torch import utils import glob import random import logging import argparse import json import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torchvision.transforms as transforms import torch.backends.cudnn as cudn...
8,489
38.859155
170
py
sharpDARTS
sharpDARTS-master/cnn/visualize_whole_network.py
# Example commands to run: # # python3 visualize_whole_network.py --multi_channel # # python3 visualize_whole_network.py --dataset imagenet --arch SHARP_DARTS --auxiliary # # Set matplotlib backend to Agg # *MUST* be done BEFORE importing hiddenlayer or libs that import matplotlib import matplotlib matplotlib.use...
6,350
38.447205
141
py
sharpDARTS
sharpDARTS-master/cnn/utils.py
# Some data loading code is from https://github.com/DRealArun/darts/ with the same license as darts. import os import time import numpy as np import logging import torch import shutil import argparse import glob import json import csv import torchvision.transforms as transforms from torch.autograd import Variable impor...
21,363
32.225505
151
py
sharpDARTS
sharpDARTS-master/cnn/model.py
import math import torch import torch.nn as nn from torch.nn import functional as F import numpy as np from genotypes import PRIMITIVES, MULTICHANNELNET_PRIMITIVES from operations import * import operations # from . import operations # from . import genotypes # from .operations import ReLUConvBN # from .operations impo...
34,793
39.552448
220
py
sharpDARTS
sharpDARTS-master/cnn/dataset.py
# Code to load various datasets for training. # # Some data loading code is from https://github.com/DRealArun/darts/ with the same license as DARTS. import os import sys import time import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import genotypes import torc...
14,281
46.926174
164
py
sharpDARTS
sharpDARTS-master/cnn/model_search.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from operations import * import operations from torch.autograd import Variable from genotypes import PRIMITIVES, MULTICHANNELNET_PRIMITIVES from genotypes import Genotype import networkx as nx from networkx.readwrite import json_graph...
27,726
42.188474
218
py
sharpDARTS
sharpDARTS-master/cnn/train_search.py
import os import sys import time import glob import numpy as np import torch import utils import logging import argparse import copy import torch.nn as nn import torch.utils import torch.nn.functional as F import torchvision.datasets as dset import torch.backends.cudnn as cudnn import networkx as nx from torch.autogra...
18,217
43.434146
161
py
sharpDARTS
sharpDARTS-master/cnn/flops_counter.py
# source: https://github.com/sovrasov/flops-counter.pytorch # license: MIT import torch.nn as nn import torch import numpy as np def flops_to_string(flops): if flops // 10**9 > 0: return str(round(flops / 10.**9, 2)) + 'GMac' elif flops // 10**6 > 0: return str(round(flops / 10.**6, 2)) + 'MMac...
8,348
30.988506
100
py
sharpDARTS
sharpDARTS-master/cnn/test_imagenet.py
import os import sys import numpy as np import torch import utils import glob import random import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torchvision.transforms as transforms import torch.backends.cudnn as cudnn from torch.autograd i...
3,791
32.557522
104
py
sharpDARTS
sharpDARTS-master/cnn/train.py
import os import sys import time import glob import json import copy import numpy as np import torch import utils import logging import argparse import torch.nn as nn import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import Networ...
17,359
47.627451
172
py