input
stringlengths
33
5k
output
stringlengths
32
5k
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.1.0.dev0", author="Nils Reimers, Tom Aarsen", author_email="info@nils-reimers.de", description="Multilingu...
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.2.2", author="Nils Reimers", author_email="info@nils-reimers.de", description="Multilingual text embeddin...
"""Output classes. **Output** classes are used to represent the output of a language model call and the output of a chat. The top container for information is the `LLMResult` object. `LLMResult` is used by both chat models and LLMs. This object contains the output of the language model and any additional information ...
"""Output classes. **Output** classes are used to represent the output of a language model call and the output of a chat. The top container for information is the `LLMResult` object. `LLMResult` is used by both chat models and LLMs. This object contains the output of the language model and any additional information ...
"""In memory document index.""" import operator import uuid from collections.abc import Sequence from typing import Any, Optional, cast from pydantic import Field from langchain_core._api import beta from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document fro...
"""In memory document index.""" import operator import uuid from collections.abc import Sequence from typing import Any, Optional, cast from pydantic import Field from langchain_core._api import beta from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document fro...
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
""" Given a dataset with parallel sentences, one "english" column and one "non_english" column, this script evaluates a model on the translation task. Given a sentence in the "english" column, the model should find the correct translation in the "non_english" column, based on just the embeddings. It then computes an a...
""" Given a tab separated file (.tsv) with parallel sentences, where the second column is the translation of the sentence in the first column, for example, in the format: src1 trg1 src2 trg2 ... where trg_i is the translation of src_i. Given src_i, the TranslationEvaluator checks which trg_j has the highest sim...
import os from pathlib import Path from typing import List, Tuple, Union import torchaudio from torch import Tensor from torch.utils.data import Dataset from torchaudio._internal import download_url_to_file from torchaudio.datasets.utils import _extract_tar _RELEASE_CONFIGS = { "release1": { "folder_in_a...
import os from pathlib import Path from typing import List, Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.utils import _extract_tar _RELEASE_CONFIGS = { "release1": { "folder_in_archive": "w...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.vgg19 import VGG19 as VGG19 from keras.src.applications.vgg19 import ( decode_predictions as decode_predictions, ) from keras.src.applications.vgg19 import preprocess...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.vgg19 import VGG19 from keras.src.applications.vgg19 import decode_predictions from keras.src.applications.vgg19 import preprocess_input
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import NdArray, PointCloud3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR...
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import NdArray, PointCloud3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR...
import pytest from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.upstage import UpstageEmbedding UPSTAGE_TEST_API_KEY = "upstage_test_key" @pytest.fixture() def upstage_embedding(): return pytest.importorskip( "llama_index.embeddings.upstage", reason="Cannot impor...
import pytest from llama_index.core.base.embeddings.base import BaseEmbedding UPSTAGE_TEST_API_KEY = "upstage_test_key" @pytest.fixture() def upstage_embedding(): return pytest.importorskip( "llama_index.embeddings.upstage", reason="Cannot import UpstageEmbedding" ).UpstageEmbedding @pytest.fixture...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.xception import Xception as Xception from keras.src.applications.xception import ( decode_predictions as decode_predictions, ) from keras.src.applications.xception im...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.xception import Xception from keras.src.applications.xception import decode_predictions from keras.src.applications.xception import preprocess_input
""" ========================================= Label Propagation digits: Active learning ========================================= Demonstrates an active learning technique to learn handwritten digits using label propagation. We start by training a label propagation model with only 10 labeled points, then we select th...
""" ======================================== Label Propagation digits active learning ======================================== Demonstrates an active learning technique to learn handwritten digits using label propagation. We start by training a label propagation model with only 10 labeled points, then we select the t...
from jina import Client from docarray import DocList from docarray.documents import TextDoc if __name__ == '__main__': c = Client(host='grpc://0.0.0.0:54321') da = c.post('/', DocList[TextDoc]([TextDoc(), TextDoc()]), return_type=DocList[TextDoc]) print(da.text)
from jina import Client, DocumentArray if __name__ == '__main__': c = Client(host='grpc://0.0.0.0:54321') da = c.post('/', DocumentArray.empty(2)) print(da.texts)
import numpy as np import pytest from docarray.documents import Image REMOTE_JPG = ( 'https://upload.wikimedia.org/wikipedia/commons/8/80/' 'Dag_Sebastian_Ahlander_at_G%C3%B6teborg_Book_Fair_2012b.jpg' ) @pytest.mark.slow @pytest.mark.internet def test_image(): image = Image(url=REMOTE_JPG) image....
import numpy as np import pytest from docarray import Image REMOTE_JPG = ( 'https://upload.wikimedia.org/wikipedia/commons/8/80/' 'Dag_Sebastian_Ahlander_at_G%C3%B6teborg_Book_Fair_2012b.jpg' ) @pytest.mark.slow @pytest.mark.internet def test_image(): image = Image(url=REMOTE_JPG) image.tensor = i...
from typing import Any, Dict, Union from torchvision import tv_tensors from torchvision.transforms.v2 import functional as F, Transform class ConvertBoundingBoxFormat(Transform): """Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". Args: format (str or tv_tensors....
from typing import Any, Dict, Union from torchvision import tv_tensors from torchvision.transforms.v2 import functional as F, Transform class ConvertBoundingBoxFormat(Transform): """[BETA] Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". .. v2betastatus:: ConvertBounding...
"""Utils for pretty print.""" import textwrap from pprint import pprint from typing import Any, Dict from llama_index.core.base.response.schema import Response from llama_index.core.schema import NodeWithScore from llama_index.core.utils import truncate_text def pprint_metadata(metadata: Dict[str, Any]) -> None: ...
"""Utils for pretty print.""" import textwrap from pprint import pprint from typing import Any, Dict from llama_index.core.base.response.schema import Response from llama_index.core.schema import NodeWithScore from llama_index.core.utils import truncate_text def pprint_metadata(metadata: Dict[str, Any]) -> None: ...
import logging import pathlib from argparse import ArgumentParser import sentencepiece as spm import torch import torchaudio from lightning import ConformerRNNTModule from transforms import get_data_module logger = logging.getLogger() def compute_word_level_distance(seq1, seq2): return torchaudio.functional.e...
import logging import pathlib from argparse import ArgumentParser import torch import torchaudio from lightning import ConformerRNNTModule from transforms import get_data_module logger = logging.getLogger() def compute_word_level_distance(seq1, seq2): return torchaudio.functional.edit_distance(seq1.lower().spl...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.builder import HEADS from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from .fcn_mask_head import FCNMaskHead @HEADS.register_module() class SCNetMaskHead(FCNMaskHead): """Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_. ...
from mmdet.models.builder import HEADS from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from .fcn_mask_head import FCNMaskHead @HEADS.register_module() class SCNetMaskHead(FCNMaskHead): """Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_. Args: conv_to_res (bool, optional): if T...
import logging import os import sys from torchaudio._internal.module_utils import eval_env, fail_with_message, is_module_available, no_op from .utils import ( _check_cuda_version, _fail_since_no_sox, _init_dll_path, _init_ffmpeg, _init_sox, _LazyImporter, _load_lib, ) _LG = logging.getLog...
import logging import os import sys from torchaudio._internal.module_utils import eval_env, fail_with_message, is_module_available, no_op try: from .fb import _init_ffmpeg except ImportError: from .utils import _init_ffmpeg from .utils import _check_cuda_version, _fail_since_no_ffmpeg, _fail_since_no_sox, _in...
from jina.serve.runtimes.gateway.gateway import BaseGateway class PlaceHolderGateway(BaseGateway): pass
from jina.serve.runtimes.gateway.gateway import BaseGateway class PlaceHolderGateway(BaseGateway): pass
_base_ = './faster-rcnn_hrnetv2p-w32-1x_coco.py' # learning policy max_epochs = 24 train_cfg = dict(max_epochs=max_epochs) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, ...
_base_ = './faster_rcnn_hrnetv2p_w32_1x_coco.py' # learning policy max_epochs = 24 train_cfg = dict(max_epochs=max_epochs) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, ...
# 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.data_elements import SampleList from mmdet.registry import MODELS from mmdet.utils import InstanceList, OptConfigType, OptMultiConf...
# 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...
import copy from pathlib import Path import clip import numpy as np import pytest import torch from jina import Document, DocumentArray, Executor from ...clip_text import CLIPTextEncoder @pytest.fixture(scope="module") def encoder() -> CLIPTextEncoder: return CLIPTextEncoder() def test_config(): ex = Exec...
import copy import clip import numpy as np import pytest import torch from jina import Document, DocumentArray from ...clip_text import CLIPTextEncoder @pytest.fixture(scope="module") def encoder() -> CLIPTextEncoder: return CLIPTextEncoder() def test_no_documents(encoder: CLIPTextEncoder): docs = Document...
import numpy as np import pytest from docarray import Image REMOTE_JPG = ( 'https://upload.wikimedia.org/wikipedia/commons/8/80/' 'Dag_Sebastian_Ahlander_at_G%C3%B6teborg_Book_Fair_2012b.jpg' ) @pytest.mark.slow @pytest.mark.internet def test_image(): image = Image(url=REMOTE_JPG) image.tensor = i...
import numpy as np from docarray import Image REMOTE_JPG = ( 'https://upload.wikimedia.org/wikipedia/commons/8/80/' 'Dag_Sebastian_Ahlander_at_G%C3%B6teborg_Book_Fair_2012b.jpg' ) def test_image(): image = Image(url=REMOTE_JPG) image.tensor = image.url.load() assert isinstance(image.tensor, n...
# model settings preprocess_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False, pad_size_divisor=32) model = dict( type='RPN', preprocess_cfg=preprocess_cfg, backbone=dict( type='ResNet', depth=50, num_stages=3, strides=(1, 2, 2),...
# model settings model = dict( type='RPN', backbone=dict( type='ResNet', depth=50, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=(2, ), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, ...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.24.0' short_version = __version__ def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.23.0' short_version = __version__ def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version...
from typing import Dict, Iterable, Sequence from docarray import Document from docarray.array.storage.base.getsetdel import BaseGetSetDelMixin from docarray.array.storage.base.helper import Offset2ID class GetSetDelMixin(BaseGetSetDelMixin): """Provide concrete implementation for ``__getitem__``, ``__setitem__``...
from typing import Dict, Iterable, Sequence from docarray import Document from docarray.array.storage.base.getsetdel import BaseGetSetDelMixin from docarray.array.storage.base.helper import Offset2ID class GetSetDelMixin(BaseGetSetDelMixin): """Provide concrete implementation for ``__getitem__``, ``__setitem__``...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.transforms import Compose from mmengine.hooks import Hook from mmdet.registry import HOOKS @HOOKS.register_module() class PipelineSwitchHook(Hook): """Switch data pipeline at switch_epoch. Args: switch_epoch (int): switch pipeline at this epo...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.transforms import Compose from mmengine.hooks import Hook from mmdet.registry import HOOKS @HOOKS.register_module() class PipelineSwitchHook(Hook): """Switch data pipeline at switch_epoch. Args: switch_epoch (int): switch pipeline at this epo...
# 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 .condinst import CondInst from .cornernet import CornerNet from .crowddet import CrowdDet from .d2_wrapper ...
# 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 .crowddet import CrowdDet from .d2_wrapper import Detectron2Wrapper from ....
_base_ = [ '../_base_/models/mask-rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] vis_backends = [dict(type='LocalVisBackend'), dict(type='WandbVisBackend')] visualizer = dict(vis_backends=vis_backends) # MMEngine support the ...
_base_ = [ '../_base_/models/mask-rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] vis_backends = [dict(type='LocalVisBackend'), dict(type='WandBVisBackend')] visualizer = dict(vis_backends=vis_backends) # MMEngine support the ...
from textwrap import dedent from types import SimpleNamespace from unittest.mock import patch from urllib.parse import quote import pytest from huggingface_hub import CommitOperationAdd, CommitOperationDelete import datasets from datasets.config import METADATA_CONFIGS_FIELD from datasets.hub import delete_from_hub f...
from urllib.parse import quote import pytest from datasets.utils.hub import hf_dataset_url @pytest.mark.parametrize("repo_id", ["canonical_dataset_name", "org-name/dataset-name"]) @pytest.mark.parametrize("filename", ["filename.csv", "filename with blanks.csv"]) @pytest.mark.parametrize("revision", [None, "v2"]) de...
import numpy as np import scipy.linalg as sl from keras.src.backend import standardize_dtype from keras.src.backend.common import dtypes from keras.src.backend.numpy.core import convert_to_tensor def cholesky(a): return np.linalg.cholesky(a) def det(a): return np.linalg.det(a) def eig(a): return np.l...
import numpy as np import scipy.linalg as sl from keras.src.backend import standardize_dtype from keras.src.backend.common import dtypes from keras.src.backend.numpy.core import convert_to_tensor def cholesky(a): return np.linalg.cholesky(a) def det(a): return np.linalg.det(a) def eig(a): return np.l...
# Copyright (c) OpenMMLab. All rights reserved. from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .boxinst import BoxInst from .base_detr import DetectionTransformer from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .condinst import CondInst from .co...
# Copyright (c) OpenMMLab. All rights reserved. from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .boxinst import BoxInst from .base_detr import DetectionTransformer from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .condinst import CondInst from .co...
# Copyright (c) OpenMMLab. All rights reserved. from pathlib import Path import mmcv import torch from mmcv.runner import load_checkpoint from mmdet.registry import MODELS from .. import build_detector from .single_stage import SingleStageDetector @MODELS.register_module() class KnowledgeDistillationSingleStageDete...
# Copyright (c) OpenMMLab. All rights reserved. from pathlib import Path import mmcv import torch from mmcv.runner import load_checkpoint from .. import build_detector from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class KnowledgeDistillationSingleStageDet...
# Copyright (c) OpenMMLab. All rights reserved. from collections import OrderedDict from mmcv.runner import get_dist_info from mmcv.runner.hooks import HOOKS, Hook from torch import nn from ..utils.dist_utils import all_reduce_dict def get_norm_states(module): async_norm_states = OrderedDict() for name, chi...
from collections import OrderedDict from mmcv.runner import get_dist_info from mmcv.runner.hooks import HOOKS, Hook from torch import nn from ..utils.dist_utils import all_reduce_dict def get_norm_states(module): async_norm_states = OrderedDict() for name, child in module.named_modules(): if isinsta...
import json from json import JSONDecodeError from typing import Union from langchain_core.agents import AgentAction, AgentActionMessageLog, AgentFinish from langchain_core.exceptions import OutputParserException from langchain_core.messages import ( AIMessage, BaseMessage, ToolCall, ) from langchain_core.o...
import json from json import JSONDecodeError from typing import Union from langchain_core.agents import AgentAction, AgentActionMessageLog, AgentFinish from langchain_core.exceptions import OutputParserException from langchain_core.messages import ( AIMessage, BaseMessage, ToolCall, ) from langchain_core.o...
_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' conv_cfg = dict(type='ConvWS') norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( backbone=dict( conv_cfg=conv_cfg, norm_cfg=norm_cfg, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://jhu/resn...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' conv_cfg = dict(type='ConvWS') norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( backbone=dict( conv_cfg=conv_cfg, norm_cfg=norm_cfg, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://jhu/resn...
# Copyright 2020 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 2020 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...
import torch from docarray.typing.tensor.torch_tensor import TorchTensor import copy from docarray import BaseDoc from docarray.typing import TorchEmbedding, TorchTensor def test_set_torch_tensor(): class MyDocument(BaseDoc): tensor: TorchTensor d = MyDocument(tensor=torch.zeros((3, 224, 224))) ...
import torch from docarray.typing.tensor.torch_tensor import TorchTensor import copy from docarray import BaseDoc from docarray.typing import TorchEmbedding, TorchTensor def test_set_torch_tensor(): class MyDocument(BaseDoc): tensor: TorchTensor d = MyDocument(tensor=torch.zeros((3, 224, 224))) ...
from keras.src import ops from keras.src import quantizers from keras.src import random from keras.src import testing class QuantizersTest(testing.TestCase): def test_get_method(self): quantizer = quantizers.get("abs_max_quantizer", axis=-1) self.assertTrue(quantizer, quantizers.AbsMaxQuantizer) ...
from keras.src import ops from keras.src import quantizers from keras.src import random from keras.src import testing class QuantizersTest(testing.TestCase): def test_get_method(self): quantizer = quantizers.get("abs_max_quantizer", axis=-1) self.assertTrue(quantizer, quantizers.AbsMaxQuantizer) ...
from docarray import BaseDoc, DocArray from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDoc): embedding: NdArray text: str image: ImageDoc def test_from_to_json(): da = DocArray[MyDoc]( [ MyDoc( embedding=[1, 2, 3, 4, 5],...
from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDocument): embedding: NdArray text: str image: ImageDoc def test_from_to_json(): da = DocumentArray[MyDoc]( [ MyDoc( embedd...
import os from unittest import TestCase import cv2 import numpy as np import torch from mmengine.data import InstanceData from mmdet.structures import DetDataSample from mmdet.visualization import DetLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, cy, bw, bh = torch.rand(num_boxes, 4).T tl_x = ((cx ...
import os from unittest import TestCase import cv2 import numpy as np import torch from mmengine.data import InstanceData from mmdet.data_elements import DetDataSample from mmdet.visualization import DetLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, cy, bw, bh = torch.rand(num_boxes, 4).T tl_x = ((...
import os import numpy as np import keras from keras.src import testing from keras.src.saving.file_editor import KerasFileEditor def get_source_model(): inputs = keras.Input((2,)) x = keras.layers.Dense(3, name="mydense")(inputs) outputs = keras.layers.Dense(3, name="output_layer")(x) model = keras....
import os import numpy as np import keras from keras.src import testing from keras.src.saving.file_editor import KerasFileEditor def get_source_model(): inputs = keras.Input((2,)) x = keras.layers.Dense(3, name="mydense")(inputs) outputs = keras.layers.Dense(3, name="output_layer")(x) model = keras....
_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...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='InstaBoost', action_candidate=('normal', 'horizontal', 'skip'), action_pr...
# Copyright (c) OpenMMLab. All rights reserved. # flake8: noqa from .config import * from .data import * from .dataset import * from .fileio import * from .hooks import * from .logging import * from .registry import * from .runner import * from .utils import * from .visualization import *
# Copyright (c) OpenMMLab. All rights reserved. # flake8: noqa from .config import * from .data import * from .dataset import * from .fileio import * from .hooks import * from .logging import * from .registry import * from .runner import * from .utils import *
import pytest from jina import Document, DocumentArray, Flow from ...text_paddle import TextPaddleEncoder @pytest.fixture(scope='function') def flow(): return Flow().add(uses=TextPaddleEncoder) @pytest.fixture(scope='function') def content(): return 'hello world' @pytest.fixture(scope='function') def doc...
import pytest from jina import Document, DocumentArray, Flow from jinahub.encoder.text_paddle import TextPaddleEncoder @pytest.fixture(scope='function') def flow(): return Flow().add(uses=TextPaddleEncoder) @pytest.fixture(scope='function') def content(): return 'hello world' @pytest.fixture(scope='funct...
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from torch.autograd import gradcheck from mmdet.models.utils import interpolate_as, sigmoid_geometric_mean def test_interpolate_as(): source = torch.rand((1, 5, 4, 4)) target = torch.rand((1, 1, 16, 16)) # Test 4D source and...
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmdet.models.utils import interpolate_as def test_interpolate_as(): source = torch.rand((1, 5, 4, 4)) target = torch.rand((1, 1, 16, 16)) # Test 4D source and target result = interpolate_as(source, target) asser...
"""Scrapfly Web Reader.""" import logging from typing import List, Optional, Literal from llama_index.core.readers.base import BasePydanticReader from llama_index.core.schema import Document logger = logging.getLogger(__file__) class ScrapflyReader(BasePydanticReader): """ Turn a url to llm accessible markd...
"""Scrapfly Web Reader.""" import logging from typing import List, Optional, Literal from llama_index.core.readers.base import BasePydanticReader from llama_index.core.schema import Document logger = logging.getLogger(__file__) class ScrapflyReader(BasePydanticReader): """Turn a url to llm accessible markdown w...
import abc from abc import ABC from typing import TYPE_CHECKING, Any, Generic, List, Tuple, Type, TypeVar, Union from docarray.computation import AbstractComputationalBackend from docarray.typing.abstract_type import AbstractType if TYPE_CHECKING: from pydantic import BaseConfig from pydantic.fields import Mo...
import abc from abc import ABC from typing import TYPE_CHECKING, Any, Generic, List, Tuple, Type, TypeVar, Union from docarray.computation import AbstractComputationalBackend from docarray.typing.abstract_type import AbstractType if TYPE_CHECKING: from pydantic import BaseConfig from pydantic.fields import Mo...
from functools import partial from torchaudio.models import hdemucs_high from torchaudio.pipelines import SourceSeparationBundle HDEMUCS_HIGH_MUSDB_PLUS = SourceSeparationBundle( _model_path="models/hdemucs_high_trained.pt", _model_factory_func=partial(hdemucs_high, sources=["drums", "bass", "other", "vocal...
from dataclasses import dataclass from functools import partial from typing import Callable import torch import torchaudio from torchaudio.models import hdemucs_high from torchaudio.prototype.models import conv_tasnet_base @dataclass class SourceSeparationBundle: """torchaudio.prototype.pipelines.SourceSeparati...
from abc import abstractmethod from typing import Protocol # NOTE: This is a bare-bone suggestion for an abstract protocol to define GraphRAG for llama-index # This should be expanded upon and integrated to llama-index-core to support multiple different GraphRAG # libraries in the future class GraphRAG(Protocol): ...
from abc import abstractmethod from typing import Protocol # NOTE: This is a bare-bone suggestion for an abstract protocol to define GraphRAG for llama-index # This should be expanded upon and integrated to llama-index-core to support multiple different GraphRAG # libraries in the future class GraphRAG(Protocol): ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path import librosa import numpy as np from jina import Document, DocumentArray, Executor from ...audio_clip_encoder import AudioCLIPEncoder def test_config(): ex = Executor.load_conf...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os import librosa import numpy as np from jina import Executor, Document, DocumentArray from audio_clip_encoder import AudioCLIPEncoder cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_lo...
from pathlib import Path import librosa import pytest from executor.vggish import vggish_input from executor.vggish_audio_encoder import VggishAudioEncoder from jina import Document, DocumentArray, Executor from tensorflow.python.framework import ops def test_config(): ex = Executor.load_config(str(Path(__file__...
from pathlib import Path import librosa import pytest from jina import Document, DocumentArray, Executor from tensorflow.python.framework import ops from ...vggish import vggish_input from ...vggish_audio_encoder import VggishAudioEncoder def test_config(): ex = Executor.load_config(str(Path(__file__).parents[2...
from abc import ABC from contextlib import ExitStack from rich.table import Table from jina.helper import CatchAllCleanupContextManager, get_internal_ip, get_public_ip class BaseOrchestrator(ExitStack, ABC): """Base orchestrator class""" def __enter__(self): with CatchAllCleanupContextManager(self)...
from abc import ABC from contextlib import ExitStack from rich.table import Table from jina.helper import CatchAllCleanupContextManager, get_internal_ip, get_public_ip class BaseOrchestrator(ExitStack, ABC): """Base orchestrator class""" def __enter__(self): with CatchAllCleanupContextManager(self)...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmdet.registry import MODELS, TASK_UTILS from mmdet.testing import demo_track_inputs, random_boxes from mmdet.utils import register_all_modules class TestByteTracker(TestCase): @classmethod def setUpClass(cls): ...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmdet.registry import MODELS, TASK_UTILS from mmdet.testing import demo_track_inputs, random_boxes from mmdet.utils import register_all_modules class TestByteTracker(TestCase): @classmethod def setUpClass(cls): ...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from tempfile import TemporaryDirectory from unittest import TestCase, skipIf from mmengine.registry import (Registry, count_registered_modules, root, traverse_registry_tree) from mmengine.utils import is_installed c...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from tempfile import TemporaryDirectory from unittest import TestCase from mmengine.registry import (Registry, count_registered_modules, root, traverse_registry_tree) class TestUtils(TestCase): def test_traverse...
from typing import Any, Dict, Iterator import torch from ..utils import _log_api_usage_once try: from ._load_gpu_decoder import _HAS_GPU_VIDEO_DECODER except ModuleNotFoundError: _HAS_GPU_VIDEO_DECODER = False from ._video_opt import ( _HAS_CPU_VIDEO_DECODER, _HAS_VIDEO_OPT, _probe_video_from_fi...
from typing import Any, Dict, Iterator import torch from ..utils import _log_api_usage_once try: from ._load_gpu_decoder import _HAS_GPU_VIDEO_DECODER except ModuleNotFoundError: _HAS_GPU_VIDEO_DECODER = False from ._video_opt import ( _HAS_CPU_VIDEO_DECODER, _HAS_VIDEO_OPT, _probe_video_from_fi...
import logging import re from collections.abc import Sequence from typing import Optional, Union from urllib.parse import urljoin, urlparse logger = logging.getLogger(__name__) PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#") SUFFIXES_TO_IGNORE = ( ".css", ".js", ".ico", ".png", ".jpg", "....
import logging import re from collections.abc import Sequence from typing import Optional, Union from urllib.parse import urljoin, urlparse logger = logging.getLogger(__name__) PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#") SUFFIXES_TO_IGNORE = ( ".css", ".js", ".ico", ".png", ".jpg", "....
import numpy as np from docarray import DocumentArray, Document def random_docs( num_docs, chunks_per_doc=5, embed_dim=10, jitter=1, start_id=0, embedding=True, sparse_embedding=False, text='hello world', ) -> DocumentArray: da = DocumentArray() next_chunk_doc_id = start_id + n...
import numpy as np from docarray import DocumentArray, Document def random_docs( num_docs, chunks_per_doc=5, embed_dim=10, jitter=1, start_id=0, embedding=True, sparse_embedding=False, text='hello world', ) -> DocumentArray: da = DocumentArray() next_chunk_doc_id = start_id + ...
""" This tool allows agents to interact with the NASA API, specifically the the NASA Image & Video Library and Exoplanet """ from typing import Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.utiliti...
""" This tool allows agents to interact with the NASA API, specifically the the NASA Image & Video Library and Exoplanet """ from typing import Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.utiliti...
import os from typing import Type from pydantic import BaseModel, Field from docarray.document.abstract_document import AbstractDocument from docarray.document.base_node import BaseNode from docarray.typing import ID from .mixins import ProtoMixin class BaseDocument(BaseModel, ProtoMixin, AbstractDocument, BaseNod...
import os from typing import Union from uuid import UUID from pydantic import BaseModel, Field from docarray.document.abstract_document import AbstractDocument from docarray.document.base_node import BaseNode from .mixins import ProtoMixin class BaseDocument(BaseModel, ProtoMixin, AbstractDocument, BaseNode): ...
from __future__ import annotations from typing import Any, List, Optional, Tuple, Union import PIL.Image import torch from torchvision.transforms import InterpolationMode from ._datapoint import Datapoint, FillTypeJIT class Mask(Datapoint): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: ...
from __future__ import annotations from typing import Any, List, Optional, Tuple, Union import torch from torchvision.transforms import InterpolationMode from ._datapoint import Datapoint, FillTypeJIT class Mask(Datapoint): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: return tensor.as...
from typing import Union import numpy as np import pytest import torch from docarray import BaseDocument, DocumentArray from docarray.typing import NdArray, TorchTensor @pytest.fixture() def batch(): class Image(BaseDocument): tensor: TorchTensor[3, 224, 224] batch = DocumentArray[Image]( [...
from typing import Union import numpy as np import pytest import torch from docarray import Document, DocumentArray from docarray.typing import NdArray, TorchTensor @pytest.fixture() def batch(): class Image(Document): tensor: TorchTensor[3, 224, 224] batch = DocumentArray[Image]( [Image(te...
import sys import pytest from hypothesis import given, settings, strategies import xgboost as xgb from xgboost import testing as tm from xgboost.testing import no_cupy from xgboost.testing.updater import check_extmem_qdm, check_quantile_loss_extmem sys.path.append("tests/python") from test_data_iterator import run_d...
import sys import pytest from hypothesis import given, settings, strategies import xgboost as xgb from xgboost import testing as tm from xgboost.testing import no_cupy from xgboost.testing.updater import check_extmem_qdm, check_quantile_loss_extmem sys.path.append("tests/python") from test_data_iterator import run_d...
"""Various utilities to help with development.""" # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from ..exceptions import DataConversionWarning from . import metadata_routing from ._bunch import Bunch from ._chunking import gen_batches, gen_even_slices from ._estimator_html_repr import...
"""Various utilities to help with development.""" # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import platform import warnings from collections.abc import Sequence import numpy as np from ..exceptions import DataConversionWarning from . import _joblib, metadata_routing from ._bunch...
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.116.1" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile from...
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.116.0" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile from...
import logging import os from argparse import ArgumentParser import sentencepiece as spm from average_checkpoints import ensemble from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint from pytorch_lightning.strategies import DDPStrategy from...
import logging import os from argparse import ArgumentParser import sentencepiece as spm from average_checkpoints import ensemble from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint from pytorch_lightning.strategies import DDPStrategy from...
import os from pathlib import Path from typing import List, Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.librispeech import _get_librispeech_metadata from torchaudio.datasets.utils import extract_archive...
import os from pathlib import Path from typing import List, Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.librispeech import _get_librispeech_metadata from torchaudio.datasets.utils import extract_archive...
# coding=utf-8 # Copyright 2025 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 2025 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 2025 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 typing import List, Optional, Tuple import torch from torch import Tensor from mmdet.core.utils.typing import ConfigType, OptMultiConfig from mmdet.registry import MODELS from .base_roi_extractor import BaseRoIExtractor @MODELS.register_module() class SingleRoIEx...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.registry import MODELS from .base_roi_extractor import BaseRoIExtractor @MODELS.register_module() class SingleRoIExtractor(BaseRoIExtractor): """Extract RoI features from a single level feature map. If there are multiple input feature l...
import pytest from langchain._api import suppress_langchain_deprecation_warning as sup2 from langchain_core._api import suppress_langchain_deprecation_warning as sup1 from langchain_cli.namespaces.migrate.generate.generic import ( generate_simplified_migrations, ) @pytest.mark.xfail(reason="Unknown reason") def ...
import pytest from langchain._api import suppress_langchain_deprecation_warning as sup2 from langchain_core._api import suppress_langchain_deprecation_warning as sup1 from langchain_cli.namespaces.migrate.generate.generic import ( generate_simplified_migrations, ) @pytest.mark.xfail(reason="Unknown reason") def ...
""" Prompts for implementing Chain of Abstraction. While official prompts are not given (and the paper finetunes models for the task), we can take inspiration and use few-shot prompting to generate a prompt for implementing chain of abstraction in an LLM agent. """ REASONING_PROMPT_TEMPALTE = """Generate an abstract ...
""" Prompts for implementing Chain of Abstraction. While official prompts are not given (and the paper finetunes models for the task), we can take inspiration and use few-shot prompting to generate a prompt for implementing chain of abstraction in an LLM agent. """ REASONING_PROMPT_TEMPALTE = """Generate an abstract...
_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( # use ResNeSt img_norm data_preprocessor=dict( mean=[123.68, 116.779, 103.939], std=[58.393, 57.12, 57.375], bgr_to_rgb=True), backbone=dict( type='ResNeS...
_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( # use ResNeSt img_norm data_preprocessor=dict( mean=[123.68, 116.779, 103.939], std=[58.393, 57.12, 57.375], bgr_to_rgb=True), backbone=dict( type='ResNeS...
import numpy as np import pytest from pydantic import Field from docarray import BaseDoc, DocList from docarray.index.backends.in_memory import InMemoryExactNNIndex from docarray.typing import NdArray class SchemaDoc(BaseDoc): text: str price: int tensor: NdArray[10] @pytest.fixture def docs(): doc...
import numpy as np import pytest from pydantic import Field from docarray import BaseDoc, DocList from docarray.index.backends.in_memory import InMemoryExactNNIndex from docarray.typing import NdArray class SchemaDoc(BaseDoc): text: str price: int tensor: NdArray[10] @pytest.fixture def docs(): doc...
import unittest import torch import torchaudio.prototype.functional as F from torchaudio_unittest.common_utils import nested_params, TestBaseMixin, torch_script class TorchScriptConsistencyTestImpl(TestBaseMixin): def _assert_consistency(self, func, inputs, shape_only=False): inputs_ = [] for i i...
import unittest import torch import torchaudio.prototype.functional as F from torchaudio_unittest.common_utils import nested_params, TestBaseMixin, torch_script class TorchScriptConsistencyTestImpl(TestBaseMixin): def _assert_consistency(self, func, inputs, shape_only=False): inputs_ = [] for i i...
from langchain_core.prompts.prompt import PromptTemplate web_search_template = """Please write a passage to answer the question Question: {QUESTION} Passage:""" web_search = PromptTemplate(template=web_search_template, input_variables=["QUESTION"]) sci_fact_template = """Please write a scientific paper passage to supp...
# flake8: noqa from langchain_core.prompts.prompt import PromptTemplate web_search_template = """Please write a passage to answer the question Question: {QUESTION} Passage:""" web_search = PromptTemplate(template=web_search_template, input_variables=["QUESTION"]) sci_fact_template = """Please write a scientific paper...
""" This script downloads the WikiMatrix corpus (https://github.com/facebookresearch/LASER/tree/master/tasks/WikiMatrix) and create parallel sentences tsv files that can be used to extend existent sentence embedding models to new languages. The WikiMatrix mined parallel sentences from Wikipedia in various languages. ...
""" This script downloads the WikiMatrix corpus (https://github.com/facebookresearch/LASER/tree/master/tasks/WikiMatrix) and create parallel sentences tsv files that can be used to extend existent sentence embedding models to new languages. The WikiMatrix mined parallel sentences from Wikipedia in various languages. ...
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn from sentence_transformers import util from sentence_transformers.sparse_encoder.losses.CSRReconstructionLoss import CSRReconstructionLoss from sentence_transformers.sparse_encoder.losses.SparseMultipleNegative...
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn from sentence_transformers.sparse_encoder.losses.CSRReconstructionLoss import CSRReconstructionLoss from sentence_transformers.sparse_encoder.losses.SparseMultipleNegativesRankingLoss import ( SparseMultipl...
"""Common test fixtures with proper setup and teardown.""" from contextlib import asynccontextmanager from typing import AsyncGenerator from unittest.mock import Mock, patch import pytest from prisma import Prisma @pytest.fixture async def test_db_connection() -> AsyncGenerator[Prisma, None]: """Provide a test ...
"""Common test fixtures with proper setup and teardown.""" from contextlib import asynccontextmanager from typing import AsyncGenerator from unittest.mock import Mock, patch import pytest from prisma import Prisma @pytest.fixture async def test_db_connection() -> AsyncGenerator[Prisma, None]: """Provide a test ...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.activations import deserialize from keras.src.activations import get from keras.src.activations import serialize from keras.src.activations.activations import celu from keras.src.acti...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.activations import deserialize from keras.src.activations import get from keras.src.activations import serialize from keras.src.activations.activations import celu from keras.src.acti...
from typing import Annotated, Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
from typing import Annotated, Union from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results
from collections import defaultdict import torch import transforms as reference_transforms def get_modules(use_v2): # We need a protected import to avoid the V2 warning in case just V1 is used if use_v2: import torchvision.datapoints import torchvision.transforms.v2 return torchvisio...
from collections import defaultdict import torch import transforms as reference_transforms def get_modules(use_v2): # We need a protected import to avoid the V2 warning in case just V1 is used if use_v2: import torchvision.datapoints import torchvision.transforms.v2 return torchvisio...
from __future__ import annotations from typing import Any import torch from torch import nn from transformers import AutoConfig, AutoModelForMaskedLM, AutoTokenizer # TODO: Check the tokenizer problem and if more need to be implement like the Transformer class class MLMTransformer(nn.Module): """A minimal Tran...
from __future__ import annotations from typing import Any import torch from torch import nn from transformers import AutoConfig, AutoModelForMaskedLM, AutoTokenizer class MLMTransformer(nn.Module): """A minimal Transformer model that uses MLM (Masked Language Modeling). This model implements only the essen...
"""Standard LangChain interface tests""" from langchain_core.language_models import BaseChatModel from langchain_tests.unit_tests import ( # type: ignore[import-not-found] ChatModelUnitTests, # type: ignore[import-not-found] ) from langchain_fireworks import ChatFireworks class TestFireworksStandard(ChatModel...
"""Standard LangChain interface tests""" from langchain_core.language_models import BaseChatModel from langchain_tests.unit_tests import ( # type: ignore[import-not-found] ChatModelUnitTests, # type: ignore[import-not-found] ) from langchain_fireworks import ChatFireworks class TestFireworksStandard(ChatModel...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, auto_fp16, force_fp32 from mmdet.models.builder import HEADS from mmdet.models.utils import ResLayer, SimplifiedBasicBlock @HEADS.register_module() class GlobalContextHead(BaseMod...
import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, auto_fp16, force_fp32 from mmdet.models.builder import HEADS from mmdet.models.utils import ResLayer, SimplifiedBasicBlock @HEADS.register_module() class GlobalContextHead(BaseModule): """Global context head used in `SCNet ...
import numpy as np import pytest from keras.src import layers from keras.src.testing import test_case class ActivityRegularizationTest(test_case.TestCase): def test_correctness(self): layer = layers.ActivityRegularization(l1=0.2, l2=0.3) layer(2 * np.ones((1,))) self.assertLen(layer.losse...
import numpy as np import pytest from keras.src import layers from keras.src.testing import test_case class ActivityRegularizationTest(test_case.TestCase): def test_correctness(self): layer = layers.ActivityRegularization(l1=0.2, l2=0.3) layer(2 * np.ones((1,))) self.assertLen(layer.losse...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase from unittest.mock import MagicMock, Mock, patch from mmengine.hooks import IterTimerHook from mmengine.logging import MessageHub def time_patch(): if not hasattr(time_patch, 'time'): time_patch.time = 0 else: time_...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock from mmengine.hooks import IterTimerHook class TestIterTimerHook: def test_before_epoch(self): hook = IterTimerHook() runner = Mock() hook._before_epoch(runner) assert isinstance(hook.t, float) de...
from unittest.mock import patch import pytest from llama_index.utils.workflow import ( draw_all_possible_flows, draw_most_recent_execution, ) @pytest.mark.asyncio async def test_workflow_draw_methods(workflow): with patch("pyvis.network.Network") as mock_network: draw_all_possible_flows(workflow...
from unittest.mock import patch import pytest from llama_index.utils.workflow import ( draw_all_possible_flows, draw_most_recent_execution, ) @pytest.mark.asyncio() async def test_workflow_draw_methods(workflow): with patch("pyvis.network.Network") as mock_network: draw_all_possible_flows(workfl...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np 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 balanced_l1_loss(pred, target, beta...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np 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 balanced_l1_loss(pred, target, beta=1.0,...
from __future__ import annotations import json import os from typing import Any import torch from torch import nn class SpladePooling(nn.Module): """SPLADE pooling layer that aggregates MLM logits using max or sum pooling. This pooling layer takes MLM logits (shape: batch_size, seq_length, vocab_size) ...
from __future__ import annotations import json import os from typing import Any import torch from torch import nn class SpladePooling(nn.Module): """SPLADE pooling layer that aggregates MLM logits using max or sum pooling. This pooling layer takes MLM logits (shape: batch_size, seq_length, vocab_size) ...
import os import numpy as np import pytest from docarray import BaseDoc, DocList, DocVec from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDoc): embedding: NdArray text: str image: ImageDoc @pytest.mark.slow @pytest.mark.parametrize( 'protocol', ['pickle-a...
import os import numpy as np import pytest from docarray import BaseDoc, DocList from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDoc): embedding: NdArray text: str image: ImageDoc @pytest.mark.slow @pytest.mark.parametrize( 'protocol', ['pickle-array', '...
_base_ = './fcos_r50-caffe_fpn_gn-head_1x_coco.py' # model settings model = dict( data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32), backbone=dict( type='ResNeXt'...
_base_ = './fcos_r50-caffe_fpn_gn-head_1x_coco.py' # model settings model = dict( data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32), backbone=dict( type='ResNeXt'...
_base_ = './cascade-mask-rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings preprocess_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, pad_size_divisor=32) model = dict( preprocess_cfg=prepr...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='PAA', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=di...
# 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 threading import fsspec.asyn import torch from ...iterable_dataset import IterableDataset, _apply_feature_types_on_example from ...utils.logging import get_logger logger = get_logger(__name__) def _set_fsspec_for_multiprocess() -> None: """ Clear reference to the loop and thread. This is necess...
import threading import fsspec.asyn import torch from ...iterable_dataset import IterableDataset, _apply_feature_types from ...utils.logging import get_logger logger = get_logger(__name__) def _set_fsspec_for_multiprocess() -> None: """ Clear reference to the loop and thread. This is necessary otherwi...
from typing import Union, Iterable, Dict, List import warnings from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, ...
from typing import Union, Iterable, Dict, List import warnings from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, ...
""" 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...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import logging import os import os.path as osp from mmengine.config import Config, DictAction from mmengine.logging import print_log from mmengine.registry import RUNNERS from mmengine.runner import Runner from mmdet.utils import register_all_modules d...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import logging import os import os.path as osp from mmengine.config import Config, DictAction from mmengine.logging import print_log from mmengine.registry import RUNNERS from mmengine.runner import Runner from mmdet.utils import register_all_modules d...
"""Utilities for environment variables.""" from __future__ import annotations import os from typing import Any, Optional, Union def env_var_is_set(env_var: str) -> bool: """Check if an environment variable is set. Args: env_var (str): The name of the environment variable. Returns: bool...
from __future__ import annotations import os from typing import Any, Optional, Union def env_var_is_set(env_var: str) -> bool: """Check if an environment variable is set. Args: env_var (str): The name of the environment variable. Returns: bool: True if the environment variable is set, F...