input
stringlengths
33
5k
output
stringlengths
32
5k
# Copyright (c) OpenMMLab. All rights reserved. from .det_inferencer import DetInferencer from .inference import (async_inference_detector, inference_detector, inference_mot, init_detector, init_track_model) __all__ = [ 'init_detector', 'async_inference_detector', 'inference_detector', ...
# Copyright (c) OpenMMLab. All rights reserved. from .det_inferencer import DetInferencer from .inference import (async_inference_detector, inference_detector, init_detector) __all__ = [ 'init_detector', 'async_inference_detector', 'inference_detector', 'DetInferencer' ]
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.models.utils.misc import get_box_tensor from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox_overlaps def cast_tensor_type(x, scale=1., dtype=None): if dtype == 'fp16': # scale is for preventing overflows ...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox_overlaps def cast_tensor_type(x, scale=1., dtype=None): if dtype == 'fp16': # scale is for preventing overflows x = (x / scale).half() return x @TASK_UTI...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.util import fullname class CosineSimilarityLoss(nn.Module): def __init__(...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.util import fullname class CosineSimilarityLoss(nn.Module): def __init__(...
# Copyright (c) OpenMMLab. All rights reserved. from .collect_env import collect_env from .compat_config import compat_cfg from .dist_utils import (all_reduce_dict, allreduce_grads, reduce_mean, sync_random_seed) from .logger import get_caller_name, log_img_scale from .memory import AvoidCUDAOO...
# Copyright (c) OpenMMLab. All rights reserved. from .collect_env import collect_env from .compat_config import compat_cfg from .dist_utils import (all_reduce_dict, allreduce_grads, reduce_mean, sync_random_seed) from .logger import get_caller_name, log_img_scale from .memory import AvoidCUDAOO...
import importlib import shutil import warnings from typing import List import fsspec import fsspec.asyn from fsspec.implementations.local import LocalFileSystem from ..utils.deprecation_utils import deprecated from . import compression _has_s3fs = importlib.util.find_spec("s3fs") is not None if _has_s3fs: from...
import importlib import shutil import warnings from typing import List import fsspec import fsspec.asyn from fsspec.implementations.local import LocalFileSystem from ..utils.deprecation_utils import deprecated from . import compression _has_s3fs = importlib.util.find_spec("s3fs") is not None if _has_s3fs: from...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright (c) OpenMMLab. All rights reserved. import re from mmengine.config import Config def replace_cfg_vals(ori_cfg): """Replace the string "${key}" with the corresponding value. Replace the "${key}" with the value of ori_cfg.key in the config. And support replacing the chained ${key}. Such as, re...
# Copyright (c) OpenMMLab. All rights reserved. import re from mmcv.utils import Config def replace_cfg_vals(ori_cfg): """Replace the string "${key}" with the corresponding value. Replace the "${key}" with the value of ori_cfg.key in the config. And support replacing the chained ${key}. Such as, replace...
""" Empty index. An index that doesn't contain any documents. Can only be used for pure LLM calls. """ from typing import Any, Dict, Optional, Sequence from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.data_struct...
"""Empty index. An index that doesn't contain any documents. Can only be used for pure LLM calls. """ from typing import Any, Dict, Optional, Sequence from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.data_structs...
# Copyright (c) OpenMMLab. All rights reserved. import copy import torch.nn as nn from mmcv.cnn import ConvModule, Scale from mmdet.models.dense_heads.fcos_head import FCOSHead from mmdet.registry import MODELS @MODELS.register_module() class NASFCOSHead(FCOSHead): """Anchor-free head used in `NASFCOS <https://...
# Copyright (c) OpenMMLab. All rights reserved. import copy import torch.nn as nn from mmcv.cnn import ConvModule, Scale from mmdet.models.dense_heads.fcos_head import FCOSHead from ..builder import HEADS @HEADS.register_module() class NASFCOSHead(FCOSHead): """Anchor-free head used in `NASFCOS <https://arxiv.o...
import random import pytest from jina import Document, DocumentArray from lightgbm_ranker import LightGBMRanker NUM_DOCS = 1000 NUM_MATCHES = 5 @pytest.fixture def ranker(): return LightGBMRanker( query_features=['brand_query', 'price_query'], match_features=['brand_match', 'price_match'], ...
import random import pytest from jina import Document, DocumentArray from ..lightgbm_ranker import LightGBMRanker NUM_DOCS = 1000 NUM_MATCHES = 5 @pytest.fixture def ranker(): return LightGBMRanker( query_features=['brand_query', 'price_query'], match_features=['brand_match', 'price_match'], ...
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_detection.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_ou...
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_detection.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_ou...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
import os from pathlib import Path from torchaudio.datasets import gtzan from torchaudio_unittest.common_utils import get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ mocked_samples = [] moc...
import os from pathlib import Path from torchaudio.datasets import gtzan from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ mo...
# Copyright (c) OpenMMLab. All rights reserved. from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .cornernet import CornerNet from .deformable_detr import DeformableDETR from .detr import DETR from .fast_r...
from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .cornernet import CornerNet from .deformable_detr import DeformableDETR from .detr import DETR from .fast_rcnn import FastRCNN from .faster_rcnn import Fas...
from __future__ import annotations try: from typing import Self except ImportError: from typing_extensions import Self from torch import Tensor, nn from sentence_transformers.models.Module import Module class LayerNorm(Module): config_keys: list[str] = ["dimension"] def __init__(self, dimension: i...
from __future__ import annotations import json import os import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import Tensor, nn class LayerNorm(nn.Module): def __init__(self, dimension: int): super()...
from typing import List, Optional from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document import asana class AsanaReader(BaseReader): """ Asana reader. Reads data from an Asana workspace. Args: asana_token (str): Asana token. """ def __init__(...
from typing import List, Optional from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document import asana class AsanaReader(BaseReader): """Asana reader. Reads data from an Asana workspace. Args: asana_token (str): Asana token. """ def __init__(self, ...
from typing import Any, Dict from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2.utils import is_simple_tensor class UniformTemporalSubsample(Transform): _transformed_types = (is_simple_tensor, datapoints.Video) def __init__(sel...
from typing import Any, Dict from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2.utils import is_simple_tensor class UniformTemporalSubsample(Transform): _transformed_types = (is_simple_tensor, datapoints.Video) def __init__(sel...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.initializers import deserialize as deserialize from keras.src.initializers import get as get from keras.src.initializers import serialize as serialize from keras.src.initializers.cons...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.initializers import deserialize from keras.src.initializers import get from keras.src.initializers import serialize from keras.src.initializers.constant_initializers import STFT from ...
_base_ = ['./ld_r18-gflv1-r101_fpn_1x_coco.py'] model = dict( backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_c...
_base_ = ['./ld_r18_gflv1_r101_fpn_coco_1x.py'] model = dict( backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_c...
from typing import TYPE_CHECKING, Any, Dict, Type, TypeVar from docarray.document.abstract_document import AbstractDocument from docarray.document.base_node import BaseNode if TYPE_CHECKING: from docarray.proto import DocumentProto, NodeProto try: import torch # noqa: F401 except ImportError: torch_imp...
from typing import TYPE_CHECKING, Any, Dict, Type, TypeVar from docarray.document.abstract_document import AbstractDocument from docarray.document.base_node import BaseNode if TYPE_CHECKING: from docarray.proto import DocumentProto, NodeProto try: import torch # noqa: F401 except ImportError: torch_imp...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Optional, Sequence, Tuple, Union from mmengine.data import BaseDataElement from .base import BaseEvaluator class ComposedEvaluator: """Wrapper class to compose multiple :class:`BaseEvaluator` instances. Args: evaluators (Sequenc...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Optional, Sequence, Tuple, Union from mmengine.data import BaseDataSample from .base import BaseEvaluator class ComposedEvaluator: """Wrapper class to compose multiple :class:`BaseEvaluator` instances. Args: evaluators (Sequence...
from langchain.chains.router.base import MultiRouteChain, RouterChain from langchain.chains.router.llm_router import LLMRouterChain from langchain.chains.router.multi_prompt import MultiPromptChain from langchain.chains.router.multi_retrieval_qa import MultiRetrievalQAChain __all__ = [ "LLMRouterChain", "Multi...
from langchain.chains.router.base import MultiRouteChain, RouterChain from langchain.chains.router.llm_router import LLMRouterChain from langchain.chains.router.multi_prompt import MultiPromptChain from langchain.chains.router.multi_retrieval_qa import MultiRetrievalQAChain __all__ = [ "RouterChain", "MultiRou...
import os import time import pytest from jina import Flow, Executor class SlowExecutor(Executor): def close(self) -> None: with open(os.path.join(self.metas.workspace, 'test'), 'w', encoding='utf-8') as f: time.sleep(10) f.write('x') @pytest.mark.slow def test_slow_executor_clo...
import os import time import pytest from jina import Flow, Executor class SlowExecutor(Executor): def close(self) -> None: with open(os.path.join(self.metas.workspace, 'test'), 'w') as f: time.sleep(10) f.write('x') @pytest.mark.slow def test_slow_executor_close(tmpdir): wi...
"""Standard LangChain interface tests""" import os from typing import Type from langchain_core.language_models import BaseChatModel from langchain_tests.integration_tests import ChatModelIntegrationTests from langchain_openai import AzureChatOpenAI OPENAI_API_VERSION = os.environ.get("AZURE_OPENAI_API_VERSION", "")...
"""Standard LangChain interface tests""" import os from typing import Type import pytest from langchain_core.language_models import BaseChatModel from langchain_tests.integration_tests import ChatModelIntegrationTests from langchain_openai import AzureChatOpenAI OPENAI_API_VERSION = os.environ.get("AZURE_OPENAI_API...
import math from keras.src import backend from keras.src import layers from keras.src import ops from keras.src.api_export import keras_export @keras_export("keras.layers.GaussianDropout") class GaussianDropout(layers.Layer): """Apply multiplicative 1-centered Gaussian noise. As it is a regularization layer...
import math from keras.src import backend from keras.src import layers from keras.src import ops from keras.src.api_export import keras_export @keras_export("keras.layers.GaussianDropout") class GaussianDropout(layers.Layer): """Apply multiplicative 1-centered Gaussian noise. As it is a regularization layer...
import os from typing import Dict, Tuple import numpy as np from jina import Document, DocumentArray, Executor, requests from jina.logging.logger import JinaLogger class CrudIndexer(Executor): """Simple indexer class""" def __init__(self, **kwargs): super().__init__(**kwargs) self.logger = ...
import os from typing import Dict, Tuple import numpy as np from jina import Document, DocumentArray, Executor, requests from jina.logging.logger import JinaLogger class CrudIndexer(Executor): """Simple indexer class""" def __init__(self, **kwargs): super().__init__(**kwargs) self.logger = ...
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmdet.models.backbones import ResNeSt from mmdet.models.backbones.resnest import Bottleneck as BottleneckS def test_resnest_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] Bot...
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmdet.models.backbones import ResNeSt from mmdet.models.backbones.resnest import Bottleneck as BottleneckS def test_resnest_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] Bot...
import os from pathlib import Path from torchaudio.datasets import cmuarctic from torchaudio_unittest.common_utils import get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ mocked_data = [] sa...
import os from pathlib import Path from torchaudio.datasets import cmuarctic from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ ...
from keras.src import backend from keras.src import tree from keras.src.api_export import keras_export from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501 BaseImagePreprocessingLayer, ) @keras_export("keras.layers.RandomGrayscale") class RandomGrayscale(Ba...
from keras.src import backend from keras.src.api_export import keras_export from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501 BaseImagePreprocessingLayer, ) @keras_export("keras.layers.RandomGrayscale") class RandomGrayscale(BaseImagePreprocessingLayer):...
_base_ = '../cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
_base_ = '../cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)))
from abc import abstractmethod from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, TypeVar, Union from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore from qdrant_client.http import models from qdrant_client.http.models.models import Distanc...
from abc import abstractmethod from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, TypeVar, Union from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore from qdrant_client.http import models from qdrant_client.http.models.models import Distanc...
from __future__ import annotations from sentence_transformers.losses.MSELoss import MSELoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseMSELoss(MSELoss): def __init__(self, model: SparseEncoder) -> None: """ # TODO: Update as it's mentionned trainings ...
from __future__ import annotations from sentence_transformers.losses.MSELoss import MSELoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseMSELoss(MSELoss): def __init__(self, model: SparseEncoder) -> None: return super().__init__(model)
from keras.src.api_export import keras_export # Unique source of truth for the version number. __version__ = "3.9.0" @keras_export("keras.version") def version(): return __version__
from keras.src.api_export import keras_export # Unique source of truth for the version number. __version__ = "3.8.0" @keras_export("keras.version") def version(): return __version__
# Copyright (c) OpenMMLab. All rights reserved. from .augment_wrappers import AutoAugment, RandAugment from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, Contrast, Equalize, Invert, Posterize, Sharpness, Solarize, SolarizeAdd) from .compose import...
# Copyright (c) OpenMMLab. All rights reserved. from .auto_augment import (AutoAugment, BrightnessTransform, ColorTransform, ContrastTransform, EqualizeTransform, Rotate, Shear, Translate) from .compose import Compose from .formatting import (ImageToTensor, PackDetI...
from typing import List, Optional from docarray.base_doc.doc import BaseDoc def test_base_document_init(): doc = BaseDoc() assert doc.id is not None def test_update(): class MyDocument(BaseDoc): content: str title: Optional[str] = None tags_: List doc1 = MyDocument( ...
from typing import List, Optional from docarray.base_doc.doc import BaseDoc def test_base_document_init(): doc = BaseDoc() assert doc.id is not None def test_update(): class MyDocument(BaseDoc): content: str title: Optional[str] = None tags_: List doc1 = MyDocument( ...
# coding: utf-8 """Script for generating files with NuGet package metadata.""" import datetime import sys from pathlib import Path from shutil import copyfile if __name__ == "__main__": source = Path(sys.argv[1]) nuget_dir = Path(__file__).absolute().parent / "nuget" linux_folder_path = nuget_dir / "runti...
# coding: utf-8 """Script for generating files with NuGet package metadata.""" import datetime import sys from pathlib import Path from shutil import copyfile if __name__ == "__main__": source = Path(sys.argv[1]) current_dir = Path(__file__).absolute().parent linux_folder_path = current_dir / "runtimes" /...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from ..layers import (ConditionalDetrTransformerDecoder, DetrTransformerEncoder, SinePositionalEncoding) from .detr import DETR @MODELS.regis...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from ..layers import (ConditionalDetrTransformerDecoder, DetrTransformerEncoder, SinePositionalEncoding) from .detr import DETR @MODELS.regis...
import warnings from typing import Optional, TypeVar from docarray.typing.bytes.video_bytes import VideoBytes, VideoLoadResult from docarray.typing.proto_register import _register_proto from docarray.typing.url.any_url import AnyUrl from docarray.utils._internal.misc import is_notebook T = TypeVar('T', bound='VideoUr...
import warnings from typing import Optional, TypeVar from docarray.typing.bytes.video_bytes import VideoBytes, VideoLoadResult from docarray.typing.proto_register import _register_proto from docarray.typing.url.any_url import AnyUrl from docarray.utils._internal.misc import is_notebook T = TypeVar('T', bound='VideoUr...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import MAP_TO_NONE from keras.src.tree.tree_api import assert_same_paths from keras.src.tree.tree_api import assert_same_structure from keras.src.tree.tree_api import fl...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import assert_same_paths from keras.src.tree.tree_api import assert_same_structure from keras.src.tree.tree_api import flatten from keras.src.tree.tree_api import flatte...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize from keras.src.quantizers import get from keras.src.quantizers import serialize from keras.src.quantizers.quantizers import AbsMaxQuantizer from keras.sr...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize from keras.src.quantizers import get from keras.src.quantizers import serialize from keras.src.quantizers.quantizers import AbsMaxQuantizer from keras.sr...
"""Callback Handler that writes to a file.""" from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any, Optional, TextIO, cast from typing_extensions import override from langchain_core.callbacks import BaseCallbackHandler from langchain_core.utils.input import print_text i...
"""Callback Handler that writes to a file.""" from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any, Optional, TextIO, cast from typing_extensions import override from langchain_core.callbacks import BaseCallbackHandler from langchain_core.utils.input import print_text i...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. Args: data (tensor-like, PIL.Image.Image): Any data that can be turned into a tens...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. Args: data (tensor-like, PIL.Image.Image): Any data that can be turned into a tens...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fcn_mask_head import FCNMaskHead @MODELS.register_module() class SCNetMaskHead(FCNMaskHead): """Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_. Args...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fcn_mask_head import FCNMaskHead @MODELS.register_module() class SCNetMaskHead(FCNMaskHead): """Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_. Args...
import torch from torch import Tensor from torch import nn from typing import List, Dict import os import json import logging import numpy as np from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(nn.Module): """Implements a Bag-of-Words (BoW) model to derive sentence embed...
import torch from torch import Tensor from torch import nn from typing import List, Dict import os import json import logging import numpy as np from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(nn.Module): """Implements a Bag-of-Words (BoW) model to derive sentence embed...
import argparse import logging from typing import Optional import torch import torchaudio from torchaudio.prototype.ctc_decoder import lexicon_decoder logger = logging.getLogger(__name__) def _download_files(lexicon_file, kenlm_file): torch.hub.download_url_to_file( "https://pytorch.s3.amazonaws.com/to...
import argparse import logging from typing import Optional import torch import torchaudio from torchaudio.prototype.ctc_decoder import lexicon_decoder logger = logging.getLogger(__name__) def _download_files(lexicon_file, kenlm_file): torch.hub.download_url_to_file( "https://pytorch.s3.amazonaws.com/to...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright (c) OpenMMLab. All rights reserved. from .default_scope import DefaultScope from .registry import Registry, build_from_cfg from .root import (DATA_SAMPLERS, DATASETS, EVALUATORS, HOOKS, LOOPS, MODEL_WRAPPERS, MODELS, OPTIMIZER_CONSTRUCTORS, OPTIMIZERS, PARAM_SCHEDULERS,...
# Copyright (c) OpenMMLab. All rights reserved. from .registry import Registry, build_from_cfg from .root import (DATA_SAMPLERS, DATASETS, EVALUATORS, HOOKS, LOOPS, MODEL_WRAPPERS, MODELS, OPTIMIZER_CONSTRUCTORS, OPTIMIZERS, PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, TASK_UTIL...
""" This script contains an example how to perform semantic search with Seismic. For more information, please refer to the documentation: https://github.com/TusKANNy/seismic/blob/main/docs/Guidelines.md All you need is installing the `pyseismic-lsr` package: ``` pip install pyseismic-lsr ``` """ import time from dat...
""" This script contains an example how to perform semantic search with Seismic. For more information, please refer to the documentation: https://github.com/TusKANNy/seismic/blob/main/docs/Guidelines.md All you need is installing the `pyseismic-lsr` package: ``` pip install pyseismic-lsr ``` """ import time from dat...
from __future__ import annotations import collections import json import logging import os import string from typing import Iterable from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from .WordTokenizer import ENGLISH_STOP_WORDS, WordTokenizer logger = logging.getLogger(__name__) cl...
import collections import json import logging import os import string from typing import Iterable, List from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from .WordTokenizer import ENGLISH_STOP_WORDS, WordTokenizer logger = logging.getLogger(__name__) class PhraseTokenizer(WordTokeni...
from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip from . import functional, utils # usort: skip from ._transform import Transform # usort: skip from ._augment import CutMix, MixUp, RandomErasing from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide fro...
from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip from . import functional, utils # usort: skip from ._transform import Transform # usort: skip from ._augment import CutMix, MixUp, RandomErasing from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide fro...
# Copyright 2020 The HuggingFace Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
# Copyright 2020 The HuggingFace Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import importlib.util import warnings from functools import wraps from typing import Optional import torch def is_module_available(*modules: str) -> bool: r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. ...
import importlib.util import warnings from functools import wraps from typing import Optional import torch def is_module_available(*modules: str) -> bool: r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. ...
#!/usr/bin/env python # Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
#!/usr/bin/env python # Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
import types from typing import TYPE_CHECKING from docarray.utils._internal.misc import ( _get_path_from_docarray_root_level, import_library, ) if TYPE_CHECKING: from docarray.index.backends.elastic import ElasticDocIndex # noqa: F401 from docarray.index.backends.elasticv7 import ElasticV7DocIndex #...
import types from typing import TYPE_CHECKING from docarray.utils._internal.misc import ( _get_path_from_docarray_root_level, import_library, ) if TYPE_CHECKING: from docarray.index.backends.elastic import ElasticDocIndex # noqa: F401 from docarray.index.backends.elasticv7 import ElasticV7DocIndex #...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .torchscript_consistency_test_impl import TorchScriptConsistencyCPUOnlyTestImpl, TorchScriptConsistencyTestImpl class TorchScriptConsistencyCPUFloat32Test(TorchScriptConsistencyTestImpl, PytorchTestCase): dtype = torch.float32 dev...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .torchscript_consistency_test_impl import TorchScriptConsistencyTestImpl class TorchScriptConsistencyCPUFloat32Test(TorchScriptConsistencyTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class Torch...
"""Test program utils.""" import pytest from typing import List, Optional from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.base.llms.types import ChatMessage, ChatResponse, MessageRole from llama_index.core.program.utils import ( _repair_incomplete_json, process_streaming_obj...
"""Test program utils.""" import pytest from typing import List, Optional from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.base.llms.types import ChatMessage, ChatResponse, MessageRole from llama_index.core.program.utils import ( _repair_incomplete_json, process_streaming_obje...
"""Hypothetical Document Embeddings. https://arxiv.org/abs/2212.10496 """ from __future__ import annotations import logging from typing import Any, Dict, List, Optional from langchain_core.callbacks import CallbackManagerForChainRun from langchain_core.embeddings import Embeddings from langchain_core.language_model...
"""Hypothetical Document Embeddings. https://arxiv.org/abs/2212.10496 """ from __future__ import annotations from typing import Any, Dict, List, Optional import numpy as np from langchain_core.callbacks import CallbackManagerForChainRun from langchain_core.embeddings import Embeddings from langchain_core.language_m...
import datetime import prisma.fields import prisma.models import pytest import backend.server.v2.library.model as library_model @pytest.mark.asyncio async def test_agent_preset_from_db(): # Create mock DB agent db_agent = prisma.models.AgentPreset( id="test-agent-123", createdAt=datetime.dat...
import datetime import prisma.fields import prisma.models import pytest import backend.server.v2.library.model as library_model @pytest.mark.asyncio async def test_agent_preset_from_db(): # Create mock DB agent db_agent = prisma.models.AgentPreset( id="test-agent-123", createdAt=datetime.dat...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox_overlaps, get_box_tensor def cast_tensor_type(x, scale=1., dtype=None): if dtype == 'fp16': # scale is for preventing overflows x = (x / scale).half() retu...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.models.utils.misc import get_box_tensor from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox_overlaps def cast_tensor_type(x, scale=1., dtype=None): if dtype == 'fp16': # scale is for preventing overflows ...
# pants requires this import to recognize the dep import pytest_asyncio # noqa: F401 import pytest import os from llama_index.multi_modal_llms.nvidia import NVIDIAMultiModal as Interface from llama_index.multi_modal_llms.nvidia.utils import DEFAULT_MODEL from typing import Generator # this fixture is used to mask...
import pytest import os from llama_index.multi_modal_llms.nvidia import NVIDIAMultiModal as Interface from llama_index.multi_modal_llms.nvidia.utils import DEFAULT_MODEL from typing import Generator # this fixture is used to mask the NVIDIA_API_KEY environment variable and restore it # after the test. it also retur...
import os import tempfile import httpx import pytest from PIL import Image from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.cohere import CohereEmbedding from llama_index.embeddings.cohere.base import VALID_MODEL_INPUT_TYPES def test_embedding_class(): emb = CohereEmbed...
import os import tempfile import httpx import pytest from PIL import Image from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.cohere import CohereEmbedding from llama_index.embeddings.cohere.base import VALID_MODEL_INPUT_TYPES def test_embedding_class(): emb = CohereEmbed...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='dis...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='dis...
from langchain_core.callbacks import __all__ EXPECTED_ALL = [ "RetrieverManagerMixin", "LLMManagerMixin", "ChainManagerMixin", "ToolManagerMixin", "Callbacks", "CallbackManagerMixin", "RunManagerMixin", "BaseCallbackHandler", "AsyncCallbackHandler", "BaseCallbackManager", "B...
from langchain_core.callbacks import __all__ EXPECTED_ALL = [ "RetrieverManagerMixin", "LLMManagerMixin", "ChainManagerMixin", "ToolManagerMixin", "Callbacks", "CallbackManagerMixin", "RunManagerMixin", "BaseCallbackHandler", "AsyncCallbackHandler", "BaseCallbackManager", "B...
import json import logging import os from typing import Dict, List import torch from torch import Tensor, nn logger = logging.getLogger(__name__) class WordWeights(nn.Module): """This model can weight word embeddings, for example, with idf-values.""" def __init__(self, vocab: List[str], word_weights: Dict[...
import torch from torch import Tensor from torch import nn from typing import List, Dict import os import json import logging logger = logging.getLogger(__name__) class WordWeights(nn.Module): """This model can weight word embeddings, for example, with idf-values.""" def __init__(self, vocab: List[str], wo...
import pytest from backend.data import db from backend.executor.scheduler import SchedulerClient from backend.server.model import CreateGraph from backend.usecases.sample import create_test_graph, create_test_user from backend.util.service import get_service_client from backend.util.test import SpinTestServer @pytes...
import pytest from backend.data import db from backend.executor import Scheduler from backend.server.model import CreateGraph from backend.usecases.sample import create_test_graph, create_test_user from backend.util.service import get_service_client from backend.util.test import SpinTestServer @pytest.mark.asyncio(l...
import types from typing_extensions import TYPE_CHECKING from docarray.typing.tensor.embedding.embedding import AnyEmbedding from docarray.typing.tensor.embedding.ndarray import NdArrayEmbedding from docarray.utils._internal.misc import ( _get_path_from_docarray_root_level, import_library, ) if TYPE_CHECKING...
import types from typing_extensions import TYPE_CHECKING from docarray.typing.tensor.embedding.embedding import AnyEmbedding from docarray.typing.tensor.embedding.ndarray import NdArrayEmbedding from docarray.utils._internal.misc import ( _get_path_from_docarray_root_level, import_library, ) if TYPE_CHECKING...
""" Quantile Regression =================== .. versionadded:: 2.0.0 The script is inspired by this awesome example in sklearn: https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html .. note:: The feature is only supported using the Python, R, and C packages. In addition,...
""" Quantile Regression =================== .. versionadded:: 2.0.0 The script is inspired by this awesome example in sklearn: https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html .. note:: The feature is only supported using the Python, R, and C packages. In addition,...
import numpy as np from sentence_transformers.sparse_encoder import SparseEncoder from sentence_transformers.sparse_encoder.models import MLMTransformer, SpladePooling def main(): # Initialize the SPLADE model model_name = "naver/splade-cocondenser-ensembledistil" # "opensearch-project/opensearch-neural-spa...
import numpy as np from sentence_transformers.sparse_encoder import SparseEncoder from sentence_transformers.sparse_encoder.models import MLMTransformer, SpladePooling def main(): # Initialize the SPLADE model model_name = "opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill" # "prithivida/S...
import importlib.machinery import os from torch.hub import _get_torch_home _HOME = os.path.join(_get_torch_home(), "datasets", "vision") _USE_SHARDED_DATASETS = False IN_FBCODE = False def _download_file_from_remote_location(fpath: str, url: str) -> None: pass def _is_remote_location_available() -> bool: ...
import importlib.machinery import os from torch.hub import _get_torch_home _HOME = os.path.join(_get_torch_home(), "datasets", "vision") _USE_SHARDED_DATASETS = False def _download_file_from_remote_location(fpath: str, url: str) -> None: pass def _is_remote_location_available() -> bool: return False tr...
import numpy as np from docarray import BaseDoc from docarray.array import DocVec from docarray.array.doc_vec.column_storage import ColumnStorageView from docarray.typing import AnyTensor def test_column_storage_init(): class InnerDoc(BaseDoc): price: int class MyDoc(BaseDoc): tensor: AnyTen...
import numpy as np from docarray import BaseDoc from docarray.array import DocVec from docarray.array.doc_vec.column_storage import ColumnStorageView from docarray.typing import AnyTensor def test_column_storage_init(): class InnerDoc(BaseDoc): price: int class MyDoc(BaseDoc): tensor: AnyTen...
import os import sys import pytest import torch import torchaudio from torchaudio.prototype.pipelines import CONVTASNET_BASE_LIBRI2MIX, HDEMUCS_HIGH_MUSDB_PLUS sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "examples")) from source_separation.utils.metrics import sdr @pytest.mark.parametrize( ...
import os import sys import torch import torchaudio from torchaudio.prototype.pipelines import CONVTASNET_BASE_LIBRI2MIX sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "examples")) from source_separation.utils.metrics import PIT, sdr def test_source_separation_models(mixture_source, clean_sour...
_base_ = './queryinst_r50_fpn_ms-480-800-3x_coco.py' num_proposals = 300 model = dict( rpn_head=dict(num_proposals=num_proposals), test_cfg=dict( _delete_=True, rpn=None, rcnn=dict(max_per_img=num_proposals, mask_thr_binary=0.5))) # augmentation strategy originates from DETR. train_pipe...
_base_ = './queryinst_r50_fpn_ms-480-800-3x_coco.py' num_proposals = 300 model = dict( rpn_head=dict(num_proposals=num_proposals), test_cfg=dict( _delete_=True, rpn=None, rcnn=dict(max_per_img=num_proposals, mask_thr_binary=0.5))) # augmentation strategy originates from DETR. train_pipe...
"""Custom query engine.""" from abc import abstractmethod from typing import Union from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.bridge.pydantic import BaseModel, Field, ConfigDict from llama_index.co...
"""Custom query engine.""" from abc import abstractmethod from typing import Union from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.response.schema import RESPONSE_TYPE, Response from llama_index.core.bridge.pydantic import BaseModel, Field, ConfigDict from llama_index.co...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict, Optional, Union from mmengine.optim import _ParamScheduler from mmengine.registry import HOOKS from mmengine.utils import is_list_of from .hook import Hook DATA_BATCH = Optional[Union[dict, tuple, list]] @HOOKS.register_module() class ParamSch...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Union from mmengine.registry import HOOKS from .hook import Hook DATA_BATCH = Optional[Union[dict, tuple, list]] @HOOKS.register_module() class ParamSchedulerHook(Hook): """A hook to update some hyper-parameters in optimizer, e.g., lea...
import torch from torchaudio_unittest.common_utils import PytorchTestCase, skipIfNoCuda from torchaudio_unittest.models.emformer.emformer_test_impl import EmformerTestImpl @skipIfNoCuda class EmformerFloat32GPUTest(EmformerTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cuda") @skip...
import torch from torchaudio_unittest.common_utils import skipIfNoCuda, PytorchTestCase from torchaudio_unittest.models.emformer.emformer_test_impl import EmformerTestImpl @skipIfNoCuda class EmformerFloat32GPUTest(EmformerTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cuda") @skip...
_base_ = './retinanet_r50-caffe_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomChoiceResize', scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], ke...
_base_ = './retinanet_r50-caffe_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomChoiceResize', scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], keep...
"""Unit tests for verifying event dispatching. Much of this code is indirectly tested already through many end-to-end tests that generate traces based on the callbacks. The traces are all verified via snapshot testing (e.g., see unit tests for runnables). """ import contextvars from contextlib import asynccontextmana...
"""Unit tests for verifying event dispatching. Much of this code is indirectly tested already through many end-to-end tests that generate traces based on the callbacks. The traces are all verified via snapshot testing (e.g., see unit tests for runnables). """ import contextvars from contextlib import asynccontextmana...
# Owner(s): ["module: inductor"] import sys import unittest from torch.testing._internal.common_utils import IS_CI, IS_WINDOWS, skipIfXpu from torch.testing._internal.inductor_utils import GPU_TYPE, HAS_GPU, requires_gpu if IS_WINDOWS and IS_CI: sys.stderr.write( "Windows CI does not have necessary depe...
# Owner(s): ["module: inductor"] import sys import unittest from torch.testing._internal.common_utils import IS_CI, IS_WINDOWS, skipIfXpu from torch.testing._internal.inductor_utils import GPU_TYPE, HAS_GPU, requires_gpu if IS_WINDOWS and IS_CI: sys.stderr.write( "Windows CI does not have necessary depe...
_base_ = '../_base_/default_runtime.py' # model settings model = dict( type='YOLOV3', backbone=dict( type='MobileNetV2', out_indices=(2, 4, 6), act_cfg=dict(type='LeakyReLU', negative_slope=0.1), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://mmdet/mobilen...
_base_ = '../_base_/default_runtime.py' # model settings model = dict( type='YOLOV3', backbone=dict( type='MobileNetV2', out_indices=(2, 4, 6), act_cfg=dict(type='LeakyReLU', negative_slope=0.1), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://mmdet/mobilen...
"""**OutputParser** classes parse the output of an LLM call. **Class hierarchy:** .. code-block:: BaseLLMOutputParser --> BaseOutputParser --> <name>OutputParser # ListOutputParser, PydanticOutputParser **Main helpers:** .. code-block:: Serializable, Generation, PromptValue """ # noqa: E501 from typing...
"""**OutputParser** classes parse the output of an LLM call. **Class hierarchy:** .. code-block:: BaseLLMOutputParser --> BaseOutputParser --> <name>OutputParser # ListOutputParser, PydanticOutputParser **Main helpers:** .. code-block:: Serializable, Generation, PromptValue """ # noqa: E501 from import...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
"""Module containing the base parser for arguments of Jina.""" import argparse from jina.parsers.helper import _chf def set_base_parser(): """Set the base parser :return: the parser """ from jina import __version__ from jina.helper import colored, format_full_version_info, get_full_version ...
"""Module containing the base parser for arguments of Jina.""" import argparse from jina.parsers.helper import _chf def set_base_parser(): """Set the base parser :return: the parser """ from jina import __version__ from jina.helper import colored, format_full_version_info, get_full_version ...
# Copyright (c) OpenMMLab. All rights reserved. import os import unittest from unittest.mock import MagicMock, patch import pytest from mmdet.datasets import DATASETS @patch('mmdet.datasets.CocoDataset.load_annotations', MagicMock()) @patch('mmdet.datasets.CustomDataset.load_annotations', MagicMock()) @patch('mmdet...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import MagicMock, patch import pytest from mmdet.datasets import DATASETS @patch('mmdet.datasets.CocoDataset.load_annotations', MagicMock()) @patch('mmdet.datasets.CustomDataset.load_annotations', MagicMock()) @patch('mmdet.datasets.XMLDataset.load_...
import json import logging from typing import List from langchain_core._api.deprecation import deprecated from langchain_core.chat_history import BaseChatMessageHistory from langchain_core.messages import ( BaseMessage, message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_D...
import json import logging from typing import List from langchain_core._api.deprecation import deprecated from langchain_core.chat_history import BaseChatMessageHistory from langchain_core.messages import ( BaseMessage, message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_D...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '3.0.0rc1' short_version = __version__ def parse_version_info(version_str): """Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is par...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '3.0.0rc0' short_version = __version__ def parse_version_info(version_str): """Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is par...
from typing import Any, Dict, List, Optional, Sequence, Type, Union import PIL.Image import torch from torchvision import datapoints from torchvision.prototype.datapoints import Label, OneHotLabel from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2._utils import _FillType, ...
from typing import Any, Dict, List, Optional, Sequence, Type, Union import PIL.Image import torch from torchvision import datapoints from torchvision.prototype.datapoints import Label, OneHotLabel from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2._utils import _FillType, ...
_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), dict( type='InstaBoost', action_candidate=('normal', 'horizontal', 'skip'), action_prob=(1, 0, 0), scale=(0.8, 1.2), dx=15, ...
_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict( type='InstaBoost', action_candidate=('normal', 'horizontal', 'skip'), action_prob=(1, 0, 0), scale=(0.8, 1...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Sequence from mmengine.registry import HOOKS from .hook import Hook DATA_BATCH = Optional[Sequence[dict]] @HOOKS.register_module() class ParamSchedulerHook(Hook): """A hook to update some hyper-parameters in optimizer, e.g., learning r...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Optional, Sequence, Tuple from mmengine.data import BaseDataElement from mmengine.registry import HOOKS from .hook import Hook DATA_BATCH = Optional[Sequence[Tuple[Any, BaseDataElement]]] @HOOKS.register_module() class ParamSchedulerHook(Hook):...
from typing import Any, Dict import torch from torchvision.transforms.v2 import functional as F, Transform class UniformTemporalSubsample(Transform): """[BETA] Uniformly subsample ``num_samples`` indices from the temporal dimension of the video. .. v2betastatus:: UniformTemporalSubsample transform Vide...
from typing import Any, Dict import torch from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform class UniformTemporalSubsample(Transform): """[BETA] Uniformly subsample ``num_samples`` indices from the temporal dimension of the video. .. v2betastatus:: UniformTe...
import asyncio from typing import Any, Dict, Generator, List, Union import pytest from llama_index.core.schema import ( BaseNode, IndexNode, TextNode, ) from llama_index.core.vector_stores.types import ( VectorStoreQuery, ) from llama_index.vector_stores.lantern import LanternVectorStore # for testing...
import asyncio from typing import Any, Dict, Generator, List, Union import pytest from llama_index.core.schema import ( BaseNode, IndexNode, TextNode, ) from llama_index.core.vector_stores.types import ( VectorStoreQuery, ) from llama_index.vector_stores.lantern import LanternVectorStore # for testing...
_base_ = '../grid_rcnn/grid-rcnn_r50_fpn_gn-head_1x_coco.py' # model settings model = dict( roi_head=dict( bbox_roi_extractor=dict( type='GenericRoIExtractor', aggregation='sum', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=25...
_base_ = '../grid_rcnn/grid_rcnn_r50_fpn_gn-head_1x_coco.py' # model settings model = dict( roi_head=dict( bbox_roi_extractor=dict( type='GenericRoIExtractor', aggregation='sum', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=25...
import numpy as np import orjson from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import NdArray def test_proto_tensor(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) tensor._to_node_protobuf() def test_from_list():...
import numpy as np import orjson from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import Tensor def test_proto_tensor(): tensor = parse_obj_as(Tensor, np.zeros((3, 224, 224))) tensor._to_node_protobuf() def test_from_list(): ...
from __future__ import annotations import logging from typing import Literal import torch from torch import Tensor from sentence_transformers.models.InputModule import InputModule from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(InputModule): """Implements a Bag-of-Wo...
from __future__ import annotations import json import logging import os from typing import Literal import torch from torch import Tensor, nn from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(nn.Module): """Implements a Bag-of-Words (BoW) model to derive sentence embeddi...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses MatryoshkaLoss with the powerful CoSENTLoss to train models that perform well at output dimensions [768, 512, 256, 128, 64]. It generates sentence embeddings that can be compared using...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses MatryoshkaLoss with the powerful CoSENTLoss to train models that perform well at output dimensions [768, 512, 256, 128, 64]. It generates sentence embeddings that can be compared using...
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import torch def convert_stem(model_key, model_weight, state_dict, converted_names): new_key = model_key.replace('stem.conv', 'conv1') new_key = new_key.replace('stem.bn', 'bn1') state_dict[new_key] = mode...
import argparse from collections import OrderedDict import torch def convert_stem(model_key, model_weight, state_dict, converted_names): new_key = model_key.replace('stem.conv', 'conv1') new_key = new_key.replace('stem.bn', 'bn1') state_dict[new_key] = model_weight converted_names.add(model_key) ...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class MaskRCNN(TwoStageDetector): """Implementation of `Mask R-CNN <https://arxiv.org/abs/1703.06870>`_""" def __init__(self, backbone, ...
from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class MaskRCNN(TwoStageDetector): """Implementation of `Mask R-CNN <https://arxiv.org/abs/1703.06870>`_""" def __init__(self, backbone, rpn_head, roi_head, ...
from __future__ import annotations from collections.abc import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer, util class DistillKLDivLoss(nn.Module): # TODO def __init__(self, model: SentenceTransformer, similarity_fct=util.pairwise_dot_score) -> ...
from __future__ import annotations from collections.abc import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer, util class DistillKLDivLoss(nn.Module): # TODO def __init__(self, model: SentenceTransformer, similarity_fct=util.pairwise_dot_score) -> ...
# dataset settings dataset_type = 'CityscapesDataset' data_root = 'data/cityscapes/' # Example to use different file client # Method 1: simply set the data root and let the file I/O module # automatically infer from prefix (not support LMDB and Memcache yet) # data_root = 's3://openmmlab/datasets/segmentation/citysca...
# dataset settings dataset_type = 'CityscapesDataset' data_root = 'data/cityscapes/' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(2048, 800), (2048, 1024)], keep_ratio=True), dict(type='Random...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule from mmdet.registry import MODELS from .anchor_head import AnchorHead @MODELS.register_module() class RetinaHead(AnchorHead): r"""An anchor-based head used in `RetinaNet <https://arxiv.org/pdf/1708.02002.pdf...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule from mmdet.registry import MODELS from .anchor_head import AnchorHead @MODELS.register_module() class RetinaHead(AnchorHead): r"""An anchor-based head used in `RetinaNet <https://arxiv.org/pdf/1708.02002.pdf...
import torch from keras.src.backend import config from keras.src.backend import standardize_dtype from keras.src.backend.common import dtypes from keras.src.backend.torch.core import cast from keras.src.backend.torch.core import convert_to_tensor def cholesky(x): return torch.linalg.cholesky(x) def det(x): ...
import torch from keras.src.backend import config from keras.src.backend import standardize_dtype from keras.src.backend.common import dtypes from keras.src.backend.torch.core import cast from keras.src.backend.torch.core import convert_to_tensor def cholesky(x): return torch.linalg.cholesky(x) def det(x): ...