input
stringlengths
33
5k
output
stringlengths
32
5k
import asyncio from typing import Any, List, Optional from zhipuai import ZhipuAI as ZhipuAIClient from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks import CallbackManager class ZhipuAIEmbedding(BaseEmbedding...
import asyncio from typing import Any, List, Optional from zhipuai import ZhipuAI as ZhipuAIClient from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks import CallbackManager class ZhipuAIEmbedding(BaseEmbedding...
import logging from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseNanoBEIREvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") evaluator = SparseNanoBEIR...
import logging from sentence_transformers.sparse_encoder import ( SparseEncoder, SparseNanoBEIREvaluator, ) logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") evaluator = SparseNanoBEIREvaluator( dataset_names=No...
import json from jina.logging.logger import JinaLogger from jina.parsers import set_gateway_parser from jina.serve.runtimes.gateway.http.app import get_fastapi_app from jina.serve.runtimes.gateway.streamer import GatewayStreamer JINA_LOGO_URL = 'https://api.jina.ai/logo/logo-product/jina-core/horizontal-layout/colore...
import json from jina.logging.logger import JinaLogger from jina.parsers import set_gateway_parser from jina.serve.runtimes.gateway.http.app import get_fastapi_app from jina.serve.streamer import GatewayStreamer JINA_LOGO_URL = 'https://api.jina.ai/logo/logo-product/jina-core/horizontal-layout/colored/Product%20logo_...
from typing import Optional from llama_index.core.storage.index_store.keyval_index_store import KVIndexStore from llama_index.storage.kvstore.postgres import PostgresKVStore class PostgresIndexStore(KVIndexStore): """ Postgres Index store. Args: postgres_kvstore (PostgresKVStore): Postgres key-v...
from typing import Optional from llama_index.core.storage.index_store.keyval_index_store import KVIndexStore from llama_index.storage.kvstore.postgres import PostgresKVStore class PostgresIndexStore(KVIndexStore): """Postgres Index store. Args: postgres_kvstore (PostgresKVStore): Postgres key-value ...
import pytest from llama_index.embeddings.modelscope.base import ModelScopeEmbedding @pytest.fixture() def modelscope_embedding(): return ModelScopeEmbedding() @pytest.fixture() def query(): return "吃完海鲜可以喝牛奶吗?" @pytest.fixture() def text(): return [ "不可以,早晨喝牛奶不科学", "吃了海鲜后是不能再喝牛奶的,因为牛奶...
import pytest from llama_index.embeddings.modelscope.base import ModelScopeEmbedding @pytest.fixture() def modelscope_embedding(): return ModelScopeEmbedding() @pytest.fixture() def query(): return "吃完海鲜可以喝牛奶吗?" @pytest.fixture() def text(): return [ "不可以,早晨喝牛奶不科学", "吃了海鲜后是不能再喝牛奶的,因为牛奶...
_base_ = [ '../_base_/models/ssd300.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' input_size = 300 train_pipeline = [ dict(type='LoadImageFromFile'), dict(type=...
_base_ = [ '../_base_/models/ssd300.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' input_size = 300 train_pipeline = [ dict(type='LoadImageFromFile'), dict(type=...
# Copyright (c) OpenMMLab. All rights reserved. import copy import inspect from typing import List, Union import torch import torch.nn as nn from mmengine.config import Config, ConfigDict from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS from .optimizer_wrapper import OptimWrapper def register_to...
# Copyright (c) OpenMMLab. All rights reserved. import copy import inspect from typing import List import torch import torch.nn as nn from mmengine.registry import OPTIMIZER_CONSTRUCTORS, OPTIMIZERS def register_torch_optimizers() -> List[str]: """Register optimizers in ``torch.optim`` to the ``OPTIMIZERS`` reg...
""" This scripts demonstrates how to train a Sparse Encoder model for Information Retrieval. As dataset, we use sentence-transformers/msmarco-bm25, where we have triplets versions of MSMARCO mined thanks to BM25. As loss function, we use MultipleNegativesRankingLoss in the SpladeLoss. """ import logging import trac...
""" This scripts demonstrates how to train a Sparse Encoder model for Information Retrieval. As dataset, we use sentence-transformers/msmarco-bm25, where we have triplets versions of MSMARCO mined thanks to BM25. As loss function, we use MultipleNegativesRankingLoss in the SpladeLoss. """ import logging import trac...
model = dict( detector=dict( type='FasterRCNN', backbone=dict( type='ResNet', depth=18, base_channels=2, num_stages=4, out_indices=(3, ), strides=(1, 2, 2, 1), dilations=(1, 1, 1, 2), frozen_stages=1, ...
model = dict( detector=dict( type='FasterRCNN', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(3, ), strides=(1, 2, 2, 1), dilations=(1, 1, 1, 2), froz...
from keras.src import backend from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.AlphaDropout") class AlphaDropout(Layer): """Applies Alpha Dropout to the input. Alpha Dropout is a `Dropout` that keeps mean and variance...
from keras.src import backend from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.AlphaDropout") class AlphaDropout(Layer): """Applies Alpha Dropout to the input. Alpha Dropout is a `Dropout` that keeps mean and variance...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', # 270k iterations with batch_size 64 is roughly equivalent to 144 epochs '../common/ssj_scp_270k_coco_instance.py' ] norm_cfg = dict(type='SyncBN', requires_grad=True) # Use MMSyncBN that handles empty tensor in head. It can be changed to # SyncBN after h...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', # 270k iterations with batch_size 64 is roughly equivalent to 144 epochs '../common/ssj_scp_270k_coco_instance.py' ] norm_cfg = dict(type='SyncBN', requires_grad=True) # Use MMSyncBN that handles empty tensor in head. It can be changed to # SyncBN after h...
# training schedule for 20e train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=20, val_interval=1) val_cfg = dict(type='ValLoop') test_cfg = dict(type='TestLoop') # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='M...
# training schedule for 20e train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=20, val_interval=1) val_cfg = dict(type='ValLoop') test_cfg = dict(type='TestLoop') # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='M...
from typing import Any, Optional from langchain_core.callbacks.manager import CallbackManagerForLLMRun from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, BaseMessage from langchain_core.outputs import ChatGeneration, ChatResult from pytest_mock import Mo...
from typing import Any, Optional from langchain_core.callbacks.manager import CallbackManagerForLLMRun from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, BaseMessage from langchain_core.outputs import ChatGeneration, ChatResult from pytest_mock import Mo...
from setuptools import find_packages, setup with open("README.md", mode="r", encoding="utf-8") as readme_file: readme = readme_file.read() setup( name="sentence-transformers", version="3.0.0.dev0", author="Nils Reimers", author_email="info@nils-reimers.de", description="Multilingual text embe...
from setuptools import setup, find_packages with open("README.md", mode="r", encoding="utf-8") as readme_file: readme = readme_file.read() setup( name="sentence-transformers", version="2.8.0.dev0", author="Nils Reimers", author_email="info@nils-reimers.de", description="Multilingual text embe...
import torch from torchaudio_unittest.common_utils import PytorchTestCase, skipIfNoCuda from torchaudio_unittest.prototype.conv_emformer_test_impl import ConvEmformerTestImpl @skipIfNoCuda class ConvEmformerFloat32GPUTest(ConvEmformerTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cud...
import torch from torchaudio_unittest.common_utils import skipIfNoCuda, PytorchTestCase from torchaudio_unittest.prototype.conv_emformer_test_impl import ConvEmformerTestImpl @skipIfNoCuda class ConvEmformerFloat32GPUTest(ConvEmformerTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cud...
# Copyright (c) OpenMMLab. All rights reserved. import importlib import os.path as osp from mmengine.config import Config from mmengine.config.utils import (_get_cfg_metainfo, _get_external_cfg_base_path, _get_package_and_cfg_path) from mmengine.reg...
# Copyright (c) OpenMMLab. All rights reserved. import importlib import os.path as osp from mmengine.config import Config from mmengine.config.utils import (_get_cfg_metainfo, _get_external_cfg_base_path, _get_package_and_cfg_path) from mmengine.reg...
import os from source_separation.utils.dataset import wsj0mix from torchaudio_unittest.common_utils import get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase _FILENAMES = [ "012c0207_1.9952_01cc0202_-1.9952.wav", "01co0302_1.63_014c020q_-1.63.wav", "01do0316_0.24011_205a0104_-0.240...
import os from source_separation.utils.dataset import wsj0mix from torchaudio_unittest.common_utils import get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase _FILENAMES = [ "012c0207_1.9952_01cc0202_-1.9952.wav", "01co0302_1.63_014c020q_-1.63.wav", "01do0316_0.24011_205a0104_-0.240...
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_doc import BaseDoc from docarray.typing import AnyEmbedding, ImageBytes, ImageUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.image.image_tensor import ImageTen...
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_doc import BaseDoc from docarray.typing import AnyEmbedding, ImageBytes, ImageUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.image.image_tensor import ImageTen...
import numpy as np from docarray.base_document import AnyDocument, BaseDocument from docarray.typing import NdArray def test_any_doc(): class InnerDocument(BaseDocument): text: str tensor: NdArray class CustomDoc(BaseDocument): inner: InnerDocument text: str doc = Custom...
import numpy as np from docarray.document import AnyDocument, BaseDocument from docarray.typing import NdArray def test_any_doc(): class InnerDocument(BaseDocument): text: str tensor: NdArray class CustomDoc(BaseDocument): inner: InnerDocument text: str doc = CustomDoc( ...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead from .centernet_head import CenterNetHead from .c...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead from .centernet_head import CenterNetHead from .c...
import json from typing import Any, Type, TypeVar, overload import jsonschema from fastapi.encoders import jsonable_encoder from .type import type_match def to_dict(data) -> dict: return jsonable_encoder(data) def dumps(data) -> str: return json.dumps(jsonable_encoder(data)) T = TypeVar("T") @overload...
import json from typing import Any, Type, TypeVar, overload from fastapi.encoders import jsonable_encoder from .type import type_match def to_dict(data) -> dict: return jsonable_encoder(data) def dumps(data) -> str: return json.dumps(jsonable_encoder(data)) T = TypeVar("T") @overload def loads(data: s...
"""String output parser.""" from langchain_core.output_parsers.transform import BaseTransformOutputParser class StrOutputParser(BaseTransformOutputParser[str]): """OutputParser that parses LLMResult into the top likely string.""" @classmethod def is_lc_serializable(cls) -> bool: """StrOutputPars...
"""String output parser.""" from typing import Optional as Optional from langchain_core.output_parsers.transform import BaseTransformOutputParser class StrOutputParser(BaseTransformOutputParser[str]): """OutputParser that parses LLMResult into the top likely string.""" @classmethod def is_lc_serializab...
import inspect import re from typing import Dict, List, Tuple from huggingface_hub.utils import insecure_hashlib from .arrow import arrow from .audiofolder import audiofolder from .cache import cache from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parq...
import inspect import re from typing import Dict, List, Tuple from huggingface_hub.utils import insecure_hashlib from .arrow import arrow from .audiofolder import audiofolder from .cache import cache from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parq...
import requests from packaging import version from typing import Sequence, Union, List, Optional from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ) from text_generation.types import ( Message, ) def resolve_tgi_function_call(url: str) -> bool: url = f"{url}/info" model_inf...
import requests from packaging import version from typing import Sequence, Union, List, Optional from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ) from text_generation.types import ( Message, ) def resolve_tgi_function_call(url: str) -> bool: url = f"{url}/info" model_inf...
"""IndexStructType class.""" from enum import Enum class IndexStructType(str, Enum): """ Index struct type. Identifier for a "type" of index. Attributes: TREE ("tree"): Tree index. See :ref:`Ref-Indices-Tree` for tree indices. LIST ("list"): Summary index. See :ref:`Ref-Indices-List` for...
"""IndexStructType class.""" from enum import Enum class IndexStructType(str, Enum): """Index struct type. Identifier for a "type" of index. Attributes: TREE ("tree"): Tree index. See :ref:`Ref-Indices-Tree` for tree indices. LIST ("list"): Summary index. See :ref:`Ref-Indices-List` for summ...
"""Run smoke tests""" import os from pathlib import Path import torch import torchvision from torchvision.io import read_image from torchvision.models import resnet50, ResNet50_Weights SCRIPT_DIR = Path(__file__).parent def smoke_test_torchvision() -> None: print( "Is torchvision usable?", all(...
"""Run smoke tests""" import os from pathlib import Path import torch import torchvision from torchvision.io import read_image from torchvision.models import resnet50, ResNet50_Weights SCRIPT_DIR = Path(__file__).parent def smoke_test_torchvision() -> None: print( "Is torchvision useable?", all...
from typing import Any, Dict, Optional from llama_index.core.storage.kvstore.types import BaseKVStore from llama_index.storage.kvstore.azurecosmosnosql import AzureCosmosNoSqlKVStore DEFAULT_DOCUMENT_DATABASE = "DocumentStoreDB" DEFAULT_DOCUMENT_CONTAINER = "DocumentStoreContainer" class AzureCosmosNoSqlDocumentSto...
from typing import Any, Dict, Optional from llama_index.core.storage.docstore.keyval_docstore import KVDocumentStore from llama_index.storage.kvstore.azurecosmosnosql import AzureCosmosNoSqlKVStore DEFAULT_DOCUMENT_DATABASE = "DocumentStoreDB" DEFAULT_DOCUMENT_CONTAINER = "DocumentStoreContainer" class AzureCosmosN...
from __future__ import annotations from sentence_transformers.training_args import SentenceTransformerTrainingArguments class CrossEncoderTrainingArguments(SentenceTransformerTrainingArguments): r""" CrossEncoderTrainingArguments extends :class:`~transformers.TrainingArguments` with additional arguments ...
from __future__ import annotations from sentence_transformers.training_args import SentenceTransformerTrainingArguments class CrossEncoderTrainingArguments(SentenceTransformerTrainingArguments): r""" CrossEncoderTrainingArguments extends :class:`~transformers.TrainingArguments` with additional arguments ...
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def hf_hub_url(repo_id: str, path: str, revision: Optional[str] = None) -> str: if version.parse(hfh.__version__).release < version.parse("0.11.0").release: # old versions of hfh don't u...
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def hf_hub_url(repo_id: str, path: str, revision: Optional[str] = None) -> str: if version.parse(hfh.__version__) < version.parse("0.11.0"): # old versions of hfh don't url-encode the fi...
import re from typing import TYPE_CHECKING, Any, Dict, Union if TYPE_CHECKING: from sentence_transformers.SentenceTransformer import SentenceTransformer class SentenceEvaluator: """ Base class for all evaluators Extend this class and implement __call__ for custom evaluators. """ def __init_...
import re from typing import TYPE_CHECKING, Any, Dict, Union if TYPE_CHECKING: from sentence_transformers.SentenceTransformer import SentenceTransformer class SentenceEvaluator: """ Base class for all evaluators Extend this class and implement __call__ for custom evaluators. """ def __init_...
""" 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...
"""Chat Message.""" from typing import Any, Literal from typing_extensions import override from langchain_core.messages.base import ( BaseMessage, BaseMessageChunk, merge_content, ) from langchain_core.utils._merge import merge_dicts class ChatMessage(BaseMessage): """Message that can be assigned a...
"""Chat Message.""" from typing import Any, Literal from typing_extensions import override from langchain_core.messages.base import ( BaseMessage, BaseMessageChunk, merge_content, ) from langchain_core.utils._merge import merge_dicts class ChatMessage(BaseMessage): """Message that can be assigned a...
# 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. import os from unittest.mock import MagicMock import torch import torch.distributed as torch_dist import torch.nn as nn from mmengine.dist import all_gather from mmengine.hooks import SyncBuffersHook from mmengine.registry import MODELS from mmengine.testing._internal i...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock from mmengine.hooks import SyncBuffersHook class TestSyncBuffersHook: def test_sync_buffers_hook(self): runner = Mock() runner.model = Mock() hook = SyncBuffersHook() hook._after_epoch(runner)
import os import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDocument from docarray.typing.tensor.audio.audio_ndarray import AudioNdArray from docarray.typing.tensor.audio.audio_torch_tensor import AudioTorchTensor @pytest.mark.parametrize( 'tensor,cls_audio...
import os import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDocument from docarray.typing.tensor.audio.audio_ndarray import AudioNdArray from docarray.typing.tensor.audio.audio_torch_tensor import AudioTorchTensor @pytest.mark.parametrize( 'tensor,cls_audio...
from abc import ABC import pytest from docarray import DocumentArray from docarray.array.storage.memory import GetSetDelMixin, SequenceLikeMixin from docarray.array.storage.redis.backend import BackendMixin, RedisConfig class StorageMixins(BackendMixin, GetSetDelMixin, SequenceLikeMixin, ABC): ... class Docume...
from abc import ABC import pytest from docarray import DocumentArray from docarray.array.storage.memory import GetSetDelMixin, SequenceLikeMixin from docarray.array.storage.redis.backend import BackendMixin, RedisConfig class StorageMixins(BackendMixin, GetSetDelMixin, SequenceLikeMixin, ABC): ... class Docume...
# Copyright (c) OpenMMLab. All rights reserved. # This script consists of several convert functions which # can modify the weights of model in original repo to be # pre-trained weights. from collections import OrderedDict def swin_converter(ckpt): new_ckpt = OrderedDict() def correct_unfold_reduction_orde...
# Copyright (c) OpenMMLab. All rights reserved. # This script consists of several convert functions which # can modify the weights of model in original repo to be # pre-trained weights. from collections import OrderedDict def swin_converter(ckpt): new_ckpt = OrderedDict() def correct_unfold_reduction_orde...
from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch import pytest from langchain_community.document_loaders import ArcGISLoader if TYPE_CHECKING: from collections.abc import Iterator from arcgis.features import FeatureLayer from arcgis.gis impo...
from unittest.mock import MagicMock, patch import pytest from langchain_community.document_loaders import ArcGISLoader @pytest.fixture def arcgis_mocks(mock_feature_layer, mock_gis): # type: ignore sys_modules = { "arcgis": MagicMock(), "arcgis.features.FeatureLayer": mock_feature_layer, ...
# Copyright (c) OpenMMLab. All rights reserved. from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .custom import CustomDataset from .dataset_wrappers import (ClassBalancedD...
# Copyright (c) OpenMMLab. All rights reserved. from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .custom import CustomDataset from .dataset_wrappers import (ClassBalancedD...
"""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...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class FastRCNN(TwoStageDetector): """Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_""" def __init__(self, backbone, ...
from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class FastRCNN(TwoStageDetector): """Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_""" def __init__(self, backbone, roi_head, train_cfg, ...
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 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...
# Copyright (c) OpenMMLab. All rights reserved. from .activations import SiLU from .bbox_nms import fast_nms, multiclass_nms from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .dropblock import DropBlock from .ema import ExpMom...
# Copyright (c) OpenMMLab. All rights reserved. from .activations import SiLU from .bbox_nms import fast_nms, multiclass_nms from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .dropblock import DropBlock from .ema import ExpMom...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. from .generation import Llama, Dialog from .model import ModelArgs, Transformer from .tokenizer import Tokenizer
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. from .generation import Llama from .model import ModelArgs, Transformer from .tokenizer import Tokenizer
from typing import Union, Dict, Any import google.ai.generativelanguage as glm import google.generativeai as genai from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ImageBlock, TextBlock, ) from llama_index.core.multi_modal_llms.base import ChatMessage fr...
from typing import Union, Dict, Any import google.ai.generativelanguage as glm import google.generativeai as genai from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ImageBlock, TextBlock, ) from llama_index.core.multi_modal_llms.base import ChatMessage fr...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class CoSENTLoss(nn.Module): def __init__(self, model: Senten...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class CoSENTLoss(nn.Module): def __init__(self, model: Senten...
import pytest from llama_index.core.sparse_embeddings.mock_sparse_embedding import MockSparseEmbedding text_embedding_map = { "hello": {0: 0.25}, "world": {1: 0.5}, "foo": {2: 0.75}, } @pytest.fixture() def mock_sparse_embedding(): return MockSparseEmbedding(text_to_embedding=text_embedding_map) d...
import pytest from llama_index.core.sparse_embeddings.mock_sparse_embedding import MockSparseEmbedding text_embedding_map = { "hello": {0: 0.25}, "world": {1: 0.5}, "foo": {2: 0.75}, } @pytest.fixture() def mock_sparse_embedding(): return MockSparseEmbedding(text_to_embedding=text_embedding_map) d...
import json from collections.abc import Sequence from langchain_core.agents import AgentAction, AgentActionMessageLog from langchain_core.messages import AIMessage, BaseMessage, FunctionMessage def _convert_agent_action_to_messages( agent_action: AgentAction, observation: str ) -> list[BaseMessage]: """Conve...
import json from collections.abc import Sequence from langchain_core.agents import AgentAction, AgentActionMessageLog from langchain_core.messages import AIMessage, BaseMessage, FunctionMessage def _convert_agent_action_to_messages( agent_action: AgentAction, observation: str ) -> list[BaseMessage]: """Conve...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses AdaptiveLayerLoss 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 us...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses AdaptiveLayerLoss 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 us...
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. 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 r...
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. 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 r...
"""Init file of LlamaIndex.""" __version__ = "0.12.10" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
"""Init file of LlamaIndex.""" __version__ = "0.12.9" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core.b...
""" This examples trains a CrossEncoder for the Quora Duplicate Questions Detection task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it output a continuous labels 0...1 to indicate the similarity between the input pair. It does NOT produce a sentence embedding and does NOT work for indivi...
""" This examples trains a CrossEncoder for the Quora Duplicate Questions Detection task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it output a continuous labels 0...1 to indicate the similarity between the input pair. It does NOT produce a sentence embedding and does NOT work for indivi...
from abc import ABC from typing import Any, Optional, Tuple, Type, TypeVar, Union from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.ndarray import NdArray from docarray.typing.tensor.torch_tensor import TorchTensor T = TypeVar('T', bound='Embedding') class EmbeddingMixin(...
from abc import ABC from typing import Any, Optional, Tuple, Type, TypeVar, Union from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.ndarray import NdArray from docarray.typing.tensor.torch_tensor import TorchTensor T = TypeVar('T', bound='Embedding') class EmbeddingMixin(...
import zlib from typing import Iterator, TextIO def exact_div(x, y): assert x % y == 0 return x // y def str2bool(string): str2val = {"True": True, "False": False} if string in str2val: return str2val[string] else: raise ValueError(f"Expected one of {set(str2val.keys())}, got {st...
import zlib from typing import Iterator, TextIO def exact_div(x, y): assert x % y == 0 return x // y def str2bool(string): str2val = {"True": True, "False": False} if string in str2val: return str2val[string] else: raise ValueError(f"Expected one of {set(str2val.keys())}, got {st...
"""LLM Compiler agent pack.""" from typing import Any, Dict, List, Optional from llama_index.core.agent import AgentRunner from llama_index.core.callbacks import CallbackManager from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.llms.llm import LLM from llama_index.core.tools.types impor...
"""LLM Compiler agent pack.""" from typing import Any, Dict, List, Optional from llama_index.core.agent import AgentRunner from llama_index.core.callbacks import CallbackManager from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.llms.llm import LLM from llama_index.core.tools.types impor...
from .gateway import HTTPGateway __all__ = ['HTTPGateway']
from .gateway import HTTPGateway
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect from ...utils import needs_py39, needs_py310 @pytest.fixture( name="app", params=[ "tutorial002", pytest.param("tutorial002_py310", marks=ne...
import pytest from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect from docs_src.websockets.tutorial002 import app def test_main(): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"<!DOCTYPE html>" i...
import torch from torchvision.transforms import autoaugment, transforms from torchvision.transforms.functional import InterpolationMode class ClassificationPresetTrain: def __init__( self, *, crop_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), interpol...
import torch from torchvision.transforms import autoaugment, transforms from torchvision.transforms.functional import InterpolationMode class ClassificationPresetTrain: def __init__( self, *, crop_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), interpol...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.config import ConfigDict from mmengine.structures import InstanceData from mmdet.models.dense_heads import SABLRetinaHead class TestSABLRetinaHead(TestCase): def test_sabl_retina_head(self): """Test...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.config import ConfigDict from mmengine.data import InstanceData from mmdet.models.dense_heads import SABLRetinaHead class TestSABLRetinaHead(TestCase): def test_sabl_retina_head(self): """Tests sabl...
"""Simple reader that reads weather data from OpenWeatherMap API""" from __future__ import annotations from datetime import datetime from typing import Iterator, Optional, Sequence from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader from langchain_community...
"""Simple reader that reads weather data from OpenWeatherMap API""" from __future__ import annotations from datetime import datetime from typing import Iterator, Optional, Sequence from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader from langchain_community...
# Copyright 2024 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 required by applicabl...
# Copyright 2024 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 required by applicabl...
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import numpy as np from scipy.sparse import issparse from ..base import TransformerMixin from ..utils.validation import check_is_fitted, valid...
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import numpy as np from scipy.sparse import issparse from ..base import TransformerMixin from ..utils.validation import check_is_fitted, vali...
from typing import Any, Optional, Sequence from llama_index.core.evaluation.base import BaseEvaluator, EvaluationResult from llama_index.core.prompts.mixin import PromptDictType, PromptMixinType from tonic_validate.metrics.retrieval_precision_metric import ( RetrievalPrecisionMetric, ) from tonic_validate.service...
from typing import Any, Optional, Sequence from llama_index.core.evaluation.base import BaseEvaluator, EvaluationResult from llama_index.core.prompts.mixin import PromptDictType, PromptMixinType from tonic_validate.metrics.retrieval_precision_metric import ( RetrievalPrecisionMetric, ) from tonic_validate.service...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess import pytest from jina import Document, DocumentArray, Flow from ...audioclip_text import AudioCLIPTextEncoder _EMBEDDING_DIM = 1024 @pytest.mark.parametrize('request_size', [1, 10, 50, 10...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Callable import pytest from jina import Flow from ...audioclip_text import AudioCLIPTextEncoder @pytest.mark.parametrize("request_size", [1, 10, 50, 100]) def test_integra...
# Copyright (c) OpenMMLab. All rights reserved. from .dist_utils import (DistOptimizerHook, all_reduce_dict, allreduce_grads, reduce_mean) from .misc import (center_of_mass, flip_tensor, generate_coordinate, mask2ndarray, multi_apply, select_single_mlvl, unmap) __all__ = [ ...
# Copyright (c) OpenMMLab. All rights reserved. from .dist_utils import (DistOptimizerHook, all_reduce_dict, allreduce_grads, reduce_mean) from .misc import (center_of_mass, flip_tensor, generate_coordinate, mask2ndarray, multi_apply, unmap) __all__ = [ 'allreduce_grads'...
""" Opendal file and directory reader. A loader that fetches a file or iterates through a directory on AWS S3 or other compatible service. """ import asyncio import tempfile from pathlib import Path from typing import Any, Dict, List, Optional, Union, cast from llama_index.core.readers import SimpleDirectoryReader ...
""" Opendal file and directory reader. A loader that fetches a file or iterates through a directory on AWS S3 or other compatible service. """ import asyncio import tempfile from pathlib import Path from typing import Any, Dict, List, Optional, Union, cast from llama_index.core.readers import SimpleDirectoryReader f...
import functools import time from threading import Thread import numpy as np import pytest from jina import Client, Document, Flow from jina.helper import random_port @pytest.mark.slow @pytest.mark.parametrize('protocol', ['websocket', 'http']) def test_gateway_concurrency(protocol, reraise): port = random_port...
import functools import time from threading import Thread import numpy as np import pytest from jina import Client, Document, Flow from jina.helper import random_port @pytest.mark.slow @pytest.mark.parametrize('protocol', ['websocket', 'http']) def test_gateway_concurrency(protocol, reraise): port = random_port...
from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: import botocore def get_aws_service_client( service_name: Optional[str] = None, region_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str...
from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: import botocore def get_aws_service_client( service_name: Optional[str] = None, region_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str...
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod from typing import Tuple from mmengine.model import BaseModule from torch import Tensor from mmdet.core.utils import (InstanceList, OptConfigType, OptMultiConfig, SampleList) from mmdet.registry impor...
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod from typing import Tuple from mmengine.model import BaseModule from torch import Tensor from mmdet.core.utils import (InstanceList, OptConfigType, OptMultiConfig, SampleList) from mmdet.registry impor...
from typing import Union from docarray.typing.tensor.embedding.ndarray import NdArrayEmbedding try: import torch # noqa: F401 except ImportError: AnyEmbedding = Union[NdArrayEmbedding] # type: ignore else: from docarray.typing.tensor.embedding.torch import TorchEmbedding # noqa: F401 AnyEmbedding...
from typing import Union from docarray.typing.tensor.embedding.ndarray import NdArrayEmbedding try: import torch # noqa: F401 except ImportError: Embedding = Union[NdArrayEmbedding] # type: ignore else: from docarray.typing.tensor.embedding.torch import TorchEmbedding # noqa: F401 Embedding = Uni...
import json import time import pytest from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import InMemoryMetricReader from prometheus_client import Summary from jina.serve.instrumentation import MetricsTimer @pytest.fixture def metrics_setup(): metric_reader = InMemoryMetri...
import json import time import pytest from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import InMemoryMetricReader from prometheus_client import Summary from jina.serve.instrumentation import MetricsTimer @pytest.fixture def metrics_setup(): metric_reader = InMemoryMetri...
from typing import Union from docarray.typing.tensor.ndarray import NdArray try: import torch # noqa: F401 except ImportError: AnyTensor = Union[NdArray] # type: ignore else: from docarray.typing.tensor.torch_tensor import TorchTensor # noqa: F401 AnyTensor = Union[NdArray, TorchTensor] # type: ...
from typing import Union from docarray.typing.tensor.ndarray import NdArray try: import torch # noqa: F401 except ImportError: Tensor = Union[NdArray] # type: ignore else: from docarray.typing.tensor.torch_tensor import TorchTensor # noqa: F401 Tensor = Union[NdArray, TorchTensor] # type: ignore...
# Copyright (c) OpenMMLab. All rights reserved. import warnings import mmcv from ..builder import PIPELINES from .compose import Compose @PIPELINES.register_module() class MultiScaleFlipAug: """Test-time augmentation with multiple scales and flipping. An example configuration is as followed: .. code-b...
import warnings import mmcv from ..builder import PIPELINES from .compose import Compose @PIPELINES.register_module() class MultiScaleFlipAug: """Test-time augmentation with multiple scales and flipping. An example configuration is as followed: .. code-block:: img_scale=[(1333, 400), (1333, 8...
from typing import Generator, Optional import pytest from docarray import BaseDoc, DocArray from docarray.documents import ImageDoc from docarray.typing import ImageUrl, NdArray from docarray.utils.map import map_docs, map_docs_batch from tests.units.typing.test_bytes import IMAGE_PATHS N_DOCS = 2 def load_from_do...
from typing import Generator, Optional import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc from docarray.typing import ImageUrl, NdArray from docarray.utils.map import map_docs, map_docs_batch from tests.units.typing.test_bytes import IMAGE_PATHS N_DOCS = 2 def lo...
import os from nvflare.apis.executor import Executor from nvflare.apis.fl_constant import FLContextKey, ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal import xgboost as xgb from xgboost import callback class Su...
import os from nvflare.apis.executor import Executor from nvflare.apis.fl_constant import FLContextKey, ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal import xgboost as xgb from xgboost import callback class Su...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch import torch.nn as nn from mmdet.registry import MODELS from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def smooth_l1_loss(pred, target, beta=1.0): """Smooth L1 loss. Args: pred (torch.Te...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch import torch.nn as nn from ..builder import LOSSES from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def smooth_l1_loss(pred, target, beta=1.0): """Smooth L1 loss. Args: pred (torch.Tensor)...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig from .single_stage_instance_seg import SingleStageInstanceSegmentor @MODELS.register_module() class SOLOv2(SingleStageInstanceSegmentor): """`SOLOv2: Dynamic and Fast...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig from ..builder import DETECTORS from .single_stage_instance_seg import SingleStageInstanceSegmentor @DETECTORS.register_module() class SOLOv2(SingleStageInstanceSegmentor): """`SOLOv2: Dynamic and Fas...
import os from pathlib import Path from torchaudio.datasets import yesno from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) def get_mock_data(root_dir, labels): """ root_dir: path labels: list of labels """ ...
import os from pathlib import Path from torchaudio.datasets import yesno from torchaudio_unittest.common_utils import ( TempDirMixin, TorchaudioTestCase, get_whitenoise, save_wav, normalize_wav, ) def get_mock_data(root_dir, labels): """ root_dir: path labels: list of labels """ ...
"""Test node mapping.""" from llama_index.core import SQLDatabase from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.objects.base_node_mapping import SimpleObjectNodeMapping from llama_index.core.objects.table_node_mapping import ( SQLTableNodeMapping, SQLTableSchema, ) from llama_ind...
"""Test node mapping.""" from llama_index.core import SQLDatabase from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.objects.base_node_mapping import SimpleObjectNodeMapping from llama_index.core.objects.table_node_mapping import ( SQLTableNodeMapping, SQLTableSchema, ) from llama_ind...
""" This file contains deprecated code that can only be used with the old `model.fit`-style Sentence Transformers v2.X training. It exists for backwards compatibility with the `model.old_fit` method, but will be removed in a future version. Nowadays, with Sentence Transformers v3+, it is recommended to use the `Senten...
""" This file contains deprecated code that can only be used with the old `model.fit`-style Sentence Transformers v2.X training. It exists for backwards compatibility with the `model.old_fit` method, but will be removed in a future version. Nowadays, with Sentence Transformers v3+, it is recommended to use the `Senten...
import collections from keras.src import backend from keras.src import testing from keras.src.utils import tracking class TrackingTest(testing.TestCase): def test_untracking_in_tracked_list(self): tracked_variables = [] tracker = tracking.Tracker( { "variables": ( ...
import collections from keras.src import backend from keras.src import testing from keras.src.utils import tracking class TrackingTest(testing.TestCase): def test_untracking_in_tracked_list(self): tracked_variables = [] tracker = tracking.Tracker( { "variables": ( ...
# Copyright (c) OpenMMLab. All rights reserved. from .empty_cache_hook import EmptyCacheHook from .checkpoint_hook import CheckpointHook from .hook import Hook from .iter_timer_hook import IterTimerHook from .optimizer_hook import OptimizerHook from .param_scheduler_hook import ParamSchedulerHook from .sampler_seed_hoo...
# Copyright (c) OpenMMLab. All rights reserved. from .empty_cache_hook import EmptyCacheHook from .hook import Hook from .iter_timer_hook import IterTimerHook from .optimizer_hook import OptimizerHook from .param_scheduler_hook import ParamSchedulerHook from .sampler_seed_hook import DistSamplerSeedHook __all__ = [ ...
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, ...
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, ...
"""[DEPRECATED] Pipeline prompt template.""" from typing import Any from typing import Optional as Optional from pydantic import model_validator from langchain_core._api.deprecation import deprecated from langchain_core.prompt_values import PromptValue from langchain_core.prompts.base import BasePromptTemplate from ...
from typing import Any from typing import Optional as Optional from pydantic import model_validator from langchain_core._api.deprecation import deprecated from langchain_core.prompt_values import PromptValue from langchain_core.prompts.base import BasePromptTemplate from langchain_core.prompts.chat import BaseChatPro...
from fastapi.testclient import TestClient from docs_src.configure_swagger_ui.tutorial003 import app client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text assert '"deepLinking": false,' in response.text, ( "overridden conf...
from fastapi.testclient import TestClient from docs_src.configure_swagger_ui.tutorial003 import app client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text assert ( '"deepLinking": false,' in response.text ), "overridde...
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...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Callable import numpy as np from sentence_transformers.evaluation.NanoBEIREvaluator import NanoBEIREvaluator from sentence_transformers.sparse_encoder.evaluation.SparseInformationRetrievalEvaluator import ( SparseInformationRetri...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Callable import numpy as np from sentence_transformers.evaluation.NanoBEIREvaluator import NanoBEIREvaluator from sentence_transformers.sparse_encoder.evaluation.SparseInformationRetrievalEvaluator import ( SparseInformationRetri...
""" This file contains deprecated code that can only be used with the old `model.fit`-style Sentence Transformers v2.X training. It exists for backwards compatibility with the `model.old_fit` method, but will be removed in a future version. Nowadays, with Sentence Transformers v3+, it is recommended to use the `Senten...
from __future__ import annotations import gzip import os from . import InputExample class NLIDataReader: """Reads in the Stanford NLI dataset and the MultiGenre NLI dataset""" def __init__(self, dataset_folder): self.dataset_folder = dataset_folder def get_examples(self, filename, max_examples...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.layers import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fused_semantic_head import FusedSemanticHead @MODELS.register_module() class SCNetSemanticHead(FusedSemanticHead): """Mask head for `SCNet <https://arxiv.org/abs/2...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fused_semantic_head import FusedSemanticHead @MODELS.register_module() class SCNetSemanticHead(FusedSemanticHead): """Mask head for `SCNet <https://arxiv.org/abs/20...
from typing import Any, Dict, Iterable import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class MultipleNegativesSymmetricRankingLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = ...
from typing import Dict, Iterable import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class MultipleNegativesSymmetricRankingLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = 20.0,...
# Copyright (c) OpenMMLab. All rights reserved. import ast import os.path as osp import re import warnings from typing import Tuple from mmengine.fileio import load from mmengine.utils import check_file_exist PKG2PROJECT = { 'mmcls': 'mmcls', 'mmdet': 'mmdet', 'mmdet3d': 'mmdet3d', 'mmseg': 'mmsegment...
# Copyright (c) OpenMMLab. All rights reserved. import ast import os.path as osp import re import warnings from typing import Tuple from mmengine.fileio import load from mmengine.utils import check_file_exist PKG2PROJECT = { 'mmcls': 'mmcls', 'mmdet': 'mmdet', 'mmdet3d': 'mmdet3d', 'mmseg': 'mmsegment...
# 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 agreed to in writ...
# 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 agreed to in writ...
from llama_index_instrumentation.base import BaseEvent # noqa
from typing import Any, Dict, Optional from llama_index.core.bridge.pydantic import BaseModel, Field, ConfigDict from uuid import uuid4 from datetime import datetime from llama_index.core.instrumentation.span import active_span_id class BaseEvent(BaseModel): model_config = ConfigDict( arbitrary_types_all...
"""Module definitions of agent types together with corresponding agents.""" from enum import Enum from langchain_core._api import deprecated from langchain._api.deprecation import AGENT_DEPRECATION_WARNING @deprecated( "0.1.0", message=AGENT_DEPRECATION_WARNING, removal="1.0", ) class AgentType(str, En...
"""Module definitions of agent types together with corresponding agents.""" from enum import Enum from langchain_core._api import deprecated from langchain._api.deprecation import AGENT_DEPRECATION_WARNING @deprecated( "0.1.0", message=AGENT_DEPRECATION_WARNING, removal="1.0", ) class AgentType(str, En...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Sequence from mmengine.data import BaseDataElement from mmengine.hooks import Hook from mmengine.runner import Runner from mmdet.registry import HOOKS DATA_BATCH = Optional[Sequence[dict]] @HOOKS.register_module() class MemoryProfilerHook...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Sequence, Union from mmengine.data import BaseDataElement from mmengine.hooks import Hook from mmengine.runner import Runner from mmdet.registry import HOOKS @HOOKS.register_module() class MemoryProfilerHook(Hook): """Memory profiler h...
from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.packs.corrective_rag import CorrectiveRAGPack def test_class(): names_of_base_classes = [b.__name__ for b in CorrectiveRAGPack.__mro__] assert BaseLlamaPack.__name__ in names_of_base_classes
from llama_index.core.llama_pack import BaseLlamaPack from llama_index.packs.corrective_rag import CorrectiveRAGPack def test_class(): names_of_base_classes = [b.__name__ for b in CorrectiveRAGPack.__mro__] assert BaseLlamaPack.__name__ in names_of_base_classes
"""Logic for selecting examples to include in prompts.""" from typing import TYPE_CHECKING, Any from langchain_core.example_selectors.length_based import ( LengthBasedExampleSelector, ) from langchain_core.example_selectors.semantic_similarity import ( MaxMarginalRelevanceExampleSelector, SemanticSimilari...
"""Logic for selecting examples to include in prompts.""" from typing import TYPE_CHECKING, Any from langchain_core.example_selectors.length_based import ( LengthBasedExampleSelector, ) from langchain_core.example_selectors.semantic_similarity import ( MaxMarginalRelevanceExampleSelector, SemanticSimilari...
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class GeneratorDatasetInputStream(AbstractDatasetInputStream): def __init__( self, generator: Callable, features: Optional...
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class GeneratorDatasetInputStream(AbstractDatasetInputStream): def __init__( self, generator: Callable, features: Optional...
# Licensed to the LF AI & Data foundation under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
from typing_extensions import TYPE_CHECKING if TYPE_CHECKING: from rich.console import Console, ConsoleOptions, RenderResult from rich.measure import Measurement from docarray.typing.tensor.abstract_tensor import AbstractTensor class TensorDisplay: """ Rich representation of a tensor. """ ...
# Copyright (c) OpenMMLab. All rights reserved. from .hub import load_url from .manager import ManagerMeta, ManagerMixin from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_batch_norm, has_method, import_modules_from_strings, is_list_of, is_method_overr...
# Copyright (c) OpenMMLab. All rights reserved. from .hub import load_url from .manager import ManagerMeta, ManagerMixin from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_batch_norm, has_method, import_modules_from_strings, is_list_of, is_method_overr...