input
stringlengths
33
5k
output
stringlengths
32
5k
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import numpy as np from .extmath import stable_cumsum def _weighted_percentile(array, sample_weight, percentile_rank=50): """Compute the weighted percentile with method 'inverted_cdf'. When the percentile lies between two data p...
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import numpy as np from .extmath import stable_cumsum def _weighted_percentile(array, sample_weight, percentile=50): """Compute weighted percentile Computes lower weighted percentile. If `array` is a 2D array, the `percentil...
from __future__ import annotations import os from copy import deepcopy import numpy as np import pytest from tokenizers import Tokenizer from sentence_transformers import SentenceTransformer from sentence_transformers.models import Pooling, StaticEmbedding, Transformer from sentence_transformers.util import is_datas...
from __future__ import annotations import os import pytest from sentence_transformers import SentenceTransformer from sentence_transformers.models import Pooling, Transformer from sentence_transformers.util import is_datasets_available from tests.utils import SafeTemporaryDirectory if is_datasets_available(): f...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Iterable, Optional import torch from jina import DocumentArray, Executor, requests from jina.logging.logger import JinaLogger from laserembeddings import Laser class Laser...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Iterable, Optional import torch from jina import DocumentArray, Executor, requests from jina.logging.logger import JinaLogger from jina_commons.batching import get_docs_batc...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import PLUGIN_LAYERS eps = 1e-6 @PLUGIN_LAYERS.register_module() class DropBlock(nn.Module): """Randomly drop some regions of feature maps. Please refer to the method proposed in...
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import PLUGIN_LAYERS eps = 1e-6 @PLUGIN_LAYERS.register_module() class DropBlock(nn.Module): """Randomly drop some regions of feature maps. Please refer to the method proposed in `DropBlock <https://arxiv.org/abs/1810.128...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.1.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. """ versio...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.0.1' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.0.1'. Returns: tuple: version information contains major, minor, micro version. """ versio...
import pytest from docarray.utils.misc import is_tf_available tf_available = is_tf_available() if tf_available: import tensorflow as tf from docarray.computation.tensorflow_backend import TensorFlowCompBackend from docarray.typing import TensorFlowTensor metrics = TensorFlowCompBackend.Metrics else:...
import pytest try: import tensorflow as tf from docarray.computation.tensorflow_backend import TensorFlowCompBackend from docarray.typing import TensorFlowTensor metrics = TensorFlowCompBackend.Metrics except (ImportError, TypeError): metrics = None @pytest.mark.tensorflow def test_cosine_sim_t...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
_CTC_DECODERS = [ "CTCHypothesis", "CTCDecoder", "CTCDecoderLM", "CTCDecoderLMState", "ctc_decoder", "download_pretrained_files", ] _CUDA_CTC_DECODERS = [ "CUCTCDecoder", "CUCTCHypothesis", "cuda_ctc_decoder", ] def __getattr__(name: str): if name in _CTC_DECODERS: try:...
_CTC_DECODERS = [ "CTCHypothesis", "CTCDecoder", "CTCDecoderLM", "CTCDecoderLMState", "ctc_decoder", "download_pretrained_files", ] def __getattr__(name: str): if name in _CTC_DECODERS: try: from . import _ctc_decoder except Exception as err: raise R...
import matplotlib.pyplot as plt import torch from torchvision.utils import draw_bounding_boxes, draw_segmentation_masks from torchvision import datapoints from torchvision.transforms.v2 import functional as F def plot(imgs): if not isinstance(imgs[0], list): # Make a 2d grid even if there's just 1 row ...
import matplotlib.pyplot as plt from torchvision.utils import draw_bounding_boxes def plot(imgs): if not isinstance(imgs[0], list): # Make a 2d grid even if there's just 1 row imgs = [imgs] num_rows = len(imgs) num_cols = len(imgs[0]) _, axs = plt.subplots(nrows=num_rows, ncols=num_co...
from typing import Iterator from typing import Tuple import torch from keras.src.backend.common.stateless_scope import in_stateless_scope from keras.src.ops.operation import Operation class TorchLayer(torch.nn.Module): def _post_build(self): # Do not track variables when in a stateless scope. # ...
import torch from keras.src.backend.common.stateless_scope import in_stateless_scope from keras.src.ops.operation import Operation class TorchLayer(torch.nn.Module): def _post_build(self): # Do not track variables when in a stateless scope. # The variables are not initialized. if in_state...
"""Helper functions for clients in Jina.""" from functools import wraps from typing import Callable, Optional from jina.excepts import BadClientCallback, BadServer from jina.helper import get_rich_console from jina.logging.logger import JinaLogger from jina.proto import jina_pb2 from jina.types.request.data import Re...
"""Helper functions for clients in Jina.""" from functools import wraps from typing import Callable from jina.excepts import BadClientCallback, BadServer from jina.helper import get_rich_console from jina.logging.logger import JinaLogger from jina.proto import jina_pb2 from jina.types.request.data import Response d...
"""Defines utilities for switching audio backends""" import warnings from typing import List, Optional import torchaudio from torchaudio._internal import module_utils as _mod_utils from . import no_backend, soundfile_backend, sox_io_backend __all__ = [ "list_audio_backends", "get_audio_backend", "set_aud...
"""Defines utilities for switching audio backends""" import warnings from typing import Optional, List import torchaudio from torchaudio._internal import module_utils as _mod_utils from . import ( no_backend, sox_io_backend, soundfile_backend, ) __all__ = [ "list_audio_backends", "get_audio_backe...
from llama_index.core.instrumentation.events.base import BaseEvent class SpanDropEvent(BaseEvent): """ SpanDropEvent. Args: err_str (str): Error string. """ err_str: str @classmethod def class_name(cls) -> str: """Class name.""" return "SpanDropEvent"
from llama_index.core.instrumentation.events.base import BaseEvent class SpanDropEvent(BaseEvent): """SpanDropEvent. Args: err_str (str): Error string. """ err_str: str @classmethod def class_name(cls) -> str: """Class name.""" return "SpanDropEvent"
import functools import numbers from collections import defaultdict from typing import Any, Dict, Sequence, Type, TypeVar, Union from torchvision.prototype import datapoints from torchvision.prototype.datapoints._datapoint import FillType, FillTypeJIT from torchvision.transforms.transforms import _check_sequence_inpu...
import functools import numbers from collections import defaultdict from typing import Any, Dict, Sequence, Type, TypeVar, Union from torchvision.prototype import features from torchvision.prototype.features._feature import FillType, FillTypeJIT from torchvision.transforms.transforms import _check_sequence_input, _se...
_base_ = './reppoints-moment_r50_fpn-gn_head-gn_1x_coco.py' model = dict(bbox_head=dict(transform_method='minmax'))
_base_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py' model = dict(bbox_head=dict(transform_method='minmax'))
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weighted_loss @weighted_loss def mse_loss(pred, target): """Wrapper of mse loss.""" return F.mse_loss(pred, target, reduction='none') @MODELS.register_m...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weighted_loss @weighted_loss def mse_loss(pred, target): """Warpper of mse loss.""" return F.mse_loss(pred, target, reduction='none') @MODELS.register_m...
import os import subprocess from pathlib import Path from typing import Dict import numpy as np import pytest from jina import Document, DocumentArray from PIL import Image @pytest.fixture() def test_dir() -> str: return os.path.dirname(os.path.abspath(__file__)) @pytest.fixture() def test_images(test_dir: str...
import os import subprocess from pathlib import Path from typing import Dict import numpy as np import pytest from jina import Document, DocumentArray from PIL import Image @pytest.fixture() def test_dir() -> str: return os.path.dirname(os.path.abspath(__file__)) @pytest.fixture() def test_images(test_dir: str...
"""Node PostProcessor module.""" from llama_index.core.postprocessor.llm_rerank import LLMRerank from llama_index.core.postprocessor.structured_llm_rerank import ( StructuredLLMRerank, DocumentWithRelevance, ) from llama_index.core.postprocessor.metadata_replacement import ( MetadataReplacementPostProcess...
"""Node PostProcessor module.""" from llama_index.core.postprocessor.llm_rerank import LLMRerank from llama_index.core.postprocessor.metadata_replacement import ( MetadataReplacementPostProcessor, ) from llama_index.core.postprocessor.node import ( AutoPrevNextNodePostprocessor, KeywordNodePostprocessor, ...
import functools import warnings from collections import defaultdict from typing import Any, Dict, Optional, Sequence, Tuple, Type, TypeVar, Union import torch from torchvision import datapoints from torchvision.transforms.v2 import Transform from torchvision.transforms.v2._utils import is_pure_tensor T = TypeVar(...
import functools import warnings from collections import defaultdict from typing import Any, Dict, Optional, Sequence, Tuple, Type, TypeVar, Union import torch from torchvision import datapoints from torchvision.transforms.v2 import Transform from torchvision.transforms.v2.utils import is_pure_tensor T = TypeVar("...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from .cascade_rcnn import CascadeRCNN @MODELS.register_module() class HybridTaskCascade(CascadeRCNN): """Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_""" def __init__(self, **kwargs): super(HybridTaskCasca...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .cascade_rcnn import CascadeRCNN @DETECTORS.register_module() class HybridTaskCascade(CascadeRCNN): """Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_""" def __init__(self, **kwargs): super(HybridTaskCasc...
"""langchain-core version information and utilities.""" VERSION = "0.3.52"
"""langchain-core version information and utilities.""" VERSION = "0.3.51"
from jina import Executor, requests from .helper import get_doc_value class MyExecutorToReload2(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests() def foo(self, docs, **kwargs): for doc in docs: doc.text = get_doc_value()
from jina import Executor, requests from .helper import get_doc_value class MyExecutorToReload2(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests() def foo(self, docs, **kwargs): for doc in docs: doc.text = get_doc_value()
import importlib import os import re from pathlib import Path from typing import Type, TypeVar from backend.data.block import Block # Dynamically load all modules under backend.blocks AVAILABLE_MODULES = [] current_dir = Path(__file__).parent modules = [ str(f.relative_to(current_dir))[:-3].replace(os.path.sep, "...
import importlib import os import re from pathlib import Path from typing import Type, TypeVar from backend.data.block import Block # Dynamically load all modules under backend.blocks AVAILABLE_MODULES = [] current_dir = Path(__file__).parent modules = [ str(f.relative_to(current_dir))[:-3].replace(os.path.sep, "...
_base_ = './mask-rcnn_r50_fpn_gn-all_2x_coco.py' # learning policy max_epochs = 36 train_cfg = dict(max_epochs=max_epochs) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=ma...
_base_ = './mask_rcnn_r50_fpn_gn-all_2x_coco.py' # learning policy max_epochs = 36 train_cfg = dict(max_epochs=max_epochs) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=ma...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseMSEEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model student_model = SparseEncoder("prithivida/Splade_PP_en_v1") tea...
import logging from datasets import load_dataset from sentence_transformers.sparse_encoder import ( MLMTransformer, SparseEncoder, SparseMSEEvaluator, SpladePooling, ) logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) # Initialize the SPLADE mod...
"""Top-level imports for LlamaIndex.""" __version__ = "0.12.37" 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_in...
"""Init file of LlamaIndex.""" __version__ = "0.12.37" 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....
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "tutorial004", pytest.param("tutorial004_py39", marks=needs_py39), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.im...
from fastapi.testclient import TestClient from docs_src.extra_models.tutorial004 import app client = TestClient(app) def test_get_items(): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == [ {"name": "Foo", "description": "There comes my...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.image import affine_transform from keras.src.ops.image import crop_images from keras.src.ops.image import extract_patches from keras.src.ops.image import hsv_to_rgb from keras.src...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.image import affine_transform from keras.src.ops.image import crop_images from keras.src.ops.image import extract_patches from keras.src.ops.image import map_coordinates from kera...
from typing import TYPE_CHECKING, Type, TypeVar, Union from uuid import UUID from pydantic import BaseConfig, parse_obj_as from pydantic.fields import ModelField from docarray.typing.proto_register import _register_proto if TYPE_CHECKING: from docarray.proto import NodeProto from docarray.typing.abstract_type i...
from typing import TYPE_CHECKING, Type, TypeVar, Union from uuid import UUID from pydantic import BaseConfig, parse_obj_as from pydantic.fields import ModelField from docarray.typing.proto_register import _register_proto if TYPE_CHECKING: from docarray.proto import NodeProto from docarray.typing.abstract_type i...
"""DashVector reader.""" from typing import Dict, List, Optional import json from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class DashVectorReader(BaseReader): """ DashVector reader. Args: api_key (str): DashVector API key. endpoint (str...
"""DashVector reader.""" from typing import Dict, List, Optional import json from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class DashVectorReader(BaseReader): """ DashVector reader. Args: api_key (str): DashVector API key. endpoint (str...
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
import os import time import numpy as np import pytest from jina import Document, DocumentArray from .. import MongoDBStorage NUM_DOCS = 10 @pytest.fixture def storage(): return MongoDBStorage() @pytest.fixture def docs_to_index(): docu_array = DocumentArray() for idx in range(0, NUM_DOCS): d...
import os import time import pytest import numpy as np from jina import Document, DocumentArray from .. import MongoDBStorage NUM_DOCS = 10 @pytest.fixture def storage(): return MongoDBStorage() @pytest.fixture def docs_to_index(): docu_array = DocumentArray() for idx in range(0, NUM_DOCS): d...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet.structures import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modules class TestRPN(TestCase...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet.data_elements import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modules class TestRPN(TestC...
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 jina.enums import PodRoleType from jina.hubble.helper import is_valid_huburi from jina.hubble.hubio import HubIO from jina.orchestrate.pods import Pod from jina.orchestrate.pods.container import ContainerPod if TYPE_C...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # optimizer optim_wrapper = dict( optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001))
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_chann...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_chann...
from .transcribe import cli cli()
from .transcribe import cli cli()
# 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 (...
# 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 enum import Enum from typing import Any, Dict, Iterable import torch.nn.functional as F from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer class SiameseDistanceMetric(Enum): """The metric for the contrastive loss""" EUCLIDEAN = lambda x, y: F.pairwis...
from enum import Enum from typing import Dict, Iterable import torch.nn.functional as F from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer class SiameseDistanceMetric(Enum): """The metric for the contrastive loss""" EUCLIDEAN = lambda x, y: F.pairwise_dis...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.inception_v3 import InceptionV3 as InceptionV3 from keras.src.applications.inception_v3 import ( decode_predictions as decode_predictions, ) from keras.src.applicatio...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.inception_v3 import InceptionV3 from keras.src.applications.inception_v3 import decode_predictions from keras.src.applications.inception_v3 import preprocess_input
""" This script contains an example how to perform semantic search with OpenSearch. You need OpenSearch up and running locally: https://docs.opensearch.org/docs/latest/getting-started/quickstart/ Further, you need the Python OpenSearch Client installed: https://docs.opensearch.org/docs/latest/clients/python-low-level...
""" This script contains an example how to perform semantic search with OpenSearch. You need OpenSearch up and running locally: https://docs.opensearch.org/docs/latest/getting-started/quickstart/ Further, you need the Python OpenSearch Client installed: https://docs.opensearch.org/docs/latest/clients/python-low-level...
_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' # model settings model = dict( roi_head=dict( bbox_roi_extractor=dict( type='GenericRoIExtractor', aggregation='sum', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, ...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' # model settings model = dict( roi_head=dict( bbox_roi_extractor=dict( type='GenericRoIExtractor', aggregation='sum', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, ...
from __future__ import annotations __version__ = "4.1.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_model, ) from senten...
from __future__ import annotations __version__ = "4.1.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_model, ) from senten...
"""Run smoke tests""" import os import torchvision from torchvision.io import read_image image_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "assets", "encode_jpeg", "grace_hopper_517x606.jpg" ) print("torchvision version is ", torchvision.__version__) img = read_image(image_path)
"""Run smoke tests""" import torchvision print("torchvision version is ", torchvision.__version__)
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseMSEEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model student_model = SparseEncoder("prithivida/Splade_PP_en_v1") tea...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseMSEEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model student_model = SparseEncoder("prithivida/Splade_PP_en_v1") tea...
from io import BytesIO from typing import TYPE_CHECKING, Optional, Tuple, TypeVar import numpy as np from pydantic import parse_obj_as from docarray.typing.bytes.base_bytes import BaseBytes from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.image.image_ndarray import ImageNdArray f...
from io import BytesIO from typing import TYPE_CHECKING, Any, Optional, Tuple, Type, TypeVar import numpy as np from pydantic import parse_obj_as from pydantic.validators import bytes_validator from docarray.typing.abstract_type import AbstractType from docarray.typing.proto_register import _register_proto from docar...
# CoSENTLoss must be imported before AnglELoss from __future__ import annotations from .CoSENTLoss import CoSENTLoss # isort: skip from .AdaptiveLayerLoss import AdaptiveLayerLoss from .AnglELoss import AnglELoss from .BatchAllTripletLoss import BatchAllTripletLoss from .BatchHardSoftMarginTripletLoss import BatchHa...
# CoSENTLoss must be imported before AnglELoss from __future__ import annotations from .CoSENTLoss import CoSENTLoss # isort: skip from .AdaptiveLayerLoss import AdaptiveLayerLoss from .AnglELoss import AnglELoss from .BatchAllTripletLoss import BatchAllTripletLoss from .BatchHardSoftMarginTripletLoss import BatchHa...
import os from functools import lru_cache from typing import Union import ffmpeg import numpy as np import torch import torch.nn.functional as F from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 N_MELS = 80 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_LENGTH * SA...
import os from functools import lru_cache from typing import Union import ffmpeg import numpy as np import torch import torch.nn.functional as F from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 N_MELS = 80 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_LENGTH * SA...
import logging from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseNanoBEIREvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") datasets = ["QuoraRetrieval...
import logging from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseNanoBEIREvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") datasets = ["QuoraRetrieval...
# Copyright (c) OpenMMLab. All rights reserved. from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .builder import build_linear_layer, build_transformer from .ckpt_convert import pvt_convert from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .gaussian_target import gaussia...
# Copyright (c) OpenMMLab. All rights reserved. from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .builder import build_linear_layer, build_transformer from .ckpt_convert import pvt_convert from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .gaussian_target import gaussia...
""" S3 file and directory reader. A loader that fetches a file or iterates through a directory on AWS S3 or other compatible service. """ from typing import Dict, List, Optional, Union from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.opendal....
"""S3 file and directory reader. A loader that fetches a file or iterates through a directory on AWS S3 or other compatible service. """ from typing import Dict, List, Optional, Union from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.opendal.b...
from docarray import DocList, BaseDoc from docarray.documents.text import TextDoc from jina import Executor, requests, Flow def test_issue(): class QuoteFile(BaseDoc): quote_file_id: int = None texts: DocList[TextDoc] = None class SearchResult(BaseDoc): results: DocList[QuoteFile] = N...
from docarray import DocList, BaseDoc from docarray.documents.text import TextDoc from jina import Executor, requests, Flow def test_issue(): class QuoteFile(BaseDoc): quote_file_id: int = None texts: DocList[TextDoc] = None class SearchResult(BaseDoc): results: DocList[QuoteFile] = N...
# 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 Optional import torch from docarray import BaseDoc, DocList from docarray.typing import TorchTensor def test_torch_train(): class Mmdoc(BaseDoc): text: str tensor: Optional[TorchTensor[3, 224, 224]] = None N = 10 batch = DocList[Mmdoc](Mmdoc(text=f'hello{i}') for i i...
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause def check_matplotlib_support(caller_name): """Raise ImportError with detailed error message if mpl is not installed. Plot utilities like any of the Display's plotting functions should lazily import matplotlib and call this hel...
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause def check_matplotlib_support(caller_name): """Raise ImportError with detailed error message if mpl is not installed. Plot utilities like any of the Display's plotting functions should lazily import matplotlib and call this hel...
_base_ = './ga-retinanet_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'...
_base_ = './ga_retinanet_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .boxinst_head import BoxInstBboxHead, BoxInstMaskHead from .cascade_rpn_head import CascadeRPNHead, StageCasca...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .boxinst_head import BoxInstBboxHead, BoxInstMaskHead from .cascade_rpn_head import CascadeRPNHead, StageCasca...
import pytest from ldclient import LDClient from autogpt_libs.feature_flag.client import feature_flag, mock_flag_variation @pytest.fixture def ld_client(mocker): client = mocker.Mock(spec=LDClient) mocker.patch("ldclient.get", return_value=client) client.is_initialized.return_value = True return clie...
import pytest from autogpt_libs.feature_flag.client import feature_flag, mock_flag_variation from ldclient import LDClient @pytest.fixture def ld_client(mocker): client = mocker.Mock(spec=LDClient) mocker.patch("ldclient.get", return_value=client) client.is_initialized.return_value = True return clien...
"""Defines utilities for switching audio backends""" import warnings from typing import List, Optional import torchaudio from torchaudio._internal import module_utils as _mod_utils from . import no_backend, soundfile_backend, sox_io_backend __all__ = [ "list_audio_backends", "get_audio_backend", "set_aud...
"""Defines utilities for switching audio backends""" import warnings from typing import List, Optional import torchaudio from torchaudio._internal import module_utils as _mod_utils from . import no_backend, soundfile_backend, sox_io_backend __all__ = [ "list_audio_backends", "get_audio_backend", "set_aud...
"""Experiment with different models.""" from __future__ import annotations from collections.abc import Sequence from typing import Optional from langchain_core.language_models.llms import BaseLLM from langchain_core.prompts.prompt import PromptTemplate from langchain_core.utils.input import get_color_mapping, print_...
"""Experiment with different models.""" from __future__ import annotations from collections.abc import Sequence from typing import Optional from langchain_core.language_models.llms import BaseLLM from langchain_core.prompts.prompt import PromptTemplate from langchain_core.utils.input import get_color_mapping, print_...
import gzip import os from . import InputExample class NLIDataReader(object): """Reads in the Stanford NLI dataset and the MultiGenre NLI dataset""" def __init__(self, dataset_folder): self.dataset_folder = dataset_folder def get_examples(self, filename, max_examples=0): """ dat...
from . import InputExample import gzip import os class NLIDataReader(object): """Reads in the Stanford NLI dataset and the MultiGenre NLI dataset""" def __init__(self, dataset_folder): self.dataset_folder = dataset_folder def get_examples(self, filename, max_examples=0): """ data...
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 datetime import datetime import torch from torch.utils.data import DataLoader #### Just some code to print debug information ...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import (ConvModule, caffe2_xavier_init, constant_init, is_norm, normal_init) from torch.nn import BatchNorm2d from mmdet.registry import MODELS class Bottleneck(nn.Module): """Bottleneck block for DilatedEnc...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import (ConvModule, caffe2_xavier_init, constant_init, is_norm, normal_init) from torch.nn import BatchNorm2d from ..builder import NECKS class Bottleneck(nn.Module): """Bottleneck block for DilatedEncoder u...
""" This file contains deprecated code that can only be used with the old `model.fit`-style Sentence Transformers v2.X training. It exists for backwards compatibility with the `model.old_fit` method, but will be removed in a future version. Nowadays, with Sentence Transformers v3+, it is recommended to use the `Senten...
from __future__ import annotations import math import random class NoDuplicatesDataLoader: def __init__(self, train_examples, batch_size): """ A special data loader to be used with MultipleNegativesRankingLoss. The data loader ensures that there are no duplicate sentences within the same ...
"""Test OCI Generative AI embedding service.""" from unittest.mock import MagicMock from typing import Any import pytest from pytest import MonkeyPatch from llama_index.embeddings.oci_genai import OCIGenAIEmbeddings class MockResponseDict(dict): def __getattr__(self, val) -> Any: # type: ignore[no-untyped-def...
"""Test OCI Generative AI embedding service.""" from unittest.mock import MagicMock from typing import Any import pytest from pytest import MonkeyPatch from llama_index.embeddings.oci_genai import OCIGenAIEmbeddings class MockResponseDict(dict): def __getattr__(self, val) -> Any: # type: ignore[no-untyped-def]...
_base_ = [ '../_base_/models/ssd300.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] # dataset settings input_size = 300 train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( ...
_base_ = [ '../_base_/models/ssd300.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' input_size = 300 train_pipeline = [ dict(type='LoadImageFromFile'), dict(type=...
from contextlib import suppress from docutils import nodes from docutils.parsers.rst import Directive from sklearn.utils import all_estimators from sklearn.utils._test_common.instance_generator import _construct_instances from sklearn.utils._testing import SkipTest class AllowNanEstimators(Directive): @staticme...
from contextlib import suppress from docutils import nodes from docutils.parsers.rst import Directive from sklearn.utils import all_estimators from sklearn.utils._test_common.instance_generator import _construct_instance from sklearn.utils._testing import SkipTest class AllowNanEstimators(Directive): @staticmet...
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)] @pytest.f...
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)...
"""Xgboost pyspark integration submodule for params.""" from typing import Dict from pyspark.ml.param import TypeConverters from pyspark.ml.param.shared import Param, Params class HasArbitraryParamsDict(Params): """ This is a Params based class that is extended by _SparkXGBParams and holds the variable ...
"""Xgboost pyspark integration submodule for params.""" from typing import Dict # pylint: disable=too-few-public-methods from pyspark.ml.param import TypeConverters from pyspark.ml.param.shared import Param, Params class HasArbitraryParamsDict(Params): """ This is a Params based class that is extended by _S...
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...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np import torch import torch.nn as nn from ..builder import LOSSES from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def balanced_l1_loss(pred, target, beta=1.0,...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np import torch import torch.nn as nn from ..builder import LOSSES from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def balanced_l1_loss(pred, target, beta=1.0,...
import os from typing import Optional import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray.documents import Audio from docarray.typing import AudioUrl from docarray.typing.tensor.audio import AudioNdArray, AudioTorchTensor from tests import TOYDATA_DIR LOCAL_AUDIO_FILES = [ ...
import os from typing import Optional import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray.documents import Audio from docarray.typing import AudioUrl from docarray.typing.tensor.audio import AudioNdArray, AudioTorchTensor from tests import TOYDATA_DIR LOCAL_AUDIO_FILES = [ ...
import importlib from typing import List import fsspec from . import compression from .hffilesystem import HfFileSystem _has_s3fs = importlib.util.find_spec("s3fs") is not None if _has_s3fs: from .s3filesystem import S3FileSystem # noqa: F401 COMPRESSION_FILESYSTEMS: List[compression.BaseCompressedFileFileSy...
import importlib from typing import List import fsspec from . import compression from .hffilesystem import HfFileSystem _has_s3fs = importlib.util.find_spec("s3fs") is not None if _has_s3fs: from .s3filesystem import S3FileSystem # noqa: F401 COMPRESSION_FILESYSTEMS: List[compression.BaseCompressedFileFileSy...
# Copyright (c) OpenMMLab. All rights reserved. from .base_boxes import BaseBoxes from .bbox_overlaps import bbox_overlaps from .box_type import (convert_box_type, get_box_type, register_box, register_box_converter) from .horizontal_boxes import HorizontalBoxes from .transforms import (bbox2corne...
# Copyright (c) OpenMMLab. All rights reserved. from .bbox_overlaps import bbox_overlaps from .transforms import (bbox2corner, bbox2distance, bbox2result, bbox2roi, bbox_cxcywh_to_xyxy, bbox_flip, bbox_mapping, bbox_mapping_back, bbox_project, bbox_rescale, ...
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 fastapi import APIRouter, Body, Depends, HTTPException from prisma.enums import AgentExecutionStatus, APIKeyPermission from typing_extensions import TypedDict import backend.data.block from backen...
_base_ = '../mask_rcnn/mask-rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( norm_cfg=dict(type='SyncBN', requires_grad=True), norm_eval=False, plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True, True), ...
_base_ = '../mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict( norm_cfg=dict(type='SyncBN', requires_grad=True), norm_eval=False, plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True, True), ...
""" Tool for the AskNews API. To use this tool, you must first set your credentials as environment variables: ASKNEWS_CLIENT_ID ASKNEWS_CLIENT_SECRET """ from typing import Any, Optional, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from lan...
""" Tool for the AskNews API. To use this tool, you must first set your credentials as environment variables: ASKNEWS_CLIENT_ID ASKNEWS_CLIENT_SECRET """ from typing import Any, Optional, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from lan...
import logging from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseNanoBEIREvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") evaluator = SparseNanoBEIR...
import logging from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseNanoBEIREvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") evaluator = SparseNanoBEIR...
""" This example starts multiple processes (1 per GPU), which encode sentences in parallel. This gives a near linear speed-up when encoding large text collections. """ import logging from sentence_transformers import LoggingHandler, SentenceTransformer logging.basicConfig( format="%(asctime)s - %(message)s", dat...
""" This example starts multiple processes (1 per GPU), which encode sentences in parallel. This gives a near linear speed-up when encoding large text collections. """ import logging from sentence_transformers import LoggingHandler, SentenceTransformer logging.basicConfig( format="%(asctime)s - %(message)s", dat...
import os import random import time from typing import Dict, OrderedDict import numpy as np import pytest from jina import Document, Flow, DocumentArray, requests, Executor from jina_commons.indexers.dump import dump_docs from jinahub.indexers.searcher.compound.FaissLMDBSearcher.faiss_lmdb import FaissLMDBSearcher fr...
import os import random import time from typing import Dict import numpy as np import pytest from jina import Document, Flow, DocumentArray, requests from jina_commons.indexers.dump import dump_docs from jinahub.indexers.searcher.compound.NumpyLMDBSearcher.npfile import NumpyLMDBSearcher from jinahub.indexers.storage...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
import csv import os from pathlib import Path from typing import Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.utils import extract_archive _RELEASE_CONFIGS = { "release1": { "folder_in_arch...
import csv import os from pathlib import Path from typing import Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.utils import extract_archive _RELEASE_CONFIGS = { "release1": { "folder_in_arch...
_base_ = '../faster_rcnn/faster-rcnn_x101-32x4d_fpn_1x_coco.py' model = dict( roi_head=dict( type='PISARoIHead', bbox_head=dict( loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), train_cfg=dict( rpn_proposal=dict( nms_pre=2000, max_per...
_base_ = '../faster_rcnn/faster_rcnn_x101_32x4d_fpn_1x_coco.py' model = dict( roi_head=dict( type='PISARoIHead', bbox_head=dict( loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), train_cfg=dict( rpn_proposal=dict( nms_pre=2000, max_per...
from keras.src.api_export import keras_export from keras.src.layers.pooling.base_pooling import BasePooling @keras_export(["keras.layers.AveragePooling2D", "keras.layers.AvgPool2D"]) class AveragePooling2D(BasePooling): """Average pooling operation for 2D spatial data. Downsamples the input along its spatial...
from keras.src.api_export import keras_export from keras.src.layers.pooling.base_pooling import BasePooling @keras_export(["keras.layers.AveragePooling2D", "keras.layers.AvgPool2D"]) class AveragePooling2D(BasePooling): """Average pooling operation for 2D spatial data. Downsamples the input along its spatial...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import mmengine from mmengine.utils import digit_version from .version import __version__, version_info mmcv_minimum_version = '2.0.0rc4' mmcv_maximum_version = '2.1.0' mmcv_version = digit_version(mmcv.__version__) mmengine_minimum_version = '0.4.0' mmengi...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import mmengine from mmengine.utils import digit_version from .version import __version__, version_info mmcv_minimum_version = '2.0.0rc4' mmcv_maximum_version = '2.1.0' mmcv_version = digit_version(mmcv.__version__) mmengine_minimum_version = '0.3.0' mmengi...
import multiprocessing import os import signal import time import pytest from jina import Document, DocumentArray, Executor, requests from jina.clients.request import request_generator from jina.parsers import set_gateway_parser from jina.serve.networking import GrpcConnectionPool from jina_cli.api import executor_na...
import multiprocessing import os import signal import time import pytest from jina import Document, DocumentArray, Executor, requests from jina.clients.request import request_generator from jina.parsers import set_gateway_parser, set_pod_parser from jina.serve.networking import GrpcConnectionPool from jina_cli.api im...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.resnet_v2 import ResNet50V2 as ResNet50V2 from keras.src.applications.resnet_v2 import ResNet101V2 as ResNet101V2 from keras.src.applications.resnet_v2 import ResNet152V2...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.applications.resnet_v2 import ResNet50V2 from keras.src.applications.resnet_v2 import ResNet101V2 from keras.src.applications.resnet_v2 import ResNet152V2 from keras.src.applications....
from keras.src import backend from keras.src.api_export import keras_export from keras.src.dtype_policies import dtype_policy from keras.src.dtype_policies.dtype_policy import QUANTIZATION_MODES from keras.src.dtype_policies.dtype_policy import DTypePolicy from keras.src.dtype_policies.dtype_policy import FloatDTypePol...
from keras.src import backend from keras.src.api_export import keras_export from keras.src.dtype_policies import dtype_policy from keras.src.dtype_policies.dtype_policy import QUANTIZATION_MODES from keras.src.dtype_policies.dtype_policy import DTypePolicy from keras.src.dtype_policies.dtype_policy import FloatDTypePol...
""" Example of training with Dask on GPU ==================================== """ import dask import dask_cudf from dask import array as da from dask import dataframe as dd from dask.distributed import Client from dask_cuda import LocalCUDACluster from xgboost import dask as dxgb from xgboost.dask import DaskDMatrix ...
""" Example of training with Dask on GPU ==================================== """ import dask import dask_cudf from dask import array as da from dask import dataframe as dd from dask.distributed import Client from dask_cuda import LocalCUDACluster from xgboost import dask as dxgb from xgboost.dask import DaskDMatrix ...
from . import ffmpeg_utils, sox_utils from .download import download_asset __all__ = [ "download_asset", "sox_utils", "ffmpeg_utils", ]
from torchaudio._internal import module_utils as _mod_utils from . import ffmpeg_utils, sox_utils from .download import download_asset if _mod_utils.is_sox_available(): sox_utils.set_verbosity(0) __all__ = [ "download_asset", "sox_utils", "ffmpeg_utils", ]
from keras.src import testing from keras.src.datasets import boston_housing class BostonHousingTest(testing.TestCase): def test_load_data(self): (x_train, y_train), (x_test, y_test) = boston_housing.load_data() self.assertEqual(x_train.shape[1], 13) self.assertEqual(x_train.shape[0] + x_te...
from keras.src import testing from keras.src.datasets import boston_housing class BostonHousingTest(testing.TestCase): def test_load_data(self): (x_train, y_train), (x_test, y_test) = boston_housing.load_data() self.assertEqual(x_train.shape[1], 13) self.assertEqual(x_train.shape[0] + x_t...
from __future__ import annotations from .Asym import Asym from .BoW import BoW from .CLIPModel import CLIPModel from .CNN import CNN from .Dense import Dense from .Dropout import Dropout from .InputModule import InputModule from .LayerNorm import LayerNorm from .LSTM import LSTM from .Module import Module from .Normal...
from __future__ import annotations from .Asym import Asym from .BoW import BoW from .CLIPModel import CLIPModel from .CNN import CNN from .Dense import Dense from .Dropout import Dropout from .LayerNorm import LayerNorm from .LSTM import LSTM from .Normalize import Normalize from .Pooling import Pooling from .StaticEm...
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod from typing import Any, Dict, Union from torch.utils.data import DataLoader class BaseLoop(metaclass=ABCMeta): """Base loop class. All subclasses inherited from ``BaseLoop`` should overwrite the :meth:`run` method. ...
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod from typing import Dict, Union from torch.utils.data import DataLoader class BaseLoop(metaclass=ABCMeta): """Base loop class. All subclasses inherited from ``BaseLoop`` should overwrite the :meth:`run` method. A...
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
import os import tempfile import unittest from unittest.mock import patch import transformers.commands.transformers_cli as cli from transformers.commands.chat import ChatArguments, ChatCommand from transformers.testing_utils import CaptureStd class ChatCLITest(unittest.TestCase): def test_help(self): wit...
""" Visual demo for survival analysis (regression) with Accelerated Failure Time (AFT) model. ========================================================================================= This demo uses 1D toy data and visualizes how XGBoost fits a tree ensemble. The ensemble model starts out as a flat line and evolves in...
""" Visual demo for survival analysis (regression) with Accelerated Failure Time (AFT) model. ========================================================================================= This demo uses 1D toy data and visualizes how XGBoost fits a tree ensemble. The ensemble model starts out as a flat line and evolves in...
from typing import Any from unittest.mock import patch import asyncio import pytest from llama_index.core.base.llms.types import ChatResponse, ChatMessage, MessageRole from llama_index.core.llms.mock import MockLLM from llama_index.core.postprocessor.rankGPT_rerank import RankGPTRerank from llama_index.core.schema imp...
from typing import Any from unittest.mock import patch import asyncio import pytest from llama_index.core.base.llms.types import ChatResponse, ChatMessage, MessageRole from llama_index.core.llms.mock import MockLLM from llama_index.core.postprocessor.rankGPT_rerank import RankGPTRerank from llama_index.core.schema imp...
import contextlib import os import shutil import threading import time from jina import Client, Deployment, DocumentArray, Flow cur_dir = os.path.dirname(__file__) @contextlib.contextmanager def _update_file(input_file_path, output_file_path, temp_path): backup_file = os.path.join(temp_path, 'backup.yaml') ...
import contextlib import os import shutil import threading import time import pytest from jina import Client, DocumentArray, Executor, Flow, requests, Deployment from jina.helper import random_port cur_dir = os.path.dirname(__file__) @contextlib.contextmanager def _update_file(input_file_path, output_file_path, te...
""" This script contains an example how to perform semantic search with Elasticsearch. You need Elasticsearch up and running locally: https://www.elastic.co/guide/en/elasticsearch/reference/current/run-elasticsearch-locally.html Further, you need the Python Elasticsearch Client installed: https://elasticsearch-py.rea...
""" This script contains an example how to perform semantic search with Elasticsearch. You need Elasticsearch up and running locally: https://www.elastic.co/guide/en/elasticsearch/reference/current/run-elasticsearch-locally.html Further, you need the Python Elasticsearch Client installed: https://elasticsearch-py.rea...
_base_ = [ '../_base_/models/mask_rcnn_r50_caffe_c4.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ]
_base_ = [ '../_base_/models/mask_rcnn_r50_caffe_c4.py', '../_base_/datasets/coco_instance.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 = [ dic...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...