id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
32,891
import warnings from collections import OrderedDict from typing import Optional, Union, cast import torch import torch.nn as nn from torch import Tensor from torch.nn.modules import Conv2d, Module The provided code snippet includes necessary dependencies for implementing the `reinit_initial_conv_layer` function. Write...
Clones a Conv2d layer while optionally retaining some of the original weights. When replacing the first convolutional layer in a model with one that operates over different number of input channels, we sometimes want to keep a subset of the kernel weights the same (e.g. the RGB weights of an ImageNet pretrained model)....
32,892
import os from typing import Any, Optional, Union import timm import torch import torch.nn as nn import torch.nn.functional as F from kornia import augmentation as K from torch import Tensor from torchvision.models._api import WeightsEnum from ..models import get_weight from . import utils from .base import BaseTask T...
Computes the normalized mean squared error between x and y. Args: x: tensor x y: tensor y Returns: the normalized MSE between x and y
32,893
import os import warnings from collections.abc import Sequence from typing import Any, Optional, Union import kornia.augmentation as K import lightning import timm import torch import torch.nn as nn import torch.nn.functional as F from lightly.loss import NTXentLoss from lightly.models.modules import MoCoProjectionHead...
Data augmentations used by MoCo. Args: version: Version of MoCo. size: Size of patch to crop. weights: Weight vector for grayscale computation. Returns: Data augmentation pipelines.
32,894
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Download and extract an archive. Args: url: URL to download download_root: directory to download to extract_root: directory to extract to (defaults to ``download_root``) filename: download filename (defaults to basename of ``url``) md5: checksum for download verification
32,895
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Download a dataset from Radiant Earth. Args: dataset_id: the ID of the dataset to fetch download_root: directory to download to api_key: the API key to use for all requests from the session. Can also be passed in via the ``MLHUB_API_KEY`` environment variable, or configured in ``~/.mlhub/profiles``.
32,896
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Download a collection from Radiant Earth. Args: collection_id: the ID of the collection to fetch download_root: directory to download to api_key: the API key to use for all requests from the session. Can also be passed in via the ``MLHUB_API_KEY`` environment variable, or configured in ``~/.mlhub/profiles``.
32,897
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Disambiguate partial timestamps. TorchGeo stores the timestamp of each file in a spatiotemporal R-tree. If the full timestamp isn't known, a file could represent a range of time. For example, in the CDL dataset, each mask spans an entire year. This method returns the maximum possible range of timestamps that ``date_str...
32,898
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Context manager for changing directories. Args: dirname: directory to temporarily change to create: if True, create the destination directory
32,899
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Stack a list of samples along a new axis. Useful for forming a mini-batch of samples to pass to :class:`torch.utils.data.DataLoader`. Args: samples: list of samples Returns: a single sample .. versionadded:: 0.2
32,900
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Concatenate a list of samples along an existing axis. Useful for joining samples in a :class:`torchgeo.datasets.IntersectionDataset`. Args: samples: list of samples Returns: a single sample .. versionadded:: 0.2
32,901
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Merge a list of samples. Useful for joining samples in a :class:`torchgeo.datasets.UnionDataset`. Args: samples: list of samples Returns: a single sample .. versionadded:: 0.2
32,902
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Reverse of :func:`stack_samples`. Useful for turning a mini-batch of samples into a list of samples. These individual samples can then be plotted using a dataset's ``plot`` method. Args: sample: a mini-batch of samples Returns: list of samples .. versionadded:: 0.2
32,903
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Load an image file using rasterio. Args: path: path to the image to be loaded Returns: the image
32,904
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Sort Sentinel-2 band files in the correct order.
32,905
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Overlay a semantic segmentation mask onto an image. Args: image: tensor of shape (3, h, w) and dtype uint8 mask: tensor of shape (h, w) with pixel values representing the classes and dtype bool alpha: alpha blend factor colors: list of RGB int tuples, or color strings e.g. red, #FF00FF Returns: a version of ``image`` o...
32,906
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Converts an RGB colormap mask to a integer mask. Args: rgb: array mask of coded with RGB tuples colors: list of RGB tuples to convert to integer indices Returns: integer array mask
32,907
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Applies percentile normalization to an input image. Specifically, this will rescale the values in the input such that values <= the lower percentile value will be 0 and values >= the upper percentile value will be 1. Using the 2nd and 98th percentile usually results in good visualizations. Args: img: image to normalize...
32,908
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Checks if the given path is pointing to a Virtual File System. .. note:: Does not check if the path exists, or if it is a dir or file. VSI can for instance be Cloud Storage Blobs or zip-archives. They will start with a prefix indicating this. For examples of these, see references for the two accepted syntaxes. * https:...
32,909
from __future__ import annotations import bz2 import collections import contextlib import gzip import lzma import os import sys import tarfile from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast, overload import...
Converts a :class:`numpy.ndarray` to :class:`torch.Tensor`. :func:`torch.from_tensor` rejects numpy types like uint16 that are not supported in pytorch. This function instead casts uint16 and uint32 numpy arrays to an appropriate pytorch type without loss of precision. For example, a uint32 array becomes an int64 tenso...
32,910
from collections.abc import Sequence from copy import deepcopy from itertools import accumulate from math import floor, isclose from typing import Optional, Union, cast from rtree.index import Index, Property from torch import Generator, default_generator, randint, randperm from ..datasets import GeoDataset from .utils...
Split a GeoDataset randomly assigning its index's BoundingBoxes. This function will go through each BoundingBox in the GeoDataset's index and randomly assign it to new GeoDatasets. Args: dataset: dataset to be split lengths: lengths or fractions of splits to be produced generator: (optional) generator used for the rand...
32,911
from collections.abc import Sequence from copy import deepcopy from itertools import accumulate from math import floor, isclose from typing import Optional, Union, cast from rtree.index import Index, Property from torch import Generator, default_generator, randint, randperm from ..datasets import GeoDataset from .utils...
Split a GeoDataset randomly splitting its index's BoundingBoxes. This function will go through each BoundingBox in the GeoDataset's index, split it in a random direction and assign the resulting BoundingBoxes to new GeoDatasets. Args: dataset: dataset to be split fractions: fractions of splits to be produced generator:...
32,912
from collections.abc import Sequence from copy import deepcopy from itertools import accumulate from math import floor, isclose from typing import Optional, Union, cast from rtree.index import Index, Property from torch import Generator, default_generator, randint, randperm from ..datasets import GeoDataset from .utils...
Overlays a grid over a GeoDataset and randomly assigns cells to new GeoDatasets. This function will go through each BoundingBox in the GeoDataset's index, overlay a grid over it, and randomly assign each cell to new GeoDatasets. Args: dataset: dataset to be split fractions: fractions of splits to be produced grid_size:...
32,913
from collections.abc import Sequence from copy import deepcopy from itertools import accumulate from math import floor, isclose from typing import Optional, Union, cast from rtree.index import Index, Property from torch import Generator, default_generator, randint, randperm from ..datasets import GeoDataset from .utils...
Split a GeoDataset intersecting it with a ROI for each desired new GeoDataset. Args: dataset: dataset to be split rois: regions of interest of splits to be produced Returns A list of the subset datasets. .. versionadded:: 0.5
32,914
from collections.abc import Sequence from copy import deepcopy from itertools import accumulate from math import floor, isclose from typing import Optional, Union, cast from rtree.index import Index, Property from torch import Generator, default_generator, randint, randperm from ..datasets import GeoDataset from .utils...
Split a GeoDataset on its time dimension to create non-overlapping GeoDatasets. Args: dataset: dataset to be split lengths: lengths, fractions or pairs of timestamps (start, end) of splits to be produced Returns A list of the subset datasets. .. versionadded:: 0.5
32,915
import glob import os import sys from datetime import datetime, timedelta from typing import Any import numpy as np import pandas as pd from rasterio.crs import CRS from .geo import GeoDataset from .utils import BoundingBox, DatasetNotFoundError The provided code snippet includes necessary dependencies for implementin...
Disambiguate partial timestamps. Based on :func:`torchgeo.datasets.utils.disambiguate_timestamps`. Args: year: year, possibly nan month: month, possibly nan day: day, possibly nan Returns: minimum and maximum possible time range
32,916
import glob import os from typing import Any, Callable, Optional, cast from xml.etree.ElementTree import Element, parse import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import torch from matplotlib.figure import Figure from PIL import Image from torch import Tensor from .geo impor...
Read a PASCAL VOC annotation file. Args: path: path to xml file Returns: dict of image filename, points, and class labels
32,917
import os from typing import Any, Callable, Optional import matplotlib.pyplot as plt import numpy as np import torch from matplotlib import patches from matplotlib.figure import Figure from PIL import Image from torch import Tensor from .geo import NonGeoDataset from .utils import ( DatasetNotFoundError, check_...
Convert coco polygons to mask tensor. Args: segmentations (List[int]): polygon coordinates height (int): image height width (int): image width Returns: Tensor: Mask tensor
32,918
import glob import os from typing import Any, Callable, Optional from xml.etree import ElementTree import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import torch from matplotlib.figure import Figure from PIL import Image from torch import Tensor from .geo import NonGeoDataset from ...
Read a PASCAL VOC annotation file. Args: path: path to xml file Returns: dict of image filename, points, and class labels
32,919
from typing import Any, Callable, Union import torch.nn as nn from torchvision.models._api import WeightsEnum from .resnet import ResNet18_Weights, ResNet50_Weights, resnet18, resnet50 from .swin import Swin_V2_B_Weights, swin_v2_b from .vit import ViTSmall16_Weights, vit_small_patch16_224 _model = { "resnet18": re...
Get an instantiated model from its name. .. versionadded:: 0.4 Args: name: Name of the model. *args: Additional arguments passed to the model builder method. **kwargs: Additional keyword arguments passed to the model builder method. Returns: An instantiated model.
32,920
from typing import Any, Callable, Union import torch.nn as nn from torchvision.models._api import WeightsEnum from .resnet import ResNet18_Weights, ResNet50_Weights, resnet18, resnet50 from .swin import Swin_V2_B_Weights, swin_v2_b from .vit import ViTSmall16_Weights, vit_small_patch16_224 _model_weights = { resnet...
Get the weights enum class associated with a given model. .. versionadded:: 0.4 Args: name: Model builder function or the name under which it is registered. Returns: The weights enum class associated with the model.
32,921
from typing import Any, Callable, Union import torch.nn as nn from torchvision.models._api import WeightsEnum from .resnet import ResNet18_Weights, ResNet50_Weights, resnet18, resnet50 from .swin import Swin_V2_B_Weights, swin_v2_b from .vit import ViTSmall16_Weights, vit_small_patch16_224 The provided code snippet in...
Get the weights enum value by its full name. .. versionadded:: 0.4 Args: name: Name of the weight enum entry. Returns: The requested weight enum.
32,922
from typing import Any, Callable, Union import torch.nn as nn from torchvision.models._api import WeightsEnum from .resnet import ResNet18_Weights, ResNet50_Weights, resnet18, resnet50 from .swin import Swin_V2_B_Weights, swin_v2_b from .vit import ViTSmall16_Weights, vit_small_patch16_224 _model = { "resnet18": re...
List the registered models. .. versionadded:: 0.4 Returns: A list of registered models.
32,923
from typing import Any, Optional import kornia.augmentation as K import timm import torch from timm.models.vision_transformer import VisionTransformer from torchvision.models._api import Weights, WeightsEnum from ..transforms import AugmentationSequential class ViTSmall16_Weights(WeightsEnum): # type: ignore[misc] ...
Vision Transform (ViT) small patch size 16 model. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2010.11929 .. versionadded:: 0.4 Args: weights: Pre-trained model weights to use. *args: Additional arguments to pass to :func:`timm.create_model`. **kwargs: Additional keyw...
32,924
from typing import Any, Optional import kornia.augmentation as K import torch import torchvision from kornia.contrib import Lambda from torchvision.models import SwinTransformer from torchvision.models._api import Weights, WeightsEnum from ..transforms import AugmentationSequential class Swin_V2_B_Weights(WeightsEnum):...
Swin Transformer v2 base model. If you use this model in your research, please cite the following paper: * https://arxiv.org/abs/2111.09883 .. versionadded:: 0.6 Args: weights: Pre-trained model weights to use. *args: Additional arguments to pass to :class:`torchvision.models.swin_transformer.SwinTransformer`. **kwargs...
32,925
from typing import Any, Optional import kornia.augmentation as K import timm import torch from timm.models import ResNet from torchvision.models._api import Weights, WeightsEnum from ..transforms import AugmentationSequential class ResNet18_Weights(WeightsEnum): # type: ignore[misc] """ResNet18 weights. For `t...
ResNet-18 model. If you use this model in your research, please cite the following paper: * https://arxiv.org/pdf/1512.03385.pdf .. versionadded:: 0.4 Args: weights: Pre-trained model weights to use. *args: Additional arguments to pass to :func:`timm.create_model` **kwargs: Additional keywork arguments to pass to :func...
32,926
from typing import Any, Optional import kornia.augmentation as K import timm import torch from timm.models import ResNet from torchvision.models._api import Weights, WeightsEnum from ..transforms import AugmentationSequential class ResNet50_Weights(WeightsEnum): # type: ignore[misc] """ResNet50 weights. For `t...
ResNet-50 model. If you use this model in your research, please cite the following paper: * https://arxiv.org/pdf/1512.03385.pdf .. versionchanged:: 0.4 Switched to multi-weight support API. Args: weights: Pre-trained model weights to use. *args: Additional arguments to pass to :func:`timm.create_model`. **kwargs: Addi...
32,927
import cv2 import einops import numpy as np import torch import random from pytorch_lightning import seed_everything from cldm.model import create_model, load_state_dict from cldm.ddim_hacked import DDIMSampler from cldm.hack import disable_verbosity, enable_sliced_attention from datasets.data_utils import * import al...
null
32,928
import cv2 import einops import numpy as np import torch import random from pytorch_lightning import seed_everything from cldm.model import create_model, load_state_dict from cldm.ddim_hacked import DDIMSampler from cldm.hack import disable_verbosity, enable_sliced_attention from datasets.data_utils import * cv2.setNu...
null
32,929
from pathlib import Path import re from typing import List, Tuple from setuptools import setup, find_packages HERE = Path(__file__).parent try: with open(HERE / "README.md", encoding="utf-8") as f: long_description = "\n" + f.read() except FileNotFoundError: long_description = DESCRIPTION requirements, ...
null
32,930
from pathlib import Path import re from typing import List, Tuple from setuptools import setup, find_packages HERE = Path(__file__).parent try: with open(HERE / "README.md", encoding="utf-8") as f: long_description = "\n" + f.read() except FileNotFoundError: long_description = DESCRIPTION def get_packa...
null
32,931
import torch import torch.nn as nn from torch.nn.init import trunc_normal_ from torch.nn.utils import weight_norm def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True): if nlayers == 1: return nn.Linear(in_dim, bottleneck_dim, bias=bias) else: layers = [nn.Li...
null
32,932
from torch import nn def drop_path(x, drop_prob: float = 0.0, training: bool = False): if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).berno...
null
32,933
from typing import Callable, Optional, Tuple, Union from torch import Tensor import torch.nn as nn def make_2tuple(x): if isinstance(x, tuple): assert len(x) == 2 return x assert isinstance(x, int) return (x, x)
null
32,934
import logging from typing import Callable, List, Any, Tuple, Dict import torch from torch import nn, Tensor from .attention import Attention, MemEffAttention from .drop_path import DropPath from .layer_scale import LayerScale from .mlp import Mlp def drop_add_residual_stochastic_depth( x: Tensor, residual_fun...
null
32,935
import logging from typing import Callable, List, Any, Tuple, Dict import torch from torch import nn, Tensor from .attention import Attention, MemEffAttention from .drop_path import DropPath from .layer_scale import LayerScale from .mlp import Mlp def get_branges_scales(x, sample_drop_ratio=0.0): b, n, d = x.shape ...
null
32,936
import itertools from typing import Any, Optional import warnings import numpy as np import torch from torch.utils.data.sampler import Sampler import dinov2.distributed as distributed def _get_torch_dtype(size: int) -> Any: return torch.int32 if size <= 2**31 else torch.int64 The provided code snippet includes nec...
Generate the indices of a random permutation.
32,937
import itertools from typing import Any, Optional import warnings import numpy as np import torch from torch.utils.data.sampler import Sampler import dinov2.distributed as distributed def _get_numpy_dtype(size: int) -> Any: return np.int32 if size <= 2**31 else np.int64 def _shuffle_tensor_slice( *, tensor: to...
null
32,938
import itertools from typing import Any, Optional import warnings import numpy as np import torch from torch.utils.data.sampler import Sampler import dinov2.distributed as distributed def _new_shuffle_tensor_slice( *, tensor: torch.Tensor, start: int = 0, step: int = 1, generator: torch.Generator ) -> np.ndarray: ...
null
32,939
import itertools from typing import Any, Optional import warnings import numpy as np import torch from torch.utils.data.sampler import Sampler import dinov2.distributed as distributed def _make_seed(seed: int, start: int, iter_count: int) -> int: # NOTE: Tried a few variants (including iter_count << 32), this one ...
null
32,940
from typing import Sequence import torch from torchvision import transforms class MaybeToTensor(transforms.ToTensor): """ Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor, or keep as is if already a tensor. """ def __call__(self, pic): """ Args: pic (PIL Image, numpy.nd...
null
32,941
from typing import Sequence import torch from torchvision import transforms class MaybeToTensor(transforms.ToTensor): """ Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor, or keep as is if already a tensor. """ def __call__(self, pic): """ Args: pic (PIL Image, numpy.nd...
null
32,942
import torch import random def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=None, mask_generator=None): # dtype = torch.half # TODO: Remove n_global_crops = len(samples_list[0][0]["global_crops"]) n_local_crops = len(samples_list[0][0]["local_crops"]) colla...
null
32,943
from dataclasses import dataclass from enum import Enum from functools import lru_cache from gzip import GzipFile from io import BytesIO from mmap import ACCESS_READ, mmap import os from typing import Any, Callable, List, Optional, Set, Tuple import warnings import numpy as np from .extended import ExtendedVisionDatase...
null
32,944
import logging from enum import Enum from typing import Any, Callable, List, Optional, TypeVar import torch from torch.utils.data import Sampler from .datasets import ImageNet, ImageNet22k from .samplers import EpochSampler, InfiniteSampler, ShardedInfiniteSampler def _make_bool_str(b: bool) -> str: return "yes" i...
null
32,945
import logging from enum import Enum from typing import Any, Callable, List, Optional, TypeVar import torch from torch.utils.data import Sampler from .datasets import ImageNet, ImageNet22k from .samplers import EpochSampler, InfiniteSampler, ShardedInfiniteSampler def _make_sample_transform(image_transform: Optional[C...
null
32,946
import logging from enum import Enum from typing import Any, Callable, List, Optional, TypeVar import torch from torch.utils.data import Sampler from .datasets import ImageNet, ImageNet22k from .samplers import EpochSampler, InfiniteSampler, ShardedInfiniteSampler logger = logging.getLogger("dinov2") def _parse_dataset...
Creates a dataset with the specified parameters. Args: dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN). transform: A transform to apply to images. target_transform: A transform to apply to targets. Returns: The created dataset.
32,947
import logging from enum import Enum from typing import Any, Callable, List, Optional, TypeVar import torch from torch.utils.data import Sampler from .datasets import ImageNet, ImageNet22k from .samplers import EpochSampler, InfiniteSampler, ShardedInfiniteSampler logger = logging.getLogger("dinov2") class SamplerType(...
Creates a data loader with the specified parameters. Args: dataset: A dataset (third party, LaViDa or WebDataset). batch_size: The size of batches to generate. num_workers: The number of workers to use. shuffle: Whether to shuffle samples. seed: The random seed to use. sampler_type: Which sampler to use: EPOCH, INFINIT...
32,948
import argparse import logging import math import os from functools import partial from fvcore.common.checkpoint import PeriodicCheckpointer import torch from dinov2.data import SamplerType, make_data_loader, make_dataset from dinov2.data import collate_data_and_cast, DataAugmentationDINO, MaskingGenerator import dinov...
null
32,949
import argparse import logging import math import os from functools import partial from fvcore.common.checkpoint import PeriodicCheckpointer import torch from dinov2.data import SamplerType, make_data_loader, make_dataset from dinov2.data import collate_data_and_cast, DataAugmentationDINO, MaskingGenerator import dinov...
null
32,950
import argparse import logging import os from pathlib import Path from typing import List, Optional import submitit from dinov2.utils.cluster import ( get_slurm_executor_parameters, get_slurm_partition, get_user_checkpoint_path, ) def get_args_parser( description: Optional[str] = None, parents: Opt...
null
32,951
import argparse import logging import os from pathlib import Path from typing import List, Optional import submitit from dinov2.utils.cluster import ( get_slurm_executor_parameters, get_slurm_partition, get_user_checkpoint_path, ) logger = logging.getLogger("dinov2") def get_shared_folder() -> Path: use...
null
32,952
import torch import torch.distributed as dist import torch.nn.functional as F from torch import nn import logging def lossfunc(t, s, temp): s = s.float() t = t.float() if s.ndim == 2: return -cross_entropy(s.unsqueeze(0), t.unsqueeze(0), temp, bw_inplace=True).squeeze(0) eli...
null
32,953
import torch import torch.distributed as dist import torch.nn.functional as F from torch import nn import logging def lossfunc(t, s, temp): return torch.sum(t * F.log_softmax(s / temp, dim=-1), dim=-1)
null
32,954
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block de...
null
32,955
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block Th...
ViT weight initialization, original timm impl (for reproducibility)
32,956
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block cla...
null
32,957
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block cla...
null
32,958
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block cla...
null
32,959
from functools import partial import math import logging from typing import Sequence, Tuple, Union, Callable import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn.init import trunc_normal_ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block cla...
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
32,960
from collections import defaultdict import logging logger = logging.getLogger("dinov2") def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12, force_is_backbone=False, chunked_blocks=False): """ Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. ...
null
32,961
from collections import defaultdict import logging def fuse_params_groups(all_params_groups, keys=("lr_multiplier", "wd_multiplier", "is_last_layer")): fused_params_groups = defaultdict(lambda: {"params": []}) for d in all_params_groups: identifier = "" for k in keys: identifier += ...
null
32,962
import logging import os import random import subprocess from urllib.parse import urlparse import numpy as np import torch from torch import nn logger = logging.getLogger("dinov2") def load_pretrained_weights(model, pretrained_weights, checkpoint_key): if urlparse(pretrained_weights).scheme: # If it looks like an...
null
32,963
import logging import os import random import subprocess from urllib.parse import urlparse import numpy as np import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `fix_random_seeds` function. Write a Python function `def fix_random_seeds(seed=31)` to solve th...
Fix random seeds.
32,964
import logging import os import random import subprocess from urllib.parse import urlparse import numpy as np import torch from torch import nn def get_sha(): cwd = os.path.dirname(os.path.abspath(__file__)) def _run(command): return subprocess.check_output(command, cwd=cwd).decode("ascii").strip() ...
null
32,965
import logging import os import random import subprocess from urllib.parse import urlparse import numpy as np import torch from torch import nn def has_batchnorms(model): bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) for name, module in model.named_modules(): if isinstan...
null
32,966
import math import logging import os from omegaconf import OmegaConf import dinov2.distributed as distributed from dinov2.logging import setup_logging from dinov2.utils import utils from dinov2.configs import dinov2_default_config def apply_scaling_rules_to_cfg(cfg): # to fix if cfg.optim.scaling_rule == "sqrt_wrt...
Create configs and perform basic setups.
32,967
from enum import Enum import os from pathlib import Path from typing import Any, Dict, Optional class ClusterType(Enum): def get_checkpoint_path(cluster_type: Optional[ClusterType] = None) -> Optional[Path]: def get_user_checkpoint_path(cluster_type: Optional[ClusterType] = None) -> Optional[Path]: checkpoint_path...
null
32,968
from enum import Enum import os from pathlib import Path from typing import Any, Dict, Optional class ClusterType(Enum): def get_cluster_type(cluster_type: Optional[ClusterType] = None) -> Optional[ClusterType]: def get_slurm_partition(cluster_type: Optional[ClusterType] = None) -> Optional[str]: def get_slurm_executo...
null
32,969
from typing import Dict, Union import numpy as np import torch TypeSpec = Union[str, np.dtype, torch.dtype] _NUMPY_TO_TORCH_DTYPE: Dict[np.dtype, torch.dtype] = { np.dtype("bool"): torch.bool, np.dtype("uint8"): torch.uint8, np.dtype("int8"): torch.int8, np.dtype("int16"): torch.int16, np.dtype("int...
null
32,970
import argparse from typing import Any, List, Optional, Tuple import torch import torch.backends.cudnn as cudnn from dinov2.models import build_model_from_cfg from dinov2.utils.config import setup import dinov2.utils.utils as dinov2_utils def get_args_parser( description: Optional[str] = None, parents: Optiona...
null
32,971
import argparse from typing import Any, List, Optional, Tuple import torch import torch.backends.cudnn as cudnn from dinov2.models import build_model_from_cfg from dinov2.utils.config import setup import dinov2.utils.utils as dinov2_utils def get_autocast_dtype(config): teacher_dtype_str = config.compute_precision....
null
32,972
import logging from typing import Dict, Optional import torch from torch import nn from torchmetrics import MetricCollection from dinov2.data import DatasetWithEnumeratedTargets, SamplerType, make_data_loader import dinov2.distributed as distributed from dinov2.logging import MetricLogger logger = logging.getLogger("di...
null
32,973
import logging from typing import Dict, Optional import torch from torch import nn from torchmetrics import MetricCollection from dinov2.data import DatasetWithEnumeratedTargets, SamplerType, make_data_loader import dinov2.distributed as distributed from dinov2.logging import MetricLogger def extract_features_with_data...
null
32,974
import argparse import gc import logging import sys import time from typing import List, Optional from cuml.linear_model import LogisticRegression import torch import torch.backends.cudnn as cudnn import torch.distributed from torch import nn from torch.utils.data import TensorDataset from torchmetrics import MetricTra...
null
32,975
import argparse import gc import logging import sys import time from typing import List, Optional from cuml.linear_model import LogisticRegression import torch import torch.backends.cudnn as cudnn import torch.distributed from torch import nn from torch.utils.data import TensorDataset from torchmetrics import MetricTra...
null
32,976
import argparse from functools import partial import json import logging import os import sys from typing import List, Optional import torch from torch.nn.functional import one_hot, softmax import dinov2.distributed as distributed from dinov2.data import SamplerType, make_data_loader, make_dataset from dinov2.data.tran...
null
32,977
import argparse from functools import partial import json import logging import os import sys from typing import List, Optional import torch from torch.nn.functional import one_hot, softmax import dinov2.distributed as distributed from dinov2.data import SamplerType, make_data_loader, make_dataset from dinov2.data.tran...
null
32,978
import argparse from functools import partial import json import logging import os import sys from typing import List, Optional import numpy as np import torch import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from fvcore.common.checkpoint import Checkpointer, PeriodicCheckpointer from dinov2....
null
32,979
import argparse from functools import partial import json import logging import os import sys from typing import List, Optional import numpy as np import torch import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from fvcore.common.checkpoint import Checkpointer, PeriodicCheckpointer from dinov2....
null
32,980
from enum import Enum import logging from typing import Any, Dict, Optional import torch from torch import Tensor from torchmetrics import Metric, MetricCollection from torchmetrics.classification import MulticlassAccuracy from torchmetrics.utilities.data import dim_zero_cat, select_topk class MetricType(Enum): MEA...
null
32,981
import torch import torch.nn as nn def _make_dinov2_model( *, arch_name: str = "vit_large", img_size: int = 518, patch_size: int = 14, init_values: float = 1.0, ffn_layer: str = "mlp", block_chunks: int = 0, pretrained: bool = True, **kwargs, ): from dinov2.models import vision_t...
DINOv2 ViT-S/14 model (optionally) pretrained on the LVD-142M dataset.
32,982
import torch import torch.nn as nn def _make_dinov2_model( *, arch_name: str = "vit_large", img_size: int = 518, patch_size: int = 14, init_values: float = 1.0, ffn_layer: str = "mlp", block_chunks: int = 0, pretrained: bool = True, **kwargs, ): from dinov2.models import vision_t...
DINOv2 ViT-B/14 model pretrained on the LVD-142M dataset.
32,983
import torch import torch.nn as nn def _make_dinov2_model( *, arch_name: str = "vit_large", img_size: int = 518, patch_size: int = 14, init_values: float = 1.0, ffn_layer: str = "mlp", block_chunks: int = 0, pretrained: bool = True, **kwargs, ): from dinov2.models import vision_t...
DINOv2 ViT-L/14 model (optionally) pretrained on the LVD-142M dataset.
32,984
import torch import torch.nn as nn def _make_dinov2_model( *, arch_name: str = "vit_large", img_size: int = 518, patch_size: int = 14, init_values: float = 1.0, ffn_layer: str = "mlp", block_chunks: int = 0, pretrained: bool = True, **kwargs, ): from dinov2.models import vision_t...
DINOv2 ViT-g/14 model (optionally) pretrained on the LVD-142M dataset.
32,985
import torch import torch.nn as nn def _make_dinov2_linear_classifier( *, arch_name: str = "vit_large", layers: int = 4, pretrained: bool = True, **kwargs, ): backbone = _make_dinov2_model(arch_name=arch_name, pretrained=pretrained, **kwargs) embed_dim = backbone.embed_dim patch_size = b...
Linear classifier (1 or 4 layers) on top of a DINOv2 ViT-S/14 backbone (optionally) pretrained on the LVD-142M dataset and trained on ImageNet-1k.
32,986
import torch import torch.nn as nn def _make_dinov2_linear_classifier( *, arch_name: str = "vit_large", layers: int = 4, pretrained: bool = True, **kwargs, ): backbone = _make_dinov2_model(arch_name=arch_name, pretrained=pretrained, **kwargs) embed_dim = backbone.embed_dim patch_size = b...
Linear classifier (1 or 4 layers) on top of a DINOv2 ViT-B/14 backbone (optionally) pretrained on the LVD-142M dataset and trained on ImageNet-1k.
32,987
import torch import torch.nn as nn def _make_dinov2_linear_classifier( *, arch_name: str = "vit_large", layers: int = 4, pretrained: bool = True, **kwargs, ): backbone = _make_dinov2_model(arch_name=arch_name, pretrained=pretrained, **kwargs) embed_dim = backbone.embed_dim patch_size = b...
Linear classifier (1 or 4 layers) on top of a DINOv2 ViT-L/14 backbone (optionally) pretrained on the LVD-142M dataset and trained on ImageNet-1k.
32,988
import torch import torch.nn as nn def _make_dinov2_linear_classifier( *, arch_name: str = "vit_large", layers: int = 4, pretrained: bool = True, **kwargs, ): backbone = _make_dinov2_model(arch_name=arch_name, pretrained=pretrained, **kwargs) embed_dim = backbone.embed_dim patch_size = b...
Linear classifier (1 or 4 layers) on top of a DINOv2 ViT-g/14 backbone (optionally) pretrained on the LVD-142M dataset and trained on ImageNet-1k.
32,989
from cog import BasePredictor, Input, Path import os import cv2 import time import torch import einops import random import subprocess import numpy as np from cldm.ddim_hacked import DDIMSampler from cldm.model import create_model, load_state_dict from cldm.hack import disable_verbosity from datasets.data_utils import ...
null
32,990
from cog import BasePredictor, Input, Path import os import cv2 import time import torch import einops import random import subprocess import numpy as np from cldm.ddim_hacked import DDIMSampler from cldm.model import create_model, load_state_dict from cldm.hack import disable_verbosity from datasets.data_utils import ...
null