input
stringlengths
33
5k
output
stringlengths
32
5k
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderCo...
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderCo...
import warnings from sys import platform from typing import Optional import torch import torchaudio from torchaudio.io import StreamWriter dict_format = { torch.uint8: "u8", torch.int16: "s16", torch.int32: "s32", torch.int64: "s64", torch.float32: "flt", torch.float64: "dbl", } @torchaudio....
import warnings from sys import platform from typing import Optional import torch import torchaudio from torchaudio.io import StreamWriter dict_format = { torch.uint8: "u8", torch.int16: "s16", torch.int32: "s32", torch.int64: "s64", torch.float32: "flt", torch.float64: "dbl", } def play_aud...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import tempfile from collections import OrderedDict import torch from mmengine import Config def parse_config(config_strings): temp_file = tempfile.NamedTemporaryFile() config_path = f'{temp_file.name}.py' with open(config_path, 'w') as f: ...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import tempfile from collections import OrderedDict import torch from mmcv import Config def parse_config(config_strings): temp_file = tempfile.NamedTemporaryFile() config_path = f'{temp_file.name}.py' with open(config_path, 'w') as f: ...
import pytest import torch import torchaudio class GreedyCTCDecoder(torch.nn.Module): def __init__(self, labels, blank: int = 0): super().__init__() self.blank = blank self.labels = labels def forward(self, logits: torch.Tensor) -> str: """Given a sequence logits over labels, ...
import pytest import torch import torchaudio class GreedyCTCDecoder(torch.nn.Module): def __init__(self, labels, blank: int = 0): super().__init__() self.blank = blank self.labels = labels def forward(self, logits: torch.Tensor) -> str: """Given a sequence logits over labels, ...
from dataclasses import dataclass from typing import List, Optional, Tuple import torch from torch import Tensor from torchaudio._extension import fail_if_no_align __all__ = [] @fail_if_no_align def forced_align( log_probs: Tensor, targets: Tensor, input_lengths: Optional[Tensor] = None, target_leng...
from dataclasses import dataclass from typing import List, Optional, Tuple import torch from torch import Tensor from torchaudio._extension import fail_if_no_align __all__ = [] @fail_if_no_align def forced_align( log_probs: Tensor, targets: Tensor, input_lengths: Optional[Tensor] = None, target_leng...
from docarray.typing.url.any_url import AnyUrl from docarray.typing.url.image_url import ImageUrl __all__ = ['ImageUrl', 'AnyUrl']
from .image_url import ImageUrl __all__ = ['ImageUrl']
# 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.7.1' 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.6.0' mmengi...
"""Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from collections.abc import Mapping from typing import Any, Optional from langchain_core._api import deprecated from langchain_core.callba...
"""Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from collections.abc import Mapping from typing import Any, Optional from langchain_core._api import deprecated from langchain_core.callba...
from torchaudio._internal.module_utils import dropping_support from ._alignment import forced_align as _forced_align, merge_tokens, TokenSpan from .filtering import ( allpass_biquad, band_biquad, bandpass_biquad, bandreject_biquad, bass_biquad, biquad, contrast, dcshift, deemph_biqu...
from torchaudio._internal.module_utils import dropping_support from ._alignment import forced_align as _forced_align, merge_tokens, TokenSpan from .filtering import ( allpass_biquad, band_biquad, bandpass_biquad, bandreject_biquad, bass_biquad, biquad, contrast, dcshift, deemph_biqu...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Dict import hnswlib import numpy as np from jina import Executor, requests, DocumentArray, Document from jina_commons import get_logger from jina_commons.indexers.dump import import...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Dict import hnswlib import numpy as np from jina import Executor, requests, DocumentArray, Document from jina_commons import get_logger from jina_commons.indexers.dump import import...
"""Init file of LlamaIndex.""" __version__ = "0.12.31" 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.30" 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....
# flake8: noqa """Test SQL database wrapper with schema support. Using DuckDB as SQLite does not support schemas. """ import pytest from sqlalchemy import ( Column, Integer, MetaData, Sequence, String, Table, create_engine, event, insert, schema, ) import sqlalchemy as sa fro...
# flake8: noqa """Test SQL database wrapper with schema support. Using DuckDB as SQLite does not support schemas. """ import pytest from sqlalchemy import ( Column, Integer, MetaData, Sequence, String, Table, create_engine, event, insert, schema, ) import sqlalchemy as sa fro...
from llama_index.core.base.llms.types import ( LLMMetadata, ) from llama_index.core.bridge.pydantic import Field from llama_index.llms.openai_like.base import OpenAILike class OPEA(OpenAILike): """ Adapter for a OPEA LLM. Examples: `pip install llama-index-llms-opea` ```python ...
from llama_index.core.base.llms.types import ( LLMMetadata, ) from llama_index.core.bridge.pydantic import Field from llama_index.llms.openai_like.base import OpenAILike class OPEA(OpenAILike): """Adapter for a OPEA LLM. Examples: `pip install llama-index-llms-opea` ```python fro...
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 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...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. SimCSE will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_simcse_from_file.py path/to/sentences.txt """ import gzi...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. SimCSE will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_simcse_from_file.py path/to/sentences.txt """ from torch...
# Copyright (c) OpenMMLab. All rights reserved. from .cityscapes_metric import CityScapesMetric from .coco_metric import CocoMetric from .coco_panoptic_metric import CocoPanopticMetric from .crowdhuman_metric import CrowdHumanMetric from .lvis_metric import LVISMetric from .openimages_metric import OpenImagesMetric fro...
# Copyright (c) OpenMMLab. All rights reserved. from .cityscapes_metric import CityScapesMetric from .coco_metric import CocoMetric from .coco_panoptic_metric import CocoPanopticMetric from .lvis_metric import LVISMetric from .openimages_metric import OpenImagesMetric from .voc_metric import VOCMetric __all__ = [ ...
import numpy as np from docarray import BaseDoc, DocList from docarray.typing import NdArray from pydantic import Field from jina import Executor, requests class TextDoc(BaseDoc): text: str = Field(description="The text of the document", default="") class EmbeddingResponseModel(TextDoc): embeddings: NdArra...
import numpy as np from docarray import BaseDoc, DocList from docarray.typing import NdArray from pydantic import Field from jina import Executor, requests class TextDoc(BaseDoc): text: str class EmbeddingResponseModel(BaseDoc): embeddings: NdArray = Field(description="The embedding of the texts", default=...
import os import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDocument from docarray.typing.tensor.audio.audio_ndarray import AudioNdArray from docarray.typing.tensor.audio.audio_torch_tensor import AudioTorchTensor from docarray.utils.misc import is_tf_available ...
import os import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDocument from docarray.typing.tensor.audio.audio_ndarray import AudioNdArray from docarray.typing.tensor.audio.audio_torch_tensor import AudioTorchTensor from docarray.utils.misc import is_tf_available ...
_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-1x_coco.py' # model settings model = dict( type='PointRend', roi_head=dict( type='PointRendRoIHead', mask_roi_extractor=dict( type='GenericRoIExtractor', aggregation='concat', roi_layer=dict( _d...
_base_ = '../mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain_1x_coco.py' # model settings model = dict( type='PointRend', roi_head=dict( type='PointRendRoIHead', mask_roi_extractor=dict( type='GenericRoIExtractor', aggregation='concat', roi_layer=dict( ...
import PIL.Image import pytest import torch import torchvision.transforms.v2._utils from common_utils import DEFAULT_SIZE, make_bounding_boxes, make_detection_masks, make_image from torchvision import tv_tensors from torchvision.transforms.v2._utils import has_all, has_any from torchvision.transforms.v2.functional i...
import PIL.Image import pytest import torch import torchvision.transforms.v2._utils from common_utils import DEFAULT_SIZE, make_bounding_boxes, make_detection_mask, make_image from torchvision import tv_tensors from torchvision.transforms.v2._utils import has_all, has_any from torchvision.transforms.v2.functional im...
from .cmuarctic import CMUARCTIC from .cmudict import CMUDict from .commonvoice import COMMONVOICE from .dr_vctk import DR_VCTK from .fluentcommands import FluentSpeechCommands from .gtzan import GTZAN from .iemocap import IEMOCAP from .librilight_limited import LibriLightLimited from .librimix import LibriMix from .li...
from .cmuarctic import CMUARCTIC from .cmudict import CMUDict from .commonvoice import COMMONVOICE from .dr_vctk import DR_VCTK from .fluentcommands import FluentSpeechCommands from .gtzan import GTZAN from .iemocap import IEMOCAP from .librilight_limited import LibriLightLimited from .librimix import LibriMix from .li...
"""Simple Reader for Memos.""" from typing import Dict, List from urllib.parse import urljoin from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class MemosReader(BaseReader): """ Memos reader. Reads content from an Memos. """ def __init__(self, ...
"""Simple Reader for Memos.""" from typing import Dict, List from urllib.parse import urljoin from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class MemosReader(BaseReader): """Memos reader. Reads content from an Memos. """ def __init__(self, host:...
#!/usr/bin/env python # Copyright 2023 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 # # U...
#!/usr/bin/env python # coding=utf-8 # Copyright 2023 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/LI...
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type from llama_index.core.bridge.pydantic import BaseModel, ConfigDict from .errors import WorkflowValidationError from .utils import ( is_free_function, validate_step_signature, inspect_signature, ServiceDefinition, ) if TYPE_CHECKING...
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type from llama_index.core.bridge.pydantic import BaseModel, ConfigDict from .errors import WorkflowValidationError from .utils import ( is_free_function, validate_step_signature, inspect_signature, ServiceDefinition, ) if TYPE_CHECKING...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize as deserialize from keras.src.quantizers import get as get from keras.src.quantizers import serialize as serialize from keras.src.quantizers.quantizers i...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize from keras.src.quantizers import get from keras.src.quantizers import serialize from keras.src.quantizers.quantizers import AbsMaxQuantizer from keras.sr...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # Example to use different file client # Method 1: simply set the data root and let the file I/O module # automatically infer from prefix (not support LMDB and Memcache yet) # data_root = 's3://openmmlab/d...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import ClickTool from langchain_community.tools.playwright.click import ClickToolInput # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for ra...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import ClickTool from langchain_community.tools.playwright.click import ClickToolInput # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for ra...
"""Retrieval evaluators.""" from typing import List, Optional, Tuple from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.bridge.pydantic import Field, SerializeAsAny from llama_index.core.evaluation.retrieval.base import ( BaseRetrievalEvaluator, RetrievalEvalMode, ) from llam...
"""Retrieval evaluators.""" from typing import List, Optional, Tuple from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.bridge.pydantic import Field, SerializeAsAny from llama_index.core.evaluation.retrieval.base import ( BaseRetrievalEvaluator, RetrievalEvalMode, ) from llam...
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class Translation: """`Feature` for translations with fixed languages per example. Here for compatibility with tf...
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class Translation: """`Feature` for translations with fixed languages per example. Here for compatibility with tf...
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '3.1.0' short_version = __version__ def parse_version_info(version_str): """Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is parsed...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '3.0.0' short_version = __version__ def parse_version_info(version_str): """Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is parsed...
import random import numpy as np import torch from torchvision import transforms as T from torchvision.transforms import functional as F def pad_if_smaller(img, size, fill=0): min_size = min(img.size) if min_size < size: ow, oh = img.size padh = size - oh if oh < size else 0 padw = si...
import random import numpy as np import torch from torchvision import transforms as T from torchvision.transforms import functional as F def pad_if_smaller(img, size, fill=0): min_size = min(img.size) if min_size < size: ow, oh = img.size padh = size - oh if oh < size else 0 padw = si...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.10.6' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versi...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.10.5' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versi...
from __future__ import annotations import logging from typing import Literal import torch from torch import Tensor from sentence_transformers.models.InputModule import InputModule from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(InputModule): """Implements a Bag-of-Wo...
from __future__ import annotations import json import logging import os from typing import Literal import torch from torch import Tensor, nn from .tokenizer import WhitespaceTokenizer logger = logging.getLogger(__name__) class BoW(nn.Module): """Implements a Bag-of-Words (BoW) model to derive sentence embeddi...
"""Tests for dask shared by different test modules.""" from typing import Literal import numpy as np import pandas as pd from dask import array as da from dask import dataframe as dd from distributed import Client import xgboost as xgb from xgboost.testing.updater import get_basescore def check_init_estimation_clf...
"""Tests for dask shared by different test modules.""" import numpy as np import pandas as pd from dask import array as da from dask import dataframe as dd from distributed import Client import xgboost as xgb from xgboost.testing.updater import get_basescore def check_init_estimation_clf(tree_method: str, client: C...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import MagicMock, Mock import torch from torch import nn from mmengine.hooks import OptimizerHook class TestOptimizerHook: def test_after_train_iter(self): class Model(nn.Module): def __init__(self): super(...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import MagicMock, Mock import torch from torch import nn from mmengine.hooks import OptimizerHook class TestOptimizerHook: def test_after_train_iter(self): class Model(nn.Module): def __init__(self): super(...
from __future__ import annotations # TODO: Consider renaming all evaluators to CrossEncoder..., e.g. CrossEncoderNanoBEIREvaluator, CrossEncoderClassificationEvaluator, etc. from .CEBinaryAccuracyEvaluator import CEBinaryAccuracyEvaluator from .CEBinaryClassificationEvaluator import CEBinaryClassificationEvaluator fro...
from __future__ import annotations from .CEBinaryAccuracyEvaluator import CEBinaryAccuracyEvaluator from .CEBinaryClassificationEvaluator import CEBinaryClassificationEvaluator from .CECorrelationEvaluator import CECorrelationEvaluator from .CEF1Evaluator import CEF1Evaluator from .CERerankingEvaluator import CERerank...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class VFNet(SingleStageDetector): """Implementation of `VarifocalNet (VFNet).<https://arxiv.org/abs/2008.13367>`_""" def __init__(self, ...
from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class VFNet(SingleStageDetector): """Implementation of `VarifocalNet (VFNet).<https://arxiv.org/abs/2008.13367>`_""" def __init__(self, backbone, neck, ...
"""LLM Compiler agent pack.""" from typing import Any, Dict, List, Optional from llama_index.core.agent import AgentRunner from llama_index.core.callbacks import CallbackManager from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.llms.llm import LLM from llama_index.core.tools.types impor...
"""LLM Compiler agent pack.""" from typing import Any, Dict, List, Optional from llama_index.core.agent import AgentRunner from llama_index.core.callbacks import CallbackManager from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.llms.llm import LLM from llama_index.core.tools.types impor...
"""Test PremChat model""" from typing import cast import pytest from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage from pydantic import SecretStr from pytest import CaptureFixture from langchain_community.chat_models import ChatPremAI from langchain_community.chat_models.premai i...
"""Test PremChat model""" from typing import cast import pytest from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage from pydantic import SecretStr from pytest import CaptureFixture from langchain_community.chat_models import ChatPremAI from langchain_community.chat_models.premai i...
from __future__ import annotations try: from typing import Self except ImportError: from typing_extensions import Self import torch from torch import Tensor, nn from sentence_transformers.models.Module import Module class WeightedLayerPooling(Module): """Token embeddings are weighted mean of their diff...
from __future__ import annotations import json import os 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 Tensor, nn class WeightedLayerPooling(nn.Module): """Token embeddings are weighted mean of...
import logging import re from typing import Any import uvicorn.config from colorama import Fore def remove_color_codes(s: str) -> str: return re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", s) def fmt_kwargs(kwargs: dict) -> str: return ", ".join(f"{n}={repr(v)}" for n, v in kwargs.items()) def prin...
import logging import re from typing import Any import uvicorn.config from colorama import Fore def remove_color_codes(s: str) -> str: return re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", s) def fmt_kwargs(kwargs: dict) -> str: return ", ".join(f"{n}={repr(v)}" for n, v in kwargs.items()) def print...
import torch from torchaudio_unittest.common_utils import PytorchTestCase, skipIfNoCuda from .tacotron2_loss_impl import Tacotron2LossGradcheckTests, Tacotron2LossShapeTests, Tacotron2LossTorchscriptTests @skipIfNoCuda class TestTacotron2LossShapeFloat32CUDA(PytorchTestCase, Tacotron2LossShapeTests): dtype = tor...
import torch from torchaudio_unittest.common_utils import PytorchTestCase, skipIfNoCuda from .tacotron2_loss_impl import ( Tacotron2LossGradcheckTests, Tacotron2LossShapeTests, Tacotron2LossTorchscriptTests, ) @skipIfNoCuda class TestTacotron2LossShapeFloat32CUDA(PytorchTestCase, Tacotron2LossShapeTests)...
_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( plugins=[ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='1111', ...
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( plugins=[ dict( cfg=dict( type='GeneralizedAttention', spatial_range=-1, num_heads=8, attention_type='1111', ...
from ._dsp import oscillator_bank from .functional import add_noise, barkscale_fbanks, convolve, fftconvolve __all__ = [ "add_noise", "barkscale_fbanks", "convolve", "fftconvolve", "oscillator_bank", ]
from .functional import add_noise, barkscale_fbanks, convolve, fftconvolve __all__ = ["add_noise", "barkscale_fbanks", "convolve", "fftconvolve"]
_base_ = './mask-rcnn_x101-32x4d_fpn_gn-ws-all_2x_coco.py' # learning policy max_epochs = 24 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, ...
_base_ = './mask_rcnn_x101_32x4d_fpn_gn_ws-all_2x_coco.py' # learning policy max_epochs = 24 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, ...
from __future__ import annotations from collections.abc import Iterable from torch import Tensor from sentence_transformers import util from sentence_transformers.losses.CoSENTLoss import CoSENTLoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseCoSENTLoss(CoSENTLoss): ...
from __future__ import annotations from collections.abc import Iterable from torch import Tensor from sentence_transformers import util from sentence_transformers.losses.CoSENTLoss import CoSENTLoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseCoSENTLoss(CoSENTLoss): ...
import warnings from abc import ABC from typing import Any, Optional from langchain_core._api import deprecated from langchain_core.chat_history import ( BaseChatMessageHistory, InMemoryChatMessageHistory, ) from langchain_core.memory import BaseMemory from langchain_core.messages import AIMessage, HumanMessag...
import warnings from abc import ABC from typing import Any, Dict, Optional, Tuple from langchain_core._api import deprecated from langchain_core.chat_history import ( BaseChatMessageHistory, InMemoryChatMessageHistory, ) from langchain_core.memory import BaseMemory from langchain_core.messages import AIMessage...
# 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 ...
import numpy as np import pytest import torch from docarray import BaseDocument from docarray.base_document import AnyDocument from docarray.typing import ( AnyEmbedding, AnyUrl, ImageUrl, Mesh3DUrl, NdArray, PointCloud3DUrl, TextUrl, TorchTensor, ) @pytest.mark.proto def test_proto_a...
import numpy as np import torch from docarray import BaseDocument from docarray.base_document import AnyDocument from docarray.typing import ( AnyEmbedding, AnyUrl, ImageUrl, Mesh3DUrl, NdArray, PointCloud3DUrl, TextUrl, TorchTensor, ) def test_proto_all_types(): class Mymmdoc(Bas...
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 Optional from docarray.base_document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import AnyEmbedding class Text(BaseDocument): """ Document for handling text. It can contain a TextUrl (`Text.url`), a str (`Text.text`), and an AnyEmb...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.ops import MaskedConv2d from ..builder import HEADS from .guided_anchor_head import FeatureAdaption, GuidedAnchorHead @HEADS.register_module() class GARetinaHead(GuidedAnchorHead): """Guided-Anchor-bas...
import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.ops import MaskedConv2d from ..builder import HEADS from .guided_anchor_head import FeatureAdaption, GuidedAnchorHead @HEADS.register_module() class GARetinaHead(GuidedAnchorHead): """Guided-Anchor-based RetinaNet head.""" def __init__(self, ...
"""Init file of LlamaIndex.""" __version__ = "0.12.11" 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.10" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/'...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='CenterNet', backbone=dict( type='ResNet', depth=18, norm_eval=False, norm_cfg=dict(type='BN'), init_cfg=dict(type='Pretra...
import PIL.Image import pytest import torch import torchvision.transforms.v2.utils from common_utils import DEFAULT_SIZE, make_bounding_box, make_detection_mask, make_image from torchvision import datapoints from torchvision.transforms.v2.functional import to_pil_image from torchvision.transforms.v2.utils import has...
import PIL.Image import pytest import torch import torchvision.transforms.v2.utils from common_utils import DEFAULT_SIZE, make_bounding_box, make_detection_mask, make_image from torchvision import datapoints from torchvision.transforms.v2.functional import to_image_pil from torchvision.transforms.v2.utils import has...
"""Hubspot reader.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class HubspotReader(BaseReader): """ Hubspot reader. Reads data from a Hubspot account. Args: access_token(str): Hubspot API key. """ def __i...
"""Hubspot reader.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class HubspotReader(BaseReader): """Hubspot reader. Reads data from a Hubspot account. Args: access_token(str): Hubspot API key. """ def __init__(...
"""LangChain **Runnable** and the **LangChain Expression Language (LCEL)**. The LangChain Expression Language (LCEL) offers a declarative method to build production-grade programs that harness the power of LLMs. Programs created using LCEL and LangChain Runnables inherently support synchronous, asynchronous, batch, a...
"""LangChain **Runnable** and the **LangChain Expression Language (LCEL)**. The LangChain Expression Language (LCEL) offers a declarative method to build production-grade programs that harness the power of LLMs. Programs created using LCEL and LangChain Runnables inherently support synchronous, asynchronous, batch, a...
""" 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...
_base_ = '../grounding_dino_swin-t_pretrain_obj365.py' data_root = 'data/cityscapes/' class_name = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') palette = [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)...
_base_ = '../grounding_dino_swin-t_pretrain_obj365.py' data_root = 'data/cityscapes/' class_name = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') palette = [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)...
checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable custom_hooks = [dict(type='NumClassCheckHook')] dist_params = dict(backend='nccl') log_level = 'INFO' load_from = No...
checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable custom_hooks = [dict(type='NumClassCheckHook')] dist_params = dict(backend='nccl') log_level = 'INFO' load_from = No...
_base_ = './yolox_s_8xb8-300e_coco.py' # model settings model = dict( data_preprocessor=dict(batch_augments=[ dict( type='BatchSyncRandomResize', random_size_range=(320, 640), size_divisor=32, interval=10) ]), backbone=dict(deepen_factor=0.33, widen_f...
_base_ = './yolox_s_8xb8-300e_coco.py' # model settings model = dict( data_preprocessor=dict(batch_augments=[ dict( type='BatchSyncRandomResize', random_size_range=(320, 640), size_divisor=32, interval=10) ]), backbone=dict(deepen_factor=0.33, widen_f...
import logging from datasets import load_dataset from sentence_transformers.sparse_encoder import ( SparseEncoder, SparseTripletEvaluator, ) logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") # Load triplets from the...
import logging from datasets import load_dataset from sentence_transformers.sparse_encoder import ( MLMTransformer, SparseEncoder, SparseTripletEvaluator, SpladePooling, ) logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) # Initialize the SPLADE...
""" 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, Literal from pydantic import SecretStr from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import ( APIKeyCredentials, CredentialsField, CredentialsMetaInput, SchemaField, ) from backend.integrations.providers import ProviderNam...
from typing import Any, Literal from pydantic import SecretStr from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import ( APIKeyCredentials, CredentialsField, CredentialsMetaInput, SchemaField, ) from backend.integrations.providers import ProviderNam...
# Owner(s): ["module: inductor"] import torch from torch._inductor import config, metrics from torch._inductor.test_case import run_tests, TestCase from torch._inductor.utils import collect_defined_kernels from torch._inductor.wrapper_benchmark import get_kernel_category_by_source_code from torch.testing._internal.comm...
# Owner(s): ["module: inductor"] import torch from torch._inductor import config, metrics from torch._inductor.test_case import run_tests, TestCase from torch._inductor.utils import collect_defined_kernels from torch._inductor.wrapper_benchmark import get_kernel_category_by_source_code from torch.testing._internal.comm...
from enum import Enum # --8<-- [start:ProviderName] class ProviderName(str, Enum): ANTHROPIC = "anthropic" DISCORD = "discord" D_ID = "d_id" E2B = "e2b" EXA = "exa" FAL = "fal" GITHUB = "github" GOOGLE = "google" GOOGLE_MAPS = "google_maps" GROQ = "groq" HUBSPOT = "hubspot"...
from enum import Enum class ProviderName(str, Enum): GITHUB = "github" GOOGLE = "google" NOTION = "notion"
_base_ = './yolov3_d53_8xb8-ms-608-273e_coco.py' # fp16 settings optim_wrapper = dict(type='AmpOptimWrapper', loss_scale='dynamic')
_base_ = './yolov3_d53_mstrain-608_273e_coco.py' # fp16 settings optim_wrapper = dict(type='AmpOptimWrapper', loss_scale='dynamic')
import random import pytest from pathlib import Path from typing import Dict, Tuple, Callable import opentelemetry.sdk.metrics.export import opentelemetry.sdk.metrics.view from opentelemetry.sdk.metrics.export import ( AggregationTemporality, MetricExporter, MetricExportResult, MetricsData, Periodic...
import random import pytest from pathlib import Path from typing import Dict, Tuple, Callable import opentelemetry.sdk.metrics.export import opentelemetry.sdk.metrics.view from opentelemetry.sdk.metrics.export import ( AggregationTemporality, MetricExporter, MetricExportResult, MetricsData, ) class Di...
# Copyright (c) OpenMMLab. All rights reserved. from .builder import DATASETS, PIPELINES, build_dataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .dataset_wrappers import MultiImageMixDataset from .deepfashion import DeepFashionDataset fr...
# Copyright (c) OpenMMLab. All rights reserved. from .builder import DATASETS, PIPELINES, build_dataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .dataset_wrappers import MultiImageMixDataset from .deepfashion import DeepFashionDataset fr...
"""Linkup tool spec.""" from llama_index.core.tools.tool_spec.base import BaseToolSpec class LinkupToolSpec(BaseToolSpec): """Linkup tool spec.""" spec_functions = [ "search", ] def __init__(self, api_key: str, depth: str, output_type: str) -> None: """Initialize with parameters."""...
"""Linkup tool spec.""" from llama_index.core.tools.tool_spec.base import BaseToolSpec class LinkupToolSpec(BaseToolSpec): """Linkup tool spec.""" spec_functions = [ "search", ] def __init__(self, api_key: str, depth: str, output_type: str) -> None: """Initialize with parameters."""...
"""LLama Kibela Reader.""" from typing import Dict, Generic, List, Optional, TypeVar from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.core.bridge.pydantic import BaseModel NodeType = TypeVar("NodeType") class Edge(BaseModel, Generic[NodeType]): ...
"""LLama Kibela Reader.""" from typing import Dict, Generic, List, Optional, TypeVar from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.core.bridge.pydantic import BaseModel NodeType = TypeVar("NodeType") class Edge(BaseModel, Generic[NodeType]): ...
# 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...
# Copyright (c) OpenMMLab. All rights reserved. from .det_inferencer import DetInferencer from .inference import (async_inference_detector, inference_detector, init_detector) __all__ = [ 'init_detector', 'async_inference_detector', 'inference_detector', 'DetInferencer' ]
# Copyright (c) OpenMMLab. All rights reserved. from .inference import (async_inference_detector, inference_detector, init_detector) __all__ = [ 'init_detector', 'async_inference_detector', 'inference_detector', ]
import pytest from llama_index.voice_agents.openai.types import ( ConversationDeltaEvent, ConversationDoneEvent, ConversationSession, ConversationSessionUpdate, ) @pytest.fixture() def session_json() -> dict: return { "modalities": ["text", "audio"], "instructions": ...
import pytest from llama_index.voice_agents.openai.types import ( ConversationDeltaEvent, ConversationDoneEvent, ConversationSession, ConversationSessionUpdate, ) @pytest.fixture() def session_json() -> dict: return { "modalities": ["text", "audio"], "instructions": ...
_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', backend_args={{_base_.backend_args}}), dict(type='LoadAnnotations...
_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_ = './ms-rcnn_x101-64x4d_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_x101_64x4d_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', ...
from pathlib import Path from typing import Dict, 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 _URL = "https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip" _...
from pathlib import Path from typing import Dict, 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 _URL = "https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip" _...
_base_ = './fovea_r50_fpn_4xb4-1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './fovea_r50_fpn_4x4_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
from typing import Dict, List import numpy as np import pytest from docarray import DocList from docarray.base_doc import AnyDoc, BaseDoc from docarray.typing import NdArray def test_any_doc(): class InnerDocument(BaseDoc): text: str tensor: NdArray class CustomDoc(BaseDoc): inner: ...
from typing import Dict, List import numpy as np import pytest from orjson import orjson from docarray import DocList from docarray.base_doc import AnyDoc, BaseDoc from docarray.base_doc.io.json import orjson_dumps_and_decode from docarray.typing import NdArray from docarray.typing.tensor.abstract_tensor import Abstr...
_base_ = [ '../_base_/models/cascade-mask-rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvisio...
_base_ = [ '../_base_/models/cascade-mask-rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvisio...
import importlib.util import warnings from functools import wraps from typing import Optional def is_module_available(*modules: str) -> bool: r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. It avoids thir...
import importlib.util import warnings from functools import wraps from typing import Optional import torch def is_module_available(*modules: str) -> bool: r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. ...
try: from llama_index.readers.imdb_review.scraper import main_scraper except ImportError: from scraper import main_scraper from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class IMDBReviews(BaseReader): def __init__( self, ...
try: from llama_index.readers.imdb_review.scraper import main_scraper except ImportError: from scraper import main_scraper from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class IMDBReviews(BaseReader): def __init__( self, ...
from __future__ import annotations from collections import Counter import pytest from sentence_transformers.sampler import GroupByLabelBatchSampler from sentence_transformers.util import is_datasets_available if is_datasets_available(): from datasets import Dataset else: pytest.skip( reason='Sentenc...
from __future__ import annotations from collections import Counter import pytest from datasets import Dataset from sentence_transformers.sampler import GroupByLabelBatchSampler @pytest.fixture def dummy_dataset(): """ Dummy dataset for testing purposes. The dataset looks as follows: { "data": ...
from typing import Any, Dict, Iterator import torch from ..utils import _log_api_usage_once try: from ._load_gpu_decoder import _HAS_GPU_VIDEO_DECODER except ModuleNotFoundError: _HAS_GPU_VIDEO_DECODER = False from ._video_opt import ( _HAS_CPU_VIDEO_DECODER, _HAS_VIDEO_OPT, _probe_video_from_fi...
from typing import Any, Dict, Iterator import torch from ..utils import _log_api_usage_once try: from ._load_gpu_decoder import _HAS_GPU_VIDEO_DECODER except ModuleNotFoundError: _HAS_GPU_VIDEO_DECODER = False from ._video_opt import ( _HAS_CPU_VIDEO_DECODER, _HAS_VIDEO_OPT, _probe_video_from_fi...
"""Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain_core.embeddings import Embeddings from langchain_community.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, ) class DocArrayInMemorySear...
"""Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain_core.embeddings import Embeddings from langchain_community.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, ) class DocArrayInMemorySear...
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
""" This example trains a SparseEncoder for the Natural Questions (NQ) dataset. The training script fine-tunes a SparseEncoder using the Splade loss function for retrieval. It loads a subset of the Natural Questions dataset, splits it into training and evaluation subsets, and trains the model as a retriever. After trai...
""" This example trains a SparseEncoder for the Natural Questions (NQ) dataset. The training script fine-tunes a SparseEncoder using the Splade loss function for retrieval. It loads a subset of the Natural Questions dataset, splits it into training and evaluation subsets, and trains the model as a retriever. After trai...
import json from enum import Enum from typing import Any from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.request import requests class HttpMethod(Enum): GET = "GET" POST = "POST" PUT = "PUT" DELETE = "DELETE" ...
import json from enum import Enum import requests from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField class HttpMethod(Enum): GET = "GET" POST = "POST" PUT = "PUT" DELETE = "DELETE" PATCH = "PATCH" OPTIONS = "OPTIONS" H...
_base_ = './mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py' train_cfg = dict(max_epochs=36) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=24, by_epoch=True, mil...
_base_ = './mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py' train_cfg = dict(max_epochs=36) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=24, by_epoch=True, ...
"""Base classes for chain routing.""" from __future__ import annotations from abc import ABC from collections.abc import Mapping from typing import Any, NamedTuple, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, Callbacks, ) from pydantic impo...
"""Base classes for chain routing.""" from __future__ import annotations from abc import ABC from typing import Any, Dict, List, Mapping, NamedTuple, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, Callbacks, ) from pydantic import ConfigDict ...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule, auto_fp16 from mmdet.models.builder import HEADS @HEADS.register_module() class FeatureRelayHead(BaseModule): """Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_. Args: in_...
import torch.nn as nn from mmcv.runner import BaseModule, auto_fp16 from mmdet.models.builder import HEADS @HEADS.register_module() class FeatureRelayHead(BaseModule): """Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_. Args: in_channels (int, optional): number of input channe...
from typing import Union import numpy as np Matrix = Union[list[list[float]], list[np.ndarray], np.ndarray] def maximal_marginal_relevance( query_embedding: np.ndarray, embedding_list: list, lambda_mult: float = 0.5, k: int = 4, ) -> list[int]: """Calculate maximal marginal relevance.""" if ...
from typing import List, Union import numpy as np Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray] def maximal_marginal_relevance( query_embedding: np.ndarray, embedding_list: list, lambda_mult: float = 0.5, k: int = 4, ) -> List[int]: """Calculate maximal marginal relevance.""" ...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from mmengine.config import Config from mmdet.models.seg_heads.panoptic_fusion_heads import MaskFormerFusionHead from mmdet.structures import DetDataSample class TestMaskFormerFusionHead(unittest.TestCase): def test_loss(self): ...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from mmengine.config import Config from mmdet.data_elements import DetDataSample from mmdet.models.seg_heads.panoptic_fusion_heads import MaskFormerFusionHead class TestMaskFormerFusionHead(unittest.TestCase): def test_loss(self): ...
import torch from parameterized import parameterized from torchaudio.prototype.models import squim_objective_base, squim_subjective_base from torchaudio_unittest.common_utils import skipIfNoCuda, torch_script, TorchaudioTestCase class TestSquimObjective(TorchaudioTestCase): def _smoke_test_objective(self, model, ...
import torch from parameterized import parameterized from torchaudio.prototype.models import squim_objective_base from torchaudio_unittest.common_utils import skipIfNoCuda, torch_script, TorchaudioTestCase class TestSQUIM(TorchaudioTestCase): def _smoke_test_objective(self, model, device, dtype): model = ...
from __future__ import annotations from .CrossEncoder import CrossEncoder from .model_card import CrossEncoderModelCardData from .trainer import CrossEncoderTrainer from .training_args import CrossEncoderTrainingArguments __all__ = [ "CrossEncoder", "CrossEncoderTrainer", "CrossEncoderTrainingArguments", ...
from __future__ import annotations from .CrossEncoder import CrossEncoder __all__ = ["CrossEncoder"]
_base_ = '../mask_rcnn/mask-rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict(plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True, True), position='after_conv3') ]))
_base_ = '../mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict(plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 16), stages=(False, True, True, True), position='after_conv3') ]))
from typing import ( Union, TYPE_CHECKING, TypeVar, Sequence, Optional, List, Dict, Generator, Iterable, Tuple, ForwardRef, ) if TYPE_CHECKING: # pragma: no cover import scipy.sparse import tensorflow import torch import numpy as np from PIL.Image import...
from typing import ( Union, TYPE_CHECKING, TypeVar, Sequence, Optional, List, Dict, Generator, Iterable, Tuple, ForwardRef, ) if TYPE_CHECKING: import scipy.sparse import tensorflow import torch import numpy as np from PIL.Image import Image as PILImage ...
import tracemalloc from functools import wraps from docarray import DocList from docarray.documents import TextDoc def get_test_da(n: int): return DocList[TextDoc](gen_text_docs(n)) def gen_text_docs(n: int): for i in range(n): yield TextDoc(text=f'text {i}') def profile_memory(func): """Deco...
import tracemalloc from functools import wraps from docarray import DocArray from docarray.documents import TextDoc def get_test_da(n: int): return DocArray[TextDoc](gen_text_docs(n)) def gen_text_docs(n: int): for i in range(n): yield TextDoc(text=f'text {i}') def profile_memory(func): """De...
"""Init composability.""" from llama_index.core.composability.base import ComposableGraph from llama_index.core.composability.joint_qa_summary import ( QASummaryQueryEngineBuilder, ) __all__ = ["ComposableGraph", "QASummaryQueryEngineBuilder"]
"""Init composability.""" from llama_index.core.composability.base import ComposableGraph from llama_index.core.composability.joint_qa_summary import ( QASummaryQueryEngineBuilder, ) __all__ = ["ComposableGraph", "QASummaryQueryEngineBuilder"]
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule, is_norm from mmengine.model import caffe2_xavier_init, constant_init, normal_init from torch.nn import BatchNorm2d from mmdet.registry import MODELS class Bottleneck(nn.Module): """Bottleneck block for DilatedE...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule, is_norm from mmengine.model.utils import caffe2_xavier_init, constant_init, normal_init from torch.nn import BatchNorm2d from mmdet.registry import MODELS class Bottleneck(nn.Module): """Bottleneck block for Di...