input
stringlengths
33
5k
output
stringlengths
32
5k
# 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 Dict, List, Optional, Set, Tuple, Union import pytest from docarray.typing import NdArray, TorchTensor from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.utils._internal._typing import ( is_tensor_union, is_type_tensor, safe_issubclass, ) from docarray.utils...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import logging import os import os.path as osp from mmengine.config import Config, DictAction from mmengine.logging import print_log from mmengine.registry import RUNNERS from mmengine.runner import Runner def parse_args(): parser = argparse.Argumen...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import logging import os import os.path as osp from mmengine.config import Config, DictAction from mmengine.logging import print_log from mmengine.registry import RUNNERS from mmengine.runner import Runner from mmdet.utils import register_all_modules d...
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# model settings preprocess_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False, pad_size_divisor=32) norm_cfg = dict(type='BN', requires_grad=False) model = dict( preprocess_cfg=preprocess_cfg, type='FasterRCNN', backbone=dict( type='ResNet', dept...
# model settings norm_cfg = dict(type='BN', requires_grad=False) model = dict( type='FasterRCNN', backbone=dict( type='ResNet', depth=50, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=(2, ), frozen_stages=1, norm_cfg=norm_cfg, ...
import os from pathlib import Path from typing import List, Tuple, Union import torch from torch.utils.data import Dataset from torchaudio.datasets.utils import _load_waveform _TASKS_TO_MIXTURE = { "sep_clean": "mix_clean", "enh_single": "mix_single", "enh_both": "mix_both", "sep_noisy": "mix_both", }...
from pathlib import Path from typing import List, Tuple, Union import torch import torchaudio from torch.utils.data import Dataset SampleType = Tuple[int, torch.Tensor, List[torch.Tensor]] _TASKS_TO_MIXTURE = { "sep_clean": "mix_clean", "enh_single": "mix_single", "enh_both": "mix_both", "sep_noisy":...
# coding: utf-8 """Helper script for checking versions in the dynamic symbol table. This script checks that LightGBM library is linked to the appropriate symbol versions. """ import re import sys from pathlib import Path def check_dependicies(objdump_string: str) -> None: """Check the dynamic symbol versions. ...
# coding: utf-8 """Helper script for checking versions in the dynamic symbol table. This script checks that LightGBM library is linked to the appropriate symbol versions. """ import re import sys from pathlib import Path def check_dependicies(objdump_string: str) -> None: """Check the dynamic symbol versions. ...
import logging import pathlib from postmarker.core import PostmarkClient from postmarker.models.emails import EmailManager from prisma.enums import NotificationType from pydantic import BaseModel from backend.data.notifications import ( NotificationEventModel, NotificationTypeOverride, T_co, ) from backen...
import logging import pathlib from postmarker.core import PostmarkClient from postmarker.models.emails import EmailManager from prisma.enums import NotificationType from pydantic import BaseModel from backend.data.notifications import ( NotificationEventModel, NotificationTypeOverride, T_co, ) from backen...
import collections import itertools import numpy as np from absl.testing import parameterized from torch.utils.data import Dataset as TorchDataset from keras.src.testing import test_case from keras.src.testing.test_utils import named_product from keras.src.utils.dataset_utils import split_dataset from keras.src.utils...
import itertools import numpy as np from absl.testing import parameterized from torch.utils.data import Dataset as TorchDataset from keras.src.testing import test_case from keras.src.testing.test_utils import named_product from keras.src.utils.dataset_utils import split_dataset from keras.src.utils.module_utils impor...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict(pad_size_divisor=64), neck=dict( type='FPN_CARAFE', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5, start_level=0, end_level=-1, norm_cfg=None, ...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( neck=dict( type='FPN_CARAFE', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5, start_level=0, end_level=-1, norm_cfg=None, act_cfg=None, order=('conv', 'norm', ...
from textwrap import dedent from types import SimpleNamespace from unittest.mock import patch from urllib.parse import quote import pytest from huggingface_hub import CommitOperationAdd, CommitOperationDelete import datasets from datasets.config import METADATA_CONFIGS_FIELD from datasets.hub import delete_from_hub f...
from textwrap import dedent from types import SimpleNamespace from unittest.mock import patch from urllib.parse import quote import pytest from huggingface_hub import CommitOperationAdd, CommitOperationDelete import datasets from datasets.config import METADATA_CONFIGS_FIELD from datasets.hub import delete_from_hub f...
"""Example of parametrized tests for analytics endpoints.""" import json from unittest.mock import AsyncMock, Mock import fastapi import fastapi.testclient import pytest import pytest_mock from pytest_snapshot.plugin import Snapshot import backend.server.routers.analytics as analytics_routes from backend.server.conf...
"""Example of parametrized tests for analytics endpoints.""" import json from unittest.mock import AsyncMock, Mock import fastapi import fastapi.testclient import pytest import pytest_mock from pytest_snapshot.plugin import Snapshot import backend.server.routers.analytics as analytics_routes from backend.server.conf...
from __future__ import annotations from typing import Any, cast, List, Optional, Tuple, Union import torch from torchvision.transforms import InterpolationMode from ._feature import _Feature, FillTypeJIT class Mask(_Feature): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: return tensor....
from __future__ import annotations from typing import Any, cast, List, Optional, Tuple, Union import torch from torchvision.transforms import InterpolationMode from ._feature import _Feature, FillTypeJIT class Mask(_Feature): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: return tensor....
import warnings from typing import Any, Dict, List, Union import numpy as np import PIL.Image import torch from torchvision.prototype import features from torchvision.prototype.transforms import Transform from torchvision.transforms import functional as _F from typing_extensions import Literal from ._transform impor...
import warnings from typing import Any, Dict, Union import numpy as np import PIL.Image import torch from torchvision.prototype import features from torchvision.prototype.transforms import Transform from torchvision.transforms import functional as _F from typing_extensions import Literal from ._transform import _Ran...
# Copyright (c) OpenMMLab. All rights reserved. import importlib import os.path as osp from mmengine.config import Config from mmengine.config.utils import (_get_cfg_metainfo, _get_external_cfg_base_path, _get_package_and_cfg_path) from mmengine.reg...
# Copyright (c) OpenMMLab. All rights reserved. import importlib import os.path as osp from mmengine.config import Config from mmengine.config.utils import (_get_cfg_metainfo, _get_external_cfg_base_path, _get_package_and_cfg_path) from mmengine.reg...
""" This scripts demonstrates how to train a Sparse Encoder model for Information Retrieval. As dataset, we use sentence-transformers/msmarco-bm25, where we have triplets versions of MSMARCO mined thanks to BM25. As loss function, we use MultipleNegativesRankingLoss in the SpladeLoss. """ import logging import trac...
""" This scripts demonstrates how to train a Sparse Encoder model for Information Retrieval. As dataset, we use sentence-transformers/msmarco-bm25, where we have triplets versions of MSMARCO mined thanks to BM25. As loss function, we use MultipleNegativesRankingLoss in the SpladeLoss. """ import logging import trac...
from functools import partial from huggingface_hub import hf_hub_url from huggingface_hub.utils import get_session, hf_raise_for_status hf_dataset_url = partial(hf_hub_url, repo_type="dataset") def check_auth(hf_api, repo_id, token=None): headers = hf_api._build_hf_headers(token=token) path = f"{hf_api.end...
from functools import partial from huggingface_hub import hf_hub_url hf_dataset_url = partial(hf_hub_url, repo_type="dataset")
import numpy as np import pytest from keras.src import backend from keras.src import layers from keras.src.testing import test_case class SpatialDropoutTest(test_case.TestCase): @pytest.mark.requires_trainable_backend def test_spatial_dropout_1d(self): self.run_layer_test( layers.SpatialD...
import numpy as np import pytest from keras.src import backend from keras.src import layers from keras.src.testing import test_case class SpatialDropoutTest(test_case.TestCase): @pytest.mark.requires_trainable_backend def test_spatial_dropout_1d(self): self.run_layer_test( layers.SpatialD...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' image_size = (1024, 1024) file_client_args = dict(backend='disk') # comment out the code below to use different file client # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # ...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) image_size = (1024, 1024) file_client_args = dict(backend='disk') # comment out the code below to use diffe...
from ._conformer_wav2vec2 import ( conformer_wav2vec2_base, conformer_wav2vec2_model, conformer_wav2vec2_pretrain_base, conformer_wav2vec2_pretrain_large, conformer_wav2vec2_pretrain_model, ConformerWav2Vec2PretrainModel, ) from ._emformer_hubert import emformer_hubert_base, emformer_hubert_mode...
from ._conformer_wav2vec2 import ( conformer_wav2vec2_base, conformer_wav2vec2_model, conformer_wav2vec2_pretrain_base, conformer_wav2vec2_pretrain_large, conformer_wav2vec2_pretrain_model, ConformerWav2Vec2PretrainModel, ) from ._emformer_hubert import emformer_hubert_base, emformer_hubert_mode...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from mmengine.structures import InstanceData from mmengine.testing import assert_allclose from mmdet.models.task_modules.assigners import PointAssigner class TestPointAssigner(unittest.TestCase): def test_point_assigner(self): ...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch from mmengine.data import InstanceData from mmengine.testing import assert_allclose from mmdet.models.task_modules.assigners import PointAssigner class TestPointAssigner(unittest.TestCase): def test_point_assigner(self): assig...
# coding: utf-8 import pytest import lightgbm as lgb from .utils import SERIALIZERS, pickle_and_unpickle_object def reset_feature_fraction(boosting_round): return 0.6 if boosting_round < 15 else 0.8 @pytest.mark.parametrize('serializer', SERIALIZERS) def test_early_stopping_callback_is_picklable(serializer): ...
# coding: utf-8 import pytest import lightgbm as lgb from .utils import SERIALIZERS, pickle_and_unpickle_object, pickle_obj, unpickle_obj def reset_feature_fraction(boosting_round): return 0.6 if boosting_round < 15 else 0.8 @pytest.mark.parametrize('serializer', SERIALIZERS) def test_early_stopping_callback_...
"""Loads rich text files.""" from pathlib import Path from typing import Any, List, Union from langchain_community.document_loaders.unstructured import ( UnstructuredFileLoader, validate_unstructured_version, ) class UnstructuredRTFLoader(UnstructuredFileLoader): """Load `RTF` files using `Unstructured`...
"""Loads rich text files.""" from pathlib import Path from typing import Any, List, Union from langchain_community.document_loaders.unstructured import ( UnstructuredFileLoader, validate_unstructured_version, ) class UnstructuredRTFLoader(UnstructuredFileLoader): """Load `RTF` files using `Unstructured`...
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS class ConvoOutputParser(AgentOutputPar...
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS class ConvoOutputParser(AgentOutputPar...
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_VIDEO_OPT, _probe_video_from_file, _probe_video_from_me...
from typing import Any, Dict, Iterator import torch from ..utils import _log_api_usage_once from ._video_opt import ( _HAS_VIDEO_OPT, _probe_video_from_file, _probe_video_from_memory, _read_video_from_file, _read_video_from_memory, _read_video_timestamps_from_file, _read_video_timestamps_...
import abc import argparse import functools import inspect from typing import TYPE_CHECKING, Callable, Optional from jina.helper import convert_tuple_to_list from jina.jaml import JAMLCompatible from jina.logging.logger import JinaLogger from jina.serve.helper import store_init_kwargs, wrap_func from jina.serve.stream...
import abc import argparse from typing import TYPE_CHECKING, Optional from jina.jaml import JAMLCompatible from jina.logging.logger import JinaLogger from jina.serve.streamer import GatewayStreamer __all__ = ['BaseGateway'] if TYPE_CHECKING: from prometheus_client import CollectorRegistry class BaseGateway(JAM...
"""Tool for the Serper.dev Google Search API.""" from typing import Optional from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.utilities.google_serper import GoogleS...
"""Tool for the Serper.dev Google Search API.""" from typing import Optional from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.utilities.google_serper import GoogleS...
from docarray.predefined_document.audio import Audio from docarray.predefined_document.image import Image from docarray.predefined_document.mesh import Mesh3D from docarray.predefined_document.point_cloud import PointCloud3D from docarray.predefined_document.text import Text __all__ = ['Text', 'Image', 'Audio', 'Mesh3...
from docarray.predefined_document.image import Image from docarray.predefined_document.mesh import Mesh3D from docarray.predefined_document.point_cloud import PointCloud3D from docarray.predefined_document.text import Text __all__ = ['Text', 'Image', 'Mesh3D', 'PointCloud3D']
""" Integration Tests of llama-index-vector-stores-mongodb with MongoDB Atlas Vector Datastore and OPENAI Embedding model. As described in docs/providers/mongodb/setup.md, to run this, one must have a running MongoDB Atlas Cluster, and provide a valid OPENAI_API_KEY. """ import os from time import sleep from typing i...
"""Integration Tests of llama-index-vector-stores-mongodb with MongoDB Atlas Vector Datastore and OPENAI Embedding model. As described in docs/providers/mongodb/setup.md, to run this, one must have a running MongoDB Atlas Cluster, and provide a valid OPENAI_API_KEY. """ import os from time import sleep from typing im...
# Copyright (c) OpenMMLab. All rights reserved. import tempfile from unittest import TestCase from unittest.mock import Mock import torch import torch.nn as nn from mmengine.evaluator import Evaluator from mmengine.model import BaseModel from mmengine.optim import OptimWrapper from mmengine.runner import Runner from t...
# Copyright (c) OpenMMLab. All rights reserved. import tempfile from unittest import TestCase from unittest.mock import Mock import torch import torch.nn as nn from mmengine.evaluator import Evaluator from mmengine.model import BaseModel from mmengine.optim import OptimWrapper from mmengine.runner import Runner from t...
import json import os import requests import sys import time from typing import Dict, List, Tuple CHECK_INTERVAL = 30 def get_environment_variables() -> Tuple[str, str, str, str, str]: """Retrieve and return necessary environment variables.""" try: with open(os.environ["GITHUB_EVENT_PATH"]) as f: ...
import json import os import requests import sys import time from typing import Dict, List, Tuple CHECK_INTERVAL = 30 def get_environment_variables() -> Tuple[str, str, str, str, str]: """Retrieve and return necessary environment variables.""" try: with open(os.environ["GITHUB_EVENT_PATH"]) as f: ...
# pyre-strict # mypy: allow-untyped-defs import os from concurrent.futures import Future, ThreadPoolExecutor from typing import Optional, Union import torch.distributed as dist from torch.distributed.checkpoint._async_executor import _AsyncCheckpointExecutor from torch.distributed.checkpoint.metadata import STATE_DICT...
# pyre-strict # mypy: allow-untyped-defs import os from concurrent.futures import Future, ThreadPoolExecutor from typing import Optional, Union import torch.distributed as dist from torch.distributed.checkpoint._async_executor import _AsyncCheckpointExecutor from torch.distributed.checkpoint.metadata import STATE_DICT...
from typing import Dict from jina import Client, Document, DocumentArray, Executor, Flow, requests ORIGINAL_PARAMS = {'param1': 50, 'param2': 60, 'exec_name': {'param1': 'changed'}} OVERRIDEN_EXECUTOR1_PARAMS = { 'param1': 'changed', 'param2': 60, 'exec_name': {'param1': 'changed'}, } class DummyOverrid...
from typing import Dict from jina import Flow, DocumentArray, Document, Executor, Client, requests ORIGINAL_PARAMS = {'param1': 50, 'param2': 60, 'exec_name': {'param1': 'changed'}} OVERRIDEN_EXECUTOR1_PARAMS = { 'param1': 'changed', 'param2': 60, 'exec_name': {'param1': 'changed'}, } class DummyOverrid...
"""Functionality for loading agents.""" import json import logging from pathlib import Path from typing import Any, Optional, Union import yaml from langchain_core._api import deprecated from langchain_core.language_models import BaseLanguageModel from langchain_core.tools import Tool from langchain.agents.agent imp...
"""Functionality for loading agents.""" import json import logging from pathlib import Path from typing import Any, List, Optional, Union import yaml from langchain_core._api import deprecated from langchain_core.language_models import BaseLanguageModel from langchain_core.tools import Tool from langchain.agents.age...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.document_loaders import TencentCOSDirectoryLoader # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optio...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.document_loaders import TencentCOSDirectoryLoader # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optio...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras import _tf_keras as _tf_keras from keras import activations as activations from keras import applications as applications from keras import backend as backend from keras import callbacks ...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.api import _tf_keras from keras.api import activations from keras.api import applications from keras.api import backend from keras.api import callbacks from keras.api import config from k...
_base_ = '../retinanet/retinanet_x101-32x4d_fpn_1x_coco.py' model = dict( bbox_head=dict( type='PISARetinaHead', loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0)), train_cfg=dict(isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2)))
_base_ = '../retinanet/retinanet_x101_32x4d_fpn_1x_coco.py' model = dict( bbox_head=dict( type='PISARetinaHead', loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0)), train_cfg=dict(isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2)))
# Copyright 2019-present, the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# Copyright 2019-present, the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder from sentence_transformers.util import fullname class MSELoss(nn.Module): def __init__(self, model: CrossEncoder, activation_fct: nn.Module = nn.Identity(), **kwargs) -> None...
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder import CrossEncoder from sentence_transformers.util import fullname class MSELoss(nn.Module): def __init__(self, model: CrossEncoder, **kwargs) -> None: super().__init__() self.model = model ...
import torch from torch import nn, Tensor from typing import Iterable, Dict from ..SentenceTransformer import SentenceTransformer from .. import util class CoSENTLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = 20.0, similarity_fct=util.pairwise_cos_sim): """ This cla...
import torch from torch import nn, Tensor from typing import Iterable, Dict from ..SentenceTransformer import SentenceTransformer from .. import util class CoSENTLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = 20.0, similarity_fct=util.pairwise_cos_sim): """ This cla...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
# Copyright 2024 The TensorFlow Authors. 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 applica...
# Copyright 2024 The TensorFlow Authors. 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 applica...
# dataset settings dataset_type = 'OpenImagesDataset' data_root = 'data/OpenImages/' # 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/datasets/detection/coco/' # ...
# dataset settings dataset_type = 'OpenImagesDataset' data_root = 'data/OpenImages/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend...
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# Copyright 2024 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...
from abc import abstractmethod from typing import ( TYPE_CHECKING, TypeVar, Sequence, List, Union, Optional, Dict, ) from qdrant_client.http.models.models import Distance from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore if...
from abc import abstractmethod from typing import ( TYPE_CHECKING, TypeVar, Sequence, List, Dict, Optional, ) from qdrant_client.http.models.models import Distance from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore if TYPE_CHEC...
from typing import Optional import torch def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen,...
from typing import Optional, Tuple import torch def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, ...
from abc import ABC import pytest from docarray import DocumentArray from docarray.array.storage.memory import GetSetDelMixin, SequenceLikeMixin from docarray.array.storage.redis.backend import BackendMixin, RedisConfig class StorageMixins(BackendMixin, GetSetDelMixin, SequenceLikeMixin, ABC): ... class Docume...
from abc import ABC import pytest from docarray import DocumentArray from docarray.array.storage.memory import GetSetDelMixin, SequenceLikeMixin from docarray.array.storage.redis.backend import BackendMixin, RedisConfig class StorageMixins(BackendMixin, GetSetDelMixin, SequenceLikeMixin, ABC): ... class Docume...
"""Test GooseAI""" import pytest from pydantic import SecretStr from pytest import MonkeyPatch from langchain_community.llms.gooseai import GooseAI from langchain_community.utils.openai import is_openai_v1 def _openai_v1_installed() -> bool: try: return is_openai_v1() except Exception as _: ...
"""Test GooseAI""" import pytest from pydantic import SecretStr from pytest import MonkeyPatch from langchain_community.llms.gooseai import GooseAI from langchain_community.utils.openai import is_openai_v1 def _openai_v1_installed() -> bool: try: return is_openai_v1() except Exception as _: ...
_base_ = './decoupled-solo_r50_fpn_3x_coco.py' # model settings model = dict( mask_head=dict( type='DecoupledSOLOLightHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 8, 16, 32, 32], scale_ranges=((1, 64), (32, 128), (64...
_base_ = './decoupled-solo_r50_fpn_3x_coco.py' # model settings model = dict( mask_head=dict( type='DecoupledSOLOLightHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 8, 16, 32, 32], scale_ranges=((1, 64), (32, 128), (64...
"""Base class for Slack tools.""" from __future__ import annotations from typing import TYPE_CHECKING from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.tools.slack.utils import login if TYPE_CHECKING: # This is for linting and IDE typehints from slack_sdk import ...
"""Base class for Slack tools.""" from __future__ import annotations from typing import TYPE_CHECKING from langchain_core.tools import BaseTool from pydantic import Field from langchain_community.tools.slack.utils import login if TYPE_CHECKING: # This is for linting and IDE typehints from slack_sdk import ...
from __future__ import annotations from .splade_callbacks import SchedulerType, SpladeRegularizerWeightSchedulerCallback __all__ = ["SpladeRegularizerWeightSchedulerCallback", "SchedulerType"]
from __future__ import annotations from .splade_callbacks import SchedulerType, SpladeLambdaSchedulerCallback __all__ = ["SpladeLambdaSchedulerCallback", "SchedulerType"]
import csv import gzip import logging import os from datetime import datetime import torch from sentence_transformers import InputExample, LoggingHandler, SentenceTransformer, losses, models, util from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator #### Just some code to print debug information...
import torch from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator from sentence_transformers import SentenceTransformer, LoggingHandler, models, util, InputExample from sentence_transformers import losses import os import gzip import csv from datetime import datetime import logging #### Just some ...
_base_ = 'yolact_r50_1x8_coco.py' optimizer = dict(type='SGD', lr=8e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[20, 42, 49, 52]) ...
_base_ = 'yolact_r50_1x8_coco.py' optimizer = dict(type='SGD', lr=8e-3, momentum=0.9, weight_decay=5e-4) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[20, 42, 49, 52])
from backend.data.credit import get_user_credit_model from backend.data.execution import ( ExecutionResult, NodeExecutionEntry, RedisExecutionEventBus, create_graph_execution, get_execution_results, get_incomplete_executions, get_latest_execution, update_execution_status, update_grap...
from backend.data.credit import get_user_credit_model from backend.data.execution import ( ExecutionResult, NodeExecutionEntry, RedisExecutionEventBus, create_graph_execution, get_execution_results, get_incomplete_executions, get_latest_execution, update_execution_status, update_grap...
# flake8: noqa import numpy as np from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.adamw import AdamW class AdamWTest(testing.TestCase): def test_config(self): optimizer = AdamW( learning_rate=0.5, weight_decay=0.008...
# flake8: noqa import numpy as np from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.adamw import AdamW class AdamWTest(testing.TestCase): def test_config(self): optimizer = AdamW( learning_rate=0.5, weight_decay=0.008...
_base_ = './faster-rcnn_r50-caffe_c4-1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile', backend_args=_base_.backend_args), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomChoiceResize', scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), ...
_base_ = './faster-rcnn_r50-caffe_c4-1x_coco.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 = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Resize', img_scale=...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import AINRuleOps from langchain_community.tools.ainetwork.rule import RuleSchema # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import AINRuleOps from langchain_community.tools.ainetwork.rule import RuleSchema # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising...
"""Official evaluation script for v1.1 of the SQuAD dataset.""" import argparse import json import re import string import sys from collections import Counter def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r"\...
""" Official evaluation script for v1.1 of the SQuAD dataset. """ import argparse import json import re import string import sys from collections import Counter def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r...
import os from typing import Any, Optional from llama_index.llms.openai_like import OpenAILike class Groq(OpenAILike): """ Groq LLM. Examples: `pip install llama-index-llms-groq` ```python from llama_index.llms.groq import Groq # Set up the Groq class with the required ...
import os from typing import Any, Optional from llama_index.llms.openai_like import OpenAILike class Groq(OpenAILike): """ Groq LLM. Examples: `pip install llama-index-llms-groq` ```python from llama_index.llms.groq import Groq # Set up the Groq class with the required ...
import copy from dataclasses import dataclass, asdict, field from typing import ( Union, Dict, Optional, TYPE_CHECKING, Iterable, List, Tuple, ) import numpy as np from docarray.array.storage.base.backend import BaseBackendMixin, TypeMap from docarray.helper import dataclass_from_dict, fil...
import copy from dataclasses import dataclass, asdict, field from typing import ( Union, Dict, Optional, TYPE_CHECKING, Iterable, List, Tuple, ) import numpy as np from docarray.array.storage.base.backend import BaseBackendMixin, TypeMap from docarray.helper import dataclass_from_dict, fil...
import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.testing.monotone_constraints import is_correctly_constrained, training_dset rng = np.random.RandomState(1994) def non_decreasing(L: np.ndarray) -> bool: return all((x - y) < 0.001 for x, y in zip(L, L[1:])) d...
import sys import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm sys.path.append("tests/python") import test_monotone_constraints as tmc rng = np.random.RandomState(1994) def non_decreasing(L): return all((x - y) < 0.001 for x, y in zip(L, L[1:])) def non_increasing(L): ...
# Copyright (c) OpenMMLab. All rights reserved. import functools from typing import Callable, Optional import torch import torch.nn.functional as F from torch import Tensor def reduce_loss(loss: Tensor, reduction: str) -> Tensor: """Reduce loss as specified. Args: loss (Tensor): Elementwise loss ten...
# Copyright (c) OpenMMLab. All rights reserved. import functools import torch import torch.nn.functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: ...
from typing import List, Optional import torchaudio from torchaudio._internal.module_utils import deprecated # TODO: Once legacy global backend is removed, move this to torchaudio.__init__ def _init_backend(): from . import utils torchaudio.info = utils.get_info_func() torchaudio.load = utils.get_load_f...
from typing import List, Optional import torchaudio from torchaudio._internal.module_utils import deprecated from . import utils # TODO: Once legacy global backend is removed, move this to torchaudio.__init__ def _init_backend(): torchaudio.info = utils.get_info_func() torchaudio.load = utils.get_load_func(...
import os import urllib import pytest from pydantic import parse_obj_as, schema_json_of from docarray.base_doc.io.json import orjson_dumps from docarray.typing import TextUrl from tests import TOYDATA_DIR REMOTE_TEXT_FILE = 'https://de.wikipedia.org/wiki/Brixen' CUR_DIR = os.path.dirname(os.path.abspath(__file__)) L...
import os import urllib import pytest from pydantic import parse_obj_as, schema_json_of from docarray.base_doc.io.json import orjson_dumps from docarray.typing import TextUrl from tests import TOYDATA_DIR REMOTE_TEXT_FILE = 'https://de.wikipedia.org/wiki/Brixen' CUR_DIR = os.path.dirname(os.path.abspath(__file__)) L...
from __future__ import annotations from .splade_callbacks import SchedulerType, SpladeRegularizerWeightSchedulerCallback __all__ = ["SpladeRegularizerWeightSchedulerCallback", "SchedulerType"]
from __future__ import annotations from .splade_callbacks import SchedulerType, SpladeWeightRegulizerSchedulerCallback __all__ = ["SpladeWeightRegulizerSchedulerCallback", "SchedulerType"]
"""Embeddings.""" from importlib import import_module from typing import TYPE_CHECKING if TYPE_CHECKING: from langchain_core.embeddings.embeddings import Embeddings from langchain_core.embeddings.fake import ( DeterministicFakeEmbedding, FakeEmbeddings, ) __all__ = ["DeterministicFakeEmbe...
"""Embeddings.""" from langchain_core.embeddings.embeddings import Embeddings from langchain_core.embeddings.fake import DeterministicFakeEmbedding, FakeEmbeddings __all__ = ["DeterministicFakeEmbedding", "Embeddings", "FakeEmbeddings"]
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from examples/modular-transformers/modular_add_function.py. # Do NOT edit this file manually as any edits will be overwritten by the generatio...
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from examples/modular-transformers/modular_add_function.py. # Do NOT edit this file manually as any edits will be overwritten by the generatio...
import pathlib from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union from torchdata.datapipes.iter import Demultiplexer, Filter, IterDataPipe, IterKeyZipper, JsonParser, Mapper, UnBatcher from torchvision.prototype.datasets.utils import Dataset, EncodedImage, HttpResource, OnlineResource from torchvisio...
import pathlib from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union from torchdata.datapipes.iter import Demultiplexer, Filter, IterDataPipe, IterKeyZipper, JsonParser, Mapper, UnBatcher from torchvision.prototype.datapoints import Label from torchvision.prototype.datasets.utils import Dataset, Encoded...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os.path as osp import mmcv from mmcv import Config def parse_args(): parser = argparse.ArgumentParser( description='Gather benchmarked models metric') parser.add_argument('config', help='test config file path') par...
import argparse import glob import os.path as osp import mmcv from mmcv import Config def parse_args(): parser = argparse.ArgumentParser( description='Gather benchmarked models metric') parser.add_argument('config', help='test config file path') parser.add_argument( 'root', type=s...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.losses.losses import binary_crossentropy from keras.src.losses.losses import binary_focal_crossentropy from keras.src.losses.losses import categorical_crossentropy from keras.src.loss...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.losses.losses import binary_crossentropy from keras.src.losses.losses import binary_focal_crossentropy from keras.src.losses.losses import categorical_crossentropy from keras.src.loss...
from typing import List import numpy as np from torch.utils.data import Dataset from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from sentence_transformers.readers.InputExample import InputExample class DenoisingAutoEncoderDataset(Dataset): """ The DenoisingAutoEncoderDataset...
from typing import List import numpy as np from torch.utils.data import Dataset from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from sentence_transformers.readers.InputExample import InputExample class DenoisingAutoEncoderDataset(Dataset): """ The DenoisingAutoEncoderDataset...
from typing import TYPE_CHECKING, Dict, Iterable from sentence_transformers.evaluation.SentenceEvaluator import SentenceEvaluator if TYPE_CHECKING: from sentence_transformers.SentenceTransformer import SentenceTransformer class SequentialEvaluator(SentenceEvaluator): """ This evaluator allows that multi...
from sentence_transformers import SentenceTransformer from . import SentenceEvaluator from typing import Dict, Iterable class SequentialEvaluator(SentenceEvaluator): """ This evaluator allows that multiple sub-evaluators are passed. When the model is evaluated, the data is passed sequentially to all sub-e...
import pytest from jina import Flow from jina.enums import GatewayProtocolType from tests import random_docs @pytest.mark.slow @pytest.mark.parametrize('protocol', ['http', 'websocket', 'grpc']) @pytest.mark.parametrize('changeto_protocol', ['grpc', 'http', 'websocket']) def test_change_gateway(protocol, changeto_pr...
import pytest from jina import Flow from jina.enums import GatewayProtocolType from tests import random_docs @pytest.mark.slow @pytest.mark.parametrize('protocol', ['http', 'websocket', 'grpc']) @pytest.mark.parametrize('changeto_protocol', ['grpc', 'http', 'websocket']) def test_change_gateway(protocol, changeto_pr...
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
from typing import TYPE_CHECKING if TYPE_CHECKING: from argparse import Namespace def deployment(args: 'Namespace'): """ Start a Deployment :param args: arguments coming from the CLI. """ from jina.orchestrate.deployments import Deployment try: with Deployment(args) as d: ...
from typing import TYPE_CHECKING if TYPE_CHECKING: from argparse import Namespace def deployment(args: 'Namespace'): """ Start a Deployment :param args: arguments coming from the CLI. """ from jina.orchestrate.deployments import Deployment try: with Deployment(args) as d: ...
# Copyright (c) OpenMMLab. All rights reserved. from .base_sampler import BaseSampler from .combined_sampler import CombinedSampler from .instance_balanced_pos_sampler import InstanceBalancedPosSampler from .iou_balanced_neg_sampler import IoUBalancedNegSampler from .mask_pseudo_sampler import MaskPseudoSampler from .m...
# Copyright (c) OpenMMLab. All rights reserved. from .base_sampler import BaseSampler from .combined_sampler import CombinedSampler from .instance_balanced_pos_sampler import InstanceBalancedPosSampler from .iou_balanced_neg_sampler import IoUBalancedNegSampler from .ohem_sampler import OHEMSampler from .pseudo_sampler...
# Copyright (c) OpenMMLab. All rights reserved. from .checkloss_hook import CheckInvalidLossHook from .mean_teacher_hook import MeanTeacherHook from .memory_profiler_hook import MemoryProfilerHook from .num_class_check_hook import NumClassCheckHook from .pipeline_switch_hook import PipelineSwitchHook from .set_epoch_in...
# Copyright (c) OpenMMLab. All rights reserved. from .checkloss_hook import CheckInvalidLossHook from .mean_teacher_hook import MeanTeacherHook from .memory_profiler_hook import MemoryProfilerHook from .num_class_check_hook import NumClassCheckHook from .set_epoch_info_hook import SetEpochInfoHook from .sync_norm_hook ...
import urllib.request from typing import List from defusedxml.ElementTree import fromstring from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.web.async_web.base import AsyncWebPageReader class SitemapReader(BaseReader): """ Asynchronous...
import urllib.request import xml.etree.ElementTree as ET from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.web.async_web.base import AsyncWebPageReader class SitemapReader(BaseReader): """Asynchronous sitemap reader ...
import jax from jax import numpy as jnp from keras.src.optimizers import base_optimizer class JaxOptimizer(base_optimizer.BaseOptimizer): """A class for JAX specific optimizer logic. Its purpose is to route around statelessness requirements in cond ops used for EMA handling and gradient accumulation...
import jax from jax import numpy as jnp from keras.src.optimizers import base_optimizer class JaxOptimizer(base_optimizer.BaseOptimizer): """A class for JAX specific optimizer logic. Its purpose is to route around statelessness requirements in cond ops used for EMA handling and gradient accumulation...
# 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...
# Copyright 2024 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...
# model settings model = dict( type='RPN', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32), backbone=dict( type='ResNet', depth=50, num_stage...
# model settings preprocess_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, pad_size_divisor=32) model = dict( type='RPN', preprocess_cfg=preprocess_cfg, backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(...
_base_ = '../mask_rcnn/mask-rcnn_r50_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_img=2000, ...
_base_ = '../mask_rcnn/mask_rcnn_r50_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_img=2000, ...
import random from collections import defaultdict import torch from torch.utils.data.sampler import Sampler def create_groups(groups, k): """Bins sample indices with respect to groups, remove bins with less than k samples Args: groups (list[int]): where ith index stores ith sample's group id Re...
import random from collections import defaultdict import torch from torch.utils.data.sampler import Sampler def create_groups(groups, k): """Bins sample indices with respect to groups, remove bins with less than k samples Args: groups (list[int]): where ith index stores ith sample's group id Re...
"""Feedly Rss Reader.""" import json from pathlib import Path from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class FeedlyRssReader(BaseReader): """ Feedly Rss Reader. Get entries from Feedly Rss Reader Uses Feedly Official python-api-client: https...
"""Feedly Rss Reader.""" import json from pathlib import Path from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class FeedlyRssReader(BaseReader): """Feedly Rss Reader. Get entries from Feedly Rss Reader Uses Feedly Official python-api-client: https://gi...
from typing import Optional from docarray.document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import Embedding class Text(BaseDocument): """ Document for handling text. It can contain a TextUrl (`Text.url`), a str (`Text.text`), and an Embedding (`Te...
from typing import Optional from docarray.document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import Embedding class Text(BaseDocument): """ Document for handling text. It can contain a TextUrl (`Text.url`), a str (`Text.text`), and an Embedding (`Te...
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...
_base_ = './rtmdet-ins_s_8xb32-300e_coco.py' checkpoint = 'https://download.openmmlab.com/mmdetection/v3.0/rtmdet/cspnext_rsb_pretrain/cspnext-tiny_imagenet_600e.pth' # noqa model = dict( backbone=dict( deepen_factor=0.167, widen_factor=0.375, init_cfg=dict( type='Pretrained',...
_base_ = './rtmdet-ins_s_8xb32-300e_coco.py' checkpoint = 'https://download.openmmlab.com/mmdetection/v3.0/rtmdet/cspnext_rsb_pretrain/cspnext-tiny_imagenet_600e.pth' # noqa model = dict( backbone=dict( deepen_factor=0.167, widen_factor=0.375, init_cfg=dict( type='Pretrained',...
_base_ = './solov2_r50_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='RandomChoiceResize', scales=[(1333, 800), (1333, 768), (1333, 73...
_base_ = 'solov2_r50_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='RandomChoiceResize', scales=[(1333, 800), (1333, 768), (1333, 736)...
import numpy as np import pytest from tensorflow import data as tf_data import keras from keras.src import backend from keras.src import layers from keras.src import testing class RandomHueTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( ...
import numpy as np import pytest from tensorflow import data as tf_data import keras from keras.src import backend from keras.src import layers from keras.src import testing class RandomHueTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( ...
# Owner(s): ["oncall: distributed checkpointing"] import unittest.mock as mock from torch.distributed.checkpoint._experimental.barriers import TCPStoreBarrier from torch.distributed.checkpoint._experimental.types import RankInfo from torch.testing._internal.common_utils import run_tests, TestCase class TestBarriers...
# Owner(s): ["oncall: distributed checkpointing"] import unittest.mock as mock from torch.distributed.checkpoint._experimental.barriers import TCPStoreBarrier from torch.testing._internal.common_utils import run_tests, TestCase class TestBarriers(TestCase): @mock.patch("torch.distributed.TCPStore") @mock.pa...
from __future__ import annotations from typing import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer class MSELoss(nn.Module): def __init__(self, model: SentenceTransformer) -> None: """ Computes the MSE loss between the computed sentenc...
from __future__ import annotations from typing import Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer class MSELoss(nn.Module): def __init__(self, model: SentenceTransformer) -> None: """ Computes the MSE loss between the computed sentenc...
import csv import os from pathlib import Path from typing import Union import torchaudio from torch.utils.data import Dataset class FluentSpeechCommands(Dataset): """Create *Fluent Speech Commands* [:footcite:`fluent`] Dataset Args: root (str of Path): Path to the directory where the dataset is foun...
import csv import os from pathlib import Path from typing import Union import torchaudio from torch.utils.data import Dataset class FluentSpeechCommands(Dataset): """Create *Fluent Speech Commands* [:footcite:`fluent`] Dataset Args: root (str of Path): Path to the directory where the dataset is foun...
_base_ = '../fast_rcnn/fast-rcnn_r50_fpn_1x_coco.py' # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict( type='BFP', in_channels=256, num_l...
_base_ = '../fast_rcnn/fast_rcnn_r50_fpn_1x_coco.py' # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict( type='BFP', in_channels=256, num_l...
import functools import torch import torch._custom_ops import torch.library # Ensure that torch.ops.torchvision is visible import torchvision.extension # noqa: F401 @functools.lru_cache(None) def get_meta_lib(): return torch.library.Library("torchvision", "IMPL", "Meta") def register_meta(op_name, overload_n...
import functools import torch import torch.library # Ensure that torch.ops.torchvision is visible import torchvision.extension # noqa: F401 @functools.lru_cache(None) def get_meta_lib(): return torch.library.Library("torchvision", "IMPL", "Meta") def register_meta(op_name, overload_name="default"): def w...
__version__ = '0.13.34' import os from docarray.document import Document from docarray.array import DocumentArray from docarray.dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
__version__ = '0.13.34' import os from .document import Document from .array import DocumentArray from .dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
from __future__ import annotations from enum import Enum from typing import Callable from numpy import ndarray from torch import Tensor from .util import ( cos_sim, dot_score, euclidean_sim, manhattan_sim, pairwise_cos_sim, pairwise_dot_score, pairwise_euclidean_sim, pairwise_manhatta...
from enum import Enum from typing import Callable, List, Union from numpy import ndarray from torch import Tensor from .util import ( cos_sim, dot_score, euclidean_sim, manhattan_sim, pairwise_cos_sim, pairwise_dot_score, pairwise_euclidean_sim, pairwise_manhattan_sim, ) class Simila...
_base_ = ['./mask2former_r50_lsj_8x2_50e_coco.py'] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa depths = [2, 2, 6, 2] model = dict( type='Mask2Former', backbone=dict( _delete_=True, type='SwinTransformer', emb...
_base_ = ['./mask2former_r50_lsj_8x2_50e_coco.py'] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa depths = [2, 2, 6, 2] model = dict( type='Mask2Former', backbone=dict( _delete_=True, type='SwinTransformer', em...
# flake8: noqa import torchaudio from torchaudio._backend.utils import get_info_func, get_load_func, get_save_func from . import utils from .utils import _is_backend_dispatcher_enabled, get_audio_backend, list_audio_backends, set_audio_backend if _is_backend_dispatcher_enabled(): torchaudio.info = get_info_func(...
# flake8: noqa from . import utils from .utils import get_audio_backend, list_audio_backends, set_audio_backend utils._init_audio_backend()
_base_ = './faster-rcnn_hrnetv2p-w18-1x_coco.py' # learning policy max_epochs = 24 train_cfg = dict(max_epochs=max_epochs) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, ...
_base_ = './faster_rcnn_hrnetv2p_w18_1x_coco.py' # learning policy max_epochs = 24 train_cfg = dict(max_epochs=max_epochs) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, ...
import numpy as np from docarray import BaseDoc, DocList from docarray.typing import NdArray from pydantic import Field, BaseModel from typing import Optional, Literal from jina import Executor, requests class TextDoc(BaseDoc): text: str = Field(description="The text of the document", default="") class Embeddi...
import numpy as np from docarray import BaseDoc, DocList from docarray.typing import NdArray from pydantic import Field, BaseModel from jina import Executor, requests class TextDoc(BaseDoc): text: str = Field(description="The text of the document", default="") class EmbeddingResponseModel(TextDoc): embeddi...
import torch from ._bounding_boxes import BoundingBoxes, BoundingBoxFormat, is_rotated_bounding_format from ._image import Image from ._keypoints import KeyPoints from ._mask import Mask from ._torch_function_helpers import set_return_type from ._tv_tensor import TVTensor from ._video import Video # TODO: Fix this. ...
import torch from ._bounding_boxes import BoundingBoxes, BoundingBoxFormat, is_rotated_bounding_format from ._image import Image from ._keypoints import KeyPoints from ._mask import Mask from ._torch_function_helpers import set_return_type from ._tv_tensor import TVTensor from ._video import Video # TODO: Fix this. ...