python_code stringlengths 0 679k | repo_name stringlengths 9 41 | file_path stringlengths 6 149 |
|---|---|---|
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.midas import MidasDetector
from cldm.model import create_model, load_state_dict
from c... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_normal2image.py |
from tutorial_dataset import MyDataset
dataset = MyDataset()
print(len(dataset))
item = dataset[1234]
jpg = item['jpg']
txt = item['txt']
hint = item['hint']
print(txt)
print(jpg.shape)
print(hint.shape)
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tutorial_dataset_test.py |
from share import *
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from tutorial_dataset import MyDataset
from cldm.logger import ImageLogger
from cldm.model import create_model, load_state_dict
# Configs
resume_path = './models/control_sd15_ini.ckpt'
batch_size = 4
logger_freq = 300
learning... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tutorial_train.py |
import sys
import os
assert len(sys.argv) == 3, 'Args are wrong.'
input_path = sys.argv[1]
output_path = sys.argv[2]
assert os.path.exists(input_path), 'Input model does not exist.'
assert not os.path.exists(output_path), 'Output filename already exists.'
assert os.path.exists(os.path.dirname(output_path)), 'Output ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tool_add_control.py |
import gradio as gr
from annotator.util import resize_image, HWC3
model_canny = None
def canny(img, res, l, h):
img = resize_image(HWC3(img), res)
global model_canny
if model_canny is None:
from annotator.canny import CannyDetector
model_canny = CannyDetector()
result = model_canny(... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_annotator.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
model... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_scribble2image.py |
from share import *
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from tutorial_dataset import MyDataset
from cldm.logger import ImageLogger
from cldm.model import create_model, load_state_dict
# Configs
resume_path = './models/control_sd21_ini.ckpt'
batch_size = 4
logger_freq = 300
learning... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tutorial_train_sd21.py |
import config
from cldm.hack import disable_verbosity, enable_sliced_attention
disable_verbosity()
if config.save_memory:
enable_sliced_attention()
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/share.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.hed import HEDdetector
from cldm.model import create_model, load_state_dict
from cldm.... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_hed2image.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
model... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_scribble2image_interactive.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.canny import CannyDetector
from cldm.model import create_model, load_state_dict
from c... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_canny2image.py |
import json
import cv2
import numpy as np
from torch.utils.data import Dataset
class MyDataset(Dataset):
def __init__(self):
self.data = []
with open('./training/fill50k/prompt.json', 'rt') as f:
for line in f:
self.data.append(json.loads(line))
def __len__(self):... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tutorial_dataset.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.openpose import OpenposeDetector
from cldm.model import create_model, load_state_dict
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_pose2image.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.hed import HEDdetector, nms
from cldm.model import create_model, load_state_dict
from ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_fake_scribble2image.py |
import einops
import torch
import torch as th
import torch.nn as nn
from ldm.modules.diffusionmodules.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
)
from einops import rearrange, repeat
from torchvision.utils import make_grid
from ldm.modules.attention import SpatialTransformer
from... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/cldm/cldm.py |
import torch
import einops
import ldm.modules.encoders.modules
import ldm.modules.attention
from transformers import logging
from ldm.modules.attention import default
def disable_verbosity():
logging.set_verbosity_error()
print('logging improved.')
return
def enable_sliced_attention():
ldm.modules... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/cldm/hack.py |
import os
import numpy as np
import torch
import torchvision
from PIL import Image
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.utilities.distributed import rank_zero_only
class ImageLogger(Callback):
def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/cldm/logger.py |
import os
import torch
from omegaconf import OmegaConf
from ldm.util import instantiate_from_config
def get_state_dict(d):
return d.get('state_dict', d)
def load_state_dict(ckpt_path, location='cpu'):
_, extension = os.path.splitext(ckpt_path)
if extension.lower() == ".safetensors":
import safe... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/cldm/model.py |
"""SAMPLING ONLY."""
import torch
import numpy as np
from tqdm import tqdm
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/cldm/ddim_hacked.py |
import numpy as np
import cv2
import os
annotator_ckpts_path = os.path.join(os.path.dirname(__file__), 'ckpts')
def HWC3(x):
assert x.dtype == np.uint8
if x.ndim == 2:
x = x[:, :, None]
assert x.ndim == 3
H, W, C = x.shape
assert C == 1 or C == 3 or C == 4
if C == 3:
return x... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/util.py |
# Uniformer
# From https://github.com/Sense-X/UniFormer
# # Apache-2.0 license
import os
from annotator.uniformer.mmseg.apis import init_segmentor, inference_segmentor, show_result_pyplot
from annotator.uniformer.mmseg.core.evaluation import get_palette
from annotator.util import annotator_ckpts_path
checkpoint_fil... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/__init__.py |
from .inference import inference_segmentor, init_segmentor, show_result_pyplot
from .test import multi_gpu_test, single_gpu_test
from .train import get_root_logger, set_random_seed, train_segmentor
__all__ = [
'get_root_logger', 'set_random_seed', 'train_segmentor', 'init_segmentor',
'inference_segmentor', 'mu... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/apis/__init__.py |
import os.path as osp
import pickle
import shutil
import tempfile
import annotator.uniformer.mmcv as mmcv
import numpy as np
import torch
import torch.distributed as dist
from annotator.uniformer.mmcv.image import tensor2imgs
from annotator.uniformer.mmcv.runner import get_dist_info
def np2tmp(array, temp_file_name=... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/apis/test.py |
import random
import warnings
import numpy as np
import torch
from annotator.uniformer.mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from annotator.uniformer.mmcv.runner import build_optimizer, build_runner
from annotator.uniformer.mmseg.core import DistEvalHook, EvalHook
from annotator.uniformer.mms... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/apis/train.py |
import matplotlib.pyplot as plt
import annotator.uniformer.mmcv as mmcv
import torch
from annotator.uniformer.mmcv.parallel import collate, scatter
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmseg.datasets.pipelines import Compose
from annotator.uniformer.mmseg.models import b... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/apis/inference.py |
from .evaluation import * # noqa: F401, F403
from .seg import * # noqa: F401, F403
from .utils import * # noqa: F401, F403
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/__init__.py |
def add_prefix(inputs, prefix):
"""Add prefix for dict.
Args:
inputs (dict): The input dict with str keys.
prefix (str): The prefix to add.
Returns:
dict: The dict with keys updated with ``prefix``.
"""
outputs = dict()
for name, value in inputs.items():
outpu... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/utils/misc.py |
from .misc import add_prefix
__all__ = ['add_prefix']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/utils/__init__.py |
from collections import OrderedDict
import annotator.uniformer.mmcv as mmcv
import numpy as np
import torch
def f_score(precision, recall, beta=1):
"""calcuate the f-score value.
Args:
precision (float | torch.Tensor): The precision value.
recall (float | torch.Tensor): The recall value.
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/evaluation/metrics.py |
import annotator.uniformer.mmcv as mmcv
def cityscapes_classes():
"""Cityscapes class names for external use."""
return [
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
'person', 'rider', 'car', 'truck', 'bus', ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/evaluation/class_names.py |
import os.path as osp
from annotator.uniformer.mmcv.runner import DistEvalHook as _DistEvalHook
from annotator.uniformer.mmcv.runner import EvalHook as _EvalHook
class EvalHook(_EvalHook):
"""Single GPU EvalHook, with efficient test support.
Args:
by_epoch (bool): Determine perform evaluation by epo... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/evaluation/eval_hooks.py |
from .class_names import get_classes, get_palette
from .eval_hooks import DistEvalHook, EvalHook
from .metrics import eval_metrics, mean_dice, mean_fscore, mean_iou
__all__ = [
'EvalHook', 'DistEvalHook', 'mean_dice', 'mean_iou', 'mean_fscore',
'eval_metrics', 'get_classes', 'get_palette'
]
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/evaluation/__init__.py |
from .builder import build_pixel_sampler
from .sampler import BasePixelSampler, OHEMPixelSampler
__all__ = ['build_pixel_sampler', 'BasePixelSampler', 'OHEMPixelSampler']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/seg/__init__.py |
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg
PIXEL_SAMPLERS = Registry('pixel sampler')
def build_pixel_sampler(cfg, **default_args):
"""Build pixel sampler for segmentation map."""
return build_from_cfg(cfg, PIXEL_SAMPLERS, default_args)
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/seg/builder.py |
from abc import ABCMeta, abstractmethod
class BasePixelSampler(metaclass=ABCMeta):
"""Base class of pixel sampler."""
def __init__(self, **kwargs):
pass
@abstractmethod
def sample(self, seg_logit, seg_label):
"""Placeholder for sample function."""
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/seg/sampler/base_pixel_sampler.py |
from .base_pixel_sampler import BasePixelSampler
from .ohem_pixel_sampler import OHEMPixelSampler
__all__ = ['BasePixelSampler', 'OHEMPixelSampler']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/seg/sampler/__init__.py |
import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
context (nn.Module): The contex... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/core/seg/sampler/ohem_pixel_sampler.py |
import os.path as osp
import tempfile
import annotator.uniformer.mmcv as mmcv
import numpy as np
from annotator.uniformer.mmcv.utils import print_log
from PIL import Image
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class CityscapesDataset(CustomDataset):
"""Citys... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/cityscapes.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class PascalContextDataset(CustomDataset):
"""PascalContext dataset.
In segmentation map annotation for PascalContext, 0 stands for background,
which is included in 60 categories. ``reduce_z... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pascal_context.py |
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class ADE20KDataset(CustomDataset):
"""ADE20K dataset.
In segmentation map annotation for ADE20K, 0 stands for background, which
is not included in 150 categories. ``reduce_zero_label`` is fixed to True.
The `... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/ade.py |
import os
import os.path as osp
from collections import OrderedDict
from functools import reduce
import annotator.uniformer.mmcv as mmcv
import numpy as np
from annotator.uniformer.mmcv.utils import print_log
from prettytable import PrettyTable
from torch.utils.data import Dataset
from annotator.uniformer.mmseg.core ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/custom.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class HRFDataset(CustomDataset):
"""HRF dataset.
In segmentation map annotation for HRF, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to False. ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/hrf.py |
from .ade import ADE20KDataset
from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset
from .chase_db1 import ChaseDB1Dataset
from .cityscapes import CityscapesDataset
from .custom import CustomDataset
from .dataset_wrappers import ConcatDataset, RepeatDataset
from .drive import DRIVEDataset
from .hrf... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/__init__.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class ChaseDB1Dataset(CustomDataset):
"""Chase_db1 dataset.
In segmentation map annotation for Chase_db1, 0 stands for background,
which is included in 2 categories. ``reduce_zero_label`` is... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/chase_db1.py |
import copy
import platform
import random
from functools import partial
import numpy as np
from annotator.uniformer.mmcv.parallel import collate
from annotator.uniformer.mmcv.runner import get_dist_info
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg
from annotator.uniformer.mmcv.utils.parrots_wrap... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/builder.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class PascalVOCDataset(CustomDataset):
"""Pascal VOC dataset.
Args:
split (str): Split txt file for Pascal VOC.
"""
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boa... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/voc.py |
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .builder import DATASETS
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
concat the group flag for image aspect rati... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/dataset_wrappers.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class STAREDataset(CustomDataset):
"""STARE dataset.
In segmentation map annotation for STARE, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to F... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/stare.py |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class DRIVEDataset(CustomDataset):
"""DRIVE dataset.
In segmentation map annotation for DRIVE, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to F... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/drive.py |
import annotator.uniformer.mmcv as mmcv
import numpy as np
from annotator.uniformer.mmcv.utils import deprecated_api_warning, is_tuple_of
from numpy import random
from ..builder import PIPELINES
@PIPELINES.register_module()
class Resize(object):
"""Resize images & seg.
This transform resizes the input image... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/transforms.py |
import warnings
import annotator.uniformer.mmcv as mmcv
from ..builder import PIPELINES
from .compose import Compose
@PIPELINES.register_module()
class MultiScaleFlipAug(object):
"""Test-time augmentation with multiple scales and flipping.
An example configuration is as followed:
.. code-block::
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/test_time_aug.py |
import os.path as osp
import annotator.uniformer.mmcv as mmcv
import numpy as np
from ..builder import PIPELINES
@PIPELINES.register_module()
class LoadImageFromFile(object):
"""Load an image from file.
Required keys are "img_prefix" and "img_info" (a dict that must contain the
key "filename"). Added o... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/loading.py |
import collections
from annotator.uniformer.mmcv.utils import build_from_cfg
from ..builder import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose multiple transforms sequentially.
Args:
transforms (Sequence[dict | callable]): Sequence of transform object or
con... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/compose.py |
from .compose import Compose
from .formating import (Collect, ImageToTensor, ToDataContainer, ToTensor,
Transpose, to_tensor)
from .loading import LoadAnnotations, LoadImageFromFile
from .test_time_aug import MultiScaleFlipAug
from .transforms import (CLAHE, AdjustGamma, Normalize, Pad,
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/__init__.py |
from collections.abc import Sequence
import annotator.uniformer.mmcv as mmcv
import numpy as np
import torch
from annotator.uniformer.mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported ty... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/datasets/pipelines/formating.py |
from annotator.uniformer.mmcv.utils import collect_env as collect_base_env
from annotator.uniformer.mmcv.utils import get_git_hash
import annotator.uniformer.mmseg as mmseg
def collect_env():
"""Collect the information of the running environments."""
env_info = collect_base_env()
env_info['MMSegmentation... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/utils/collect_env.py |
from .collect_env import collect_env
from .logger import get_root_logger
__all__ = ['get_root_logger', 'collect_env']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/utils/__init__.py |
import logging
from annotator.uniformer.mmcv.utils import get_logger
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is specified, a FileHandler will... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/utils/logger.py |
from .backbones import * # noqa: F401,F403
from .builder import (BACKBONES, HEADS, LOSSES, SEGMENTORS, build_backbone,
build_head, build_loss, build_segmentor)
from .decode_heads import * # noqa: F401,F403
from .losses import * # noqa: F401,F403
from .necks import * # noqa: F401,F403
from .seg... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/__init__.py |
import warnings
from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS
from annotator.uniformer.mmcv.utils import Registry
MODELS = Registry('models', parent=MMCV_MODELS)
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
SEGMENTORS = MODELS
def build_backbone(cfg):
"""Build backbone."""
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/builder.py |
"""Modified from https://github.com/LikeLy-Journey/SegmenTron/blob/master/
segmentron/solver/loss.py (Apache-2.0 License)"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weighted_loss
@weighted_loss
def dice_loss(pred,
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/dice_loss.py |
from .accuracy import Accuracy, accuracy
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
cross_entropy, mask_cross_entropy)
from .dice_loss import DiceLoss
from .lovasz_loss import LovaszLoss
from .utils import reduce_loss, weight_reduce_loss, weighted_loss
__a... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/__init__.py |
import functools
import annotator.uniformer.mmcv as mmcv
import numpy as np
import torch.nn.functional as F
def get_class_weight(class_weight):
"""Get class weight for loss function.
Args:
class_weight (list[float] | str | None): If class_weight is a str,
take it as a file name and read ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/utils.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
class_weight=None,
reduction='mean',
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/cross_entropy_loss.py |
import torch.nn as nn
def accuracy(pred, target, topk=1, thresh=None):
"""Calculate accuracy according to the prediction and target.
Args:
pred (torch.Tensor): The model prediction, shape (N, num_class, ...)
target (torch.Tensor): The target of each prediction, shape (N, , ...)
topk (... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/accuracy.py |
"""Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor
ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim
Berman 2018 ESAT-PSI KU Leuven (MIT License)"""
import annotator.uniformer.mmcv as mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..b... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/losses/lovasz_loss.py |
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import ConvModule
from ..builder import NECKS
@NECKS.register_module()
class MultiLevelNeck(nn.Module):
"""MultiLevelNeck.
A neck structure connect vit backbone and decoder_heads.
Args:
in_channels (List[int]... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/necks/multilevel_neck.py |
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import ConvModule, xavier_init
from ..builder import NECKS
@NECKS.register_module()
class FPN(nn.Module):
"""Feature Pyramid Network.
This is an implementation of - Feature Pyramid Networks for Object
Detection (http... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/necks/fpn.py |
from .fpn import FPN
from .multilevel_neck import MultiLevelNeck
__all__ = ['FPN', 'MultiLevelNeck']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/necks/__init__.py |
import annotator.uniformer.mmcv as mmcv
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import ConvModule
from .make_divisible import make_divisible
class SELayer(nn.Module):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) channels of the SE layer.
rati... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/se_layer.py |
from annotator.uniformer.mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/inverted_residual.py |
from annotator.uniformer.mmcv.cnn import build_conv_layer, build_norm_layer
from torch import nn as nn
class ResLayer(nn.Sequential):
"""ResLayer to build ResNet style backbone.
Args:
block (nn.Module): block used to build ResLayer.
inplanes (int): inplanes of block.
planes (int): pla... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/res_layer.py |
import torch
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import ConvModule, build_upsample_layer
class UpConvBlock(nn.Module):
"""Upsample convolution block in decoder for UNet.
This upsample convolution block consists of one upsample module
followed by one convolution block. The upsample mod... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/up_conv_block.py |
from .drop import DropPath
from .inverted_residual import InvertedResidual, InvertedResidualV3
from .make_divisible import make_divisible
from .res_layer import ResLayer
from .se_layer import SELayer
from .self_attention_block import SelfAttentionBlock
from .up_conv_block import UpConvBlock
from .weight_init import tru... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/__init__.py |
import torch
from annotator.uniformer.mmcv.cnn import ConvModule, constant_init
from torch import nn as nn
from torch.nn import functional as F
class SelfAttentionBlock(nn.Module):
"""General self-attention block/non-local block.
Please refer to https://arxiv.org/abs/1706.03762 for details about key,
que... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/self_attention_block.py |
def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
"""Make divisible function.
This function rounds the channel number to the nearest value that can be
divisible by the divisor. It is taken from the original tf repo. It ensures
that all layers have a channel number that is divisible by ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/make_divisible.py |
"""Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import torch
from torch import nn
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of
residual blocks).
Args:
drop_prob (float): Drop r... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/drop.py |
"""Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import math
import warnings
import torch
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
"""Reference: https://people.sc.fsu.edu/~jburkardt/presentations
/truncated_normal.pdf"""
def norm... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/utils/weight_init.py |
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmcv.utils.parrots_wrapper import _BatchNorm
from annotator.uniformer.mmseg.ops imp... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/hrnet.py |
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import (ConvModule, build_conv_layer, build_norm_layer,
constant_init, kaiming_init)
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmcv.utils.parrots_wrap... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/cgnet.py |
import torch.nn as nn
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import (UPSAMPLE_LAYERS, ConvModule, build_activation_layer,
build_norm_layer, constant_init, kaiming_init)
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmcv.utils.pa... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/unet.py |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from ..utils import ResLayer
from .resnet import Bottleneck as _Bottleneck
from .resnet import ... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/resnest.py |
import logging
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import ConvModule, constant_init, kaiming_init
from annotator.uniformer.mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from ..builder import BACKBONES
from ..utils import InvertedResidual, make_divisible
@BA... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/mobilenet_v2.py |
from .cgnet import CGNet
# from .fast_scnn import FastSCNN
from .hrnet import HRNet
from .mobilenet_v2 import MobileNetV2
from .mobilenet_v3 import MobileNetV3
from .resnest import ResNeSt
from .resnet import ResNet, ResNetV1c, ResNetV1d
from .resnext import ResNeXt
from .unet import UNet
from .vit import VisionTransfo... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/__init__.py |
import logging
import annotator.uniformer.mmcv as mmcv
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import ConvModule, constant_init, kaiming_init
from annotator.uniformer.mmcv.cnn.bricks import Conv2dAdaptivePadding
from annotator.uniformer.mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/mobilenet_v3.py |
import torch
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule, constant_init,
kaiming_init)
from torch.nn.modules.batchnorm import _BatchNorm
from annotator.uniformer.mmseg.models.decode_heads.psp_head import PPM
from annotator.uniformer.mms... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/fast_scnn.py |
import math
from annotator.uniformer.mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from ..utils import ResLayer
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottleneck(_Bottleneck):
"""Bottleneck block for ResNeXt.
If style is "pytorch"... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/resnext.py |
"""Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/vision_transformer.py."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import (Conv2d, Linear, build_activation_layer, bui... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/vit.py |
import torch.nn as nn
import torch.utils.checkpoint as cp
from annotator.uniformer.mmcv.cnn import (build_conv_layer, build_norm_layer, build_plugin_layer,
constant_init, kaiming_init)
from annotator.uniformer.mmcv.runner import load_checkpoint
from annotator.uniformer.mmcv.utils.parrots_wrapper i... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/resnet.py |
# --------------------------------------------------------
# UniFormer
# Copyright (c) 2022 SenseTime X-Lab
# Licensed under The MIT License [see LICENSE for details]
# Written by Kunchang Li
# --------------------------------------------------------
from collections import OrderedDict
import math
from functools impo... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/backbones/uniformer.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmseg.core import add_prefix
from annotator.uniformer.mmseg.ops import resize
from .. import builder
from ..builder import SEGMENTORS
from .base import BaseSegmentor
@SEGMENTORS.register_module()
class EncoderDecoder(BaseSegm... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/segmentors/encoder_decoder.py |
from .base import BaseSegmentor
from .cascade_encoder_decoder import CascadeEncoderDecoder
from .encoder_decoder import EncoderDecoder
__all__ = ['BaseSegmentor', 'EncoderDecoder', 'CascadeEncoderDecoder']
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/segmentors/__init__.py |
from torch import nn
from annotator.uniformer.mmseg.core import add_prefix
from annotator.uniformer.mmseg.ops import resize
from .. import builder
from ..builder import SEGMENTORS
from .encoder_decoder import EncoderDecoder
@SEGMENTORS.register_module()
class CascadeEncoderDecoder(EncoderDecoder):
"""Cascade Enc... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/segmentors/cascade_encoder_decoder.py |
import logging
import warnings
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
import annotator.uniformer.mmcv as mmcv
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from annotator.uniformer.mmcv.runner import auto_fp16
class BaseSegmentor(nn.Module... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/segmentors/base.py |
import torch
import torch.nn as nn
from annotator.uniformer.mmcv.cnn import ConvModule
from annotator.uniformer.mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
from .psp_head import PPM
@HEADS.register_module()
class UPerHead(BaseDecodeHead):
"""Unified Perceptual Pars... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/uper_head.py |
import math
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import ConvModule
from ..builder import HEADS
from .decode_head import BaseDecodeHead
def reduce_mean(tensor):
"""Reduce mean when distributed training."""
if not... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/ema_head.py |
import torch
import torch.nn as nn
from annotator.uniformer.mmcv import is_tuple_of
from annotator.uniformer.mmcv.cnn import ConvModule
from annotator.uniformer.mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class LRASPPHead(BaseDecodeHead):
"... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/lraspp_head.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import ConvModule
from annotator.uniformer.mmseg.ops import resize
from ..builder import HEADS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from .cascade_decode_head import BaseCascadeDecodeHead
clas... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/ocr_head.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
from ..builder import HEADS
from .decode_head import BaseDecodeHead
class DCM(nn.Module):
"""Dynamic Convolutional Module used in DMNet.
Args:
... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/dm_head.py |
import torch
from annotator.uniformer.mmcv.cnn import ContextBlock
from ..builder import HEADS
from .fcn_head import FCNHead
@HEADS.register_module()
class GCHead(FCNHead):
"""GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond.
This head is the implementation of `GCNet
<https://arxiv.... | trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/annotator/uniformer/mmseg/models/decode_heads/gc_head.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.