id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
31,825
import logging import json from typing import Dict from omegaconf import OmegaConf from minigpt4.common.registry import registry class ConfigValidator: """ This is a preliminary implementation to centralize and validate the configuration. May be altered in the future. A helper class to validate configur...
null
31,826
import math from minigpt4.common.registry import registry The provided code snippet includes necessary dependencies for implementing the `cosine_lr_schedule` function. Write a Python function `def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr)` to solve the following problem: Decay the learning rate ...
Decay the learning rate
31,827
import math from minigpt4.common.registry import registry The provided code snippet includes necessary dependencies for implementing the `warmup_lr_schedule` function. Write a Python function `def warmup_lr_schedule(optimizer, step, max_step, init_lr, max_lr)` to solve the following problem: Warmup the learning rate ...
Warmup the learning rate
31,828
import math from minigpt4.common.registry import registry The provided code snippet includes necessary dependencies for implementing the `step_lr_schedule` function. Write a Python function `def step_lr_schedule(optimizer, epoch, init_lr, min_lr, decay_rate)` to solve the following problem: Decay the learning rate He...
Decay the learning rate
31,829
import datetime import logging import time from collections import defaultdict, deque import torch import torch.distributed as dist from minigpt4.common import dist_utils def setup_logger(): logging.basicConfig( level=logging.INFO if dist_utils.is_main_process() else logging.WARN, format="%(asctime...
null
31,830
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithP...
Make causal mask used for bi-directional self-attention.
31,831
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithP...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
31,832
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithP...
null
31,833
import os import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import drop_path, to_2tuple, trunc_normal_ from timm.models.registry import register_model from minigpt4.common.dist_utils import dow...
null
31,834
import os import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import drop_path, to_2tuple, trunc_normal_ from timm.models.registry import register_model from minigpt4.common.dist_utils import dow...
null
31,835
import logging import os import numpy as np import torch import torch.nn as nn from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized from minigpt4.common.utils import get_abs_path, is_url from omegaconf import OmegaConf class GatherLayer(torch.autograd.Function): """ Gather ...
Performs all_gather operation on the provided tensors. Graph remains connected for backward grad computation.
31,836
import logging import os import numpy as np import torch import torch.nn as nn from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized from minigpt4.common.utils import get_abs_path, is_url from omegaconf import OmegaConf def is_dist_avail_and_initialized(): if not dist.is_availa...
Performs all_gather operation on the provided tensors. *** Warning ***: torch.distributed.all_gather has no gradient.
31,837
import logging import os import numpy as np import torch import torch.nn as nn from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized from minigpt4.common.utils import get_abs_path, is_url from omegaconf import OmegaConf def tile(x, dim, n_tile): init_dim = x.size(dim) repea...
null
31,838
import contextlib import logging import os import time import datetime import torch import torch.nn as nn import torch.distributed as dist import torch.nn.functional as F import minigpt4.common.dist_utils as dist_utils from minigpt4.common.dist_utils import download_cached_file from minigpt4.common.utils import is_url ...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
31,839
import contextlib import logging import os import time import datetime import torch import torch.nn as nn import torch.distributed as dist import torch.nn.functional as F import minigpt4.common.dist_utils as dist_utils from minigpt4.common.dist_utils import download_cached_file from minigpt4.common.utils import is_url ...
null
31,840
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) de...
null
31,841
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) cl...
null
31,842
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) cla...
null
31,843
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) de...
null
31,844
from decord import VideoReader from decord import cpu import numpy as np import torchvision.transforms as transforms from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) def loadvideo_decord(sample, sample_rate_scale=1,new_width=384, new_height=384, clip_len=8, fr...
null
31,845
from decord import VideoReader from decord import cpu import numpy as np import torchvision.transforms as transforms from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) def loadvideo_decord_origin(sample, sample_rate_scale=1,new_width=384, new_height=384, clip_le...
null
31,846
from langchain.agents.initialize import initialize_agent from langchain.agents.tools import Tool from langchain.chains.conversation.memory import ConversationBufferMemory from langchain.llms.openai import OpenAI import re import gradio as gr import openai def cut_dialogue_history(history_memory, keep_last_n_words=400)...
null
31,847
import os import numpy as np import random import torch import torchvision.transforms as transforms from PIL import Image from models.tag2text import tag2text_caption from util import * import gradio as gr from chatbot import * from load_internvideo import * device = torch.device('cuda' if torch.cuda.is_available() els...
null
31,848
import os import numpy as np import random import torch import torchvision.transforms as transforms from PIL import Image from models.tag2text import tag2text_caption from util import * import gradio as gr from chatbot import * from load_internvideo import * from simplet5 import SimpleT5 from models.grit_model import D...
null
31,851
import warnings from models.vit import VisionTransformer, interpolate_pos_embed from models.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.funct...
null
31,852
import warnings from models.vit import VisionTransformer, interpolate_pos_embed from models.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.funct...
null
31,853
import warnings from models.vit import VisionTransformer, interpolate_pos_embed from models.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.funct...
null
31,854
import warnings from models.vit import VisionTransformer, interpolate_pos_embed from models.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.funct...
null
31,873
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn from functools import partial from detectron2.layers import CNNBlockBase, Conv2d, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers import ShapeSpec from centernet.mod...
null
31,883
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
31,884
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
31,885
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
31,901
import contextlib from unittest import mock import torch from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.modeling.roi_heads import keypoint_head, mask_head from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers from .c10 import ( Caffe...
null
31,918
import collections import contextlib import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_p...
null
31,958
import os from detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco import load_sem_seg, r...
null
32,077
import cv2 import torch from torch import nn from detectron2.utils.comm import get_world_size from detectron2.structures import pairwise_iou, Boxes import torch.nn.functional as F import numpy as np from detectron2.structures import Boxes, ImageList, Instances def get_world_size() -> int: def reduce_sum(tensor): ...
null
32,083
import cv2 import numpy as np import torch import torch.nn.functional as F COLORS = ((np.random.rand(1300, 3) * 0.4 + 0.6) * 255).astype( np.uint8).reshape(1300, 1, 1, 3) def _imagelist_to_tensor(images): images = [x for x in images] image_sizes = [x.shape[-2:] for x in images] h = max([size[0] for size i...
null
32,089
import argparse import glob import multiprocessing as mp import numpy as np import os import tempfile import time import warnings import cv2 import tqdm from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from predictor import Vis...
null
32,120
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) cl...
null
32,121
from intern_action import intern_action_b16 from huggingface_hub import hf_hub_download import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np from transforms import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, ToTorchFormatTensor ) cla...
null
32,125
import os import numpy as np import random import torch import torchvision.transforms as transforms from PIL import Image from models.tag2text import tag2text_caption from util import * import gradio as gr from stablelm import * from load_internvideo import * device = torch.device('cuda' if torch.cuda.is_available() el...
null
32,126
import os import numpy as np import random import torch import torchvision.transforms as transforms from PIL import Image from models.tag2text import tag2text_caption from util import * import gradio as gr from stablelm import * from load_internvideo import * from models.grit_model import DenseCaptioning with gr.Blocks...
null
32,127
import os from collections import OrderedDict from timm.models.layers import DropPath import torch from torch import nn from torch.nn import MultiheadAttention import torch.nn.functional as F import torch.utils.checkpoint as checkpoint _MODELS = { "ViT-B/16": os.path.join(MODEL_PATH, "vit_b16.pth"), "ViT-L/14":...
null
32,135
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.vision_transformer import _cfg, PatchEmbed from timm.models.registry import register_model from timm.models.layers import trunc_normal_, DropPath from timm.models.helpers import named_apply, adapt_input_con...
null
32,138
import numpy as np from scipy import interpolate import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ def interpolate_relative_pos_embed(rel_pos_bias, dst_num_pos, param_name=''): # from: https://github.com/microsoft/unilm/...
null
32,146
import operator import torch import torch.utils.data from detectron2.utils.comm import get_world_size from detectron2.config import configurable from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset from detectron2.data.dataset_mapper import DatasetMap...
null
32,165
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
32,166
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
32,167
import argparse import multiprocessing as mp import os import time import cv2 import tqdm import sys from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger from centernet.config import add_centernet_config from models.grit_src.grit.c...
null
32,192
import functools import io import struct import types import torch from detectron2.modeling import meta_arch from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import keypoint_head from detectron2.structures import Boxes, ImageList, Instances, RotatedBoxes from .c10 impor...
null
32,213
from __future__ import absolute_import, division, print_function, unicode_literals import torch The provided code snippet includes necessary dependencies for implementing the `pairwise_iou_rotated` function. Write a Python function `def pairwise_iou_rotated(boxes1, boxes2)` to solve the following problem: Return inter...
Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x_center, y_center, width, height, angle) format. Arguments: boxes1 (Tensor[N, 5]) boxes2 (Tensor[M, 5]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes...
32,222
import logging import numpy as np from typing import List, Union import pycocotools.mask as mask_util import torch from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) from detectron2....
Read an image into the given format. Will apply rotation and flipping if the image has such exif information. Args: file_name (str): image file path format (str): one of the supported image modes in PIL, or "BGR" or "YUV-BT.601". Returns: image (np.ndarray): an HWC image in the given format, which is 0-255, uint8 for s...
32,241
import os from detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco import load_sem_seg, r...
null
32,245
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from detectron2.config import configurable from detectron2.structur...
null
32,246
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from detectron2.config import configurable from detectron2.structur...
Build a dataloader for object detection with some default features. Args: dataset (list or torch.utils.data.Dataset): a list of dataset dicts, or a pytorch dataset (either map-style or iterable). It can be obtained by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. mapper (callable): a callable...
32,248
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from detectron2.config import configurable from detectron2.structur...
Similar to `build_detection_train_loader`, with default batch size = 1, and sampler = :class:`InferenceSampler`. This sampler coordinates all workers to produce the exact set of all samples. Args: dataset: a list of dataset dicts, or a pytorch dataset (either map-style or iterable). They can be obtained by using :func:...
32,255
import torch from torch.nn import functional as F from detectron2.structures import Instances, ROIMasks The provided code snippet includes necessary dependencies for implementing the `detector_postprocess` function. Write a Python function `def detector_postprocess( results: Instances, output_height: int, output_w...
Resize the output instances. The input images are often resized when entering an object detector. As a result, we often need the outputs of the detector in a different resolution from its inputs. This function will resize the raw outputs of an R-CNN detector to produce outputs according to the desired output resolution...
32,272
import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from detectron2.layers import ShapeSpec from detectron2.s...
null
32,282
from typing import List import torch from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate from detectron2.structures import Instances, heatmaps_to_keypoints from detectron2.utils.events import get_eve...
Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) and add it to the `pred_instances` as a `pred_keypoints` field. Args: pred_keypoint_logits (Tensor): A tensor of shape (R, K, S, S) where R is the total number of instances in the batch, K is the number of keypoints, and S is the ...
32,307
import dataclasses import logging from collections import abc from typing import Any from detectron2.utils.registry import _convert_target_to_string, locate def locate(name: str) -> Any: """ Locate and return an object ``x`` using an input string ``{x.__module__}.{x.__qualname__}``, such as "module.submodu...
Recursively instantiate objects defined in dictionaries by "_target_" and arguments. Args: cfg: a dict-like object with "_target_" that defines the caller, and other keys that define the arguments Returns: object instantiated by cfg
32,315
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import detectron2.data.transforms as T fro...
Create a DistributedDataParallel model if there are >1 processes. Args: model: a torch.nn.Module fp16_compression: add fp16 compression hooks to the ddp object. See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook kwargs: other argu...
32,318
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import detectron2.data.transforms as T fro...
Build a list of :class:`EventWriter` to be used. It now consists of a :class:`CommonMetricPrinter`, :class:`TensorboardXWriter` and :class:`JSONWriter`. Args: output_dir: directory to store JSON metrics and tensorboard events max_iter: the total number of iterations Returns: list[EventWriter]: a list of :class:`EventWr...
32,322
import datetime import json import logging import os import time from collections import defaultdict from contextlib import contextmanager from typing import Optional import torch from fvcore.common.history_buffer import HistoryBuffer from detectron2.utils.file_io import PathManager _CURRENT_STORAGE_STACK = [] The pro...
Returns: The :class:`EventStorage` object that's currently being used. Throws an error if no :class:`EventStorage` is currently enabled.
32,323
import importlib import numpy as np import os import re import subprocess import sys from collections import defaultdict import PIL import torch import torchvision from tabulate import tabulate def collect_torch_env(): try: import torch.__config__ return torch.__config__.show() except ImportErro...
null
32,325
import functools import numpy as np import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() The provided code snippet includes necessary dependencies f...
Returns: The rank of the current process within the local (per-machine) process group.
32,327
import functools import numpy as np import torch import torch.distributed as dist def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def is_main_process() -> bool: return get_rank() == 0
null
32,328
import functools import numpy as np import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() The provided code snippet includes necessary dependencies for implementing ...
Helper function to synchronize (barrier) among all processes when using distributed training
32,331
import functools import numpy as np import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not dist.is_available(): return 0 ...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same keys as input_dict, after reduction.
32,332
from typing import Any import pydoc from fvcore.common.registry import Registry def locate(name: str) -> Any: """ Locate and return an object ``x`` using an input string ``{x.__module__}.{x.__qualname__}``, such as "module.submodule.class_name". Raise Exception if it cannot be found. """ obj = ...
Inverse of ``locate()``. Args: t: any object with ``__module__`` and ``__qualname__``
32,337
import typing from typing import Any, List import fvcore from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table from torch import nn from detectron2.export import TracingAdapter ACTIVATIONS_MODE = "activations" def _wrapper_count_operators( model: nn.Module, inputs: list, mode: s...
Implement operator-level activations counting using jit. This is a wrapper of fvcore.nn.activation_count, that supports standard detection models in detectron2. Note: The function runs the input through the model to compute activations. The activations of a detection model is often input-dependent, for example, the act...
32,340
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from detectron2.utils.file_io import PathManager class _ColorfulFormatter(logging.Formatter): def __init__(self, *args, **kwargs): ...
Initialize the detectron2 logger and set its verbosity level to "DEBUG". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logg...
32,341
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from detectron2.utils.file_io import PathManager def _find_caller(): """ Returns: str: module name of the caller ...
Log only for the first n times. Args: lvl (int): the logging level msg (str): n (int): name (str): name of the logger to use. Will use the caller's module by default. key (str or tuple[str]): the string(s) can be one of "caller" or "message", which defines how to identify duplicated logs. For example, if called with `n...
32,343
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from detectron2.utils.file_io import PathManager def _find_caller(): """ Returns: str: module name of the caller ...
Log no more than once per n seconds. Args: lvl (int): the logging level msg (str): n (int): name (str): name of the logger to use. Will use the caller's module by default.
32,344
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from detectron2.utils.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `create...
Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. Args: small_dict (dict): a result dictionary of only a few items. Returns: str: the table as a string.
32,345
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from detectron2.utils.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `_log_a...
Internal function used to log the usage of different detectron2 components inside facebook's infra.
32,350
import logging import numpy as np import pycocotools.mask as mask_util import torch from fvcore.common.file_io import PathManager from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) f...
Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation]
32,354
import copy import logging import numpy as np import operator import torch import torch.utils.data import json from detectron2.utils.comm import get_world_size from detectron2.data import samplers from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset f...
Modified from detectron2.data.build.build_custom_train_loader, but supports different samplers
32,391
from detectron2.config import CfgNode as CN def add_centernet_config(cfg): _C = cfg _C.MODEL.CENTERNET = CN() _C.MODEL.CENTERNET.NUM_CLASSES = 80 _C.MODEL.CENTERNET.IN_FEATURES = ["p3", "p4", "p5", "p6", "p7"] _C.MODEL.CENTERNET.FPN_STRIDES = [8, 16, 32, 64, 128] _C.MODEL.CENTERNET.PRIOR_PROB ...
null
32,414
import logging import numpy as np from collections import Counter import tqdm from fvcore.nn import flop_count_table from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import CfgNode, LazyConfig, get_cfg, instantiate from detectron2.data import build_detection_test_loader from detectron2.en...
null
32,424
import itertools import logging import psutil import torch import tqdm from fvcore.common.timer import Timer from torch.nn.parallel import DistributedDataParallel from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import LazyConfig, get_cfg, instantiate from detectron2.data import ( Data...
null
32,427
from PIL import Image import torch from transformers import StoppingCriteria, StoppingCriteriaList from enum import auto, Enum import numpy as np from decord import VideoReader, cpu import torchvision.transforms as T from models.video_transformers import ( GroupNormalize, GroupScale, GroupCenterCrop, Stack, To...
null
32,428
import random import io import av import cv2 import decord import imageio from decord import VideoReader import torch import numpy as np import math import logging def get_frame_indices_by_fps(): pass
null
32,429
import random import io import av import cv2 import decord import imageio from decord import VideoReader import torch import numpy as np import math import logging def get_pyav_video_duration(video_reader): video_stream = video_reader.streams.video[0] video_duration = pts_to_secs( video_stream.duration,...
null
32,430
import random import io import av import cv2 import decord import imageio from decord import VideoReader import torch import numpy as np import math import logging def get_frame_indices(num_frames, vlen, sample='rand', fix_start=None, input_fps=1, max_num_frames=-1): def read_frames_gif( video_path, num_frames...
null
32,431
import random import io import av import cv2 import decord import imageio from decord import VideoReader import torch import numpy as np import math import logging def get_frame_indices(num_frames, vlen, sample='rand', fix_start=None, input_fps=1, max_num_frames=-1): if sample in ["rand", "middle"]: # uniform sampl...
null
32,432
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
null
32,433
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
[summary] Args: ann_file_list (List[List[str, str]] or List[str, str]): the latter will be automatically converted to the former. Each sublist contains [anno_path, image_root], (or [anno_path, video_root, 'video']) which specifies the data type, video or image Returns: List(dict): each dict is { image: str or List[str]...
32,434
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
null
32,435
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
null
32,436
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
gather results from multiple GPUs
32,437
from utils.distributed import is_main_process, get_rank, get_world_size import logging import torch.distributed as dist import torch import io import os import json import re import numpy as np from os.path import join from tqdm import trange from PIL import Image from PIL import ImageFile from torchvision.transforms i...
Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray) into a (n+1)-d array, only allow the first dim has variable lengths. Args: sequences: list(n-d tensor or list) dtype: np.dtype or torch.dtype device: fixed_length: pad all seq in sequences to fixed length. All seq should have a length <= f...
32,438
import logging import os import json import sqlite3 import random from os.path import basename import numpy as np from dataset.base_dataset import ImageVideoBaseDataset from dataset.utils import load_anno, pre_text from dataset.video_utils import VIDEO_READER_FUNCS from utils.distributed import is_main_process The pro...
TODO: Docstring for get_anno_by_id. Args: cur (sqlite3.Cursor): The dataset cursor. id (int): The annotation id. Returns:
32,439
import datetime import logging import time from os.path import join import pandas as pd import torch import torch.backends.cudnn as cudnn import torch.distributed as dist import wandb from torch.utils.data import ConcatDataset from dataset import MetaLoader, create_dataset, create_loader, create_sampler from models.vid...
null
32,440
import datetime import logging import time from os.path import join import pandas as pd import torch import torch.backends.cudnn as cudnn import torch.distributed as dist import wandb from torch.utils.data import ConcatDataset from dataset import MetaLoader, create_dataset, create_loader, create_sampler from models.vid...
null
32,441
import copy import logging import os import os.path as osp from os.path import join import torch from torch.utils.data import ConcatDataset, DataLoader from utils.optimizer import create_optimizer from utils.scheduler import create_scheduler logger = logging.getLogger(__name__) def create_optimizer(args, model, filter...
null
32,442
import torch import gradio as gr from gradio.themes.utils import colors, fonts, sizes from conversation import Chat from utils.config import Config from utils.easydict import EasyDict from models.videochat import VideoChat class Chat: def __init__(self, model, device='cuda:0'): def ask(self,text,conv): ...
null
32,443
import torch import gradio as gr from gradio.themes.utils import colors, fonts, sizes from conversation import Chat from utils.config import Config from utils.easydict import EasyDict from models.videochat import VideoChat with gr.Blocks(title="InternVideo-VideoChat!",theme=gvlabtheme,css="#chatbot {overflow:auto; heig...
null
32,444
import torch import gradio as gr from gradio.themes.utils import colors, fonts, sizes from conversation import Chat from utils.config import Config from utils.easydict import EasyDict from models.videochat import VideoChat with gr.Blocks(title="InternVideo-VideoChat!",theme=gvlabtheme,css="#chatbot {overflow:auto; heig...
null
32,445
import torch import gradio as gr from gradio.themes.utils import colors, fonts, sizes from conversation import Chat from utils.config import Config from utils.easydict import EasyDict from models.videochat import VideoChat with gr.Blocks(title="InternVideo-VideoChat!",theme=gvlabtheme,css="#chatbot {overflow:auto; heig...
null
32,446
import torch import gradio as gr from gradio.themes.utils import colors, fonts, sizes from conversation import Chat from utils.config import Config from utils.easydict import EasyDict from models.videochat import VideoChat def gradio_answer(chatbot, chat_state, img_list, num_beams, temperature): llm_message,llm_me...
null