input
stringlengths
33
5k
output
stringlengths
32
5k
# Copyright (c) OpenMMLab. All rights reserved. from .base_loop import BaseLoop from .checkpoint import (CheckpointLoader, get_deprecated_model_names, get_external_models, get_mmcls_models, get_state_dict, get_torchvision_models, load_checkpoint, ...
# Copyright (c) OpenMMLab. All rights reserved. from .checkpoint import (CheckpointLoader, get_deprecated_model_names, get_external_models, get_mmcls_models, get_state_dict, get_torchvision_models, load_checkpoint, load_state_dict, save_checkpoi...
"""Embeddings.""" from typing import Any, List from unittest.mock import patch from llama_index.core.base.embeddings.base import SimilarityMode, mean_agg from llama_index.core.embeddings.mock_embed_model import MockEmbedding def mock_get_text_embedding(text: str) -> List[float]: """Mock get text embedding.""" ...
"""Embeddings.""" from typing import Any, List from unittest.mock import patch from llama_index.core.base.embeddings.base import SimilarityMode, mean_agg from llama_index.core.embeddings.mock_embed_model import MockEmbedding def mock_get_text_embedding(text: str) -> List[float]: """Mock get text embedding.""" ...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS MODELS.register_module('Linear', module=nn.Linear) @MODELS.register_module(name='NormedLinear') class NormedLinear(nn.Linear): """Normalized Linear Layer. Arg...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import CONV_LAYERS from .builder import LINEAR_LAYERS @LINEAR_LAYERS.register_module(name='NormedLinear') class NormedLinear(nn.Linear): """Normalized Linear Layer. Args: ...
# Copyright (c) OpenMMLab. All rights reserved. from .dist import (all_gather_object, all_reduce, all_gather, all_reduce_dict, collect_results, gather, broadcast, gather_object, sync_random_seed, broadcast_object_list, collect_results_cpu, collect_results_gpu) fr...
# Copyright (c) OpenMMLab. All rights reserved. from .dist import (all_gather_object, all_reduce, all_gather, all_reduce_dict, collect_results, gather, broadcast, gather_object, sync_random_seed, broadcast_object_list, collect_results_cpu, collect_results_gpu) fr...
from docarray.dataclasses.types import dataclass, is_multimodal, field
from .types import dataclass, is_multimodal, field
import os import subprocess import sys import time def wait_for_postgres(max_retries=5, delay=5): for _ in range(max_retries): try: result = subprocess.run( [ "docker", "compose", "-f", "docker-comp...
import subprocess import sys import time def wait_for_postgres(max_retries=5, delay=5): for _ in range(max_retries): try: result = subprocess.run( [ "docker", "compose", "-f", "docker-compose.test.y...
"""Init file of LlamaIndex.""" __version__ = "0.12.34.post1" 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...
"""Init file of LlamaIndex.""" __version__ = "0.12.33.post1" 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...
from typing import Callable, Dict, Any, List, Optional, Awaitable from ag_ui.core import RunAgentInput from fastapi import APIRouter from fastapi.responses import StreamingResponse from llama_index.core.llms.function_calling import FunctionCallingLLM from llama_index.core.workflow import Workflow from llama_index.pro...
from typing import Callable, Dict, Any, List, Optional, Awaitable from ag_ui.core import RunAgentInput from fastapi import APIRouter from fastapi.responses import StreamingResponse from llama_index.core.llms.function_calling import FunctionCallingLLM from llama_index.core.workflow import Workflow from llama_index.pro...
from ._tts import ( TACOTRON2_GRIFFINLIM_CHAR_LJSPEECH, TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH, TACOTRON2_WAVERNN_CHAR_LJSPEECH, TACOTRON2_WAVERNN_PHONE_LJSPEECH, Tacotron2TTSBundle, ) from ._wav2vec2.impl import ( HUBERT_ASR_LARGE, HUBERT_ASR_XLARGE, HUBERT_BASE, HUBERT_LARGE, HUBE...
from ._tts import ( Tacotron2TTSBundle, TACOTRON2_GRIFFINLIM_CHAR_LJSPEECH, TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH, TACOTRON2_WAVERNN_CHAR_LJSPEECH, TACOTRON2_WAVERNN_PHONE_LJSPEECH, ) from ._wav2vec2.impl import ( Wav2Vec2Bundle, Wav2Vec2ASRBundle, WAV2VEC2_BASE, WAV2VEC2_LARGE, WA...
import os import pytest from docarray import Document from jina import Executor, Flow, requests class MyExec(Executor): @requests def foo(self, docs, **kwargs): pass @pytest.fixture def cert_prefix(): cur_dir = os.path.dirname(os.path.abspath(__file__)) return f'{cur_dir}/../../../unit/ser...
import os import pytest from docarray import Document from jina import Executor, Flow, requests class MyExec(Executor): @requests def foo(self, docs, **kwargs): pass @pytest.fixture def cert_prefix(): cur_dir = os.path.dirname(os.path.abspath(__file__)) return f'{cur_dir}/../../../unit/ser...
# coding=utf-8 # Copyright 2025 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 2024 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...
import os import urllib import numpy as np import PIL 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 ImageUrl CUR_DIR = os.path.dirname(os.path.abspath(__file__)) PATH_TO_IMAGE_DATA = os.path.join(CUR_DIR, '..'...
import os import urllib import numpy as np import PIL import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import ImageUrl CUR_DIR = os.path.dirname(os.path.abspath(__file__)) PATH_TO_IMAGE_DATA = os.path.join(CUR_DIR, '..', '.....
"""Testing code shared by other tests.""" # pylint: disable=invalid-name import collections import importlib.util import json import os import tempfile from typing import Any, Callable, Dict, Type import numpy as np import xgboost as xgb from xgboost._typing import ArrayLike def validate_leaf_output(leaf: np.ndarr...
"""Testing code shared by other tests.""" # pylint: disable=invalid-name import collections import importlib.util import json import os import tempfile from typing import Any, Callable, Dict, Type import numpy as np import xgboost as xgb from xgboost._typing import ArrayLike def validate_leaf_output(leaf: np.ndarr...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: docarray.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: docarray.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool...
""" Quantile Regression =================== .. versionadded:: 2.0.0 The script is inspired by this awesome example in sklearn: https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html .. note:: The feature is only supported using the Python, R, and C packages. In addition,...
""" Quantile Regression =================== .. versionadded:: 2.0.0 The script is inspired by this awesome example in sklearn: https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html .. note:: The feature is only supported using the Python, R, and C packages. In addition,...
from langchain_core.messages import AIMessage, ToolCall, ToolMessage from langchain.agents.format_scratchpad.openai_tools import ( format_to_openai_tool_messages, ) from langchain.agents.output_parsers.openai_tools import ( parse_ai_message_to_openai_tool_action, ) def test_calls_convert_agent_action_to_mess...
from langchain_core.messages import AIMessage, ToolCall, ToolMessage from langchain.agents.format_scratchpad.openai_tools import ( format_to_openai_tool_messages, ) from langchain.agents.output_parsers.openai_tools import ( parse_ai_message_to_openai_tool_action, ) def test_calls_convert_agent_action_to_mess...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule, auto_fp16 from mmdet.registry import MODELS @MODELS.register_module() class FeatureRelayHead(BaseModule): """Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_. Args: in_chan...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule, auto_fp16 from mmdet.models.builder import HEADS @HEADS.register_module() class FeatureRelayHead(BaseModule): """Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_. Args: in_...
import asyncio import copy from typing import Any, List, TYPE_CHECKING from jina.serve.runtimes.servers import BaseServer if TYPE_CHECKING: from jina.logging.logger import JinaLogger class CompositeBaseServer(BaseServer): """Composite Base Server implementation from which u can inherit a specific custom com...
import asyncio import copy from typing import Any, List, TYPE_CHECKING from jina.serve.runtimes.servers import BaseServer if TYPE_CHECKING: from jina.logging.logger import JinaLogger class CompositeBaseServer(BaseServer): """Composite Base Server implementation from which u can inherit a specific custom com...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' 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='LoadPanopticAnnotations', with_bbox=True, wit...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' 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='LoadPanopticAnnotations', with_bbox=True, wit...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict, List import torch from torch.nn.parallel.distributed import DistributedDataParallel from mmengine.data import BaseDataElement from mmengine.optim import OptimWrapper from mmengine.registry import MODEL_WRAPPERS from ..utils import detect_anomalo...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict, List import torch from torch.nn.parallel.distributed import DistributedDataParallel from mmengine.data import BaseDataElement from mmengine.optim import OptimWrapper from mmengine.registry import MODEL_WRAPPERS from ..utils import detect_anomalo...
from typing import Union, Iterable, Dict import warnings from ..base.seqlike import BaseSequenceLikeMixin from .... import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, other): """Compare this...
from typing import Union, Iterable, Dict from ..base.seqlike import BaseSequenceLikeMixin from .... import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, other): """Compare this object to the o...
# 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...
import os from pathlib import Path import cv2 import pytest from jina import Document, DocumentArray, Executor from yolov5_segmenter import YoloV5Segmenter cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_load(): segmenter = Executor.load_config(str(Path(__file__).parents[2] / 'config.yml')) as...
import os from pathlib import Path import cv2 import pytest from jina import Document, DocumentArray, Executor from ...yolov5_segmenter import YoloV5Segmenter cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_load(): segmenter = Executor.load_config(str(Path(__file__).parents[2] / 'config.yml')) ...
from os.path import join from typing import Any, Callable, List, Optional, Tuple from PIL import Image from .utils import check_integrity, download_and_extract_archive, list_dir, list_files from .vision import VisionDataset class Omniglot(VisionDataset): """`Omniglot <https://github.com/brendenlake/omniglot>`_ ...
from os.path import join from typing import Any, Callable, List, Optional, Tuple from PIL import Image from .utils import check_integrity, download_and_extract_archive, list_dir, list_files from .vision import VisionDataset class Omniglot(VisionDataset): """`Omniglot <https://github.com/brendenlake/omniglot>`_ ...
from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode from llama_index.vector_stores.qdrant import QdrantVectorStore import qdrant_client import pytest_asyncio @pytest_asyncio.fixture async def vector_store() -> QdrantVectorStore: client = qdrant_client.QdrantClient(":memory:") aclie...
from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode from llama_index.vector_stores.qdrant import QdrantVectorStore import qdrant_client import pytest_asyncio @pytest_asyncio.fixture async def vector_store() -> QdrantVectorStore: client = qdrant_client.QdrantClient(":memory:") aclie...
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_doc import BaseDoc from docarray.documents.point_cloud.points_and_colors import PointsAndColors from docarray.typing import AnyEmbedding, PointCloud3DUrl from docarray.typing.tensor.abstract_tensor import Abstr...
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_doc import BaseDoc from docarray.documents.point_cloud.points_and_colors import PointsAndColors from docarray.typing import AnyEmbedding, PointCloud3DUrl from docarray.typing.tensor.abstract_tensor import Abstr...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2024 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 # # Unles...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2024 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 # # Unles...
""" Tool implementations for the Riza (https://riza.io) code interpreter API. Documentation: https://docs.riza.io API keys: https://dashboard.riza.io """ from typing import Any, Optional, Type from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool, Tool...
""" Tool implementations for the Riza (https://riza.io) code interpreter API. Documentation: https://docs.riza.io API keys: https://dashboard.riza.io """ from typing import Any, Optional, Type from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool, Tool...
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.utils.parrots_wrapper import TORCH_VERSION from mmengine.utils.version_utils import digit_version from .averaged_model import (ExponentialMovingAverage, MomentumAnnealingEMA, StochasticWeightAverage) from .base_model import BaseD...
# Copyright (c) OpenMMLab. All rights reserved. from .averaged_model import (ExponentialMovingAverage, MomentumAnnealingEMA, StochasticWeightAverage) from .base_model import BaseDataPreprocessor, BaseModel, ImgDataPreprocessor from .base_module import BaseModule, ModuleDict, ModuleList, Seq...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.10.1' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versi...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.10.0' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versi...
_base_ = [ '../_base_/models/faster-rcnn_r50-caffe-dc5.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # use caffe img_norm img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ ...
_base_ = [ '../_base_/models/faster_rcnn_r50_caffe_dc5.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # use caffe img_norm img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ ...
from __future__ import annotations from collections.abc import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer, util class DistillKLDivLoss(nn.Module): # TODO def __init__(self, model: SentenceTransformer, similarity_fct=util.pairwise_dot_score) -> ...
from __future__ import annotations from collections.abc import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer, util class DistillKLDivLoss(nn.Module): # TODO def __init__(self, model: SentenceTransformer, similarity_fct=util.pairwise_dot_score) -> ...
from dataclasses import dataclass, asdict, field from typing import ( Union, Dict, Optional, TYPE_CHECKING, Iterable, List, Tuple, ) import numpy as np from docarray.array.storage.base.backend import BaseBackendMixin, TypeMap from docarray.helper import dataclass_from_dict, filter_dict, _s...
from dataclasses import dataclass, asdict, field from typing import ( Union, Dict, Optional, TYPE_CHECKING, Iterable, List, Tuple, ) import numpy as np from docarray.array.storage.base.backend import BaseBackendMixin, TypeMap from docarray.helper import dataclass_from_dict, filter_dict, _s...
from langchain_core.prompts import PromptTemplate prompt_template = """Write a concise summary of the following: "{text}" CONCISE SUMMARY:""" PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
# flake8: noqa from langchain_core.prompts import PromptTemplate prompt_template = """Write a concise summary of the following: "{text}" CONCISE SUMMARY:""" PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
from typing import List, cast import numpy as np from distributed import Client, Scheduler, Worker, get_worker from distributed.utils_test import gen_cluster import xgboost as xgb from xgboost import testing as tm from xgboost.compat import concat def run_external_memory(worker_id: int, n_workers: int, comm_args: d...
from typing import List, cast import numpy as np from distributed import Client, Scheduler, Worker, get_worker from distributed.utils_test import gen_cluster import xgboost as xgb from xgboost import testing as tm from xgboost.compat import concat def run_external_memory(worker_id: int, n_workers: int, comm_args: d...
from typing import Dict import torch.nn.functional as F from torch import Tensor, nn class Normalize(nn.Module): """This layer normalizes embeddings to unit length""" def __init__(self): super(Normalize, self).__init__() def forward(self, features: Dict[str, Tensor]): features.update({"...
from torch import Tensor from torch import nn from typing import Dict import torch.nn.functional as F class Normalize(nn.Module): """This layer normalizes embeddings to unit length""" def __init__(self): super(Normalize, self).__init__() def forward(self, features: Dict[str, Tensor]): fe...
from typing import Dict, Set from fastapi import WebSocket from backend.data import execution from backend.server.model import Methods, WsMessage class ConnectionManager: def __init__(self): self.active_connections: Set[WebSocket] = set() self.subscriptions: Dict[str, Set[WebSocket]] = {} a...
from typing import Dict, Set from fastapi import WebSocket from backend.data import execution from backend.server.model import Methods, WsMessage class ConnectionManager: def __init__(self): self.active_connections: Set[WebSocket] = set() self.subscriptions: Dict[str, Set[WebSocket]] = {} a...
# Copyright (c) OpenMMLab. All rights reserved. import copy import os.path as osp import mmcv import numpy as np from mmdet.datasets.pipelines import (LoadImageFromFile, LoadImageFromWebcam, LoadMultiChannelImageFromFiles) class TestLoading: @classmethod def setup_clas...
# Copyright (c) OpenMMLab. All rights reserved. import copy import os.path as osp import mmcv import numpy as np from mmdet.datasets.pipelines import (LoadImageFromFile, LoadImageFromWebcam, LoadMultiChannelImageFromFiles) class TestLoading: @classmethod def setup_clas...
# Copyright (c) OpenMMLab. All rights reserved. import os import os.path as osp import tempfile import mmcv import numpy as np import pytest import torch from mmdet.core import visualization as vis def test_color(): assert vis.color_val_matplotlib(mmcv.Color.blue) == (0., 0., 1.) assert vis.color_val_matplo...
# Copyright (c) Open-MMLab. All rights reserved. import os import os.path as osp import tempfile import mmcv import numpy as np import pytest import torch from mmdet.core import visualization as vis def test_color(): assert vis.color_val_matplotlib(mmcv.Color.blue) == (0., 0., 1.) assert vis.color_val_matpl...
from __future__ import annotations from typing import Any, Optional, Union import torch from ._datapoint import Datapoint class Video(Datapoint): """[BETA] :class:`torch.Tensor` subclass for videos. Args: data (tensor-like): Any data that can be turned into a tensor with :func:`torch.as_tensor`. ...
from __future__ import annotations from typing import Any, Optional, Union import torch from ._datapoint import Datapoint class Video(Datapoint): """[BETA] :class:`torch.Tensor` subclass for videos. Args: data (tensor-like): Any data that can be turned into a tensor with :func:`torch.as_tensor`. ...
# 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...
import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDoc from docarray.documents import PointCloud3D from docarray.utils._internal.misc import is_tf_available from tests import TOYDATA_DIR tf_available = is_tf_available() if tf_available: import tensorflow as tf...
_base_ = '../rpn/rpn_r50-caffe_fpn_1x_coco.py' model = dict( rpn_head=dict( _delete_=True, type='GARPNHead', in_channels=256, feat_channels=256, approx_anchor_generator=dict( type='AnchorGenerator', octave_base_scale=8, scales_per_octave=3,...
_base_ = '../rpn/rpn_r50_caffe_fpn_1x_coco.py' model = dict( rpn_head=dict( _delete_=True, type='GARPNHead', in_channels=256, feat_channels=256, approx_anchor_generator=dict( type='AnchorGenerator', octave_base_scale=8, scales_per_octave=3,...
# 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...
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS FINAL_ANSWER_ACTION = "Final Answer:" MISSING_ACT...
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS FINAL_ANSWER_ACTION = "Final Answer:" MISSING_ACT...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet import * # noqa from mmdet.structures import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modu...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet import * # noqa from mmdet.data_elements import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_m...
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder import CrossEncoder from sentence_transformers.util import fullname class MSELoss(nn.Module): def __init__(self, model: CrossEncoder, **kwargs) -> None: super().__init__() self.model = model ...
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder import CrossEncoder # TODO: This loss hasn't been tested yet class MSELoss(nn.Module): def __init__(self, model: CrossEncoder, **kwargs) -> None: super().__init__() self.model = model ...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.25.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.24.1' 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...
_base_ = './faster-rcnn_r50-caffe-dc5_ms-1x_coco.py' # learning policy lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
_base_ = './faster_rcnn_r50_caffe_dc5_mstrain_1x_coco.py' # learning policy lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
from unittest.mock import AsyncMock, Mock import pytest from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks.base import CallbackManager from llama_index.embeddings.oci_data_science import OCIDataScienceEmbedding from llama_index.embeddings.oci_data_science.client import Asyn...
from unittest.mock import AsyncMock, Mock import pytest from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.callbacks.base import CallbackManager from llama_index.embeddings.oci_data_science import OCIDataScienceEmbedding from llama_index.embeddings.oci_data_science.client import Asyn...
import asyncio import logging import sentry_sdk from pydantic import SecretStr from sentry_sdk.integrations.anthropic import AnthropicIntegration from sentry_sdk.integrations.logging import LoggingIntegration from backend.util.settings import Settings def sentry_init(): sentry_dsn = Settings().secrets.sentry_ds...
import logging import sentry_sdk from sentry_sdk.integrations.anthropic import AnthropicIntegration from sentry_sdk.integrations.logging import LoggingIntegration from backend.util.settings import Settings def sentry_init(): sentry_dsn = Settings().secrets.sentry_dsn sentry_sdk.init( dsn=sentry_dsn,...
# 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 import TYPE_CHECKING, Any, Dict, List, Optional, TypeVar import numpy as np from pydantic import parse_obj_as from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.ndarray import NdArray from docarray.typing.url.mimetypes import MESH_EXTRA_EXTENSIONS from docarray.typing.u...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseEmbeddingSimilarityEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser...
import logging from datasets import load_dataset from sentence_transformers.sparse_encoder import ( MLMTransformer, SparseEmbeddingSimilarityEvaluator, SparseEncoder, SpladePooling, ) logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) # Initializ...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from parameterized import parameterized from mmdet.models import build_detector from mmdet.structures import DetDataSample from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modules class...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from parameterized import parameterized from mmdet.models import build_detector from mmdet.structures import DetDataSample from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modules class...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseRerankingEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembled...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseRerankingEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembled...
# Copyright (c) OpenMMLab. All rights reserved. import os import subprocess import warnings from packaging.version import parse def digit_version(version_str: str, length: int = 4): """Convert a version string into a tuple of integers. This method is usually used for comparing two versions. For pre-release ...
# Copyright (c) OpenMMLab. All rights reserved. import os import subprocess import warnings from packaging.version import parse def digit_version(version_str: str, length: int = 4): """Convert a version string into a tuple of integers. This method is usually used for comparing two versions. For pre-release ...
from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.audio.abstract_audio_tensor import AbstractAudioTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode @_register_proto(proto_type_name='audio_torch_tensor') class AudioTorchTensor(AbstractAudioTensor,...
from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.audio.abstract_audio_tensor import AbstractAudioTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode @_register_proto(proto_type_name='audio_torch_tensor') class AudioTorchTensor(AbstractAudioTensor,...
import copy from dataclasses import dataclass, field from pathlib import Path from typing import Any, Optional, Union from .. import config @dataclass class DownloadConfig: """Configuration for our cached path manager. Attributes: cache_dir (`str` or `Path`, *optional*): Specify a cache ...
import copy from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Optional, Union from .. import config @dataclass class DownloadConfig: """Configuration for our cached path manager. Attributes: cache_dir (`str` or `Path`, *optional*): Specify a ...
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 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)
# mypy: allow-untyped-defs import sys from contextlib import contextmanager from typing import TYPE_CHECKING import torch from torch.backends import ( __allow_nonbracketed_mutation, _FP32Precision, _get_fp32_precision_getter, _set_fp32_precision_setter, ContextProp, PropModule, ) def is_avail...
# mypy: allow-untyped-defs import sys from contextlib import contextmanager from typing import TYPE_CHECKING import torch from torch.backends import ( __allow_nonbracketed_mutation, _FP32Precision, _get_fp32_precision_getter, _set_fp32_precision_setter, ContextProp, PropModule, ) def is_avail...
from typing import Tuple import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.testing.updater import get_basescore rng = np.random.RandomState(1994) class TestEarlyStopping: @pytest.mark.skipif(**tm.no_sklearn()) def test_early_stopping_nonparallel(self): ...
import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.testing.updater import get_basescore rng = np.random.RandomState(1994) class TestEarlyStopping: @pytest.mark.skipif(**tm.no_sklearn()) def test_early_stopping_nonparallel(self): from sklearn.dataset...
from keras.src import tree from keras.src.backend import KerasTensor class SymbolicArguments: def __init__(self, *args, **kwargs): self.args = tree.map_structure(lambda x: x, args) self.kwargs = tree.map_structure(lambda x: x, kwargs) self._flat_arguments = tree.flatten((self.args, self.kw...
from keras.src import tree from keras.src.backend import KerasTensor class SymbolicArguments: def __init__(self, *args, **kwargs): self.args = tree.map_structure(lambda x: x, args) self.kwargs = tree.map_structure(lambda x: x, kwargs) self._flat_arguments = tree.flatten((self.args, self.kw...
import numpy as np import pytest from docarray import BaseDocument, DocumentArray from docarray.array.array_stacked import DocumentArrayStacked from docarray.documents import Image, Text from docarray.typing import NdArray @pytest.mark.proto def test_simple_proto(): class CustomDoc(BaseDocument): text: s...
import numpy as np from docarray import BaseDocument, DocumentArray from docarray.array.array_stacked import DocumentArrayStacked from docarray.documents import Image, Text from docarray.typing import NdArray def test_simple_proto(): class CustomDoc(BaseDocument): text: str tensor: NdArray d...
""" A quantized model executes some or all of the operations with integers rather than floating point values. This allows for a more compact models and the use of high performance vectorized operations on many hardware platforms. As a result, you get about 40% smaller and faster models. The speed-up depends on your CP...
""" A quantized model executes some or all of the operations with integers rather than floating point values. This allows for a more compact models and the use of high performance vectorized operations on many hardware platforms. As a result, you get about 40% smaller and faster models. The speed-up depends on your CP...
import os from jina import Executor, requests class FilewriterExec(Executor): @requests def foo(self, **kwargs): print(self.workspace) file = os.path.join(self.workspace, 'out.txt') with open(file, 'w', encoding='utf-8') as f: f.write('Filewriter was here')
import os from jina import Executor, requests class FilewriterExec(Executor): @requests def foo(self, **kwargs): print(self.workspace) file = os.path.join(self.workspace, 'out.txt') with open(file, 'w') as f: f.write('Filewriter was here')
import pytest from unittest.mock import Mock, patch, AsyncMock from llama_index.embeddings.nvidia import NVIDIAEmbedding class MockEmbeddingResponse: """Mock response matching the structure expected by the code.""" def __init__(self): self.data = [ Mock(embedding=[1.0, 2.0, 3.0], index=0)...
import pytest import respx from llama_index.embeddings.nvidia import NVIDIAEmbedding import re import httpx import json @pytest.fixture() def mocked_route() -> respx.Route: all_urls = re.compile(r".*/embeddings") fake_response = httpx.Response( 200, json={"data": [{"index": 0, "embedding": [1.0, 2.0, ...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
from langchain_core.vectorstores import VST, VectorStore, VectorStoreRetriever __all__ = ["VST", "VectorStore", "VectorStoreRetriever"]
from langchain_core.vectorstores import VST, VectorStore, VectorStoreRetriever __all__ = ["VectorStore", "VectorStoreRetriever", "VST"]
from abc import abstractmethod import logging from typing import Any, Dict, List, Optional from llama_index.core.graph_stores.types import GraphStore from .neptune import refresh_schema logger = logging.getLogger(__name__) class NeptuneBaseGraphStore(GraphStore): """This is an abstract base class that represents...
from abc import abstractmethod import logging from typing import Any, Dict, List, Optional from llama_index.core.graph_stores.types import GraphStore from .neptune import refresh_schema logger = logging.getLogger(__name__) class NeptuneBaseGraphStore(GraphStore): """This is an abstract base class that represents...
from typing import Optional import numpy as np import pytest import torch from pydantic.tools import parse_obj_as, schema_json_of from docarray import BaseDocument from docarray.base_document.io.json import orjson_dumps from docarray.typing import AudioNdArray, AudioTorchTensor, AudioUrl from tests import TOYDATA_DIR...
from typing import Optional import numpy as np import pytest import torch from pydantic.tools import parse_obj_as, schema_json_of from docarray import BaseDocument from docarray.document.io.json import orjson_dumps from docarray.typing import AudioNdArray, AudioTorchTensor, AudioUrl from tests import TOYDATA_DIR AUD...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) fil...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) # In mstrain 3x config, img_scale=[(1333, 640), (1333, 800)], # multiscale_mode='range' train_pipeline = [ ...
import importlib import shutil import warnings from typing import List import fsspec import fsspec.asyn from fsspec.implementations.local import LocalFileSystem from . import compression COMPRESSION_FILESYSTEMS: list[compression.BaseCompressedFileFileSystem] = [ compression.Bz2FileSystem, compression.GzipFi...
import importlib import shutil import warnings from typing import List import fsspec import fsspec.asyn from fsspec.implementations.local import LocalFileSystem from . import compression COMPRESSION_FILESYSTEMS: List[compression.BaseCompressedFileFileSystem] = [ compression.Bz2FileSystem, compression.GzipFi...
import logging from collections import defaultdict from typing import Annotated, Any, Dict, List, Optional, Sequence from fastapi import APIRouter, Body, Depends, HTTPException from prisma.enums import AgentExecutionStatus, APIKeyPermission from typing_extensions import TypedDict import backend.data.block from backen...
import logging from collections import defaultdict from typing import Annotated, Any, Dict, List, Optional, Sequence from autogpt_libs.utils.cache import thread_cached from fastapi import APIRouter, Body, Depends, HTTPException from prisma.enums import AgentExecutionStatus, APIKeyPermission from typing_extensions impo...
import pathlib from argparse import ArgumentParser from lightning import ConformerRNNTModule, get_data_module from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor from pytorch_lightning.plugins import DDPPlugin def run_train(args): se...
import pathlib from argparse import ArgumentParser from lightning import ConformerRNNTModule from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor from pytorch_lightning.plugins import DDPPlugin def run_train(args): checkpoint_dir = args.exp_dir / "che...
"""Function components.""" from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from typing_extensions import Annotated from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import ( ...
"""Function components.""" from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from typing_extensions import Annotated from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import ( ...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch from torch.utils.data import DistributedSampler as _DistributedSampler from mmdet.core.utils import sync_random_seed class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch from torch.utils.data import DistributedSampler as _DistributedSampler class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, ...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseBinaryClassificationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Initialize the SPLADE model model = SparseEncoder("naver/sp...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseBinaryClassificationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Initialize the SPLADE model model = SparseEncoder("naver/sp...
# coding: utf-8 """Helper script for checking versions in the dynamic symbol table. This script checks that LightGBM library is linked to the appropriate symbol versions. Linking to newer symbol versions at compile time is problematic because it could result in built artifacts being unusable on older platforms. Vers...
# coding: utf-8 """Helper script for checking versions in the dynamic symbol table. This script checks that LightGBM library is linked to the appropriate symbol versions. Linking to newer symbol versions at compile time is problematic because it could result in built artifacts being unusable on older platforms. Vers...
from unittest import mock from click.testing import CliRunner from llama_dev.cli import cli def test_cmd_exec_no_package_no_all_flag(): runner = CliRunner() result = runner.invoke(cli, ["pkg", "exec", "--cmd", "echo hello"]) assert result.exit_code != 0 assert "Either specify a package name or use th...
from pathlib import Path from unittest import mock from click.testing import CliRunner from llama_dev.cli import cli def test_cmd_exec_no_package_no_all_flag(): runner = CliRunner() result = runner.invoke(cli, ["pkg", "exec", "--cmd", "echo hello"]) assert result.exit_code != 0 assert "Either specify...
from typing import Dict, List, Optional, Callable from jina.importer import ImportExtensions from jina.types.request.data import DataRequest from jina import DocumentArray from jina._docarray import docarray_v2 if docarray_v2: from docarray import DocList def get_fastapi_app( request_models_map: Dict, ...
from typing import Dict, List, Optional, Callable from jina.importer import ImportExtensions from jina.types.request.data import DataRequest from jina import DocumentArray from jina._docarray import docarray_v2 if docarray_v2: from docarray import DocList def get_fastapi_app( request_models_map: Dict, ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path import numpy as np import pytest import torch import torchvision.models.video as models from jina import Document, DocumentArray, Executor from torchvision import transforms from video_t...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path import numpy as np import pytest import torch import torchvision.models.video as models from jina import Document, DocumentArray, Executor from torchvision import transforms from video_t...
""" This is a simple application for sentence embeddings: semantic search We have a corpus with various sentences. Then, for a given query sentence, we want to find the most similar sentence in this corpus. This script outputs for various queries the top 5 most similar sentences in the corpus. """ import torch from...
""" This is a simple application for sentence embeddings: semantic search We have a corpus with various sentences. Then, for a given query sentence, we want to find the most similar sentence in this corpus. This script outputs for various queries the top 5 most similar sentences in the corpus. """ from sentence_trans...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
from typing import Optional import pytest import torch from docarray import BaseDoc, DocList from docarray.array.any_array import AnyDocArray from docarray.documents import TextDoc from docarray.typing import TorchTensor num_docs = 5 num_sub_docs = 2 num_sub_sub_docs = 3 @pytest.fixture def multi_model_docs(): ...
from typing import Optional import pytest import torch from docarray import BaseDoc, DocList from docarray.array.any_array import AnyDocArray from docarray.documents import TextDoc from docarray.typing import TorchTensor num_docs = 5 num_sub_docs = 2 num_sub_sub_docs = 3 @pytest.fixture def multi_model_docs(): ...
_base_ = './retinanet_r50_caffe_fpn_mstrain_1x_coco.py' # training schedule for 2x train_cfg = dict(max_epochs=36) # learning rate policy param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=36,...
_base_ = './retinanet_r50_caffe_fpn_mstrain_1x_coco.py' # learning policy lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.19.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.18.1' 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...
""" A quantized model executes some or all of the operations with integers rather than floating point values. This allows for a more compact models and the use of high performance vectorized operations on many hardware platforms. As a result, you get about 40% smaller and faster models. The speed-up depends on your CP...
""" A quantized model executes some or all of the operations with integers rather than floating point values. This allows for a more compact models and the use of high performance vectorized operations on many hardware platforms. As a result, you get about 40% smaller and faster models. The speed-up depends on your CP...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
""" This example runs a CNN after the word embedding lookup. The output of the CNN is than pooled, for example with mean-pooling. """ import logging import sys import traceback from datetime import datetime from datasets import load_dataset from sentence_transformers import SentenceTransformer, losses, models from...
""" This example runs a CNN after the word embedding lookup. The output of the CNN is than pooled, for example with mean-pooling. """ import logging import sys import traceback from datetime import datetime from datasets import load_dataset from sentence_transformers import SentenceTransformer, losses, models from ...
# 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.device import is_npu_available from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS from .optimizer_...
# 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.device import is_npu_available from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS from .optimizer_...
# Copyright (c) OpenMMLab. All rights reserved. from .augment_wrappers import AutoAugment, RandAugment from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, Contrast, Equalize, Invert, Posterize, Sharpness, Solarize, SolarizeAdd) from .formatting imp...
# Copyright (c) OpenMMLab. All rights reserved. from .augment_wrappers import AutoAugment, RandAugment from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, Contrast, Equalize, Invert, Posterize, Sharpness, Solarize, SolarizeAdd) from .formatting imp...
from typing import Any # noqa: F401 from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.embedding.embedding_mixin import EmbeddingMixin from docarray.typing.tensor.torch_tensor import TorchTensor torch_base = type(TorchTensor) # type: Any embedding_base = type(EmbeddingMixin) # t...
from typing import Any # noqa: F401 from docarray.typing.tensor.embedding.embedding_mixin import EmbeddingMixin from docarray.typing.tensor.torch_tensor import TorchTensor torch_base = type(TorchTensor) # type: Any embedding_base = type(EmbeddingMixin) # type: Any class metaTorchAndEmbedding(torch_base, embeddin...
from dataclasses import dataclass, field from typing import Any, Callable, Dict, List import torch @dataclass class SentenceTransformerDataCollator: """Collator for a SentenceTransformers model. This encodes the text columns to {column}_input_ids and {column}_attention_mask columns. This works with the t...
from dataclasses import dataclass, field from typing import Any, Callable, Dict, List import torch @dataclass class SentenceTransformerDataCollator: """Collator for a SentenceTransformers model. This encodes the text columns to {column}_input_ids and {column}_attention_mask columns. This works with the t...
from typing import Any, Sequence, Union from deprecated import deprecated from llama_index.core.base.llms.generic_utils import ( chat_response_to_completion_response, stream_chat_response_to_completion_response, astream_chat_response_to_completion_response, ) from llama_index.core.base.llms.types import ( ...
from typing import Any, Optional, Sequence from pathlib import Path from llama_index.core.base.llms.generic_utils import ( chat_response_to_completion_response, stream_chat_response_to_completion_response, astream_chat_response_to_completion_response, ) from llama_index.core.base.llms.types import ( Ch...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock from mmengine.hooks import ParamSchedulerHook class TestParamSchedulerHook: def test_after_iter(self): Hook = ParamSchedulerHook() Runner = Mock() scheduler = Mock() scheduler.step = Mock() sch...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock from mmengine.hooks import ParamSchedulerHook class TestParamSchedulerHook: def test_after_iter(self): Hook = ParamSchedulerHook() Runner = Mock() scheduler = Mock() scheduler.step = Mock() sch...
"""Ollama specific chat model integration tests""" from typing import Annotated, Optional import pytest from pydantic import BaseModel, Field from typing_extensions import TypedDict from langchain_ollama import ChatOllama DEFAULT_MODEL_NAME = "llama3.1" @pytest.mark.parametrize(("method"), [("function_calling"), ...
"""Ollama specific chat model integration tests""" from typing import Annotated, Optional import pytest from pydantic import BaseModel, Field from typing_extensions import TypedDict from langchain_ollama import ChatOllama @pytest.mark.parametrize(("method"), [("function_calling"), ("json_schema")]) def test_struct...
import os from abc import ABC, abstractmethod from typing import List, Optional import fsspec from llama_index.core.data_structs.data_structs import IndexStruct DEFAULT_PERSIST_DIR = "./storage" DEFAULT_PERSIST_FNAME = "index_store.json" DEFAULT_PERSIST_PATH = os.path.join(DEFAULT_PERSIST_DIR, DEFAULT_PERSIST_FNAME) ...
import os from abc import ABC, abstractmethod from typing import List, Optional import fsspec from llama_index.core.data_structs.data_structs import IndexStruct DEFAULT_PERSIST_DIR = "./storage" DEFAULT_PERSIST_FNAME = "index_store.json" DEFAULT_PERSIST_PATH = os.path.join(DEFAULT_PERSIST_DIR, DEFAULT_PERSIST_FNAME) ...
from io import BytesIO from unittest.mock import MagicMock from llama_index.core.schema import ImageDocument from llama_index.multi_modal_llms.gemini.utils import ( generate_gemini_multi_modal_chat_message, ) def test_generate_message_no_image_documents(): result = generate_gemini_multi_modal_chat_message( ...
from unittest.mock import MagicMock from llama_index.core.schema import ImageDocument from llama_index.multi_modal_llms.gemini.utils import ( generate_gemini_multi_modal_chat_message, ) def test_generate_message_no_image_documents(): result = generate_gemini_multi_modal_chat_message( prompt="Hello", r...
_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' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict( type='InstaBoost', action_candidate=('normal', 'horizontal', 'skip'), action_prob=(1, 0, 0), scale=(0.8, 1...
# Copyright (c) OpenMMLab. All rights reserved. from .assigners import (AssignResult, BaseAssigner, CenterRegionAssigner, MaxIoUAssigner, RegionAssigner) from .builder import build_assigner, build_bbox_coder, build_sampler from .coder import (BaseBBoxCoder, DeltaXYWHBBoxCoder, DistancePointBBoxC...
# Copyright (c) OpenMMLab. All rights reserved. from .assigners import (AssignResult, BaseAssigner, CenterRegionAssigner, MaxIoUAssigner, RegionAssigner) from .builder import build_assigner, build_bbox_coder, build_sampler from .coder import (BaseBBoxCoder, DeltaXYWHBBoxCoder, DistancePointBBoxC...
import subprocess 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='fun...
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 documen...