input
stringlengths
33
5k
output
stringlengths
32
5k
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import tempfile from unittest import TestCase from unittest.mock import Mock import torch import torch.nn as nn from mmengine.model import BaseModel from mmengine.optim import OptimWrapper from mmengine.registry import MODEL_WRAPPERS from mmengine.r...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import tempfile from unittest import TestCase from unittest.mock import Mock import torch import torch.nn as nn from mmengine.model import BaseModel from mmengine.optim import OptimWrapper from mmengine.registry import DATASETS, MODEL_WRAPPERS from ...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.agent_toolkits.powerbi.prompt import ( POWERBI_CHAT_PREFIX, POWERBI_CHAT_SUFFIX, POWERBI_PREFIX, POWERBI_SUFFIX, ) # Create a way to dynamically look up ...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.agent_toolkits.powerbi.prompt import ( POWERBI_CHAT_PREFIX, POWERBI_CHAT_SUFFIX, POWERBI_PREFIX, POWERBI_SUFFIX, ) # Create a way to dynamically look up ...
from __future__ import annotations import collections import json import os import string from typing import Iterable from .WordTokenizer import ENGLISH_STOP_WORDS, WordTokenizer class WhitespaceTokenizer(WordTokenizer): """ Simple and fast white-space tokenizer. Splits sentence based on white spaces. P...
import collections import json import os import string from typing import Iterable, List from .WordTokenizer import ENGLISH_STOP_WORDS, WordTokenizer class WhitespaceTokenizer(WordTokenizer): """ Simple and fast white-space tokenizer. Splits sentence based on white spaces. Punctuation are stripped from t...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.openai_info import OpenAICallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling opti...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.openai_info import OpenAICallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling opti...
_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='TOOD', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=d...
""" This is a simple application for sparse encoder: Computing embeddings. we have multiple sentences and we want to compute their embeddings. The embeddings are sparse, meaning that most of the values are zero. The embeddings are stored in a sparse matrix format, which is more efficient for storage and computation. w...
""" This is a simple application for sparse encoder: Computing embeddings. we have multiple sentences and we want to compute their embeddings. The embeddings are sparse, meaning that most of the values are zero. The embeddings are stored in a sparse matrix format, which is more efficient for storage and computation. w...
_base_ = 'faster-rcnn_regnetx-3.2GF_fpn_ms-3x_coco.py' model = dict( backbone=dict( type='RegNet', arch='regnetx_4.0gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=...
_base_ = 'faster_rcnn_regnetx-3.2GF_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( type='RegNet', arch='regnetx_4.0gf', out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init...
from typing import Any, Dict, Optional, Type from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.language_models import BaseLanguageModel from pydantic import BaseModel, Field, model_validator from langchain_community.chat_models import ChatOpenAI from langchain_community.tools.amadeus....
from typing import Any, Dict, Optional, Type from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.language_models import BaseLanguageModel from pydantic import BaseModel, Field, model_validator from langchain_community.chat_models import ChatOpenAI from langchain_community.tools.amadeus....
"""Standard LangChain interface tests""" from langchain_core.language_models import BaseChatModel from langchain_tests.unit_tests import ChatModelUnitTests from langchain_openai import ChatOpenAI class TestOpenAIStandard(ChatModelUnitTests): @property def chat_model_class(self) -> type[BaseChatModel]: ...
"""Standard LangChain interface tests""" from typing import Tuple, Type from langchain_core.language_models import BaseChatModel from langchain_tests.unit_tests import ChatModelUnitTests from langchain_openai import ChatOpenAI class TestOpenAIStandard(ChatModelUnitTests): @property def chat_model_class(sel...
from enum import Enum from langchain_core.exceptions import OutputParserException from langchain_core.output_parsers import BaseOutputParser from langchain_core.utils import pre_init class EnumOutputParser(BaseOutputParser[Enum]): """Parse an output that is one of a set of values.""" enum: type[Enum] ""...
from enum import Enum from langchain_core.exceptions import OutputParserException from langchain_core.output_parsers import BaseOutputParser from langchain_core.utils import pre_init class EnumOutputParser(BaseOutputParser[Enum]): """Parse an output that is one of a set of values.""" enum: type[Enum] ""...
"""Cohere Reranker Finetuning Engine.""" import importlib.util import os from typing import Optional from llama_index.finetuning.types import BaseCohereRerankerFinetuningEngine from llama_index.postprocessor.cohere_rerank import CohereRerank class CohereRerankerFinetuneEngine(BaseCohereRerankerFinetuningEngine): ...
"""Cohere Reranker Finetuning Engine.""" import importlib.util import os from typing import Optional from llama_index.finetuning.types import BaseCohereRerankerFinetuningEngine from llama_index.postprocessor.cohere_rerank import CohereRerank class CohereRerankerFinetuneEngine(BaseCohereRerankerFinetuningEngine): ...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTripletEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledis...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTripletEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledis...
import json import os from typing import List import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import nn class CNN(nn.Module): """CNN-layer with multiple kernel-sizes over the word embeddings""" def ...
import json import os from typing import List import torch from torch import nn class CNN(nn.Module): """CNN-layer with multiple kernel-sizes over the word embeddings""" def __init__( self, in_word_embedding_dimension: int, out_channels: int = 256, kernel_sizes: List[int] = [...
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmdet.utils.util_random import ensure_rng def random_boxes(num=1, scale=1, rng=None): """Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: ht...
import numpy as np import torch from mmdet.utils.util_random import ensure_rng def random_boxes(num=1, scale=1, rng=None): """Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage...
""" This script contains an example how to perform re-ranking with a Cross-Encoder for semantic search. First, we use an efficient Bi-Encoder to retrieve similar questions from the Quora Duplicate Questions dataset: https://www.quora.com/q/quoradata/First-Quora-Dataset-Release-Question-Pairs Then, we re-rank the hits...
""" This script contains an example how to perform re-ranking with a Cross-Encoder for semantic search. First, we use an efficient Bi-Encoder to retrieve similar questions from the Quora Duplicate Questions dataset: https://www.quora.com/q/quoradata/First-Quora-Dataset-Release-Question-Pairs Then, we re-rank the hits...
from typing import Dict, List, Optional, Set, Tuple import numpy as np import pytest import torch from docarray import DocumentArray from docarray.base_document import BaseDocument from docarray.typing import NdArray, TorchTensor @pytest.mark.proto def test_proto_simple(): class CustomDoc(BaseDocument): ...
from typing import Optional, Dict, List, Set, Tuple import numpy as np import pytest import torch from docarray import DocumentArray from docarray.base_document import BaseDocument from docarray.typing import NdArray, TorchTensor @pytest.mark.proto def test_proto_simple(): class CustomDoc(BaseDocument): ...
# Owner(s): ["module: dynamo"] import unittest import torch import torch._dynamo.test_case from torch._dynamo.testing import CompileCounter, EagerAndRecordGraphs, normalize_gm from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_utils import TEST_XPU device_type = ( acc.t...
# Owner(s): ["module: dynamo"] import unittest import torch import torch._dynamo.test_case from torch._dynamo.testing import CompileCounter, EagerAndRecordGraphs, normalize_gm from torch.testing._internal.common_cuda import TEST_CUDA class PythonDispatcherTests(torch._dynamo.test_case.TestCase): def test_dispatc...
# 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 TYPE_CHECKING from docarray.array.storage.qdrant.backend import BackendMixin, QdrantConfig from docarray.array.storage.qdrant.find import FindMixin from docarray.array.storage.qdrant.getsetdel import GetSetDelMixin from docarray.array.storage.qdrant.helper import DISTANCES from docarray.array.storag...
from typing import TYPE_CHECKING from docarray.array.storage.qdrant.backend import BackendMixin, QdrantConfig from docarray.array.storage.qdrant.find import FindMixin from docarray.array.storage.qdrant.getsetdel import GetSetDelMixin from docarray.array.storage.qdrant.helper import DISTANCES from docarray.array.storag...
from __future__ import annotations from sentence_transformers.sparse_encoder.evaluation.ReciprocalRankFusionEvaluator import ( ReciprocalRankFusionEvaluator, ) from sentence_transformers.sparse_encoder.evaluation.SparseBinaryClassificationEvaluator import ( SparseBinaryClassificationEvaluator, ) from sentence_...
from __future__ import annotations from sentence_transformers.sparse_encoder.evaluation.SparseBinaryClassificationEvaluator import ( SparseBinaryClassificationEvaluator, ) from sentence_transformers.sparse_encoder.evaluation.SparseEmbeddingSimilarityEvaluator import ( SparseEmbeddingSimilarityEvaluator, ) from...
from typing import Any from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.json import json class StepThroughItemsBlock(Block): class Input(BlockSchema): items: list = SchemaField( advanced=False, ...
from typing import Any from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.json import json class StepThroughItemsBlock(Block): class Input(BlockSchema): items: list = SchemaField( advanced=False, ...
# Copyright (c) OpenMMLab. All rights reserved. from .checkloss_hook import CheckInvalidLossHook from .memory_profiler_hook import MemoryProfilerHook from .num_class_check_hook import NumClassCheckHook from .set_epoch_info_hook import SetEpochInfoHook from .sync_norm_hook import SyncNormHook from .visualization_hook im...
# Copyright (c) OpenMMLab. All rights reserved. from .checkloss_hook import CheckInvalidLossHook from .memory_profiler_hook import MemoryProfilerHook from .num_class_check_hook import NumClassCheckHook from .set_epoch_info_hook import SetEpochInfoHook from .sync_norm_hook import SyncNormHook from .yolox_mode_switch_hoo...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.initializers import deserialize from keras.src.initializers import get from keras.src.initializers import serialize from keras.src.initializers.constant_initializers import STFT from ...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.initializers import deserialize from keras.src.initializers import get from keras.src.initializers import serialize from keras.src.initializers.constant_initializers import Constant f...
"""Document compressor.""" from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional from pydantic import BaseModel from langchain_core.runnables import run_in_executor if TYPE_CHECKING: from collections.abc import Sequence from langchain_core.callba...
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional from pydantic import BaseModel from langchain_core.runnables import run_in_executor if TYPE_CHECKING: from collections.abc import Sequence from langchain_core.callbacks import Callbacks fro...
"""Init file.""" from llama_index.readers.web.async_web.base import ( AsyncWebPageReader, ) from llama_index.readers.web.beautiful_soup_web.base import ( BeautifulSoupWebReader, ) from llama_index.readers.web.browserbase_web.base import BrowserbaseWebReader from llama_index.readers.web.firecrawl_web.base import...
"""Init file.""" from llama_index.readers.web.async_web.base import ( AsyncWebPageReader, ) from llama_index.readers.web.beautiful_soup_web.base import ( BeautifulSoupWebReader, ) from llama_index.readers.web.browserbase_web.base import BrowserbaseWebReader from llama_index.readers.web.firecrawl_web.base import...
_base_ = './libra-faster-rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './libra_faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './mask-rcnn_r50_fpn_seesaw-loss_random-ms-2x_lvis-v1.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './mask_rcnn_r50_fpn_random_seesaw_loss_mstrain_2x_lvis_v1.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
from typing import Any, Optional from typing_extensions import get_origin from typing_inspect import get_args, is_typevar, is_union_type from docarray.typing.tensor.abstract_tensor import AbstractTensor from typing import ForwardRef def is_type_tensor(type_: Any) -> bool: """Return True if type is a type Tensor...
from typing import Any, Optional from typing_extensions import get_origin from typing_inspect import get_args, is_typevar, is_union_type from docarray.typing.tensor.abstract_tensor import AbstractTensor def is_type_tensor(type_: Any) -> bool: """Return True if type is a type Tensor or an Optional Tensor type.""...
from collections import OrderedDict import pytest from docarray.array.chunk import ChunkArray from jina import Client, Document, DocumentArray, Executor, Flow, requests from jina.helper import random_port class DummyExecutor(Executor): def __init__(self, mode=None, *args, **kwargs): super().__init__(*ar...
from collections import OrderedDict import pytest from docarray.array.chunk import ChunkArray from jina import Client, Document, DocumentArray, Executor, Flow, requests from jina.helper import random_port class DummyExecutor(Executor): def __init__(self, mode=None, *args, **kwargs): super().__init__(*ar...
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`. ...
from typing import List from llama_index.core.prompts.base import BasePromptTemplate def get_empty_prompt_txt(prompt: BasePromptTemplate) -> str: """ Get empty prompt text. Substitute empty strings in parts of the prompt that have not yet been filled out. Skip variables that have already been pa...
from typing import List from llama_index.core.prompts.base import BasePromptTemplate def get_empty_prompt_txt(prompt: BasePromptTemplate) -> str: """ Get empty prompt text. Substitute empty strings in parts of the prompt that have not yet been filled out. Skip variables that have already been pa...
"""Tests related to the `DataIter` interface.""" from typing import Callable, Optional import numpy as np from xgboost import testing as tm from ..core import DataIter, DMatrix, ExtMemQuantileDMatrix, QuantileDMatrix def run_mixed_sparsity(device: str) -> None: """Check QDM with mixed batches.""" X_0, y_0...
"""Tests related to the `DataIter` interface.""" from typing import Callable, Optional import numpy as np from xgboost import testing as tm from ..core import DataIter, ExtMemQuantileDMatrix, QuantileDMatrix def run_mixed_sparsity(device: str) -> None: """Check QDM with mixed batches.""" X_0, y_0, _ = tm....
"""Parsing utils to go from string to AgentAction or Agent Finish. AgentAction means that an action should be taken. This contains the name of the tool to use, the input to pass to that tool, and a `log` variable (which contains a log of the agent's thinking). AgentFinish means that a response should be given. This c...
"""Parsing utils to go from string to AgentAction or Agent Finish. AgentAction means that an action should be taken. This contains the name of the tool to use, the input to pass to that tool, and a `log` variable (which contains a log of the agent's thinking). AgentFinish means that a response should be given. This c...
from llama_index_instrumentation.span_handlers.base import BaseSpanHandler from llama_index_instrumentation.span_handlers.null import NullSpanHandler from llama_index_instrumentation.span_handlers.simple import SimpleSpanHandler __all__ = [ "BaseSpanHandler", "NullSpanHandler", "SimpleSpanHandler", ]
from llama_index.core.instrumentation.span_handlers.base import BaseSpanHandler from llama_index.core.instrumentation.span_handlers.null import NullSpanHandler from llama_index.core.instrumentation.span_handlers.simple import SimpleSpanHandler __all__ = [ "BaseSpanHandler", "NullSpanHandler", "SimpleSpanH...
import importlib from types import ModuleType import pytest from fastapi.exceptions import FastAPIError from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="mod", params=[ "tutorial008c", "tutorial008c_an", pytest.param("tutorial008c_an_py3...
import pytest from fastapi.exceptions import FastAPIError from fastapi.testclient import TestClient @pytest.fixture(name="client") def get_client(): from docs_src.dependencies.tutorial008c import app client = TestClient(app) return client def test_get_no_item(client: TestClient): response = client....
# ruff: noqa __all__ = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import Array2D, Array3D, Array4D, Array5D, Class...
# flake8: noqa __all__ = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import Array2D, Array3D, Array4D, Array5D, Cla...
import numpy as np import pytest from keras.src import layers from keras.src import models from keras.src import ops from keras.src import testing from keras.src.saving import load_model class MaskingTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_masking_basics(self): self.r...
import numpy as np import pytest from keras.src import layers from keras.src import models from keras.src import testing class MaskingTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_masking_basics(self): self.run_layer_test( layers.Masking, init_kwargs...
import gzip import logging import os from datetime import datetime from torch.utils.data import DataLoader from sentence_transformers import InputExample, LoggingHandler, SentenceTransformer, evaluation, losses, models, util #### Just some code to print debug information to stdout logging.basicConfig( format="%(...
from sentence_transformers import SentenceTransformer, LoggingHandler, InputExample from sentence_transformers import models, util, evaluation, losses import logging import os import gzip from torch.utils.data import DataLoader from datetime import datetime #### Just some code to print debug information to stdout log...
from typing import List import pytest from sqlalchemy import create_engine, text from llama_index.readers.database import DatabaseReader from llama_index.core.schema import Document # --------------------------------------------------------------------------- # # Fixtures # -----------------------------------------...
from typing import List import pytest from sqlalchemy import create_engine, text from llama_index.readers.database import DatabaseReader from llama_index.core.schema import Document # --------------------------------------------------------------------------- # # Fixtures # -----------------------------------------...
""" 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...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import MAP_TO_NONE as MAP_TO_NONE from keras.src.tree.tree_api import assert_same_paths as assert_same_paths from keras.src.tree.tree_api import ( assert_same_struct...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import MAP_TO_NONE from keras.src.tree.tree_api import assert_same_paths from keras.src.tree.tree_api import assert_same_structure from keras.src.tree.tree_api import fl...
""" 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_tran...
""" 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_tran...
import os from shutil import rmtree from typing import Callable, Dict, List, Optional import tqdm from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.schema import Document, QueryBundle from llama_index.core.utils i...
import os from shutil import rmtree from typing import Callable, Dict, List, Optional import tqdm from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.schema import Document, QueryBundle from llama_index.core.utils i...
from keras.src.api_export import keras_export from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501 BaseImagePreprocessingLayer, ) from keras.src.random.seed_generator import SeedGenerator @keras_export("keras.layers.RandomContrast") class RandomContrast(Bas...
from keras.src.api_export import keras_export from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501 BaseImagePreprocessingLayer, ) from keras.src.random.seed_generator import SeedGenerator @keras_export("keras.layers.RandomContrast") class RandomContrast(Bas...
import zlib from typing import Iterator, TextIO def exact_div(x, y): assert x % y == 0 return x // y def str2bool(string): str2val = {"True": True, "False": False} if string in str2val: return str2val[string] else: raise ValueError(f"Expected one of {set(str2val.keys())}, got {st...
import zlib from typing import Iterator, TextIO def exact_div(x, y): assert x % y == 0 return x // y def str2bool(string): str2val = {"True": True, "False": False} if string in str2val: return str2val[string] else: raise ValueError(f"Expected one of {set(str2val.keys())}, got {st...
from typing import List, Optional from llama_index.core.data_structs.data_structs import IndexStruct from llama_index.core.storage.index_store.types import BaseIndexStore from llama_index.core.storage.index_store.utils import ( index_struct_to_json, json_to_index_struct, ) from llama_index.core.storage.kvstore...
from typing import List, Optional from llama_index.core.data_structs.data_structs import IndexStruct from llama_index.core.storage.index_store.types import BaseIndexStore from llama_index.core.storage.index_store.utils import ( index_struct_to_json, json_to_index_struct, ) from llama_index.core.storage.kvstore...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.graphs.graph_document import ( GraphDocument, Node, Relationship, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for rai...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.graphs.graph_document import ( GraphDocument, Node, Relationship, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for rai...
from typing import List, _LiteralGenericAlias, get_args, Tuple import kuzu Triple = Tuple[str, str, str] def create_fresh_database(db: str) -> None: """ Create a new Kùzu database by removing existing database directory and its contents. """ import shutil shutil.rmtree(db, ignore_errors=True) ...
from typing import List, _LiteralGenericAlias, get_args, Tuple import kuzu Triple = Tuple[str, str, str] def create_fresh_database(db: str) -> None: """ Create a new Kùzu database by removing existing database directory and its contents. """ import shutil shutil.rmtree(db, ignore_errors=True) ...
# CREDITS: https://github.com/openai/CLIP import gzip import html from functools import lru_cache from pathlib import Path import ftfy import regex as re @lru_cache() def default_bpe(): return str(Path(__file__).parents[2] / '.cache/bpe_simple_vocab_16e6.txt.gz') @lru_cache() def bytes_to_unicode(): """ ...
# CREDITS: https://github.com/openai/CLIP import gzip import html import os from functools import lru_cache import ftfy import regex as re @lru_cache() def default_bpe(): return os.path.join(os.getcwd(), '.cache', 'bpe_simple_vocab_16e6.txt.gz') @lru_cache() def bytes_to_unicode(): """ Returns list of...
"""Init file of LlamaIndex.""" __version__ = "0.12.27" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
"""Init file of LlamaIndex.""" __version__ = "0.12.26" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
"""Retriever tool.""" from typing import TYPE_CHECKING, Any, List, Optional from llama_index.core.base.base_retriever import BaseRetriever if TYPE_CHECKING: from llama_index.core.langchain_helpers.agents.tools import LlamaIndexTool from llama_index.core.schema import ( MetadataMode, Node, NodeWithSc...
"""Retriever tool.""" from typing import TYPE_CHECKING, Any, List, Optional from llama_index.core.base.base_retriever import BaseRetriever if TYPE_CHECKING: from llama_index.core.langchain_helpers.agents.tools import LlamaIndexTool from llama_index.core.schema import ( MetadataMode, Node, NodeWithSc...
# Copyright (c) OpenMMLab. All rights reserved. from .amp import autocast from .base_loop import BaseLoop from .checkpoint import (CheckpointLoader, find_latest_checkpoint, get_deprecated_model_names, get_external_models, get_mmcls_models, get_state_dict, ...
# Copyright (c) OpenMMLab. All rights reserved. from .amp import autocast from .base_loop import BaseLoop from .checkpoint import (CheckpointLoader, find_latest_checkpoint, get_deprecated_model_names, get_external_models, get_mmcls_models, get_state_dict, ...
_base_ = './cascade-rcnn_hrnetv2p-w32-20e_coco.py' # model settings model = dict( backbone=dict( extra=dict( stage2=dict(num_channels=(18, 36)), stage3=dict(num_channels=(18, 36, 72)), stage4=dict(num_channels=(18, 36, 72, 144))), init_cfg=dict( type='...
_base_ = './cascade_rcnn_hrnetv2p_w32_20e_coco.py' # model settings model = dict( backbone=dict( extra=dict( stage2=dict(num_channels=(18, 36)), stage3=dict(num_channels=(18, 36, 72)), stage4=dict(num_channels=(18, 36, 72, 144))), init_cfg=dict( type='...
# training schedule for 20e train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=20, val_interval=1) val_cfg = dict(type='ValLoop') test_cfg = dict(type='TestLoop') # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='M...
# training schedule for 20e train_cfg = dict(by_epoch=True, max_epochs=20) val_cfg = dict(interval=1) test_cfg = dict() # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=20, ...
import logging import traceback from datasets import load_dataset from sentence_transformers.cross_encoder import CrossEncoder from sentence_transformers.cross_encoder.evaluation import CrossEncoderNanoBEIREvaluator from sentence_transformers.cross_encoder.losses.BinaryCrossEntropyLoss import BinaryCrossEntropyLoss f...
import logging import traceback from datasets import load_dataset from sentence_transformers.cross_encoder import CrossEncoder from sentence_transformers.cross_encoder.evaluation import CrossEncoderNanoBEIREvaluator from sentence_transformers.cross_encoder.losses.BinaryCrossEntropyLoss import BinaryCrossEntropyLoss f...
import multiprocessing import socket import sys import time import numpy as np import pytest import xgboost as xgb from xgboost import RabitTracker, build_info, federated if sys.platform.startswith("win"): pytest.skip("Skipping collective tests on Windows", allow_module_level=True) def run_rabit_worker(rabit_e...
import multiprocessing import socket import sys import time import numpy as np import pytest import xgboost as xgb from xgboost import RabitTracker, build_info, federated if sys.platform.startswith("win"): pytest.skip("Skipping collective tests on Windows", allow_module_level=True) def run_rabit_worker(rabit_e...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] teacher_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/gfl/gfl_r101_fpn_mstrain_2x_coco/gfl_r101_fpn_mstrain_2x_coco_20200629_200126-dd12f847.pth' # noqa model = dict( type='Kn...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] teacher_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/gfl/gfl_r101_fpn_mstrain_2x_coco/gfl_r101_fpn_mstrain_2x_coco_20200629_200126-dd12f847.pth' # noqa model = dict( type='Kn...
from datetime import datetime from typing import Any, List from backend.blocks.exa._auth import ( ExaCredentials, ExaCredentialsField, ExaCredentialsInput, ) from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.request im...
from datetime import datetime from typing import Any, List from backend.blocks.exa._auth import ( ExaCredentials, ExaCredentialsField, ExaCredentialsInput, ) from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.request im...
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) pytestmark = pytest.mark.integration @pytest.mark.parametrize("path", ["paws", "csv"]) def test_inspect_dataset(p...
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) pytestmark = pytest.mark.integration @pytest.mark.parametrize("path", ["paws", "csv"]) def test_inspect_dataset(p...
import sys import traceback from importlib.machinery import SourceFileLoader if __name__ == "__main__": files = sys.argv[1:] has_failure = False for file in files: try: SourceFileLoader("x", file).load_module() except Exception: has_faillure = True traceb...
import sys import traceback from importlib.machinery import SourceFileLoader if __name__ == "__main__": files = sys.argv[1:] has_failure = False for file in files: try: SourceFileLoader("x", file).load_module() except Exception: has_faillure = True print(...
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Optional import torch import torch.nn as nn from mmengine.model import ExponentialMovingAverage from torch import Tensor from mmdet.registry import MODELS @MODELS.register_module() class ExpMomentumEMA(ExponentialMovingAverage): """E...
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Optional import torch import torch.nn as nn from mmengine.model import ExponentialMovingAverage from torch import Tensor from mmdet.registry import MODELS @MODELS.register_module() class ExpMomentumEMA(ExponentialMovingAverage): """E...
import types from keras.src.activations.activations import celu from keras.src.activations.activations import elu from keras.src.activations.activations import exponential from keras.src.activations.activations import gelu from keras.src.activations.activations import glu from keras.src.activations.activations import ...
import types from keras.src.activations.activations import celu from keras.src.activations.activations import elu from keras.src.activations.activations import exponential from keras.src.activations.activations import gelu from keras.src.activations.activations import glu from keras.src.activations.activations import ...
import numpy as np import torch from docarray import Document from docarray.document import AnyDocument from docarray.typing import AnyUrl, Embedding, ImageUrl, Tensor, TorchTensor def test_proto_all_types(): class Mymmdoc(Document): tensor: Tensor torch_tensor: TorchTensor embedding: Emb...
import numpy as np import torch from docarray import Document from docarray.document import AnyDocument from docarray.typing import AnyUrl, Embedding, ImageUrl, Tensor, TorchTensor def test_proto_all_types(): class Mymmdoc(Document): tensor: Tensor torch_tensor: TorchTensor embedding: Emb...
"""Auto Merging Retriever.""" from typing import Any, Dict, List from llama_index.core import VectorStoreIndex from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.node_parser import ( HierarchicalNodeParser, get_leaf_nodes, ) from llama_index.core.query_engine import RetrieverQuer...
"""Auto Merging Retriever.""" from typing import Any, Dict, List from llama_index.core import VectorStoreIndex from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.node_parser import ( HierarchicalNodeParser, get_leaf_nodes, ) from llama_index.core.query_engine import RetrieverQuer...
# Copyright 2024 The OpenXLA Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# Copyright 2024 The OpenXLA Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
"""Run smoke tests""" import os import sys from pathlib import Path import torch import torchvision from torchvision.io import decode_image, decode_jpeg, decode_webp, read_file from torchvision.models import resnet50, ResNet50_Weights SCRIPT_DIR = Path(__file__).parent def smoke_test_torchvision() -> None: pr...
"""Run smoke tests""" import os import sys from pathlib import Path import torch import torchvision from torchvision.io import decode_jpeg, decode_webp, read_file, read_image from torchvision.models import resnet50, ResNet50_Weights SCRIPT_DIR = Path(__file__).parent def smoke_test_torchvision() -> None: prin...
_base_ = './ms_rcnn_r101_caffe_fpn_1x_coco.py' # learning policy max_epochs = 24 train_cfg = dict( type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', ...
_base_ = './ms_rcnn_r101_caffe_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
import pytest import torchaudio from torchaudio.pipelines import ( HUBERT_ASR_LARGE, HUBERT_ASR_XLARGE, HUBERT_BASE, HUBERT_LARGE, HUBERT_XLARGE, VOXPOPULI_ASR_BASE_10K_DE, VOXPOPULI_ASR_BASE_10K_EN, VOXPOPULI_ASR_BASE_10K_ES, VOXPOPULI_ASR_BASE_10K_FR, VOXPOPULI_ASR_BASE_10K_IT,...
import pytest import torchaudio from torchaudio.pipelines import ( HUBERT_ASR_LARGE, HUBERT_ASR_XLARGE, HUBERT_BASE, HUBERT_LARGE, HUBERT_XLARGE, VOXPOPULI_ASR_BASE_10K_DE, VOXPOPULI_ASR_BASE_10K_EN, VOXPOPULI_ASR_BASE_10K_ES, VOXPOPULI_ASR_BASE_10K_FR, VOXPOPULI_ASR_BASE_10K_IT,...
_base_ = './sparse_rcnn_r50_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomChoiceResize', scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1...
_base_ = './sparse_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) min_values = (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), ...
from ._presets import StereoMatching # usort: skip from ._augment import SimpleCopyPaste from ._geometry import FixedSizeCrop from ._misc import PermuteDimensions, TransposeDimensions from ._type_conversion import LabelToOneHot
from ._presets import StereoMatching # usort: skip from ._augment import RandomCutMix, RandomMixUp, SimpleCopyPaste from ._geometry import FixedSizeCrop from ._misc import PermuteDimensions, TransposeDimensions from ._type_conversion import LabelToOneHot
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.linalg import cholesky as cholesky from keras.src.ops.linalg import det as det from keras.src.ops.linalg import eig as eig from keras.src.ops.linalg import eigh as eigh from keras...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.linalg import cholesky from keras.src.ops.linalg import det from keras.src.ops.linalg import eig from keras.src.ops.linalg import eigh from keras.src.ops.linalg import inv from ke...
from docarray.array.array import DocumentArray __all__ = ['DocumentArray']
from docarray.array.documentarray import DocumentArray __all__ = ['DocumentArray']
"""This is the langchain_ollama package. It provides infrastructure for interacting with the Ollama service. """ from importlib import metadata from langchain_ollama.chat_models import ChatOllama from langchain_ollama.embeddings import OllamaEmbeddings from langchain_ollama.llms import OllamaLLM try: __version_...
"""This is the langchain_ollama package. It provides infrastructure for interacting with the Ollama service. """ from importlib import metadata from langchain_ollama.chat_models import ChatOllama from langchain_ollama.embeddings import OllamaEmbeddings from langchain_ollama.llms import OllamaLLM try: __version...
import torch from torchvision import _BETA_TRANSFORMS_WARNING, _WARN_ABOUT_BETA_TRANSFORMS from ._bounding_box import BoundingBoxes, BoundingBoxFormat from ._datapoint import Datapoint from ._image import Image from ._mask import Mask from ._torch_function_helpers import set_return_type from ._video import Video if _...
import torch from torchvision import _BETA_TRANSFORMS_WARNING, _WARN_ABOUT_BETA_TRANSFORMS from ._bounding_box import BoundingBoxes, BoundingBoxFormat from ._datapoint import Datapoint from ._image import Image from ._mask import Mask from ._torch_function_helpers import set_return_type from ._video import Video if _...
"""OpenAI-Like embeddings.""" from typing import Any, Dict, Optional import httpx from llama_index.core.callbacks.base import CallbackManager from llama_index.embeddings.openai import OpenAIEmbedding class OpenAILikeEmbedding(OpenAIEmbedding): """ OpenAI-Like class for embeddings. Args: model_n...
"""OpenAI-Like embeddings.""" from typing import Any, Dict, Optional import httpx from llama_index.core.callbacks.base import CallbackManager from llama_index.embeddings.openai import OpenAIEmbedding class OpenAILikeEmbedding(OpenAIEmbedding): """ OpenAI-Like class for embeddings. Args: model_n...
import sqlite3 import warnings from dataclasses import dataclass, field from tempfile import NamedTemporaryFile from typing import Iterable, Dict, Optional, TYPE_CHECKING, Union from docarray.array.storage.sqlite.helper import initialize_table from docarray.array.storage.base.backend import BaseBackendMixin from docar...
import sqlite3 import warnings from dataclasses import dataclass, field from tempfile import NamedTemporaryFile from typing import Iterable, Dict, Optional, TYPE_CHECKING, Union from docarray.array.storage.sqlite.helper import initialize_table from docarray.array.storage.base.backend import BaseBackendMixin from docar...
from jina import Executor, requests class MyExecutorToReload1(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests() def foo(self, docs, **kwargs): for doc in docs: doc.text = 'MyExecutorAfterReload' @requests(on='/bar') def bar(self, docs, **...
from jina import Executor, requests class MyExecutorToReload1(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests() def foo(self, docs, **kwargs): for doc in docs: doc.text = 'MyExecutorAfterReload'
import asyncio from typing import Any, AsyncGenerator, Optional from llama_index.core.workflow.context import Context from llama_index.core.workflow.errors import WorkflowDone from llama_index.core.workflow.events import Event, StopEvent from .utils import BUSY_WAIT_DELAY class WorkflowHandler(asyncio.Future): ...
import asyncio from typing import Any, AsyncGenerator, Optional from llama_index.core.workflow.context import Context from llama_index.core.workflow.events import Event, StopEvent from llama_index.core.workflow.errors import WorkflowDone class WorkflowHandler(asyncio.Future): def __init__( self, ...
""" This example uses average word embeddings (for example from GloVe). It adds two fully-connected feed-forward layers (dense layers) to create a Deep Averaging Network (DAN). If 'glove.6B.300d.txt.gz' does not exist, it tries to download it from our server. See https://public.ukp.informatik.tu-darmstadt.de/reimers/...
""" This example uses average word embeddings (for example from GloVe). It adds two fully-connected feed-forward layers (dense layers) to create a Deep Averaging Network (DAN). If 'glove.6B.300d.txt.gz' does not exist, it tries to download it from our server. See https://public.ukp.informatik.tu-darmstadt.de/reimers/...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import MAP_TO_NONE as MAP_TO_NONE from keras.src.tree.tree_api import assert_same_paths as assert_same_paths from keras.src.tree.tree_api import ( assert_same_struct...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.tree.tree_api import MAP_TO_NONE from keras.src.tree.tree_api import assert_same_paths from keras.src.tree.tree_api import assert_same_structure from keras.src.tree.tree_api import fl...
from typing import Dict, Optional, Tuple import numpy as np import torch import torchvision.transforms as T from jina import DocumentArray, Executor, requests from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform class TimmImageEncoder(Execu...
from typing import Dict, Optional, Tuple import numpy as np import torch import torchvision.transforms as T from jina import DocumentArray, Executor, requests from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform class TimmImageEncoder(Execu...
from typing import Any, List, Optional, Union from llama_index.core.base.llms.types import ChatMessage, ContentBlock, TextBlock from llama_index.core.bridge.pydantic import Field, field_validator from llama_index.core.memory.memory import BaseMemoryBlock class StaticMemoryBlock(BaseMemoryBlock[List[ContentBlock]]): ...
from typing import Any, List, Optional, Union from llama_index.core.base.llms.types import ChatMessage, ContentBlock, TextBlock from llama_index.core.bridge.pydantic import Field, field_validator from llama_index.core.memory.memory import BaseMemoryBlock class StaticMemoryBlock(BaseMemoryBlock[List[ContentBlock]]): ...
from argparse import Namespace from copy import deepcopy from typing import TYPE_CHECKING, Type from hubble.executor.helper import is_valid_huburi from hubble.executor.hubio import HubIO from jina.enums import PodRoleType from jina.orchestrate.pods import Pod from jina.orchestrate.pods.container import ContainerPod ...
from argparse import Namespace from copy import deepcopy from typing import TYPE_CHECKING, Type from hubble.executor.helper import is_valid_huburi from hubble.executor.hubio import HubIO from jina.enums import PodRoleType from jina.orchestrate.pods import Pod from jina.orchestrate.pods.container import ContainerPod ...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .tacotron2_loss_impl import Tacotron2LossGradcheckTests, Tacotron2LossShapeTests, Tacotron2LossTorchscriptTests class TestTacotron2LossShapeFloat32CPU(Tacotron2LossShapeTests, PytorchTestCase): dtype = torch.float32 device = torch...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .tacotron2_loss_impl import ( Tacotron2LossGradcheckTests, Tacotron2LossShapeTests, Tacotron2LossTorchscriptTests, ) class TestTacotron2LossShapeFloat32CPU(Tacotron2LossShapeTests, PytorchTestCase): dtype = torch.float32 ...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2020 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 2020 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...
# Copyright (c) OpenMMLab. All rights reserved. from .manager import ManagerMeta, ManagerMixin from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_method, import_modules_from_strings, is_list_of, is_method_overridden, is_seq_of, is_str, is_tuple_of, ...
# Copyright (c) OpenMMLab. All rights reserved. from .manager import ManagerMeta, ManagerMixin from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_method, import_modules_from_strings, is_list_of, is_method_overridden, is_seq_of, is_str, is_tuple_of, ...
# Copyright (c) OpenMMLab. All rights reserved. from .gaussian_target import (gather_feat, gaussian_radius, gen_gaussian_target, get_local_maximum, get_topk_from_heatmap, transpose_and_gather_feat) from .image import imrenormalize from .make_divisible import m...
# Copyright (c) OpenMMLab. All rights reserved. from .gaussian_target import (gather_feat, gaussian_radius, gen_gaussian_target, get_local_maximum, get_topk_from_heatmap, transpose_and_gather_feat) from .make_divisible import make_divisible from .misc import (...
from typing import Any, Optional, Type, TypeVar, Union from docarray.base_document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import AnyEmbedding T = TypeVar('T', bound='Text') class Text(BaseDocument): """ Document for handling text. It can contain a T...
from typing import Any, Optional, Type, TypeVar, Union from docarray.base_document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import AnyEmbedding T = TypeVar('T', bound='Text') class Text(BaseDocument): """ Document for handling text. It can contain a T...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Literal from sentence_transformers.evaluation import BinaryClassificationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseE...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Literal from sentence_transformers.evaluation import BinaryClassificationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseE...
from typing import Any, Callable, Optional import torch from .. import transforms from .vision import VisionDataset class FakeData(VisionDataset): """A fake dataset that returns randomly generated images and returns them as PIL images Args: size (int, optional): Size of the dataset. Default: 1000 i...
from typing import Any, Callable, Optional import torch from .. import transforms from .vision import VisionDataset class FakeData(VisionDataset): """A fake dataset that returns randomly generated images and returns them as PIL images Args: size (int, optional): Size of the dataset. Default: 1000 i...
from typing import Union, Iterable from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray.array.memory import DocumentArrayInMemory from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods""" def extend(self, values: Iterab...
from typing import Union, Iterable from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray.array.memory import DocumentArrayInMemory from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods""" def extend(self, values: Iterab...
from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.merging.base_merge import Merge @keras_export("keras.layers.Maximum") class Maximum(Merge): """Computes element-wise maximum on a list of inputs. It takes as input a list of tensors, all of the same shape, and r...
from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.merging.base_merge import Merge @keras_export("keras.layers.Maximum") class Maximum(Merge): """Computes element-wise maximum on a list of inputs. It takes as input a list of tensors, all of the same shape, and r...
"""Argparser module for Deployment runtimes""" import argparse from jina import helper from jina.enums import DeploymentRoleType from jina.parsers.helper import _SHOW_ALL_ARGS, KVAppendAction, add_arg_group def mixin_base_deployment_parser(parser): """Add mixin arguments required by :class:`BaseDeployment` into ...
"""Argparser module for Deployment runtimes""" import argparse from jina import helper from jina.enums import DeploymentRoleType from jina.parsers.helper import _SHOW_ALL_ARGS, KVAppendAction, add_arg_group def mixin_base_deployment_parser(parser): """Add mixin arguments required by :class:`BaseDeployment` into ...
# 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...
from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip from . import functional, utils # usort: skip from ._transform import Transform # usort: skip from ._augment import Cutmix, Mixup, RandomErasing from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide fro...
from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip from . import functional, utils # usort: skip from ._transform import Transform # usort: skip from ._augment import RandomErasing from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide from ._color impor...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig from .single_stage import SingleStageDetector @MODELS.register_module() class TOOD(SingleStageDetector): r"""Implementation of `TOOD: Task-aligned One-stage Object De...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.core import ConfigType, OptConfigType, OptMultiConfig from mmdet.registry import MODELS from .single_stage import SingleStageDetector @MODELS.register_module() class TOOD(SingleStageDetector): r"""Implementation of `TOOD: Task-aligned One-stage Object Det...
"""Test LLM Bash functionality.""" import os import sys from unittest.mock import patch import pytest from langchain.chains.llm import LLMChain from langchain.evaluation.loading import load_evaluator from langchain.evaluation.qa.eval_chain import ( ContextQAEvalChain, CotQAEvalChain, QAEvalChain, _pa...
"""Test LLM Bash functionality.""" import os import sys from unittest.mock import patch import pytest from langchain.chains.llm import LLMChain from langchain.evaluation.loading import load_evaluator from langchain.evaluation.qa.eval_chain import ( ContextQAEvalChain, CotQAEvalChain, QAEvalChain, _pa...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
# Copyright (c) OpenMMLab. All rights reserved. """Get image shape on CrowdHuman dataset. Here is an example to run this script. Example: python tools/misc/get_crowdhuman_id_hw.py ${CONFIG} \ --dataset ${DATASET_TYPE} """ import argparse import json import logging import os.path as osp from multiprocessing im...
# Copyright (c) OpenMMLab. All rights reserved. """Get image shape on CrowdHuman dataset. Here is an example to run this script. Example: python tools/misc/get_crowdhuman_id_hw.py ${CONFIG} \ --dataset ${DATASET_TYPE} """ import argparse import json import logging import os.path as osp from multiprocessing im...