input stringlengths 33 5k | output stringlengths 32 5k |
|---|---|
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable
from sentence_transformers.evaluation import InformationRetrievalEvaluator
if TYPE_CHECKING:
import numpy as np
from torch import Tensor
from sentence_transformers.similarity_functions import SimilarityFunc... | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable
from sentence_transformers.evaluation import InformationRetrievalEvaluator
if TYPE_CHECKING:
import numpy as np
from torch import Tensor
from sentence_transformers.similarity_functions import SimilarityFunc... |
import json
import os
from typing import Dict
import torch
from torch import Tensor, nn
class WeightedLayerPooling(nn.Module):
"""Token embeddings are weighted mean of their different hidden layer representations"""
def __init__(
self, word_embedding_dimension, num_hidden_layers: int = 12, layer_sta... | import torch
from torch import Tensor
from torch import nn
from typing import Union, Tuple, List, Iterable, Dict
import os
import json
class WeightedLayerPooling(nn.Module):
"""
Token embeddings are weighted mean of their different hidden layer representations
"""
def __init__(self, word_embedding_dim... |
# mypy: allow-untyped-defs
from dataclasses import dataclass
from typing import Callable
import torch
import torch.fx.node
import torch.utils._pytree as pytree
from torch._ops import HigherOrderOperator
def is_graphable(val) -> bool:
"""Definition: a graphable type is a type that that is an acceptable input/outp... | # mypy: allow-untyped-defs
from dataclasses import dataclass
from typing import Callable
import torch
import torch.fx.node
import torch.utils._pytree as pytree
from torch._ops import HigherOrderOperator
def is_graphable(val) -> bool:
"""Definition: a graphable type is a type that that is an acceptable input/outp... |
# Copyright (c) OpenMMLab. All rights reserved.
from .collect_env import collect_env
from .compat_config import compat_cfg
from .logger import get_caller_name, get_root_logger, log_img_scale
from .memory import AvoidCUDAOOM, AvoidOOM
from .misc import find_latest_checkpoint, update_data_root
from .parallel import MMDat... | # Copyright (c) OpenMMLab. All rights reserved.
from .collect_env import collect_env
from .compat_config import compat_cfg
from .logger import get_caller_name, get_root_logger, log_img_scale
from .memory import AvoidCUDAOOM, AvoidOOM
from .misc import find_latest_checkpoint, update_data_root
from .replace_cfg_vals impo... |
# 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... | # 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... |
"""Different methods for rendering Tools to be passed to LLMs.
Depending on the LLM you are using and the prompting strategy you are using,
you may want Tools to be rendered in a different way.
This module contains various ways to render tools.
"""
# For backwards compatibility
from langchain_core.tools import (
... | """Different methods for rendering Tools to be passed to LLMs.
Depending on the LLM you are using and the prompting strategy you are using,
you may want Tools to be rendered in a different way.
This module contains various ways to render tools.
"""
# For backwards compatibility
from langchain_core.tools import (
... |
"""Utilities for loading configurations from langchain_core-hub."""
import warnings
from typing import Any
from langchain_core._api.deprecation import deprecated
@deprecated(
since="0.1.30",
removal="1.0",
message=(
"Using the hwchase17/langchain-hub "
"repo for prompts is deprecated. Pl... | """Utilities for loading configurations from langchain_core-hub."""
import warnings
from typing import Any
from langchain_core._api.deprecation import deprecated
@deprecated(
since="0.1.30",
removal="1.0",
message=(
"Using the hwchase17/langchain-hub "
"repo for prompts is deprecated. Pl... |
_base_ = './fovea_r50_fpn_4xb4-1x_coco.py'
model = dict(
bbox_head=dict(
with_deform=True,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)))
# learning policy
max_epochs = 24
param_scheduler = [
dict(
type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500),
... | _base_ = './fovea_r50_fpn_4x4_1x_coco.py'
model = dict(
bbox_head=dict(
with_deform=True,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)))
# learning policy
max_epochs = 24
param_scheduler = [
dict(
type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500),
... |
import asyncio
import logging
from abc import ABC, abstractmethod
from typing import Any, AsyncGenerator, Generator, Generic, Optional, TypeVar
from pydantic import BaseModel
from redis.asyncio.client import PubSub as AsyncPubSub
from redis.client import PubSub
from backend.data import redis
logger = logging.getLogg... | import asyncio
import json
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any, AsyncGenerator, Generator, Generic, Optional, TypeVar
from pydantic import BaseModel
from redis.asyncio.client import PubSub as AsyncPubSub
from redis.client import PubSub
from backend.d... |
import warnings
from abc import ABC
from typing import TYPE_CHECKING, Any, BinaryIO, Dict, TypeVar, Union
from docarray.typing.tensor.abstract_tensor import AbstractTensor
from docarray.utils._internal.misc import import_library, is_notebook
if TYPE_CHECKING:
from docarray.typing.bytes.audio_bytes import AudioByt... | import warnings
from abc import ABC
from typing import TYPE_CHECKING, Any, BinaryIO, Dict, TypeVar, Union
from docarray.typing.tensor.abstract_tensor import AbstractTensor
from docarray.utils._internal.misc import import_library, is_notebook
if TYPE_CHECKING:
from docarray.typing.bytes.audio_bytes import AudioByt... |
from keras.src.api_export import keras_export
# Unique source of truth for the version number.
__version__ = "3.4.1"
@keras_export("keras.version")
def version():
return __version__
| from keras.src.api_export import keras_export
# Unique source of truth for the version number.
__version__ = "3.4.0"
@keras_export("keras.version")
def version():
return __version__
|
_base_ = './mask-rcnn_r50_fpn_sample1e-3_ms-1x_lvis-v1.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
s... | _base_ = './mask_rcnn_r50_fpn_sample1e-3_mstrain_1x_lvis_v1.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
... |
import os
from typing import Optional
import numpy as np
import pytest
import torch
from pydantic import parse_obj_as
from docarray import BaseDocument
from docarray.documents import Audio
from docarray.typing import AudioUrl
from docarray.typing.tensor.audio import AudioNdArray, AudioTorchTensor
from tests import TO... | import os
from typing import Optional
import numpy as np
import pytest
import torch
from pydantic import parse_obj_as
from docarray.documents import Audio
from docarray.typing import AudioUrl
from docarray.typing.tensor.audio import AudioNdArray, AudioTorchTensor
from tests import TOYDATA_DIR
LOCAL_AUDIO_FILES = [
... |
import pytest
from keras.src import activations
from keras.src import layers
from keras.src import testing
class ActivationTest(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_activation_basics(self):
self.run_layer_test(
layers.Activation,
init_kwargs={
... | import pytest
from keras.src import activations
from keras.src import layers
from keras.src import testing
class ActivationTest(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_activation_basics(self):
self.run_layer_test(
layers.Activation,
init_kwargs={
... |
_base_ = './faster-rcnn_r50_fpn_1x_coco.py'
model = dict(
roi_head=dict(
bbox_head=dict(
reg_decoded_bbox=True,
loss_bbox=dict(type='BoundedIoULoss', loss_weight=10.0))))
| _base_ = './faster_rcnn_r50_fpn_1x_coco.py'
model = dict(
roi_head=dict(
bbox_head=dict(
reg_decoded_bbox=True,
loss_bbox=dict(type='BoundedIoULoss', loss_weight=10.0))))
|
import os
import pytest
import torch
import whisper
from whisper.tokenizer import get_tokenizer
@pytest.mark.parametrize("model_name", whisper.available_models())
def test_transcribe(model_name: str):
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper.load_model(model_name).to(device)
... | import os
import pytest
import torch
import whisper
from whisper.tokenizer import get_tokenizer
@pytest.mark.parametrize("model_name", whisper.available_models())
def test_transcribe(model_name: str):
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper.load_model(model_name).to(device)
... |
def __getattr__(name: str):
import warnings
warnings.warn(
"Torchaudio's I/O functions now support per-call backend dispatch. "
"Importing backend implementation directly is no longer guaranteed to work. "
"Please use `backend` keyword with load/save/info function, instead of "
... | def __getattr__(name: str):
import warnings
warnings.warn(
"Torchaudio's I/O functions now support par-call bakcend dispatch. "
"Importing backend implementation directly is no longer guaranteed to work. "
"Please use `backend` keyword with load/save/info function, instead of "
... |
_base_ = './cornernet_hourglass104_8xb6-210e-mstest_coco.py'
train_dataloader = dict(batch_size=5)
# NOTE: `auto_scale_lr` is for automatically scaling LR,
# USER SHOULD NOT CHANGE ITS VALUES.
# base_batch_size = (10 GPUs) x (5 samples per GPU)
auto_scale_lr = dict(base_batch_size=50)
| _base_ = './cornernet_hourglass104_mstest_8x6_210e_coco.py'
train_dataloader = dict(batch_size=5)
# NOTE: `auto_scale_lr` is for automatically scaling LR,
# USER SHOULD NOT CHANGE ITS VALUES.
# base_batch_size = (10 GPUs) x (5 samples per GPU)
auto_scale_lr = dict(base_batch_size=50)
|
# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is
# redefined at each test that fixture
# ruff: noqa
import numpy as np
import pytest
import torch
from pydantic import Field
from docarray import BaseDoc
from docarray.index.backends.weaviate import WeaviateDocumentIndex
from ... | # TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is
# redefined at each test that fixture
# ruff: noqa
import numpy as np
import pytest
import torch
from pydantic import Field
from docarray import BaseDoc
from docarray.index.backends.weaviate import WeaviateDocumentIndex
from ... |
# Copyright (c) OpenMMLab. All rights reserved.
from mmdet.core.utils import ConfigType, OptConfigType, OptMultiConfig
from mmdet.registry import MODELS
from .two_stage import TwoStageDetector
@MODELS.register_module()
class MaskScoringRCNN(TwoStageDetector):
"""Mask Scoring RCNN.
https://arxiv.org/abs/1903.... | # Copyright (c) OpenMMLab. All rights reserved.
from mmdet.registry import MODELS
from .two_stage import TwoStageDetector
@MODELS.register_module()
class MaskScoringRCNN(TwoStageDetector):
"""Mask Scoring RCNN.
https://arxiv.org/abs/1903.00241
"""
def __init__(self,
backbone,
... |
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import GoogleSearchResults, GoogleSearchRun
# 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.tools import GoogleSearchResults, GoogleSearchRun
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optio... |
from pathlib import Path
REPO_ROOT_DIR = Path(__file__).parent.parent.absolute()
TOYDATA_DIR = REPO_ROOT_DIR / 'tests' / 'toydata'
| import numpy as np
from docarray import DocumentArray, Document
def random_docs(
num_docs,
chunks_per_doc=5,
embed_dim=10,
jitter=1,
start_id=0,
embedding=True,
sparse_embedding=False,
text='hello world',
) -> DocumentArray:
da = DocumentArray()
next_chunk_doc_id = start_id + n... |
import PIL.Image
import pytest
import torch
import torchvision.prototype.transforms.utils
from prototype_common_utils import make_bounding_box, make_detection_mask, make_image
from torchvision.prototype import datapoints
from torchvision.prototype.transforms.functional import to_image_pil
from torchvision.prototype.... | import PIL.Image
import pytest
import torch
from prototype_common_utils import make_bounding_box, make_detection_mask, make_image
from torchvision.prototype import features
from torchvision.prototype.transforms.functional import to_image_pil
from torchvision.prototype.transforms.utils import has_all, has_any
IMAGE... |
from typing import Any, Dict, Optional, Union
import numpy as np
import PIL.Image
import torch
from torchvision import datapoints
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2._utils import is_pure_tensor
class PILToTensor(Transform):
"""[BETA] Convert a PIL Im... | from typing import Any, Dict, Optional, Union
import numpy as np
import PIL.Image
import torch
from torchvision import datapoints
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2.utils import is_pure_tensor
class PILToTensor(Transform):
"""[BETA] Convert a PIL Ima... |
from pathlib import Path
from typing import Any
from langchain_core._api.path import as_import_path
def __getattr__(name: str) -> Any:
"""Get attr name."""
if name == "create_xorbits_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(P... | from pathlib import Path
from typing import Any
from langchain_core._api.path import as_import_path
def __getattr__(name: str) -> Any:
"""Get attr name."""
if name == "create_xorbits_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(P... |
from keras.src.api_export import keras_export
# Unique source of truth for the version number.
__version__ = "3.3.3"
@keras_export("keras.version")
def version():
return __version__
| from keras.src.api_export import keras_export
# Unique source of truth for the version number.
__version__ = "3.3.2"
@keras_export("keras.version")
def version():
return __version__
|
from functools import wraps
from typing import TYPE_CHECKING, List
from jina.excepts import FlowBuildLevelError
# noinspection PyUnreachableCode
if TYPE_CHECKING: # pragma: no cover
from jina.enums import FlowBuildLevel
from jina.orchestrate.flow.base import Flow
def allowed_levels(levels: List['FlowBuildLe... | from functools import wraps
from typing import TYPE_CHECKING, List
from jina.excepts import FlowBuildLevelError
# noinspection PyUnreachableCode
if TYPE_CHECKING:
from jina.enums import FlowBuildLevel
from jina.orchestrate.flow.base import Flow
def allowed_levels(levels: List['FlowBuildLevel']):
"""Anno... |
# Copyright (c) OpenMMLab. All rights reserved.
from .checkloss_hook import CheckInvalidLossHook
from .ema import ExpMomentumEMAHook, LinearMomentumEMAHook
from .memory_profiler_hook import MemoryProfilerHook
from .set_epoch_info_hook import SetEpochInfoHook
from .sync_norm_hook import SyncNormHook
from .sync_random_si... | # Copyright (c) OpenMMLab. All rights reserved.
from .checkloss_hook import CheckInvalidLossHook
from .ema import ExpMomentumEMAHook, LinearMomentumEMAHook
from .memory_profiler_hook import MemoryProfilerHook
from .set_epoch_info_hook import SetEpochInfoHook
from .sync_norm_hook import SyncNormHook
from .sync_random_si... |
"""
Python polyfills for sys
"""
from __future__ import annotations
import sys
from ..decorators import substitute_in_graph
__all__ = [
"intern",
"getrecursionlimit",
]
@substitute_in_graph(sys.intern, can_constant_fold_through=True)
def intern(string: str, /) -> str:
return string
@substitute_in_g... | """
Python polyfills for sys
"""
from __future__ import annotations
import sys
from ..decorators import substitute_in_graph
__all__ = [
"intern",
"getrecursionlimit",
]
@substitute_in_graph(sys.intern, can_constant_fold_through=True)
def intern(string: str, /) -> str:
return string
@substitute_in_g... |
_base_ = [
'./bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_'
'test-mot17halfval.py'
]
dataset_type = 'MOTChallengeDataset'
img_scale = (1600, 896) # weight, height
model = dict(
data_preprocessor=dict(
type='TrackDataPreprocessor',
use_det_processor=True,
pad_size_divisor... | _base_ = [
'./bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_'
'test-mot17halfval.py'
]
dataset_type = 'MOTChallengeDataset'
img_scale = (1600, 896) # weight, height
model = dict(
data_preprocessor=dict(
type='TrackDataPreprocessor',
use_det_processor=True,
pad_size_divisor... |
_base_ = './faster-rcnn_hrnetv2p-w32-1x_coco.py'
model = dict(
backbone=dict(
type='HRNet',
extra=dict(
stage2=dict(num_channels=(40, 80)),
stage3=dict(num_channels=(40, 80, 160)),
stage4=dict(num_channels=(40, 80, 160, 320))),
init_cfg=dict(
t... | _base_ = './faster_rcnn_hrnetv2p_w32_1x_coco.py'
model = dict(
backbone=dict(
type='HRNet',
extra=dict(
stage2=dict(num_channels=(40, 80)),
stage3=dict(num_channels=(40, 80, 160)),
stage4=dict(num_channels=(40, 80, 160, 320))),
init_cfg=dict(
t... |
_base_ = ['./ld_r18-gflv1-r101_fpn_1x_coco.py']
teacher_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/gfl/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco_20200630_102002-134b07df.pth' # noqa
model = dict(
teacher_config='configs/gfl/gfl_r101-dconv-c3-c5_fpn_ms-2x_coco.py... | _base_ = ['./ld_r18-gflv1-r101_fpn_1x_coco.py']
teacher_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/gfl/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco/gfl_r101_fpn_dconv_c3-c5_mstrain_2x_coco_20200630_102002-134b07df.pth' # noqa
model = dict(
teacher_config='configs/gfl/gfl_r101-dconv-c3-c5_fpn_ms-2x_coco.py... |
import torch
from torchaudio_unittest.common_utils import PytorchTestCase
from .functional_test_impl import Functional64OnlyTestImpl, FunctionalTestImpl
class FunctionalFloat32CPUTest(FunctionalTestImpl, PytorchTestCase):
dtype = torch.float32
device = torch.device("cpu")
class FunctionalFloat64CPUTest(Fun... | import torch
from torchaudio_unittest.common_utils import PytorchTestCase
from .functional_test_impl import Functional64OnlyTestImpl, FunctionalCPUOnlyTestImpl, FunctionalTestImpl
class FunctionalFloat32CPUTest(FunctionalTestImpl, PytorchTestCase):
dtype = torch.float32
device = torch.device("cpu")
class F... |
from typing import Any, Dict, List, Optional, Sequence, Type, Union
import PIL.Image
import torch
from torchvision import datapoints
from torchvision.prototype.datapoints import Label, OneHotLabel
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2._utils import _setup_fill... | from typing import Any, Dict, List, Optional, Sequence, Type, Union
import PIL.Image
import torch
from torchvision import datapoints
from torchvision.prototype.datapoints import Label, OneHotLabel
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2._utils import _setup_fill... |
# Copyright (c) OpenMMLab. All rights reserved.
from mmdet.registry import DATASETS
from .coco import CocoDataset
@DATASETS.register_module()
class DeepFashionDataset(CocoDataset):
CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag',
'neckwear', 'headwear', 'eyeglass', 'belt', ... | # Copyright (c) OpenMMLab. All rights reserved.
from .builder import DATASETS
from .coco import CocoDataset
@DATASETS.register_module()
class DeepFashionDataset(CocoDataset):
CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag',
'neckwear', 'headwear', 'eyeglass', 'belt', 'footw... |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import re
from typing import Dict, List, Optional, Tuple
from jina import Document, DocumentArray, Executor, requests
from jina.logging.logger import JinaLogger
class Sentencizer(Executor):
"""
:class:... | __copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import re
from typing import Dict, Iterable, List, Optional
from jina import Document, DocumentArray, Executor, requests
from jina.logging.logger import JinaLogger
class Sentencizer(Executor):
"""
:cla... |
import warnings
from typing import Any, List, Union
import PIL.Image
import torch
from torchvision.prototype import datapoints
from torchvision.transforms import functional as _F
@torch.jit.unused
def to_grayscale(inpt: PIL.Image.Image, num_output_channels: int = 1) -> PIL.Image.Image:
call = ", num_output_chan... | import warnings
from typing import Any, List, Union
import PIL.Image
import torch
from torchvision.prototype import datapoints
from torchvision.transforms import functional as _F
from ._utils import is_simple_tensor
@torch.jit.unused
def to_grayscale(inpt: PIL.Image.Image, num_output_channels: int = 1) -> PIL.Imag... |
__version__ = '0.12.10'
import os
from .document import Document
from .array import DocumentArray
from .dataclasses import dataclass, field
if 'DA_NO_RICH_HANDLER' not in os.environ:
from rich.traceback import install
install()
if 'NO_VERSION_CHECK' not in os.environ:
from .helper import is_latest_vers... | __version__ = '0.12.10'
import os
from .document import Document
from .array import DocumentArray
from .dataclasses import dataclass, field
if 'DA_NO_RICH_HANDLER' not in os.environ:
from rich.traceback import install
install()
|
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... |
#!/usr/bin/env python3
"""
Create a data preprocess pipeline that can be run with libtorchaudio
"""
import argparse
import os
import torch
import torchaudio
class Pipeline(torch.nn.Module):
"""Example audio process pipeline.
This example load waveform from a file then apply effects and save it to a file.
... | #!/usr/bin/env python3
"""
Create a data preprocess pipeline that can be run with libtorchaudio
"""
import argparse
import os
import torch
import torchaudio
class Pipeline(torch.nn.Module):
"""Example audio process pipeline.
This example load waveform from a file then apply effects and save it to a file.
... |
# 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... |
import concurrent.futures
import importlib
import subprocess
from pathlib import Path
def test_importable_all() -> None:
for path in Path("../core/langchain_core/").glob("*"):
module_name = path.stem
if not module_name.startswith(".") and path.suffix != ".typed":
module = importlib.imp... | import concurrent.futures
import importlib
import subprocess
from pathlib import Path
def test_importable_all() -> None:
for path in Path("../core/langchain_core/").glob("*"):
module_name = path.stem
if not module_name.startswith(".") and path.suffix != ".typed":
module = importlib.imp... |
# Copyright (c) OpenMMLab. All rights reserved.
from pathlib import Path
from typing import Any, Optional, Union
import torch
import torch.nn as nn
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from torch import Tensor
from mmdet.registry import MODELS
from mmdet.structures import Sam... | # Copyright (c) OpenMMLab. All rights reserved.
from pathlib import Path
from typing import Any, Optional, Union
import torch
import torch.nn as nn
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from torch import Tensor
from mmdet.data_elements import SampleList
from mmdet.registry imp... |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict, Iterable, Optional
import torch
from jina import DocumentArray, Executor, requests
from sentence_transformers import SentenceTransformer
class TransformerSentenceEncoder(Executor):
... | __copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict, Iterable, Optional
import torch
from jina import DocumentArray, Executor, requests
from sentence_transformers import SentenceTransformer
class TransformerSentenceEncoder(Executor):
... |
from __future__ import annotations
from collections.abc import Iterable
import torch.nn as nn
from torch import Tensor
from sentence_transformers.losses.CosineSimilarityLoss import CosineSimilarityLoss
from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder
class SparseCosineSimilarityLoss(Cos... | from __future__ import annotations
from collections.abc import Iterable
import torch.nn as nn
from torch import Tensor
from sentence_transformers.losses.CosineSimilarityLoss import CosineSimilarityLoss
from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder
class SparseCosineSimilarityLoss(Cos... |
from __future__ import annotations
import logging
from typing import Optional, Type
from langchain_core.callbacks import CallbackManagerForToolRun
from pydantic import BaseModel, Field
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
class TextModeratio... | from __future__ import annotations
import logging
from typing import Optional, Type
from langchain_core.callbacks import CallbackManagerForToolRun
from pydantic import BaseModel, Field
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
class TextModeratio... |
from __future__ import annotations
__version__ = "3.3.0.dev0"
__MODEL_HUB_ORGANIZATION__ = "sentence-transformers"
import importlib
import os
from sentence_transformers.backend import (
export_dynamic_quantized_onnx_model,
export_optimized_onnx_model,
export_static_quantized_openvino_model,
)
from senten... | from __future__ import annotations
__version__ = "3.3.0.dev0"
__MODEL_HUB_ORGANIZATION__ = "sentence-transformers"
import importlib
import os
from sentence_transformers.backend import export_dynamic_quantized_onnx_model, export_optimized_onnx_model
from sentence_transformers.cross_encoder.CrossEncoder import CrossEn... |
"""
This example starts multiple processes (1 per GPU), which encode
sentences in parallel. This gives a near linear speed-up
when encoding large text collections.
"""
import logging
from sentence_transformers import LoggingHandler, SentenceTransformer
logging.basicConfig(
format="%(asctime)s - %(message)s", dat... | """
This example starts multiple processes (1 per GPU), which encode
sentences in parallel. This gives a near linear speed-up
when encoding large text collections.
"""
import logging
from sentence_transformers import LoggingHandler, SentenceTransformer
logging.basicConfig(
format="%(asctime)s - %(message)s", dat... |
# pylint: disable=too-many-locals
"""Tests for learning to rank."""
from types import ModuleType
from typing import Any
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
def run_ranking_qid_df(impl: ModuleType, tree_method: str) -> None:
"""Test ranking with qid packed int... | # pylint: disable=too-many-locals
"""Tests for learning to rank."""
from types import ModuleType
from typing import Any
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
def run_ranking_qid_df(impl: ModuleType, tree_method: str) -> None:
"""Test ranking with qid packed int... |
# Copyright (c) OpenMMLab. All rights reserved.
from .build_functions import (build_from_cfg, build_model_from_cfg,
build_runner_from_cfg, build_scheduler_from_cfg)
from .default_scope import DefaultScope
from .registry import Registry
from .root import (DATA_SAMPLERS, DATASETS, EVALUATOR,... | # Copyright (c) OpenMMLab. All rights reserved.
from .build_functions import (build_from_cfg, build_model_from_cfg,
build_runner_from_cfg, build_scheduler_from_cfg)
from .default_scope import DefaultScope
from .registry import Registry
from .root import (DATA_SAMPLERS, DATASETS, EVALUATOR,... |
from torchaudio import _extension # noqa: F401
from torchaudio import (
io,
compliance,
datasets,
functional,
models,
pipelines,
kaldi_io,
utils,
sox_effects,
transforms,
)
from torchaudio.backend import (
list_audio_backends,
get_audio_backend,
set_audio_backend,
)
... | from torchaudio import _extension # noqa: F401
from torchaudio import (
compliance,
datasets,
functional,
models,
pipelines,
kaldi_io,
utils,
sox_effects,
transforms,
)
from torchaudio.backend import (
list_audio_backends,
get_audio_backend,
set_audio_backend,
)
try:
... |
from abc import ABC
from docarray.array.mixins.content import ContentPropertyMixin
from docarray.array.mixins.delitem import DelItemMixin
from docarray.array.mixins.embed import EmbedMixin
from docarray.array.mixins.empty import EmptyMixin
from docarray.array.mixins.evaluation import EvaluationMixin
from docarray.arra... | from abc import ABC
from .content import ContentPropertyMixin
from .delitem import DelItemMixin
from .embed import EmbedMixin
from .empty import EmptyMixin
from .evaluation import EvaluationMixin
from .find import FindMixin
from .getattr import GetAttributeMixin
from .getitem import GetItemMixin
from .group import Gro... |
import numpy as np
import pytest
import keras
from keras.src import backend
from keras.src import ops
from keras.src import testing
from keras.src.optimizers.lion import Lion
class LionTest(testing.TestCase):
def test_invalid_beta_1(self):
with self.assertRaisesRegex(
ValueError,
... | import numpy as np
import pytest
import keras
from keras.src import backend
from keras.src import ops
from keras.src import testing
from keras.src.optimizers.lion import Lion
class LionTest(testing.TestCase):
def test_config(self):
optimizer = Lion(
learning_rate=0.5,
beta_1=0.5,
... |
from keras.src.api_export import keras_export
from keras.src.layers.pooling.base_pooling import BasePooling
@keras_export(["keras.layers.AveragePooling1D", "keras.layers.AvgPool1D"])
class AveragePooling1D(BasePooling):
"""Average pooling for temporal data.
Downsamples the input representation by taking the ... | from keras.src.api_export import keras_export
from keras.src.layers.pooling.base_pooling import BasePooling
@keras_export(["keras.layers.AveragePooling1D", "keras.layers.AvgPool1D"])
class AveragePooling1D(BasePooling):
"""Average pooling for temporal data.
Downsamples the input representation by taking the ... |
"""Utilities for working with interactive environments."""
def is_interactive_env() -> bool:
"""Determine if running within IPython or Jupyter."""
import sys
return hasattr(sys, "ps2")
| def is_interactive_env() -> bool:
"""Determine if running within IPython or Jupyter."""
import sys
return hasattr(sys, "ps2")
|
from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501
BaseImagePreprocessingLayer,
)
from keras.src.ops.core import _saturate_cast
@keras_export("keras.layers.AutoContrast")
class Au... | from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layer import ( # noqa: E501
BaseImagePreprocessingLayer,
)
from keras.src.ops.core import _saturate_cast
@keras_export("keras.layers.AutoContrast")
class Au... |
"""JSON Reader."""
import re
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Dict, List, Optional
from llama_index.core.readers.base import BaseReader
from llama_index.core.schema import Document
def _get_leaf_nodes_up_to_level(root: ET.Element, level: int) -> List[ET.Element]:
""... | """JSON Reader."""
import re
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Dict, List, Optional
from llama_index.core.readers.base import BaseReader
from llama_index.core.schema import Document
def _get_leaf_nodes_up_to_level(root: ET.Element, level: int) -> List[ET.Element]:
""... |
import os
import sys
import cognee
import pytest
from llama_index.core import Document
from llama_index.graph_rag.cognee import CogneeGraphRAG
@pytest.mark.skipif(
sys.version_info < (3, 10), reason="mock strategy requires python3.10 or higher"
)
@pytest.mark.skipif(
os.getenv("OPENAI_API_KEY") is None,
... | import os
import sys
import cognee
import pytest
from llama_index.core import Document
from llama_index.graph_rag.cognee import CogneeGraphRAG
@pytest.mark.skipif(
sys.version_info < (3, 10), reason="mock strategy requires python3.10 or higher"
)
@pytest.mark.skipif(
os.getenv("OPENAI_API_KEY") is None,
... |
import types
from keras.src.activations.activations import celu
from keras.src.activations.activations import elu
from keras.src.activations.activations import exponential
from keras.src.activations.activations import gelu
from keras.src.activations.activations import glu
from keras.src.activations.activations import ... | import types
from keras.src.activations.activations import celu
from keras.src.activations.activations import elu
from keras.src.activations.activations import exponential
from keras.src.activations.activations import gelu
from keras.src.activations.activations import glu
from keras.src.activations.activations import ... |
"""
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 typing import List, Union
from docarray.array.abstract_array import AbstractDocumentArray
from docarray.document import BaseDocument
class GetAttributeArrayMixin(AbstractDocumentArray):
"""Helpers that provide attributes getter in bulk"""
def _get_documents_attribute(
self, field: str
) -> ... | from typing import List
from docarray.array.abstract_array import AbstractDocumentArray
class GetAttributeArrayMixin(AbstractDocumentArray):
"""Helpers that provide attributes getter in bulk"""
def _get_documents_attribute(self, field: str) -> List:
"""Return all values of the fields from all docs t... |
import copy
import pytest
import torch
from mmengine.structures import InstanceData
from mmdet.models.utils import (empty_instances, filter_gt_instances,
rename_loss_dict, reweight_loss_dict,
unpack_gt_instances)
from mmdet.testing import demo_mm_inputs
... | import pytest
import torch
from mmengine.structures import InstanceData
from mmdet.models.utils import empty_instances, unpack_gt_instances
from mmdet.testing import demo_mm_inputs
def test_parse_gt_instance_info():
packed_inputs = demo_mm_inputs()['data_samples']
batch_gt_instances, batch_gt_instances_ignor... |
"""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... | """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... |
from collections.abc import Sequence
from typing import Any, Optional, Union
import PIL.Image
import torch
from torchvision import tv_tensors
from torchvision.prototype.tv_tensors import Label, OneHotLabel
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2._utils import (
... | from typing import Any, Dict, List, Optional, Sequence, Type, Union
import PIL.Image
import torch
from torchvision import tv_tensors
from torchvision.prototype.tv_tensors import Label, OneHotLabel
from torchvision.transforms.v2 import functional as F, Transform
from torchvision.transforms.v2._utils import (
_Fill... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
from mmengine.config import Config, DictAction
from mmengine.runner import Runner
from mmdet.engine.hooks.utils import trigger_visualization_hook
from mmdet.registry import RUNNERS
from mmdet.utils import add_dump_metric, ... | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
from mmengine.config import Config, DictAction
from mmengine.runner import Runner
from mmdet.registry import RUNNERS
from mmdet.utils import register_all_modules
# TODO: support fuse_conv_bn and format_only
def parse_arg... |
# deprecated, please use the `filelock` package instead
from filelock import ( # noqa: F401 # imported for backward compatibility TODO: remove in 3.0.0
BaseFileLock,
SoftFileLock,
Timeout,
UnixFileLock,
WindowsFileLock,
)
from ._filelock import FileLock # noqa: F401 # imported for backward compa... | # deprecated, please use the `filelock` package instead
from filelock import ( # noqa: F401 # imported for backward compatibility
BaseFileLock,
SoftFileLock,
Timeout,
UnixFileLock,
WindowsFileLock,
)
from ._filelock import FileLock # noqa: F401 # imported for backward compatibility
|
"""Init file of LlamaIndex."""
__version__ = "0.12.15"
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.14"
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_ = '../grounding_dino_swin-t_pretrain_obj365_goldg_cap4m.py'
dataset_type = 'Flickr30kDataset'
data_root = 'data/flickr30k_entities/'
test_pipeline = [
dict(
type='LoadImageFromFile', backend_args=None,
imdecode_backend='pillow'),
dict(
type='FixScaleResize',
scale=(800, ... | _base_ = '../grounding_dino_swin-t_pretrain_obj365_goldg_cap4m.py'
dataset_type = 'Flickr30kDataset'
data_root = 'data/flickr30k/'
test_pipeline = [
dict(
type='LoadImageFromFile', backend_args=None,
imdecode_backend='pillow'),
dict(
type='FixScaleResize',
scale=(800, 1333),
... |
# Copyright (c) OpenMMLab. All rights reserved.
from pathlib import Path
from typing import Any, Optional, Union
import torch
import torch.nn as nn
from mmengine.config import Config
from mmengine.runner import load_checkpoint
from torch import Tensor
from mmdet.core import ConfigType, OptConfigType, SampleList
from ... | # Copyright (c) OpenMMLab. All rights reserved.
from pathlib import Path
import mmcv
import torch
from mmcv.runner import load_checkpoint
from mmdet.registry import MODELS
from .. import build_detector
from .single_stage import SingleStageDetector
@MODELS.register_module()
class KnowledgeDistillationSingleStageDete... |
# coding=utf-8
# Copyright 2025 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # coding=utf-8
# Copyright 2025 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
from torchvision.transforms import InterpolationMode # usort: skip
from ._utils import is_pure_tensor, register_kernel # usort: skip
from ._meta import (
clamp_bounding_boxes,
convert_bounding_box_format,
get_dimensions_image,
get_dimensions_video,
get_dimensions,
get_num_frames_video,
g... | from torchvision.transforms import InterpolationMode # usort: skip
from ._utils import is_pure_tensor, register_kernel # usort: skip
from ._meta import (
clamp_bounding_boxes,
convert_bounding_box_format,
get_dimensions_image,
get_dimensions_video,
get_dimensions,
get_num_frames_video,
g... |
from langchain_core.retrievers import BaseRetriever, Document
class SequentialRetriever(BaseRetriever):
"""Test util that returns a sequence of documents"""
sequential_responses: list[list[Document]]
response_index: int = 0
def _get_relevant_documents( # type: ignore[override]
self,
... | from typing import List
from langchain_core.retrievers import BaseRetriever, Document
class SequentialRetriever(BaseRetriever):
"""Test util that returns a sequence of documents"""
sequential_responses: List[List[Document]]
response_index: int = 0
def _get_relevant_documents( # type: ignore[overri... |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import subprocess
from typing import List
import numpy as np
import pytest
from jina import Document, DocumentArray, Flow
from ...image_tf_encoder import ImageTFEncoder
input_dim = 336
target_output_dim = 1280... | __copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import List
import numpy as np
import pytest
from jina import Flow, Document, DocumentArray
from ...image_tf_encoder import ImageTFEncoder
input_dim = 336
target_output_dim = 1280
@pytest.mark.para... |
from typing import Dict, Iterable
import torch
from torch import Tensor, nn
class MSELoss(nn.Module):
def __init__(self, model):
"""
Computes the MSE loss between the computed sentence embedding and a target sentence embedding. This loss
is used when extending sentence embeddings to new l... | from torch import nn, Tensor
from typing import Iterable, Dict
class MSELoss(nn.Module):
def __init__(self, model):
"""
Computes the MSE loss between the computed sentence embedding and a target sentence embedding. This loss
is used when extending sentence embeddings to new languages as de... |
import subprocess
import pytest
from jina import Document, DocumentArray, Flow
from ...dpr_text import DPRTextEncoder
_EMBEDDING_DIM = 768
@pytest.mark.parametrize('request_size', [1, 10, 50, 100])
def test_integration(request_size: int):
docs = DocumentArray(
[Document(text='just some random text here... | __copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import pytest
from jina import Document, DocumentArray, Flow
from ...dpr_text import DPRTextEncoder
@pytest.mark.parametrize('request_size', [1, 10, 50, 100])
def test_integration(request_size: int):
docs ... |
_base_ = '../_base_/default_runtime.py'
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
# file_client_args = dict(
# backend='petrel',
# path_mapping=dict({
# './data/': 's3://openmmlab/datasets/detection/',
# 'data/': 's3://openmmlab/datasets/detection/'
# }))
fil... | _base_ = '../_base_/default_runtime.py'
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
# file_client_args = dict(
# backend='petrel',
# path_mapping=dict({
# './data/': 's3://openmmlab/datasets/detection/',
# 'data/': 's3://openmmlab/datasets/detection/'
# }))
fil... |
"""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... |
import os
from contextlib import ExitStack
from pathlib import Path
from langchain_community.document_loaders import (
UnstructuredAPIFileIOLoader,
UnstructuredAPIFileLoader,
UnstructuredFileLoader,
)
EXAMPLE_DOCS_DIRECTORY = str(Path(__file__).parent.parent / "examples/")
def test_unstructured_loader_w... | import os
from contextlib import ExitStack
from pathlib import Path
from langchain_community.document_loaders import (
UnstructuredAPIFileIOLoader,
UnstructuredAPIFileLoader,
UnstructuredFileLoader,
)
EXAMPLE_DOCS_DIRECTORY = str(Path(__file__).parent.parent / "examples/")
def test_unstructured_loader_w... |
from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.schema import (
BaseNode,
Document,
ImageDocument,
ImageNode,
IndexNode,
Node,
NodeRelationship,
RelatedNodeInfo,
TextNode,
)
def doc_to_json(doc: BaseNode) -> dict:
return {
DATA_KEY: doc.t... | from llama_index.core.constants import DATA_KEY, TYPE_KEY
from llama_index.core.schema import (
BaseNode,
Document,
ImageDocument,
ImageNode,
IndexNode,
NodeRelationship,
RelatedNodeInfo,
TextNode,
)
def doc_to_json(doc: BaseNode) -> dict:
return {
DATA_KEY: doc.to_dict(),
... |
import time
from functools import partial
from typing import Callable, List, Optional, Tuple
import pandas as pd
from llama_index.core import SimpleDirectoryReader
from llama_index.core.base.embeddings.base import (
DEFAULT_EMBED_BATCH_SIZE,
BaseEmbedding,
)
from llama_index.embeddings import OpenAIEmbedding, ... | import time
from functools import partial
from typing import Callable, List, Optional, Tuple
import pandas as pd
from llama_index.core import SimpleDirectoryReader
from llama_index.core.base.embeddings.base import (
DEFAULT_EMBED_BATCH_SIZE,
BaseEmbedding,
)
from llama_index.embeddings import OpenAIEmbedding, ... |
from langchain_core.agents import AgentAction, AgentFinish
from langchain.agents.output_parsers.react_json_single_input import (
ReActJsonSingleInputOutputParser,
)
def test_action() -> None:
"""Test standard parsing of action/action input."""
parser = ReActJsonSingleInputOutputParser()
_input = """T... | from langchain_core.agents import AgentAction, AgentFinish
from langchain.agents.output_parsers.react_json_single_input import (
ReActJsonSingleInputOutputParser,
)
def test_action() -> None:
"""Test standard parsing of action/action input."""
parser = ReActJsonSingleInputOutputParser()
_input = """T... |
"""Test Perplexity Chat API wrapper."""
from langchain_core.language_models import BaseChatModel
from langchain_tests.unit_tests import ChatModelUnitTests
from langchain_perplexity import ChatPerplexity
class TestPerplexityStandard(ChatModelUnitTests):
@property
def chat_model_class(self) -> type[BaseChatMo... | """Test Perplexity Chat API wrapper."""
from typing import Tuple, Type
from langchain_core.language_models import BaseChatModel
from langchain_tests.unit_tests import ChatModelUnitTests
from langchain_perplexity import ChatPerplexity
class TestPerplexityStandard(ChatModelUnitTests):
@property
def chat_mode... |
from datetime import timedelta
from typing import Optional
from torch._C._distributed_c10d import _DEFAULT_PG_TIMEOUT
__all__ = ["default_pg_timeout", "default_pg_nccl_timeout"]
# Default process group wide timeout, if applicable.
# This only applies to the non-nccl backends
# To make an attempt at backwards compat... | from datetime import timedelta
from typing import Optional
from torch._C._distributed_c10d import _DEFAULT_PG_TIMEOUT
__all__ = ["default_pg_timeout", "default_pg_nccl_timeout"]
# Default process group wide timeout, if applicable.
# This only applies to the non-nccl backends
# To make an attempt at backwards compat... |
# coding: utf-8
"""Comparison of `binary` and `xentropy` objectives.
BLUF: The `xentropy` objective does logistic regression and generalizes
to the case where labels are probabilistic (i.e. numbers between 0 and 1).
Details: Both `binary` and `xentropy` minimize the log loss and use
`boost_from_average = TRUE` by def... | # coding: utf-8
"""Comparison of `binary` and `xentropy` objectives.
BLUF: The `xentropy` objective does logistic regression and generalizes
to the case where labels are probabilistic (i.e. numbers between 0 and 1).
Details: Both `binary` and `xentropy` minimize the log loss and use
`boost_from_average = TRUE` by def... |
import time
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from sentence_transformers.quantization import quantize_embeddings, semantic_search_usearch
# 1. Load the quora corpus with questions
dataset = load_dataset("quora", split="train").map(
lambda batch: {"text": [tex... | import time
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from sentence_transformers.quantization import quantize_embeddings, semantic_search_usearch
# 1. Load the quora corpus with questions
dataset = load_dataset("quora", split="train").map(
lambda batch: {"text": [text... |
"""Sentence Transformer Finetuning Engine."""
import os
from typing import Any, Optional
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.utils import resolve_embed_model
from llama_index.finetuning.embeddings.common import EmbeddingQAFinetuneDataset
from llama_index.fi... | """Sentence Transformer Finetuning Engine."""
import os
from typing import Any, Optional
from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.embeddings.utils import resolve_embed_model
from llama_index.finetuning.embeddings.common import EmbeddingQAFinetuneDataset
from llama_index.fin... |
"""DO NOT EDIT.
This file was autogenerated. Do not edit it by hand,
since your modifications would be overwritten.
"""
from keras.src.ops.nn import average_pool
from keras.src.ops.nn import batch_normalization
from keras.src.ops.nn import binary_crossentropy
from keras.src.ops.nn import categorical_crossentropy
from... | """DO NOT EDIT.
This file was autogenerated. Do not edit it by hand,
since your modifications would be overwritten.
"""
from keras.src.ops.nn import average_pool
from keras.src.ops.nn import batch_normalization
from keras.src.ops.nn import binary_crossentropy
from keras.src.ops.nn import categorical_crossentropy
from... |
"""Interface with the LangChain Hub."""
from __future__ import annotations
import json
from collections.abc import Sequence
from typing import Any, Optional
from langchain_core.load.dump import dumps
from langchain_core.load.load import loads
from langchain_core.prompts import BasePromptTemplate
def _get_client(
... | """Interface with the LangChain Hub."""
from __future__ import annotations
import json
from typing import Any, Optional, Sequence
from langchain_core.load.dump import dumps
from langchain_core.load.load import loads
from langchain_core.prompts import BasePromptTemplate
def _get_client(
api_key: Optional[str] =... |
# Copyright (c) OpenMMLab. All rights reserved.
"""MMEngine provides 11 root registries to support using modules across
projects.
More datails can be found at
https://mmengine.readthedocs.io/en/latest/tutorials/registry.html.
"""
from .registry import Registry, build_runner_from_cfg
# manage all kinds of runners lik... | # Copyright (c) OpenMMLab. All rights reserved.
"""MMEngine provides 11 root registries to support using modules across
projects.
More datails can be found at
https://mmengine.readthedocs.io/en/latest/tutorials/registry.html.
"""
from .registry import Registry
# manage all kinds of runners like `EpochBasedRunner` an... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Optional, Sequence, Tuple
import cv2
import numpy as np
from mmengine.data import BaseDataElement
from mmengine.hooks import Hook
from mmengine.registry import HOOKS
from mmengine.utils.misc import tensor2imgs
# TODO: Due to in... | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Any, Optional, Sequence, Tuple
import cv2
import numpy as np
from mmengine.data import BaseDataElement
from mmengine.hooks import Hook
from mmengine.registry import HOOKS
from mmengine.utils.misc import tensor2imgs
@HOOKS.regis... |
_base_ = './reppoints-moment_r50_fpn-gn_head-gn_1x_coco.py'
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_ = './reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py'
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_ = './mask-rcnn_r101_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,
end... | _base_ = './mask_rcnn_r101_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,
end... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Optional, Sequence, Tuple, Union
import cv2
import numpy as np
from mmengine.hooks import Hook
from mmengine.registry import HOOKS
from mmengine.utils.dl_utils import tensor2imgs
DATA_BATCH = Optional[Union[dict, tuple, list]]
... | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Optional, Sequence, Tuple, Union
import cv2
import numpy as np
from mmengine.hooks import Hook
from mmengine.registry import HOOKS
from mmengine.utils.dl_utils import tensor2imgs
DATA_BATCH = Optional[Union[dict, tuple, list]]
... |
from jina.serve.runtimes.gateway.gateway import BaseGateway
from jina.serve.runtimes.servers.grpc import GRPCServer
__all__ = ['GRPCGateway']
class GRPCGateway(GRPCServer, BaseGateway):
"""
:class:`GRPCGateway` is a GRPCServer that can be loaded from YAML as any other Gateway
"""
pass
| from jina.serve.runtimes.gateway.gateway import BaseGateway
from jina.serve.runtimes.servers.grpc import GRPCServer
__all__ = ['GRPCGateway']
class GRPCGateway(GRPCServer, BaseGateway):
"""
:class:`GRPCGateway` is a GRPCServer that can be loaded from YAML as any other Gateway
"""
pass
|
import gc
import unittest
import torch
from diffusers import (
DDIMScheduler,
StableDiffusionXLImg2ImgPipeline,
)
from diffusers.utils import load_image
from diffusers.utils.testing_utils import (
backend_empty_cache,
enable_full_determinism,
numpy_cosine_similarity_distance,
require_torch_acc... | import gc
import unittest
import torch
from diffusers import (
DDIMScheduler,
StableDiffusionXLImg2ImgPipeline,
)
from diffusers.utils import load_image
from diffusers.utils.testing_utils import (
enable_full_determinism,
numpy_cosine_similarity_distance,
require_torch_gpu,
slow,
)
from .sing... |
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar, Union, cast
import numpy as np
from docarray.typing.abstract_type import AbstractType
if TYPE_CHECKING:
from pydantic.fields import ModelField
from pydantic import BaseConfig
from docarray.proto import NdArrayProto, NodeProto
T = Type... | from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar, Union, cast
import numpy as np
if TYPE_CHECKING:
from pydantic.fields import ModelField
from pydantic import BaseConfig
from docarray.document.base_node import BaseNode
from docarray.proto import NdArrayProto, NodeProto
T = TypeVar('T'... |
from enum import Enum
import pytest
from langchain_core.exceptions import OutputParserException
from langchain.output_parsers.enum import EnumOutputParser
class Colors(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
def test_enum_output_parser_parse() -> None:
parser = EnumOutputParser(enum=Color... | from enum import Enum
from langchain_core.exceptions import OutputParserException
from langchain.output_parsers.enum import EnumOutputParser
class Colors(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
def test_enum_output_parser_parse() -> None:
parser = EnumOutputParser(enum=Colors)
# Test... |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict, Iterable, List, Union
import numpy as np
import tensorflow as tf
from jina import DocumentArray, Executor, requests
from jina.logging.logger import JinaLogger
from jina_commons.batching ... | __copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Iterable, List, Dict
import numpy as np
from jina import DocumentArray, Executor, requests
from jina.logging.logger import JinaLogger
from jina_commons.batching import get_docs_batch_generator... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule, ModuleList
class ConvUpsample(BaseModule):
"""ConvUpsample performs 2x upsampling after Conv.
There are several `ConvModule` layers. In the first few layers, ups... | import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule, ModuleList
class ConvUpsample(BaseModule):
"""ConvUpsample performs 2x upsampling after Conv.
There are several `ConvModule` layers. In the first few layers, upsampling
will be applied after each layer of ... |
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, 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.