python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from abc import ABCMeta, abstractmethod
import torch
from ..builder import MASK_ASSIGNERS, build_match_cost
try:
from... | dinov2-main | dinov2/eval/segmentation_m2f/models/utils/assigner.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from .vit_adapter import ViTAdapter
| dinov2-main | dinov2/eval/segmentation_m2f/models/backbones/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# 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
from mmseg.models.builder import BACKBONES
f... | dinov2-main | dinov2/eval/segmentation_m2f/models/backbones/vit_adapter.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
"""Vision Transformer (ViT) in PyTorch.
A PyTorch implement of Vision Transformers as described in:
'An Image Is Worth 16 ... | dinov2-main | dinov2/eval/segmentation_m2f/models/backbones/vit.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from functools import partial
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from ...ops.modules i... | dinov2-main | dinov2/eval/segmentation_m2f/models/backbones/adapter_modules.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightma... | dinov2-main | dinov2/eval/segmentation_m2f/models/backbones/drop_path.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.core import add_prefix
from mmseg.models impor... | dinov2-main | dinov2/eval/segmentation_m2f/models/segmentors/encoder_decoder_mask2former.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from .encoder_decoder_mask2former import EncoderDecoderMask2Former
| dinov2-main | dinov2/eval/segmentation_m2f/models/segmentors/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from .mask2former_head import Mask2FormerHead
| dinov2-main | dinov2/eval/segmentation_m2f/models/decode_heads/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import Conv2d, build_plugin_la... | dinov2-main | dinov2/eval/segmentation_m2f/models/decode_heads/mask2former_head.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import math
import warnings
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Fu... | dinov2-main | dinov2/eval/segmentation_m2f/ops/modules/ms_deform_attn.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/fundamentalvision/Deformable-DETR/tree/main/models/ops/modules
# https://github.com/c... | dinov2-main | dinov2/eval/segmentation_m2f/ops/modules/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import argparse
import logging
import os
from pathlib import Path
from typing import List, Optional
import submitit
from d... | dinov2-main | dinov2/run/submit.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
| dinov2-main | dinov2/run/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
import os
import sys
from dinov2.logging import setup_logging
from dinov2.train import get_args_parser as ge... | dinov2-main | dinov2/run/train/train.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
import os
import sys
from dinov2.eval.linear import get_args_parser as get_linear_args_parser
from dinov2.lo... | dinov2-main | dinov2/run/eval/linear.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
import os
import sys
from dinov2.eval.log_regression import get_args_parser as get_log_regression_args_parse... | dinov2-main | dinov2/run/eval/log_regression.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
import os
import sys
from dinov2.eval.knn import get_args_parser as get_knn_args_parser
from dinov2.logging ... | dinov2-main | dinov2/run/eval/knn.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from typing import Sequence
import torch
from torchvision import transforms
class GaussianBlur(transforms.RandomApply):
... | dinov2-main | dinov2/data/transforms.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import torch
import random
def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=Non... | dinov2-main | dinov2/data/collate.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
from enum import Enum
from typing import Any, Callable, List, Optional, TypeVar
import torch
from torch.util... | dinov2-main | dinov2/data/loaders.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from .adapters import DatasetWithEnumeratedTargets
from .loaders import make_data_loader, make_dataset, SamplerType
from .co... | dinov2-main | dinov2/data/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import random
import math
import numpy as np
class MaskingGenerator:
def __init__(
self,
input_size,
... | dinov2-main | dinov2/data/masking.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import itertools
from typing import Any, Optional
import warnings
import numpy as np
import torch
from torch.utils.data.sam... | dinov2-main | dinov2/data/samplers.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import logging
from torchvision import transforms
from .transforms import (
GaussianBlur,
make_normalize_transform... | dinov2-main | dinov2/data/augmentations.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torch.utils.data import Dataset
class DatasetWithEnumeratedTargets(Dataset):
def _... | dinov2-main | dinov2/data/adapters.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import csv
from enum import Enum
import logging
import os
from typing import Callable, List, Optional, Tuple, Union
import ... | dinov2-main | dinov2/data/datasets/image_net.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from io import BytesIO
from typing import Any
from PIL import Image
class Decoder:
def decode(self) -> Any:
r... | dinov2-main | dinov2/data/datasets/decoders.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torchvision.datasets import VisionDataset
from .decoders import TargetDecoder, ImageDat... | dinov2-main | dinov2/data/datasets/extended.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from .image_net import ImageNet
from .image_net_22k import ImageNet22k
| dinov2-main | dinov2/data/datasets/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from enum import Enum
from functools import lru_cache
from gzip import GzipFile
from io im... | dinov2-main | dinov2/data/datasets/image_net_22k.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
import functools
import logging
import os
import sys
from typing import Optional
import dinov2.distributed as distributed
f... | dinov2-main | dinov2/logging/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from collections import defaultdict, deque
import datetime
import json
import logging
import time
import torch
import dino... | dinov2-main | dinov2/logging/helpers.py |
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation
import torch
from diffusers impo... | visual-chatgpt-main | visual_chatgpt.py |
Koi-main | example.py | |
from koi.main import Koi | Koi-main | koi/__init__.py |
import torch
from torch import nn
from copy import deepcopy
class Koi:
def __init__(
self,
model,
step_size,
num_steps,
num_iterations
):
"""
init Koi
model = nn.Sequential(
nn.Linear(1, 64),
nn.Tanh(),
nn.Linea... | Koi-main | koi/main.py |
Paper-Implementation-Template-main | example.py | |
import torch
import time
import matplotlib.pyplot as plt
import pytest
from flashlora.attention import FlashAttention
# Setup
model = FlashAttention(dim=512, heads=8, dim_head=64, lora_dim_out=64, r=8).cuda()
sequence_lengths = [2**i for i in range(10, 15)]
# Benchmarking
times = []
for sequence_length in sequence_l... | FlashLora-main | test.py |
import math
import torch
from functools import partial
from torch import nn, einsum
from torch.autograd.function import Function
from einops import rearrange
from torch.jit import fork, wait
from torch.cuda.amp import autocast, GradScaler
from torch.nn import DataParallel
from flashlora.lora import Lora
# constants... | FlashLora-main | flashlora/attention.py |
import torch
from torch import nn
#helper exists(
def exists(val):
return val is not None
def default(val, d):
return val if exists(val) else d
class Lora(nn.Module):
def __init__(
self,
dim,
dim_out,
r=8,
alpha=None,
):
super()._... | FlashLora-main | flashlora/lora.py |
import timeit
import torch
from longnet.attention import MultiHeadDilatedAttention
# Model config
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 64
device = "cuda:0"
dtype = torch.float16
# Input data
batch_size = 32
seq_len = 8192
# Create model and data
# Convert model to dtype along with moving to ... | LongNet-master | mh_example.py |
import timeit
import torch
from longnet.attention import ParallelWrapper, DilatedAttention
#model condig
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 64
device="cuda:0"
dtype=torch.float16
#inputs
batch_size = 32
seq_len = 8192
#create model
device = torch.device("cuda:0" if torch.cuda.is_availab... | LongNet-master | parallel_example.py |
from setuptools import setup, find_packages
setup(
name = 'LongNet',
packages = find_packages(exclude=[]),
version = '0.4.8',
license='MIT',
description = 'LongNet - Pytorch',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = 'https://github.c... | LongNet-master | setup.py |
import timeit
import torch
from longnet.attention import DilatedAttention
#model config
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 64
device = "cuda:0"
dtype=torch.float16
#input data
batch_size = 32
seq_len = 8192
#create model and data
model = DilatedAttention(d_model, num_heads, dilation_rate... | LongNet-master | example.py |
import time
import torch
import matplotlib.pyplot as plt
from longnet.attention import DilatedAttention
from longnet.attend import FlashAttention
class DilatedAttentionTest:
def __init__(self, batch_size, d_model, device):
self.model = DilatedAttention(d_model=d_model, num_heads=8, dilation_rate=2, segmen... | LongNet-master | benchmark/benchmark.py |
import timeit
import torch
from LongNet import DilatedAttention
#model config
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 64
device = "cuda:0"
dtype=torch.float16
#input data
batch_size = 32
seq_len = 1024
#create model and data
model = DilatedAttention(d_model, num_heads, dilation_rate, segment_... | LongNet-master | benchmark/test.py |
import time
import unittest
import torch
from LongNet import DilatedAttention
class TestDilatedAttention(unittest.TestCase):
def test_output_shape(self):
# Setup
input_tensor = torch.randn(2, 128, 512)
dilated_attention = DilatedAttention(512, 8, 2, 64)
# Action
output = ... | LongNet-master | test/attention.py |
import torch
import time
from longnet.attention import DilatedAttention
# Initialize parameters
bsz = 32
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 512 # You might want to adjust this
dropout = 0.1
casual = False
use_xpos = False
use_rel_pos_bias = False
sequence_lengths = list(range(500, 2500, 5... | LongNet-master | test/flops_test.py |
import torch
import time
from longnet.attention import DilatedAttention
import matplotlib.pyplot as plt
# Define sequence lengths to test
seq_lengths = [64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 64000]
# Define batch size and feature dimension
batch_size = 32
d_model = 512
device = 'cuda:0'
# Init... | LongNet-master | test/speed_sequence.py |
import timeit
import torch
from longnet.attention import DilatedAttention
#model config
d_model = 512
num_heads = 8
dilation_rate = 2
segment_size = 64
device = "cuda:0"
dtype=torch.float16
#input data
batch_size = 32
seq_len = 1024
#create model and data
model = DilatedAttention(d_model, num_heads, dilation_rate,... | LongNet-master | test/example_old.py |
# from longnet.model import LongNetTokenizer, LongNetSelector
import torch
# from model import LongNetTokenizer,
from longnet.model import LongNetTokenizer, LongNet
class LongNetTest:
def __init__(self):
self.longnet_selector = LongNet()
self.tokenizer = LongNetTokenizer()
def run_test(self, ... | LongNet-master | test/model/model_test.py |
import unittest
import torch
from LongNet import DilatedLongNet
class TestDilatedLongNet(unittest.TestCase):
def setUp(self):
self.model = DilatedLongNet()
def test_model_shape(self):
# Test input and output dimensions
x = torch.randint(0, 16000, (4, 1024))
out = self.mode... | LongNet-master | test/model/dilated_model.py |
import unittest
from transformers import TrainingArguments, Trainer
from longnet.model import LongNetTokenizer, LongNet
class TestLongNetModels(unittest.TestCase):
def setUp(self):
self.model = LongNet()
self.tokenizer = LongNetTokenizer()
self.training_args = TrainingArguments(
... | LongNet-master | test/model/test.py |
import torch
import time
from LongNet import DilatedLongNet
# Instantiate the DilatedLongNet model
model = DilatedLongNet()
# Define the input tensor
batch_size = 1
sequence_length = 512
input_tensor = torch.randn(batch_size, sequence_length).long()
# Enable CUDA if available
if torch.cuda.is_available():
model ... | LongNet-master | test/model/model.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from longnet.attend import FlashAttention
from longnet.utils import XPOS, MixOutputs, RelativePositionBias, SparsifyIndices
device = "cuda:0"
dtype=torch.float16
class ParallelWrapper:
"""
A simple wrapper to enable easy usage of data p... | LongNet-master | LongNet/attention.py |
from longnet.attention import ParallelWrapper, DilatedAttention
# from longnet.model import LongNetTokenizer, LongNet, DecoderConfig, Decoder, DilatedLongNet
# from longnet.iterations import DynamicDilatedAttention, DilatedAttentionOld, DilatedAttentionOP
from longnet.model import LongNet
| LongNet-master | LongNet/__init__.py |
from torch.nn import Module
from transformers import AutoTokenizer
from longnet.transformer import LongNet
class LongNetTokenizer:
def __init__(self):
self.tokenizer = AutoTokenizer.from_pretrained(
"EleutherAI/gpt-neox-20b",
eos_token="<eos>",
pad_token="<pad>",
... | LongNet-master | LongNet/model.py |
from collections import namedtuple
from functools import wraps
from packaging import version
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from einops import rearrange
from dataclasses import dataclass
# constants
EfficientAttentionConfig = namedtuple('EfficientAttentionConfig'... | LongNet-master | LongNet/attend.py |
import math
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
class StableAdamWUnfused(torch.optim.Optimizer):
def __init__(
self,
params,
lr=0.002,
weight_decay=0.2,
betas=(0.9, 0.99),
eps=1e-8,
clip_thresh=1.0,
pre... | LongNet-master | LongNet/utils.py |
import functools
from itertools import zip_longest
import torch
import torch.nn.functional as F
from torch import nn
from einops import rearrange, repeat, pack, unpack
from einops.layers.torch import Rearrange
from beartype import beartype
from beartype.typing import Tuple, Union
# from LongNet_pytorch.attfend impo... | LongNet-master | LongNet/Transformer.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
import torch
from torch.distributed.fsdp import (
FullyShardedDataParallel,
MixedPrecision,
BackwardPrefetch,
ShardingStrategy,
)
from accelerate import Accelerator
fr... | LongNet-master | LongNet/train.py |
# Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser
import mmcv
import mmcv_custom # noqa: F401,F403
import mmseg_custom # noqa: F401,F403
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
from mmcv.runner i... | ViT-Adapter-main | segmentation/image_demo.py |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import shutil
import time
import warnings
import mmcv
import mmcv_custom # noqa: F401,F403
import mmseg_custom # noqa: F401,F403
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv... | ViT-Adapter-main | segmentation/test.py |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import mmcv_custom # noqa: F401,F403
import mmseg_custom # noqa: F401,F403
import torch
from mmcv.cnn.utils import revert_sync_batchnorm
from mmcv.runner import get_di... | ViT-Adapter-main | segmentation/train.py |
# Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser
import cv2
import mmcv_custom # noqa: F401,F403
import mmseg_custom # noqa: F401,F403
from mmseg.apis import inference_segmentor, init_segmentor
from mmseg.core.evaluation import get_palette
from mmcv.runner import load_checkpoint
... | ViT-Adapter-main | segmentation/video_demo.py |
from .core import * # noqa: F401,F403
from .datasets import * # noqa: F401,F403
from .models import * # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/__init__.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from mmseg.core.evaluation import * # noqa: F401, F403
from mmseg.core.seg import * # noqa: F401, F403
from .anchor import * # noqa: F401,F403
from .box import * # noqa: F401,F403
from .evaluation import * # noqa: F401,F403
from .mask import * # noqa: F401,F4... | ViT-Adapter-main | segmentation/mmseg_custom/core/__init__.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from .builder import * # noqa: F401,F403
from .samplers import MaskPseudoSampler # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/core/box/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import Registry, build_from_cfg
BBOX_SAMPLERS = Registry('bbox_sampler')
BBOX_CODERS = Registry('bbox_coder')
def build_sampler(cfg, **default_args):
"""Builder of box sampler."""
return build_from_cfg(cfg, BBOX_SAMPLERS, default_args)
def bui... | ViT-Adapter-main | segmentation/mmseg_custom/core/box/builder.py |
# Copyright (c) OpenMMLab. All rights reserved.
"""copy from
https://github.com/ZwwWayne/K-Net/blob/main/knet/det/mask_pseudo_sampler.py."""
import torch
from .sampling_result import SamplingResult
class MaskSamplingResult(SamplingResult):
"""Mask sampling result."""
def __init__(self, pos_inds, neg_inds, m... | ViT-Adapter-main | segmentation/mmseg_custom/core/box/samplers/mask_sampling_result.py |
# Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
import torch
from .sampling_result import SamplingResult
class BaseSampler(metaclass=ABCMeta):
"""Base class of samplers."""
def __init__(self,
num,
pos_fraction,
neg_po... | ViT-Adapter-main | segmentation/mmseg_custom/core/box/samplers/base_sampler.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from .mask_pseudo_sampler import MaskPseudoSampler # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/core/box/samplers/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
"""copy from
https://github.com/ZwwWayne/K-Net/blob/main/knet/det/mask_pseudo_sampler.py."""
import torch
from ..builder import BBOX_SAMPLERS
from .base_sampler import BaseSampler
from .mask_sampling_result import MaskSamplingResult
@BBOX_SAMPLERS.register_module()
cl... | ViT-Adapter-main | segmentation/mmseg_custom/core/box/samplers/mask_pseudo_sampler.py |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdet.utils import util_mixins
class SamplingResult(util_mixins.NiceRepr):
"""Bbox sampling result.
Example:
>>> # xdoctest: +IGNORE_WANT
>>> from mmdet.core.bbox.samplers.sampling_result import * # NOQA
>>> self = Sam... | ViT-Adapter-main | segmentation/mmseg_custom/core/box/samplers/sampling_result.py |
# Copyright (c) OpenMMLab. All rights reserved.
def multi_apply(func, *args, **kwargs):
"""Apply function to a list of arguments.
Note:
This function applies the ``func`` to multiple inputs and
map the multiple outputs of the ``func`` into different
list. Each list contains the same typ... | ViT-Adapter-main | segmentation/mmseg_custom/core/utils/misc.py |
# Copyright (c) OpenMMLab. All rights reserved.
from .dist_utils import (DistOptimizerHook, all_reduce_dict, allreduce_grads,
reduce_mean)
from .misc import add_prefix, multi_apply
__all__ = [
'add_prefix', 'multi_apply', 'DistOptimizerHook', 'allreduce_grads',
'all_reduce_dict', 'redu... | ViT-Adapter-main | segmentation/mmseg_custom/core/utils/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import functools
import pickle
import warnings
from collections import OrderedDict
import torch
import torch.distributed as dist
from mmcv.runner import OptimizerHook, get_dist_info
from torch._utils import (_flatten_dense_tensors, _take_tensors,
... | ViT-Adapter-main | segmentation/mmseg_custom/core/utils/dist_utils.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from .utils import mask2bbox # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/core/mask/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
def split_combined_polys(polys, poly_lens, polys_per_mask):
"""Split the combined 1-D polys into masks.
A mask is represented as a list of polys, and a poly is represented as
a... | ViT-Adapter-main | segmentation/mmseg_custom/core/mask/utils.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from .panoptic_utils import INSTANCE_OFFSET # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/core/evaluation/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
# A custom value to distinguish instance ID and category ID; need to
# be greater than the number of categories.
# For a pixel in the panoptic result map:
# pan_id = ins_id * INSTANCE_OFFSET + cat_id
INSTANCE_OFFSET = 1000
| ViT-Adapter-main | segmentation/mmseg_custom/core/evaluation/panoptic_utils.py |
# Copyright (c) Shanghai AI Lab. All rights reserved.
from .point_generator import MlvlPointGenerator # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/core/anchor/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from torch.nn.modules.utils import _pair
from .builder import PRIOR_GENERATORS
@PRIOR_GENERATORS.register_module()
class PointGenerator:
def _meshgrid(self, x, y, row_major=True):
xx = x.repeat(len(y))
yy = y.view(-1,... | ViT-Adapter-main | segmentation/mmseg_custom/core/anchor/point_generator.py |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
from mmcv.utils import Registry, build_from_cfg
PRIOR_GENERATORS = Registry('Generator for anchors and points')
ANCHOR_GENERATORS = PRIOR_GENERATORS
def build_prior_generator(cfg, default_args=None):
return build_from_cfg(cfg, PRIOR_GENERATORS, de... | ViT-Adapter-main | segmentation/mmseg_custom/core/anchor/builder.py |
# Copyright (c) OpenMMLab. All rights reserved.
from .mapillary import MapillaryDataset # noqa: F401,F403
from .potsdam import PotsdamDataset # noqa: F401,F403
from .pipelines import * # noqa: F401,F403
| ViT-Adapter-main | segmentation/mmseg_custom/datasets/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
from mmseg.datasets.builder import DATASETS
from mmseg.datasets.custom import CustomDataset
@DATASETS.register_module(force=True)
class PotsdamDataset(CustomDataset):
"""ISPRS Potsdam dataset.
In segmentation map annotation for Potsdam dataset, 0 is the ignore i... | ViT-Adapter-main | segmentation/mmseg_custom/datasets/potsdam.py |
from mmseg.datasets.builder import DATASETS
from mmseg.datasets.custom import CustomDataset
@DATASETS.register_module()
class MapillaryDataset(CustomDataset):
"""Mapillary dataset.
"""
CLASSES = ('Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail', 'Barrier',
'Wall', 'Bike Lane', 'Crossw... | ViT-Adapter-main | segmentation/mmseg_custom/datasets/mapillary.py |
# Copyright (c) OpenMMLab. All rights reserved.
from .formatting import DefaultFormatBundle, ToMask
from .transform import MapillaryHack, PadShortSide, SETR_Resize
__all__ = [
'DefaultFormatBundle', 'ToMask', 'SETR_Resize', 'PadShortSide',
'MapillaryHack'
]
| ViT-Adapter-main | segmentation/mmseg_custom/datasets/pipelines/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from mmcv.parallel import DataContainer as DC
from mmseg.datasets.builder import PIPELINES
from mmseg.datasets.pipelines.formatting import to_tensor
@PIPELINES.register_module(force=True)
class DefaultFormatBundle(object):
"""Default formatting bu... | ViT-Adapter-main | segmentation/mmseg_custom/datasets/pipelines/formatting.py |
import mmcv
import numpy as np
import torch
from mmseg.datasets.builder import PIPELINES
@PIPELINES.register_module()
class SETR_Resize(object):
"""Resize images & seg.
This transform resizes the input image to some scale. If the input dict
contains the key "scale", then the scale in the input dict is us... | ViT-Adapter-main | segmentation/mmseg_custom/datasets/pipelines/transform.py |
# Copyright (c) OpenMMLab. All rights reserved.
from .backbones import * # noqa: F401,F403
from .builder import (MASK_ASSIGNERS, MATCH_COST, TRANSFORMER, build_assigner,
build_match_cost)
from .decode_heads import * # noqa: F401,F403
from .losses import * # noqa: F401,F403
from .plugins import ... | ViT-Adapter-main | segmentation/mmseg_custom/models/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings # noqa: F401,F403
from mmcv.utils import Registry
TRANSFORMER = Registry('Transformer')
MASK_ASSIGNERS = Registry('mask_assigner')
MATCH_COST = Registry('match_cost')
def build_match_cost(cfg):
"""Build Match Cost."""
return MATCH_COST.build(... | ViT-Adapter-main | segmentation/mmseg_custom/models/builder.py |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
def dice_loss(pred,
target,
weight=None,
eps=1e-3,
reduction='mean',
... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/dice_loss.py |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import MATCH_COST
@MATCH_COST.register_module()
class FocalLossCost:
"""FocalLossCost.
Args:
weight (int | float, optional): loss_weight
alpha (int | float, op... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/match_loss.py |
# Copyright (c) OpenMMLab. All rights reserved.
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
cross_entropy, mask_cross_entropy)
from .dice_loss import DiceLoss
from .focal_loss import FocalLoss
from .match_costs import (ClassificationCost, CrossEntropyLossCos... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/__init__.py |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import weight_reduce_loss
# This method is only for debugging
def py_... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/focal_loss.py |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models.builder import LOSSES
from mmseg.models.losses.utils import get_class_weight, weight_reduce_loss
def cross_entropy(pred,
label,
weig... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/cross_entropy_loss.py |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import MATCH_COST
@MATCH_COST.register_module()
class FocalLossCost:
"""FocalLossCost.
Args:
weight (int | float, optional): loss_weight
alpha (int | float, op... | ViT-Adapter-main | segmentation/mmseg_custom/models/losses/match_costs.py |
import torch
import torch.nn.functional as F
from mmcv.cnn import PLUGIN_LAYERS, Conv2d, ConvModule, kaiming_init
from mmcv.cnn.bricks.transformer import (build_positional_encoding,
build_transformer_layer_sequence)
from mmcv.runner import BaseModule, ModuleList
@PLUGIN_LAYERS... | ViT-Adapter-main | segmentation/mmseg_custom/models/plugins/pixel_decoder.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.