python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
import torch
from torch import nn
class Pooler(torch.nn.Module):
def __init__(
self,
dim_in: int,
projection_size: int,
widening_factor: int = 4,
use_projection_head: bool = True, #TODO: add to config
use_simsiam_mlp: bool = False
):
super().__init__... | multimodal-self-distillation-main | src/models/components/pooler.py |
from typing import Optional, List
from dataclasses import dataclass
import torch
from torch import nn
from src.models.components.preprocessor import PreprocessorType
from src.models.components.masking import mask_hidden_states
from src.models.components.outputs import ModelOutput
from src.models.components.pooler imp... | multimodal-self-distillation-main | src/models/components/hip.py |
from typing import Tuple
import torch
from torch.nn import functional as F
def k_nearest_neighbor(
prediction_features: torch.Tensor,
query_features: torch.Tensor = None,
labels: torch.Tensor = None,
num_classes: int = 1000,
k: int = 20,
chunking: bool = True,
) -> Tuple:
pro... | multimodal-self-distillation-main | src/models/components/knn.py |
import torch
# output classes for bi-encoder and mm-encoder account for flexibility in case of additional byol or data2vec outputs
class DispatcherOutput:
def __init__(
self,
student_input,
teacher_inputs,
align_fuse,
apply_mask: bool,
labels: torch.Tensor,
... | multimodal-self-distillation-main | src/models/components/outputs.py |
import pytest
import torch
import triton
import triton.language as tl
from flashtriton.attention import attention
@pytest.mark.parametrize('Z, H, N_CTX, D_HEAD', [(6, 9, 1024, 64)])
@pytest.mark.parametrize('causal', [False, True])
def test_op(Z, H, N_CTX, D_HEAD, causal, dtype=torch.float16):
torch.manual_seed... | FlashAttention20Triton-main | benchmark_flash_triton.py |
FlashAttention20Triton-main | benchmark_mpt.py | |
import time
import torch
import pytest
from flashtriton.flash_torch import FlashAttention
# Model Arguments
args = {
"dim": 512,
"heads": 8,
"dim_head": 64,
"causal": False,
"q_bucket_size": 512,
"k_bucket_size": 1024,
"parallel": False,
"mixed_precision": False
}
# Initialize ... | FlashAttention20Triton-main | benchmark_flash_torch.py |
import torch
from flashtriton.attention import attention
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import math
import torch
import torch.nn.functional as F
from torch import nn
try:
from apex.normalization import FusedLayerNorm as LayerNorm
except ModuleNotFoundE... | FlashAttention20Triton-main | flashtriton/flash_mha.py |
import pytest
import torch
import triton
import triton.language as tl
@triton.jit
def max_fn(x, y):
return tl.math.max(x, y)
@triton.jit
def _fwd_kernel(
Q, K, V, sm_scale,
L,
Out,
stride_qz, stride_qh, stride_qm, stride_qk,
stride_kz, stride_kh, stride_kn, stride_kk,
stride_vz, stride_... | FlashAttention20Triton-main | flashtriton/attention.py |
# Copyright 2022 MosaicML LLM Foundry authors
# SPDX-License-Identifier: Apache-2.0
"""Attention layers."""
import math
import warnings
from typing import Optional
import torch
import torch.nn as nn
from einops import rearrange
from packaging import version
from torch import nn
from llmfoundry.models.layers.fc impo... | FlashAttention20Triton-main | flashtriton/flash_mpt.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
# constants
EPSILON = 1e-10
# helper funct... | FlashAttention20Triton-main | flashtriton/flash_torch.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple
import fairscale.nn.model_parallel.initialize as fs_init
import torc... | FlashAttention20Triton-main | flashtriton/lama.py |
from setuptools import find_packages, setup
setup(
name='gato-tf',
version='0.0.2',
description='Unofficial Gato: A Generalist Agent',
url='https://github.com/OrigamiDream/gato.git',
author='OrigamiDream',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
i... | GATO-by-Deepmind-main | setup.py |
import copy
from typing import Dict, Any
class GatoConfig:
@staticmethod
def large():
return GatoConfig(num_transformer_blocks=24,
num_attention_heads=16,
layer_width=2048,
feedforward_hidden_size=8192,
... | GATO-by-Deepmind-main | gato/config.py |
from gato.config import GatoConfig
from gato.models import Gato
| GATO-by-Deepmind-main | gato/__init__.py |
import tensorflow as tf
from tensorflow.keras import layers, models
from gato import GatoConfig
from typing import Dict, Any, Union
def _randomized_positions(from_v, to_v):
pos = tf.random.uniform(from_v.shape, minval=0, maxval=1, dtype=tf.float32)
pos = pos * tf.cast(to_v - from_v, dtype=tf.float32)
pos... | GATO-by-Deepmind-main | gato/models/embedding.py |
import tensorflow as tf
from gato.models.transformer import TransformerBlock
from gato.models.embedding import PatchPositionEncoding, ResidualEmbedding, LocalPositionEncoding, DiscreteEmbedding
from gato.models.tokenizers import ContinuousValueTokenizer
from tensorflow.keras import models
from gato import GatoConfig
... | GATO-by-Deepmind-main | gato/models/__init__.py |
import tensorflow as tf
from tensorflow.keras import layers, models, activations
from gato import GatoConfig
from typing import Dict, Any, Union
class TransformerBlock(layers.Layer):
def __init__(self,
config: Union[GatoConfig, Dict[str, Any]],
trainable: bool = True,
... | GATO-by-Deepmind-main | gato/models/transformer.py |
import tensorflow as tf
from gato import GatoConfig
from tensorflow.keras import models
from typing import Union, Dict, Any
def mu_law_encode(x, mu=100, m=256):
# Appendix B. Agent Data Tokenization Details
sign = tf.math.sign(x)
numerator = tf.math.log(tf.abs(x) * mu + 1.0)
denominator = tf.math.log... | GATO-by-Deepmind-main | gato/models/tokenizers.py |
import os
from tiktokx.train import Trainer, parse_args
if __name__ == '__main__':
args = parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)
data_config = {
'n_users': 12345,
'n_items': 67890
}
trainer = Trainer(data_config)
best_recall, run... | Tiktokx-main | example.py |
from tiktokx.utils import *
from tiktokx.model import Tiktok
from tiktokx.train import Trainer
| Tiktokx-main | tiktokx/__init__.py |
import os
import pickle
from time import time
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from torch.nn import init
from tiktokx.utils import build_knn_normalized_graph, build_sim, parse_args
args = parse_args()
... | Tiktokx-main | tiktokx/model.py |
import argparse
import json
import os
import random as rd
from datetime import datetime
from time import time
import numpy as np
import scipy.sparse as sp
import torch
from scipy.parse import csr_matrix
from sklearn.metrics import roc_auc_score
from tiktokx.utils import parse_args
args = parse_args()
def build_s... | Tiktokx-main | tiktokx/utils.py |
import copy
import math
import os
import pickle
import random
import sys
from datetime import datetime
from time import time
import dgl
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.sparse as sparse
import visdom... | Tiktokx-main | tiktokx/train.py |
from setuptools import setup, find_packages
setup(
name = 'PaLM-rlhf-pytorch',
packages = find_packages(exclude=[]),
version = '0.2.1',
license='MIT',
description = 'PaLM + Reinforcement Learning with Human Feedback - Pytorch',
author = 'Phil Wang',
author_email = '[email protected]',
long_descripti... | PaLM-rlhf-pytorch-main | setup.py |
import gzip
import random
import tqdm
import numpy as np
import torch
from lion_pytorch import Lion
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
from palm_rlhf_pytorch import PaLM
from accelerate import Accelerator
# constants
NUM_BATCHES = int(1e5)
BATCH_SIZE = 4
GRADIENT_A... | PaLM-rlhf-pytorch-main | train.py |
import torch
from torch import nn, einsum
import torch.nn.functional as F
from collections import namedtuple
from functools import wraps
from packaging import version
from einops import rearrange
# constants
Config = namedtuple('EfficientAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])
# ... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/attention.py |
import math
import copy
from pathlib import Path
from collections import namedtuple
from functools import wraps
from itertools import zip_longest
from tqdm import tqdm
from beartype import beartype
from beartype.typing import Tuple, Optional
import torch
from torch import einsum, nn
import torch.nn.functional as F
f... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/palm.py |
from palm_rlhf_pytorch.palm import PaLM
from palm_rlhf_pytorch.reward import RewardModel
from palm_rlhf_pytorch.ppo import RLHFTrainer, ActorCritic
| PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/__init__.py |
import math
import torch
from torch import einsum, nn
import torch.nn.functional as F
from einops import rearrange
def exists(val):
return val is not None
# decorators
def eval_decorator(fn):
def inner(self, *args, **kwargs):
was_training = self.training
self.eval()
out = fn(self, *a... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/utils.py |
from torch.optim import AdamW, Adam
from lion_pytorch import Lion
def separate_weight_decayable_params(params):
wd_params, no_wd_params = [], []
for param in params:
param_list = no_wd_params if param.ndim < 2 else wd_params
param_list.append(param)
return wd_params, no_wd_params
def get_o... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/optimizer.py |
import torch
from torch import nn
# helper functions
def exists(val):
return val is not None
def default(val, d):
return val if exists(val) else d
# LoRA - https://arxiv.org/abs/2106.09685
class LoRA(nn.Module):
def __init__(
self,
dim,
dim_out,
r = 8,
alpha = No... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/lora.py |
import math
from pathlib import Path
import copy
from tqdm import tqdm
from functools import partial
from collections import deque, namedtuple
from random import randrange
from beartype import beartype
from beartype.typing import List, Optional, Callable, Deque
import torch
from torch import nn
import torch.nn.functi... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/ppo.py |
import copy
from pathlib import Path
from tqdm import tqdm
from beartype import beartype
from beartype.typing import Tuple, Optional
import torch
from torch import nn
import torch.nn.functional as F
from einops import rearrange, repeat, reduce, pack, unpack
from einops.layers.torch import Rearrange, Reduce
from pal... | PaLM-rlhf-pytorch-main | palm_rlhf_pytorch/reward.py |
# --------------------------------------------------------
# SEEM -- Segment Everything Everywhere All At Once
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected]), Jianwei Yang ([email protected])
# ---------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/app.py |
from .interactive import interactive_infer_video, interactive_infer_image | Segment-Everything-Everywhere-All-At-Once-main | demo_code/tasks/__init__.py |
# --------------------------------------------------------
# SEEM -- Segment Everything Everywhere All At Once
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected])
# --------------------------------------------------------
import torch
i... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/tasks/interactive.py |
# --------------------------------------------------------
# X-Decoder -- Generalized Decoding for Pixel, Image, and Language
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected])
# --------------------------------------------------------
... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/BaseModel.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .architectures import build_model | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/__init__.py |
from .registry import model_entrypoints
from .registry import is_model
from .xdecoder_head import *
def build_xdecoder_head(config, *args, **kwargs):
model_name = config['MODEL']['HEAD']
if not is_model(model_name):
raise ValueError(f'Unkown model: {model_name}')
body = model_entrypoints(model_n... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/build.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# --------------------------------------------------------
# X-Decoder -- Generalized Decoding for Pixel, Image, and Language
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected]), Jianwe... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/xdecoder_head.py |
_model_entrypoints = {}
def register_body(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_name in... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/registry.py |
from .build import build_xdecoder_head | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/transformer.py
"""
Transformer class.
Copy-paste from torch.nn.Transformer with modifications:
* positional encodings are passed in MHattention
* extra LN at the end of... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/transformer_blocks.py |
from .registry import model_entrypoints
from .registry import is_model
from .transformer_encoder_fpn import *
# from .transformer_encoder_deform import *
def build_encoder(config, *args, **kwargs):
model_name = config['MODEL']['ENCODER']['NAME']
if not is_model(model_name):
raise ValueError(f'Unkown ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/build.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from typing import Callable, Dict, List, Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_
from torch.cuda.amp import ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/transformer_encoder_fpn.py |
_model_entrypoints = {}
def register_encoder(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_name ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/registry.py |
from .build import build_encoder | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from typing import Callable, Dict, List, Optional, Tuple, Union
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import xavier_uniform_, constant_, u... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/transformer_encoder_deform.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/test.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/setup.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/functions/ms_deform_attn_func.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/functions/__init__.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/modules/ms_deform_attn.py |
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/encoder/ops/modules/__init__.py |
from .registry import model_entrypoints
from .registry import is_model
from .seem import *
def build_decoder(config, *args, **kwargs):
model_name = config['MODEL']['DECODER']['NAME']
if not is_model(model_name):
raise ValueError(f'Unkown model: {model_name}')
return model_entrypoints(model_name)... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/build.py |
# --------------------------------------------------------
# SEEM -- Segment Everything Everywhere All At Once
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected]), Jianwei Yang ([email protected])
# ---------------------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/seem.py |
_model_entrypoints = {}
def register_decoder(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_name ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/registry.py |
from .build import build_decoder | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/__init__.py |
from .utils import *
from .attention_data_struct import *
from .attn import * | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/utils/__init__.py |
# --------------------------------------------------------
# X-Decoder -- Generalized Decoding for Pixel, Image, and Language
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected])
# --------------------------------------------------------
... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/utils/attention_data_struct.py |
import torch
import copy
from torch import nn, Tensor
import os
import math
import torch.nn.functional as F
from torch import nn
def rand_sample(x, max_len):
if x.shape[1] <= max_len:
return x
else:
rand_idx = torch.randperm(x.shape[1])[:max_len]
return x[:,rand_idx]
def prepare_feat... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/utils/utils.py |
from typing import Callable, List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch.nn import Parameter
from torch.nn.modules.linear import Linear
from torch.nn.init import xavier_uniform_, constant_
from torch.overrides import (
has_torch_function, has_torch_function_unary, has_torch_functi... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/body/decoder/utils/attn.py |
from .registry import model_entrypoints
from .registry import is_model
def build_model(config, **kwargs):
model_name = config['MODEL']['NAME']
if not is_model(model_name):
raise ValueError(f'Unkown model: {model_name}')
return model_entrypoints(model_name)(config, **kwargs) | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/architectures/build.py |
_model_entrypoints = {}
def register_model(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_name in... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/architectures/registry.py |
# --------------------------------------------------------
# SEEM -- Segment Everything Everywhere All At Once
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected])
# --------------------------------------------------------
import random
... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/architectures/seem_model.py |
from .seem_model import *
from .build import build_model | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/architectures/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# Modified by Bowen Cheng from https://github.com/facebookresearch/detr/blob/master/util/misc.py
# Modified by Xueyan Zou
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
from typing import List, Optional
import to... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/utils/misc.py |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import functools
import inspect
def configurable(init_func=None, *, from_config=None):
"""
Decorate a function or a class's __init__ method so that it can be called
with a :class:`CfgNode` object using a :func:`from_config` functio... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/utils/config.py |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utilities for bounding box manipulation and GIoU.
"""
import torch
from torchvision.ops.boxes import box_area
def box_cxcywh_to_xyxy(x):
x_c, y_c, w, h = x.unbind(-1)
b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
(x_c + 0.5 * w), (y_... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/utils/box_ops.py |
from .config import *
from .misc import *
from .box_ops import *
from .it_contrastive import * | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/utils/__init__.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
def is_dist_initialized():
return torch.distributed.is_initialized()
def get_world_size():
if is_dist_initialized():
return torch.distributed.get_world_size()
return 1
def all_gather_grad(x):
if get_world_size() > 1:
a... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/utils/it_contrastive.py |
from .registry import model_entrypoints
from .registry import is_model
def build_language_encoder(config, **kwargs):
model_name = config['MODEL']['TEXT']['ARCH']
if not is_model(model_name):
raise ValueError(f'Unkown model: {model_name}')
return model_entrypoints(model_name)(config, **kwargs) | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/build.py |
import random
import nltk
nltk.data.path.append('/mnt/data/nltk_data')
import numpy as np
from utils.constants import IMAGENET_DEFAULT_TEMPLATES
def get_tag(tokenized, tags):
if not isinstance(tags, (list, tuple)):
tags = [tags]
ret = []
for (word, pos) in nltk.pos_tag(tokenized):
for ta... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/misc.py |
_model_entrypoints = {}
def register_model(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_name in... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/registry.py |
from .fixvlpencoder import *
from .vlpencoder import *
from .build import build_language_encoder | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/__init__.py |
import pickle
from distutils import log
import torch
import torch.nn.functional as F
import torch.distributed as dist
from einops import rearrange, repeat
from timm.loss import SoftTargetCrossEntropy
soft_cross_entropy = SoftTargetCrossEntropy()
def is_dist_initialized():
return torch.distributed.is_initialized... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/loss.py |
# --------------------------------------------------------
# X-Decoder -- Generalized Decoding for Pixel, Image, and Language
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Xueyan Zou ([email protected]), Jianwei Yang ([email protected])
# ------------------... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/vlpencoder.py |
from importlib.metadata import requires
import torch
import torch.nn as nn
from .registry import register_model
from .vlpencoder import LanguageEncoder
class FixLanguageEncoder(LanguageEncoder):
def __init__(
self,
*args, **kwargs):
super(FixLanguageEncoder, self).__init__(*args, **kwargs... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/fixvlpencoder.py |
import os
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers import AutoTokenizer
from .registry import lang_encoders
from .registry import is_lang_encoder
def build_lang_encoder(config_encoder, tokenizer, verbose, **kwargs):
model_name = config_encoder['NAME']
if not is_lang_encod... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/LangEncoder/build.py |
_lang_encoders = {}
def register_lang_encoder(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_lang_encoders[model_name] = fn
return fn
def lang_encoders(model_name):
return _lang_encoders[model_name]
def is_lang_encoder(model_name):
return model_name... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/LangEncoder/registry.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .build import build_lang_encoder
from .build import build_tokenizer
from .transformer import * | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/LangEncoder/__init__.py |
from collections import OrderedDict
from typing import Tuple, Union
import logging
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from timm.models.layers import DropPath, trunc_normal_
from .registry import register_lang_encoder
from utils.distributed import is_main_pr... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/language/LangEncoder/transformer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from torch.nn import functional as F
from detectron2.layers import cat, shapes_to_tensor
from detectron2.structures import BitMasks, Boxes
# from ..layers import cat, shapes_to_tensor
# from ..structures import BitMasks, Boxes
"""
Shape shorthand in thi... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/modules/point_features.py |
# Code copy from PyTorch, modified by Xueyan Zou
import warnings
from typing import Optional, Tuple
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
from torch.nn.parameter import Parameter
from torch.overrides import has_torch_function, ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/modules/attention.py |
# Copyright (c) Facebook, Inc. and its affiliates.
## Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/position_encoding.py
"""
Various positional encodings for the transformer.
"""
import math
import torch
from torch import nn
class PositionEmbeddingSine(nn.Module):
"""
... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/modules/position_encoding.py |
from .position_encoding import *
from .attention import *
from .postprocessing import *
from .point_features import * | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/modules/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from torch.nn import functional as F
from detectron2.structures import Instances, ROIMasks
# perhaps should rename to "resize_instance"
def detector_postprocess(
results: Instances, output_height: int, output_width: int, mask_threshold: float = 0.5
... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/modules/postprocessing.py |
from .registry import model_entrypoints
from .registry import is_model
from .backbone import *
def build_backbone(config, **kwargs):
model_name = config['MODEL']['BACKBONE']['NAME']
if not is_model(model_name):
raise ValueError(f'Unkown model: {model_name}')
return model_entrypoints(model_name)(c... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/build.py |
import os
import itertools
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from collections import OrderedDict
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from detectron2.utils.file_io import PathMan... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/davit.py |
# --------------------------------------------------------
# FocalNet for Semantic Segmentation
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Jianwei Yang
# --------------------------------------------------------
import math
import time
import numpy as np
import... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/focal.py |
_model_entrypoints = {}
def register_backbone(fn):
module_name_split = fn.__module__.split('.')
model_name = module_name_split[-1]
_model_entrypoints[model_name] = fn
return fn
def model_entrypoints(model_name):
return _model_entrypoints[model_name]
def is_model(model_name):
return model_nam... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/registry.py |
# --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu, Yutong Lin, Yixuan Wei
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliate... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/swin.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch.nn as nn
from detectron2.modeling import ShapeSpec
__all__ = ["Backbone"]
class Backbone(nn.Module):
"""
Abstract base class for network backbones.
"""
def __init__(self):
"""
The `__init__` method of any subclass can s... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/backbone.py |
# --------------------------------------------------------
# FocalNet for Semantic Segmentation
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Jianwei Yang
# --------------------------------------------------------
import math
import time
import numpy as np
import... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/focal_dw.py |
from .build import build_backbone
from .resnet import *
from .swin import *
from .focal import *
from .focal_dw import *
from .backbone import *
from .davit import * | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import pickle
import numpy as np
from typing import Any, Dict
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn.functional as F
from torch import nn
from .backbone import Backbone
from .registry import register_backbone
from detectron2.layers ... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/xdecoder/backbone/resnet.py |
"""SAMPLING ONLY."""
import torch
import numpy as np
from tqdm import tqdm
from functools import partial
from .util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.mod... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/utils/ddim.py |
import math
import numpy as np
def get_prompt_templates():
prompt_templates = [
'{}.',
'a photo of a {}.',
'a bad photo of a {}.',
'a photo of many {}.',
'a sculpture of a {}.',
'a photo of the hard to see {}.',
'a low resolution photo of the {}.',
'a... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/utils/misc.py |
from fvcore.common.config import CfgNode as _CfgNode
class CfgNode(_CfgNode):
"""
The same as `fvcore.common.config.CfgNode`, but different in:
1. Use unsafe yaml loading by default.
Note that this may lead to arbitrary code execution: you must not
load a config file from untrusted sources b... | Segment-Everything-Everywhere-All-At-Once-main | demo_code/utils/Config.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.