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 |
|---|---|---|---|---|---|---|
DG-Font | DG-Font-main/train/train.py | from tqdm import trange
import torch.nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from tools.utils import *
from tools.ops import compute_grad_gp, update_average, copy_norm_params, queue_data, dequeue_data, \
average_gradients, calc_adv_loss, calc_contra... | 5,671 | 30.511111 | 158 | py |
DG-Font | DG-Font-main/validation/validation.py | import torch.nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.utils as vutils
import torch.nn.functional as F
import numpy as np
try:
from tqdm import tqdm
except ImportError:
# If not tqdm is not available, provide a mock version of... | 4,643 | 46.387755 | 161 | py |
FPConv | FPConv-master/tools/test_scannet.py | import torch
from torch.utils.data import DataLoader
import numpy as np
import argparse
import importlib
import os
import sys
import json
from utils.switchnorm import convert_sn
from datasets.scannet_dataset_rgb_test import ScannetDatasetWholeScene_evaluation
np.seterr(divide='ignore', invalid='ignore')
parser = arg... | 7,024 | 36.367021 | 139 | py |
FPConv | FPConv-master/tools/test_s3dis.py | import os, sys
import json
import numpy as np
import argparse
import importlib
import torch
from torch.utils.data import DataLoader
from datasets.s3dis_dataset_test import S3DISWholeScene_evaluation
np.seterr(divide='ignore', invalid='ignore')
parser = argparse.ArgumentParser(description="Arg parser")
parser.add_arg... | 5,981 | 35.036145 | 87 | py |
FPConv | FPConv-master/tools/train_scannet.py | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.distributed as dist
import os, sys
import argparse
import importlib
import numpy as np
import json
import tensorboard_logger as tb_log
from datasets.scannet_dataset_rgb import ScannetDataset, ScannetDatasetWholeScene
from utils.sa... | 11,795 | 37.423453 | 137 | py |
FPConv | FPConv-master/tools/train_s3dis.py | import os, sys
import argparse
import importlib
import numpy as np
import json
import time
import tensorboard_logger as tb_log
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from datasets.s3dis_dataset import S3DIS
from utils.saver import Saver
np.seterr(divide='ignore', invalid='ignore')... | 12,945 | 35.162011 | 125 | py |
FPConv | FPConv-master/models/fpcnn_scannet.py | import torch
import torch.nn as nn
from fpconv.pointnet2.pointnet2_modules import PointnetFPModule
import fpconv.pointnet2.pytorch_utils as pt_utils
from fpconv.base import AssemRes_BaseBlock
from fpconv.fpconv import FPConv4x4_BaseBlock, FPConv6x6_BaseBlock
NPOINT = 8192
NPOINTS = [NPOINT // 2, NPOINT // 8, NPOINT ... | 4,571 | 37.1 | 94 | py |
FPConv | FPConv-master/models/fpcnn_s3dis.py | import torch
import torch.nn as nn
from fpconv.pointnet2.pointnet2_modules import PointnetFPModule, PointnetSAModule
import fpconv.pointnet2.pytorch_utils as pt_utils
from fpconv.base import AssemRes_BaseBlock
from fpconv.fpconv import FPConv4x4_BaseBlock, FPConv6x6_BaseBlock
NPOINTS = [8192, 2048, 512, 128]
RADIUS =... | 4,378 | 37.412281 | 94 | py |
FPConv | FPConv-master/fpconv/base.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from fpconv.pointnet2 import pointnet2_utils
from fpconv.pointnet2 import pytorch_utils as pt_utils
relu_alpha = 0.2
class PointNet(nn.Module):
def __init__(self, mlp, pool='max', bn=True):
super()... | 8,204 | 40.649746 | 125 | py |
FPConv | FPConv-master/fpconv/fpconv.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from fpconv.pointnet2 import pointnet2_utils
from fpconv.pointnet2 import pytorch_utils as pt_utils
from fpconv import base
relu_alpha = 0.2
class FPConv4x4_BaseBlock(nn.Module):
def __init__(self, npoint,... | 8,087 | 41.793651 | 133 | py |
FPConv | FPConv-master/fpconv/pointnet2/setup.py | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='pointnet2',
ext_modules=[
CUDAExtension('pointnet2_cuda', [
'src/pointnet2_api.cpp',
'src/ball_query.cpp',
'src/ball_query_gpu.cu',
... | 679 | 27.333333 | 67 | py |
FPConv | FPConv-master/fpconv/pointnet2/pointnet2_utils.py | import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn as nn
from typing import Tuple
import pointnet2_cuda as pointnet2
class FurthestPointSampling(Function):
@staticmethod
def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:
"""
Use... | 12,424 | 33.803922 | 118 | py |
FPConv | FPConv-master/fpconv/pointnet2/pointnet2_modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from . import pointnet2_utils
from . import pytorch_utils as pt_utils
from typing import List
class _PointnetSAModuleBase(nn.Module):
def __init__(self):
super().__init__()
self.npoint = None
self.groupers = None
... | 6,338 | 38.61875 | 119 | py |
FPConv | FPConv-master/fpconv/pointnet2/pytorch_utils.py | import torch.nn as nn
from typing import List, Tuple
class SharedMLP(nn.Sequential):
def __init__(
self,
args: List[int],
*,
bn: bool = False,
activation=nn.ReLU(inplace=True),
preact: bool = False,
first: bool = False,
... | 7,312 | 25.305755 | 95 | py |
FPConv | FPConv-master/datasets/s3dis_dataset.py | import os
import numpy as np
import sys
from torch.utils.data import Dataset
class S3DIS(Dataset):
def __init__(self, split='train', data_root='trainval_fullarea', num_point=4096, test_area=5, block_size=1.0, sample_rate=1.0, transform=None, if_normal=True):
super().__init__()
print('Initiating Da... | 7,008 | 42.265432 | 163 | py |
FPConv | FPConv-master/datasets/scannet_dataset_rgb_test.py | import pickle
import os
import sys
import numpy as np
import torch.utils.data as torch_data
class ScannetDatasetWholeScene_evaluation(torch_data.IterableDataset):
#prepare to give prediction on each points
def __init__(self, root=None, scene_list_dir=None, split='test', num_class=21, block_points=10240, with_n... | 8,118 | 42.417112 | 134 | py |
FPConv | FPConv-master/datasets/s3dis_dataset_test.py | import pickle
import os
import sys
import numpy as np
import torch.utils.data as torch_data
class S3DISWholeScene_evaluation(torch_data.IterableDataset):
# prepare to give prediction on each points
def __init__(self, root=None, split='test', test_area=5, num_class=13, block_points=8192, block_size=1.5, stride... | 8,454 | 38.143519 | 137 | py |
FPConv | FPConv-master/datasets/scannet_dataset_rgb.py | import pickle
import os
import sys
import numpy as np
import torch.utils.data as torch_data
class ScannetDataset(torch_data.Dataset):
def __init__(self, root=None, npoints=10240, split='train', with_dropout=False, with_norm=False, with_rgb=False, sample_rate=None):
super().__init__()
print(' ---- l... | 9,696 | 43.278539 | 135 | py |
FPConv | FPConv-master/utils/saver.py | import os
import torch
class Saver():
def __init__(self, save_dir, max_files=10):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
self.log_list = []
self.save_dir = save_dir
self.max_files = max_files
self.saver_log_path = os.path.join(save_dir, '... | 1,784 | 34.7 | 116 | py |
FPConv | FPConv-master/utils/switchnorm.py | import torch
import torch.nn as nn
def convert_sn(module, momentum=0.95):
module_output = module
if isinstance(module, torch.nn.BatchNorm3d):
module_output = SwitchNorm3d(module.num_features)
elif isinstance(module, torch.nn.BatchNorm2d):
module_output = SwitchNorm2d(module.num_features)
... | 10,468 | 38.958015 | 104 | py |
MPMQA | MPMQA-master/evaluate.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 21,617 | 42.761134 | 229 | py |
MPMQA | MPMQA-master/utils.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 8,686 | 35.965957 | 114 | py |
MPMQA | MPMQA-master/train.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 9,408 | 45.122549 | 192 | py |
MPMQA | MPMQA-master/detector/setup.py | #!/usr/bin/env python
import glob
import os
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension
torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
assert torch_ver >= [1, 3], "Requires PyTorch >= 1.3"
def get_extensions()... | 1,911 | 27.537313 | 100 | py |
MPMQA | MPMQA-master/detector/train_det.py | import logging
import os
from collections import OrderedDict
import torch
from torch.nn.parallel import DistributedDataParallel
import detectron2.utils.comm as comm
import bua.d2.modeling.roi_heads
from bua import add_config
from detectron2.checkpoint import DetectionCheckpointer, PeriodicCheckpointer
from detectron2.... | 7,622 | 35.3 | 99 | py |
MPMQA | MPMQA-master/detector/ROIFeatExtractor.py | import numpy as np
import cv2
import torch
import torch.nn as nn
from detectron2.config import get_cfg
from detectron2.modeling import build_model
from detectron2.structures import ImageList, Boxes
from detectron2.checkpoint import DetectionCheckpointer
import sys
sys.path.append('detector')
from bua.d2 import add_attr... | 4,030 | 37.390476 | 112 | py |
MPMQA | MPMQA-master/detector/evaluation/vg_evaluation.py | import os, io
import numpy as np
import copy
import torch
import logging
import pickle as cPickle
import itertools
import contextlib
from pycocotools.coco import COCO
from collections import OrderedDict
from fvcore.common.file_io import PathManager
import detectron2.utils.comm as comm
from detectron2.data import Meta... | 12,145 | 41.767606 | 101 | py |
MPMQA | MPMQA-master/detector/bua/__init__.py | from .d2 import add_attribute_config
from .caffe import add_bottom_up_attention_config
def add_config(args, cfg):
if args.mode == "caffe":
add_bottom_up_attention_config(cfg, True)
elif args.mode == "d2":
add_attribute_config(cfg)
else:
raise Exception("detection model not supported... | 373 | 33 | 79 | py |
MPMQA | MPMQA-master/detector/bua/d2/modeling/roi_heads.py |
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec
from detectron2.modeling.roi_heads import (
build_box_head,
build_mask_head,
select_foreground_proposals,
ROI_HEADS_REGISTRY,
ROI_BOX_HEAD_REGISTRY,
ROIHeads,
Res5ROIHeads,
St... | 14,740 | 41.359195 | 198 | py |
MPMQA | MPMQA-master/detector/bua/d2/dataloader/build_loader.py |
import logging
import operator
import torch.utils.data
from detectron2.utils.comm import get_world_size
from detectron2.data import samplers
from detectron2.data.build import get_detection_dataset_dicts, worker_init_reset_seed, trivial_batch_collator
from detectron2.data.common import AspectRatioGroupedDataset, Datas... | 3,864 | 34.458716 | 109 | py |
MPMQA | MPMQA-master/detector/bua/d2/dataloader/dataset_mapper.py |
import copy
import logging
import numpy as np
import torch
from fvcore.common.file_io import PathManager
from PIL import Image
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
from detectron2.data import DatasetMapper
from detectron2.structures import (
BitMasks,
... | 7,189 | 38.505495 | 100 | py |
MPMQA | MPMQA-master/detector/bua/caffe/config.py | # -*- coding: utf-8 -*-
from detectron2.config import CfgNode as CN
def add_bottom_up_attention_config(cfg, caffe=False):
"""
Add config for tridentnet.
"""
_C = cfg
_C.MODEL.BUA = CN()
_C.MODEL.BUA.CAFFE = caffe
_C.MODEL.BUA.RESNET_VERSION = 1
_C.MODEL.BUA.ATTRIBUTE_ON = False
... | 969 | 25.944444 | 104 | py |
MPMQA | MPMQA-master/detector/bua/caffe/postprocessing.py |
import numpy as np
import torch
from detectron2.structures import Instances
from modeling.layers.nms import nms # BC-compat
def extractor_postprocess(boxes, scores, features_pooled, input_per_image, extractor):
"""
Resize the output instances.
The input images are often resized when entering an object ... | 2,055 | 36.381818 | 87 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/box_regression.py |
import math
import torch
from detectron2.structures import Boxes
from typing import List, Tuple, Union
# Value for clamping large dw and dh predictions. The heuristic is that we clamp
# such that dw and dh are no larger than what would transform a 16px box into a
# 1000px box (based on a small anchor, 16px, and a typ... | 7,861 | 40.378947 | 99 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/fast_rcnn.py |
import logging
import numpy as np
import torch
from fvcore.nn import smooth_l1_loss
from torch import nn
from torch.nn import functional as F
from detectron2.layers import cat
from detectron2.structures import Instances
from detectron2.utils.events import get_event_storage
from detectron2.modeling.roi_heads import se... | 34,315 | 44.754667 | 184 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/rpn_outputs.py |
import itertools
import logging
import numpy as np
import torch
import torch.nn.functional as F
from fvcore.nn import smooth_l1_loss
from detectron2.layers import cat
from detectron2.structures import Instances, pairwise_iou
from detectron2.utils.events import get_event_storage
from detectron2.modeling.sampling impo... | 18,425 | 44.722084 | 147 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/rcnn.py |
import logging, os
import torch
from torch import nn
import torch.nn.functional as F
from detectron2.structures import ImageList
from detectron2.utils.logger import log_first_n
from detectron2.modeling.backbone import build_backbone
from detectron2.modeling.postprocessing import detector_postprocess
from detectron2... | 6,893 | 39.552941 | 98 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/rpn.py |
from typing import Dict, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from detectron2.modeling import RPN_HEAD_REGISTRY
from detectron2.layers import ShapeSpec
from detectron2.modeling.proposal_generator import build_rpn_head
from detectron2.modeling.proposal_generator.build import PROPOS... | 7,700 | 42.022346 | 103 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/fast_rcnn_outputs.py | import torch
import torch.functional as F
from detectron2.layers import ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple
from fvcore.nn import giou_loss, smooth_l1_loss
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.structures import Boxes
class FastRCNNOutputs:
"""
An... | 7,315 | 44.440994 | 100 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/roi_heads.py | # -*- coding: utf-8 -*-
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from detectron2.utils.events import get_event_storage
from detectron2.modeling import ROI_HEADS_REGISTRY, ROIHeads
from detectron2.structures import Boxes, Instances, pairwise_iou
from detectron2.modelin... | 21,094 | 43.882979 | 196 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/backbone.py |
import fvcore.nn.weight_init as weight_init
from torch import nn
import torch.nn.functional as F
from detectron2.layers import Conv2d, FrozenBatchNorm2d, get_norm, BatchNorm2d
from detectron2.modeling import BACKBONE_REGISTRY, ResNet, make_stage
from detectron2.modeling.backbone.resnet import BottleneckBlock, DeformB... | 9,404 | 33.076087 | 116 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/layers/nms.py |
# from ._utils import _C
from bua.caffe.modeling import _C
from apex import amp
import torch
# Only valid with fp32 inputs - give AMP the hint
nms = amp.float_function(_C.nms)
# nms.__doc__ = """
# This function performs Non-maximum suppresion"""
# NOTE: In order to be consistent with bottom-up-attention, we nms c... | 2,551 | 32.578947 | 104 | py |
MPMQA | MPMQA-master/detector/bua/caffe/modeling/layers/wrappers.py | import math
import torch
from torch.nn.modules.utils import _ntuple
class Conv2dv2(torch.nn.Conv2d):
"""
A wrapper around :class:`torch.nn.Conv2d` to support more features.
"""
def __init__(self, *args, **kwargs):
"""
Extra keyword arguments supported in addition to those in `torch.nn.... | 1,228 | 31.342105 | 84 | py |
MPMQA | MPMQA-master/detector/bua/caffe/dataloader/dataset_mapper.py |
import copy
import logging
import numpy as np
import torch
import cv2
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
from .transform_gen import ResizeShortestEdge
from .detection_utils import annotations_to_instances
"""
This file contains the default mapping that'... | 6,394 | 37.757576 | 97 | py |
MPMQA | MPMQA-master/detector/bua/caffe/dataloader/detection_utils.py | # -*- coding: utf-8 -*-
"""
Common data processing utilities that are used in a
typical object detection data pipeline.
"""
import torch
from detectron2.structures import (
Boxes,
BoxMode,
Instances,
)
def transform_instance_annotations(
annotation, transforms, image_size, *, keypoint_hflip_indices=... | 2,923 | 33.4 | 95 | py |
MPMQA | MPMQA-master/dataset/mqa_page_contrast.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 5,535 | 41.259542 | 135 | py |
MPMQA | MPMQA-master/dataset/utils.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 2,864 | 30.483516 | 86 | py |
MPMQA | MPMQA-master/dataset/mqa_dataset.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 11,026 | 42.413386 | 139 | py |
MPMQA | MPMQA-master/models/utils.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 4,078 | 32.434426 | 102 | py |
MPMQA | MPMQA-master/models/mqa_model.py | # Copyright(c) 2022 Liang Zhang
# E-Mail: <zhangliang00@ruc.edu.cn>
# 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 copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | 28,473 | 50.397112 | 159 | py |
chatgpt-refusals | chatgpt-refusals-main/bert_results.py | import os
import torch
from transformers import BertTokenizerFast, BertForSequenceClassification, Trainer, TrainingArguments
import data_processing
class TextDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem... | 2,872 | 35.367089 | 101 | py |
21cmVAE | 21cmVAE-main/VeryAccurateEmulator/emulator.py | import h5py
import tensorflow as tf
from tqdm.keras import TqdmCallback
import numpy as np
from VeryAccurateEmulator import __path__
import VeryAccurateEmulator.preprocess as pp
PATH = __path__[0] + "/"
def _gen_model(in_dim, hidden_dims, out_dim, activation_func, name=None):
"""
Generate a new keras model.... | 26,244 | 30.132859 | 79 | py |
21cmVAE | 21cmVAE-main/tests/test_emulator.py | import h5py
import numpy as np
import tensorflow as tf
from VeryAccurateEmulator import emulator, __path__
import VeryAccurateEmulator.preprocess as pp
FILE = __path__[0] + "/dataset_21cmVAE.h5"
with h5py.File(FILE, "r") as hf:
signal_train = hf["signal_train"][:]
def test_gen_model():
in_dim = 7
hidden_... | 3,644 | 30.973684 | 79 | py |
StyleMask | StyleMask-master/run_inference.py | import os
import datetime
import random
import sys
import argparse
from argparse import Namespace
import torch
from torch import nn
import numpy as np
import warnings
from tqdm import tqdm
warnings.filterwarnings("ignore")
sys.dont_write_bytecode = True
seed = 0
random.seed(seed)
import face_alignment
from libs.model... | 12,669 | 39.479233 | 162 | py |
StyleMask | StyleMask-master/extract_statistics.py | """
Script to extract the npy file with the min, max values of facial pose parameters (yaw, pitch, roll, jaw and expressions)
1. Generate a set of random synthetic images
2. Use DECA model to extract the facial shape and the corresponding parameters
3. Calculate min, max values
"""
import os
import glob
import numpy ... | 3,152 | 26.181034 | 134 | py |
StyleMask | StyleMask-master/libs/trainer.py | """
"""
import os
import json
import torch
import time
import numpy as np
import pdb
import cv2
import wandb
from torch import autograd
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from libs.utilities.utils import *
from libs.utilities.image_utils import *
from libs.DECA.estimate... | 20,832 | 40.5 | 192 | py |
StyleMask | StyleMask-master/libs/models/mask_predictor.py | import torch
from torch import nn
class MaskPredictor(nn.Module):
def __init__(self, input_dim, output_dim, inner_dim=1024):
super(MaskPredictor, self).__init__()
self.masknet = nn.Sequential(nn.Linear(input_dim, inner_dim, bias=True),
nn.ReLU(),
nn.Linear(inner_dim, output_dim, bias=True),... | 628 | 21.464286 | 74 | py |
StyleMask | StyleMask-master/libs/models/inversion/psp.py | """
This file defines the core research contribution
"""
import math
import matplotlib
matplotlib.use('Agg')
import torch
from torch import nn
import torchvision.transforms as transforms
import os
from libs.models.inversion import psp_encoders
def get_keys(d, name):
if 'state_dict' in d:
d = d['state_dict']
d_f... | 1,643 | 28.357143 | 149 | py |
StyleMask | StyleMask-master/libs/models/inversion/psp_encoders.py | from enum import Enum
import math
import numpy as np
import torch
from torch import nn
from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
from libs.models.inversion.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE, _upsample_add
from libs.models.StyleGAN2.model import EqualLinear, ScaledLeak... | 12,262 | 37.806962 | 115 | py |
StyleMask | StyleMask-master/libs/models/inversion/helpers.py | from collections import namedtuple
import torch
from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module, Linear
import torch.nn.functional as F
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Flatten(Module):... | 5,916 | 30.473404 | 120 | py |
StyleMask | StyleMask-master/libs/models/StyleGAN2/model.py | import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from .op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d
class PixelNorm(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return input * torch.rsqrt(torch.mean(inp... | 19,525 | 26.501408 | 116 | py |
StyleMask | StyleMask-master/libs/models/StyleGAN2/convert_weight.py | import argparse
import os
import sys
import pickle
import math
import torch
import numpy as np
from torchvision import utils
from models.StyleGAN2.model import Generator, Discriminator
def convert_modconv(vars, source_name, target_name, flip=False):
weight = vars[source_name + '/weight'].value().eval()
mod_... | 7,718 | 29.152344 | 131 | py |
StyleMask | StyleMask-master/libs/models/StyleGAN2/op/upfirdn2d.py | import os
import torch
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
upfirdn2d_op = load(
'upfirdn2d',
sources=[
os.path.join(module_path, 'upfirdn2d.cpp'),
os.path.join(module_path, 'upfirdn2d_kernel.cu'),
],
)
cl... | 5,186 | 26.590426 | 108 | py |
StyleMask | StyleMask-master/libs/models/StyleGAN2/op/fused_act.py | import os
import torch
from torch import nn
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
fused = load(
'fused',
sources=[
os.path.join(module_path, 'fused_bias_act.cpp'),
os.path.join(module_path, 'fused_bias_act_kernel... | 2,379 | 26.356322 | 83 | py |
StyleMask | StyleMask-master/libs/utilities/image_utils.py | import torch
import numpy as np
import cv2
import torchvision
import os
" Read image from path"
def read_image_opencv(image_path):
img = cv2.imread(image_path, cv2.IMREAD_COLOR) # BGR order!!!!
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img.astype('uint8')
" image numpy array to tensor [-1,1] range "
def... | 1,548 | 25.706897 | 77 | py |
StyleMask | StyleMask-master/libs/utilities/stylespace_utils.py | import torch
import numpy as np
from torch.nn import functional as F
import os
import math
def conv_warper(layer, input, style, noise):
# the conv should change
conv = layer.conv
batch, in_channel, height, width = input.shape
style = style.view(batch, 1, in_channel, 1, 1)
weight = conv.scale * conv.weight * s... | 3,714 | 27.576923 | 90 | py |
StyleMask | StyleMask-master/libs/utilities/dataloader.py | """
"""
import torch
import os
import glob
import cv2
import numpy as np
from torchvision import transforms, utils
from PIL import Image
from torch.utils.data import Dataset
from libs.utilities.utils import make_noise
np.random.seed(0)
class CustomDataset_validation(Dataset):
def __init__(self, synthetic_dataset_p... | 2,169 | 29.138889 | 92 | py |
StyleMask | StyleMask-master/libs/utilities/utils.py | import os
import numpy as np
import torch
from torchvision import utils as torch_utils
import glob
from datetime import datetime
import json
from libs.utilities.stylespace_utils import encoder, decoder
def make_path(filepath):
if not os.path.exists(filepath):
os.makedirs(filepath, exist_ok = True)
def save_argume... | 3,116 | 32.880435 | 158 | py |
StyleMask | StyleMask-master/libs/utilities/utils_inference.py | import os
import numpy as np
import torch
from torchvision import utils as torch_utils
import cv2
from skimage import io
from libs.utilities.image_utils import read_image_opencv, torch_image_resize
from libs.utilities.ffhq_cropping import align_crop_image
def calculate_evaluation_metrics(params_shifted, params_target... | 4,100 | 36.281818 | 144 | py |
StyleMask | StyleMask-master/libs/criteria/losses.py | import torch
import numpy as np
"""
Calculate shape losses
"""
class Losses():
def __init__(self):
self.criterion_mse = torch.nn.MSELoss()
self.criterion_l1 = torch.nn.L1Loss()
self.image_deca_size = 224
def calculate_pixel_wise_loss(self, images_shifted, images):
pixel_wise_loss = self.criterion_l1(im... | 2,137 | 32.40625 | 116 | py |
StyleMask | StyleMask-master/libs/criteria/model_irse.py | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module
from .helpers import get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm
"""
Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Backbone(Module):
def __i... | 2,821 | 32.2 | 97 | py |
StyleMask | StyleMask-master/libs/criteria/l2_loss.py | import torch
l2_criterion = torch.nn.MSELoss(reduction='mean')
def l2_loss(real_images, generated_images):
loss = l2_criterion(real_images, generated_images)
return loss
| 181 | 19.222222 | 54 | py |
StyleMask | StyleMask-master/libs/criteria/helpers.py | from collections import namedtuple
import torch
from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Flatten(Module):
def forward(self, input):
return inp... | 3,556 | 28.641667 | 112 | py |
StyleMask | StyleMask-master/libs/criteria/id_loss.py | import torch
from torch import nn
from .model_irse import Backbone
import os
import torch.backends.cudnn as cudnn
class IDLoss(nn.Module):
def __init__(self, pretrained_model_path = './pretrained_models/model_ir_se50.pth'):
super(IDLoss, self).__init__()
print('Loading ResNet ArcFace for identity l... | 1,349 | 37.571429 | 92 | py |
StyleMask | StyleMask-master/libs/criteria/lpips/lpips.py | import torch
import torch.nn as nn
from .networks import get_network, LinLayers
from .utils import get_state_dict
class LPIPS(nn.Module):
r"""Creates a criterion that measures https://github.com/eladrich/pixel2style2pixel
Learned Perceptual Image Patch Similarity (LPIPS).
Arguments:
net_type (str... | 1,220 | 33.885714 | 87 | py |
StyleMask | StyleMask-master/libs/criteria/lpips/utils.py | from collections import OrderedDict
import torch
def normalize_activation(x, eps=1e-10):
# print(torch.sum(x ** 2, dim=1, keepdim=True))
# if torch.isnan(x).any():
# # print(gradients_keep)
# pdb.set_trace()
norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True)+1e-9)
return ... | 1,033 | 28.542857 | 79 | py |
StyleMask | StyleMask-master/libs/criteria/lpips/networks.py | from typing import Sequence
from itertools import chain
import torch
import torch.nn as nn
from torchvision import models
from .utils import normalize_activation
def get_network(net_type: str):
if net_type == 'alex':
return AlexNet()
elif net_type == 'squeeze':
return SqueezeNet()
elif ... | 2,653 | 26.645833 | 79 | py |
StyleMask | StyleMask-master/libs/DECA/estimate_DECA.py | """
"""
import torch
import numpy as np
import cv2
import os
from .decalib.deca import DECA
from .decalib.datasets import datasets
from .decalib.utils import util
from .decalib.utils.config import cfg as deca_cfg
from .decalib.utils.rotation_converter import *
class DECA_model():
def __init__(self, device):
... | 2,153 | 36.137931 | 94 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/deca.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 15,374 | 46.307692 | 189 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/models/resnet.py | """
Author: Soubhik Sanyal
Copyright (c) 2019, Soubhik Sanyal
All rights reserved.
Loads different resnet models
"""
'''
file: Resnet.py
date: 2018_05_02
author: zhangxiong(1025679612@qq.com)
mark: copied from pytorch source code
'''
import torch.nn as nn
import torch.nn.functional as F
import to... | 9,332 | 31.072165 | 122 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/models/lbs.py | # -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is... | 13,783 | 35.465608 | 79 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/models/FLAME.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 12,754 | 47.683206 | 134 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/models/decoders.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 2,461 | 42.964286 | 97 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/models/encoders.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 1,424 | 33.756098 | 78 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/datasets/detectors.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 1,983 | 28.61194 | 95 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/datasets/datasets.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 3,379 | 38.302326 | 148 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/datasets/detectors_2.py | """
Calculate euler angles yaw pitch roll using deep network HopeNet
https://github.com/natanielruiz/deep-head-pose
The face detector used is SFD (taken from face-alignment FAN) https://github.com/1adrianb/face-alignment
"""
import os
import numpy as np
import sys
from matplotlib import pyplot as plt
import cv2
from... | 14,022 | 27.444219 | 110 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/utils/renderer.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 15,927 | 45.847059 | 217 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/utils/util.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 22,570 | 36.55574 | 145 | py |
StyleMask | StyleMask-master/libs/DECA/decalib/utils/rotation_converter.py | # -*- coding: utf-8 -*-
#
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with this software distribution.
# Any use not explicitly grant... | 12,670 | 30.132678 | 87 | py |
pyUSID-legacy | pyUSID-master-legacy/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 14,888 | 32.160356 | 124 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/test_regression.py | import torch
import torch.nn as nn
import torch.optim as optim
import configs
from data.qmul_loader import get_batch, train_people, test_people
from io_utils import parse_args_regression, get_resume_file
from methods.DKT_regression import DKT
from methods.feature_transfer_regression import FeatureTransfer
import backbo... | 1,301 | 31.55 | 114 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/test.py | from pathlib import Path
import torch
import numpy as np
import random
import torch.optim
import torch.utils.data.sampler
import os
import time
from typing import Type
import configs
import backbone
import data.feature_loader as feat_loader
from data.datamgr import SetDataManager
from methods.baselinefinetune import ... | 11,323 | 40.028986 | 195 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/test_uncertainty.py | import torch
import numpy as np
import random
from torch.autograd import Variable
import torch.nn as nn
import torch.optim
import json
import torch.utils.data.sampler
import os
import glob
import time
import configs
import backbone
import data.feature_loader as feat_loader
from data.datamgr import SetDataManager
from ... | 11,741 | 43.309434 | 127 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/utils.py | import torch
import numpy as np
def one_hot(y, num_class):
return torch.zeros((len(y), num_class)).scatter_(1, y.unsqueeze(1), 1)
def DBindex(cl_data_file):
class_list = cl_data_file.keys()
cl_num= len(class_list)
cl_means = []
stds = []
DBs = []
for cl in class_list:
cl_m... | 1,052 | 31.90625 | 102 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/backbone.py | # This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from torch.nn.utils.weight_norm import WeightNorm
# Basic ResNet model
def init_layer(L):
# Initialization using fan-in
if isinstance(L, n... | 21,085 | 35.355172 | 206 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/train_regression.py | import torch
import torch.nn as nn
import torch.optim as optim
import configs
from data.qmul_loader import get_batch, train_people, test_people
from io_utils import parse_args_regression, get_resume_file
from methods.DKT_regression import DKT
from methods.feature_transfer_regression import FeatureTransfer
import backbo... | 1,334 | 32.375 | 114 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/save_features.py | import numpy as np
import torch
from torch.autograd import Variable
import os
import glob
import h5py
import configs
import backbone
from data.datamgr import SimpleDataManager
from methods.baselinetrain import BaselineTrain
from methods.baselinefinetune import BaselineFinetune
from methods.hypernets import hypernet_ty... | 5,138 | 35.707143 | 178 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/train.py | import json
import sys
from collections import defaultdict
from typing import Type, List, Union, Dict, Optional
from copy import deepcopy
import numpy as np
import torch
import random
from neptune.new import Run
import torch.optim
import torch.optim.lr_scheduler as lr_scheduler
import os
import configs
import backbon... | 21,822 | 42.733467 | 186 | py |
few-shot-hypernets-public | few-shot-hypernets-public-master/methods/relationnet.py | # This code is modified from https://github.com/floodsung/LearningToCompare_FSL
import backbone
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from methods.meta_template import MetaTemplate
import utils
class RelationNet(MetaTemplate):
de... | 6,459 | 40.677419 | 170 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.