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 SimilarityFunction from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = logging.getLogger(__name__) class SparseInformationRetrievalEvaluator(InformationRetrievalEvaluator): def __init__( self, queries: dict[str, str], # qid => query corpus: dict[str, str], # cid => doc relevant_docs: dict[str, set[str]], # qid => Set[cid] corpus_chunk_size: int = 50000, mrr_at_k: list[int] = [10], ndcg_at_k: list[int] = [10], accuracy_at_k: list[int] = [1, 3, 5, 10], precision_recall_at_k: list[int] = [1, 3, 5, 10], map_at_k: list[int] = [100], show_progress_bar: bool = False, batch_size: int = 32, name: str = "", write_csv: bool = True, truncate_dim: int | None = None, score_functions: dict[str, Callable[[Tensor, Tensor], Tensor]] | None = None, main_score_function: str | SimilarityFunction | None = None, query_prompt: str | None = None, query_prompt_name: str | None = None, corpus_prompt: str | None = None, corpus_prompt_name: str | None = None, ) -> None: return super().__init__( queries=queries, corpus=corpus, relevant_docs=relevant_docs, corpus_chunk_size=corpus_chunk_size, mrr_at_k=mrr_at_k, ndcg_at_k=ndcg_at_k, accuracy_at_k=accuracy_at_k, precision_recall_at_k=precision_recall_at_k, map_at_k=map_at_k, show_progress_bar=show_progress_bar, batch_size=batch_size, name=name, write_csv=write_csv, truncate_dim=truncate_dim, score_functions=score_functions, main_score_function=main_score_function, query_prompt=query_prompt, query_prompt_name=query_prompt_name, corpus_prompt=corpus_prompt, corpus_prompt_name=corpus_prompt_name, ) def __call__( self, model: SparseEncoder, output_path: str = None, epoch: int = -1, steps: int = -1, *args, **kwargs ) -> dict[str, float]: return super().__call__(model=model, output_path=output_path, epoch=epoch, steps=steps, *args, **kwargs) def compute_metrices( self, model: SparseEncoder, corpus_model=None, corpus_embeddings: Tensor | None = None ) -> dict[str, float]: return super().compute_metrices(model=model, corpus_model=corpus_model, corpus_embeddings=corpus_embeddings) def embed_inputs( self, model: SparseEncoder, sentences: str | list[str] | np.ndarray, prompt_name: str | None = None, prompt: str | None = None, **kwargs, ) -> Tensor: kwargs["truncate_dim"] = self.truncate_dim embeddings = model.encode( sentences, prompt_name=prompt_name, prompt=prompt, batch_size=self.batch_size, show_progress_bar=self.show_progress_bar, convert_to_sparse_tensor=True, save_on_cpu=True, **kwargs, ) sparsity_infos = model.get_sparsity_stats(embeddings) if sparsity_infos["num_rows"] == self.queries_info["num_rows"] and "num_cols" not in self.queries_info.keys(): self.queries_info.update( { "num_cols": sparsity_infos["num_cols"], "row_non_zero_mean": sparsity_infos["row_non_zero_mean"], "row_sparsity_mean": sparsity_infos["row_sparsity_mean"], } ) else: self.corpus_info.update( { "num_cols": sparsity_infos["num_cols"], "row_non_zero_mean": sparsity_infos["row_non_zero_mean"], "row_sparsity_mean": sparsity_infos["row_sparsity_mean"], } ) return embeddings def store_metrics_in_model_card_data( self, model: SparseEncoder, metrics: dict[str, Any], epoch: int = 0, step: int = 0 ) -> None: model.model_card_data.set_evaluation_metrics(self, metrics, epoch=epoch, step=step)
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 SimilarityFunction from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = logging.getLogger(__name__) class SparseInformationRetrievalEvaluator(InformationRetrievalEvaluator): def __init__( self, queries: dict[str, str], # qid => query corpus: dict[str, str], # cid => doc relevant_docs: dict[str, set[str]], # qid => Set[cid] corpus_chunk_size: int = 50000, mrr_at_k: list[int] = [10], ndcg_at_k: list[int] = [10], accuracy_at_k: list[int] = [1, 3, 5, 10], precision_recall_at_k: list[int] = [1, 3, 5, 10], map_at_k: list[int] = [100], show_progress_bar: bool = False, batch_size: int = 32, name: str = "", write_csv: bool = True, truncate_dim: int | None = None, score_functions: dict[str, Callable[[Tensor, Tensor], Tensor]] | None = None, main_score_function: str | SimilarityFunction | None = None, query_prompt: str | None = None, query_prompt_name: str | None = None, corpus_prompt: str | None = None, corpus_prompt_name: str | None = None, ) -> None: return super().__init__( queries=queries, corpus=corpus, relevant_docs=relevant_docs, corpus_chunk_size=corpus_chunk_size, mrr_at_k=mrr_at_k, ndcg_at_k=ndcg_at_k, accuracy_at_k=accuracy_at_k, precision_recall_at_k=precision_recall_at_k, map_at_k=map_at_k, show_progress_bar=show_progress_bar, batch_size=batch_size, name=name, write_csv=write_csv, truncate_dim=truncate_dim, score_functions=score_functions, main_score_function=main_score_function, query_prompt=query_prompt, query_prompt_name=query_prompt_name, corpus_prompt=corpus_prompt, corpus_prompt_name=corpus_prompt_name, ) def __call__( self, model: SparseEncoder, output_path: str = None, epoch: int = -1, steps: int = -1, *args, **kwargs ) -> dict[str, float]: return super().__call__(model=model, output_path=output_path, epoch=epoch, steps=steps, *args, **kwargs) def compute_metrices( self, model: SparseEncoder, corpus_model=None, corpus_embeddings: Tensor | None = None ) -> dict[str, float]: return super().compute_metrices(model=model, corpus_model=corpus_model, corpus_embeddings=corpus_embeddings) def embed_inputs( self, model: SparseEncoder, sentences: str | list[str] | np.ndarray, prompt_name: str | None = None, prompt: str | None = None, **kwargs, ) -> Tensor: kwargs["truncate_dim"] = self.truncate_dim return model.encode( sentences, prompt_name=prompt_name, prompt=prompt, batch_size=self.batch_size, show_progress_bar=self.show_progress_bar, convert_to_sparse_tensor=True, save_on_cpu=True, **kwargs, ) def store_metrics_in_model_card_data( self, model: SparseEncoder, metrics: dict[str, Any], epoch: int = 0, step: int = 0 ) -> None: model.model_card_data.set_evaluation_metrics(self, metrics, epoch=epoch, step=step)
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_start: int = 4, layer_weights=None ): super(WeightedLayerPooling, self).__init__() self.config_keys = ["word_embedding_dimension", "layer_start", "num_hidden_layers"] self.word_embedding_dimension = word_embedding_dimension self.layer_start = layer_start self.num_hidden_layers = num_hidden_layers self.layer_weights = ( layer_weights if layer_weights is not None else nn.Parameter(torch.tensor([1] * (num_hidden_layers + 1 - layer_start), dtype=torch.float)) ) def forward(self, features: Dict[str, Tensor]): ft_all_layers = features["all_layer_embeddings"] all_layer_embedding = torch.stack(ft_all_layers) all_layer_embedding = all_layer_embedding[self.layer_start :, :, :, :] # Start from 4th layers output weight_factor = self.layer_weights.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).expand(all_layer_embedding.size()) weighted_average = (weight_factor * all_layer_embedding).sum(dim=0) / self.layer_weights.sum() features.update({"token_embeddings": weighted_average}) return features def get_word_embedding_dimension(self): return self.word_embedding_dimension def get_config_dict(self): return {key: self.__dict__[key] for key in self.config_keys} def save(self, output_path): with open(os.path.join(output_path, "config.json"), "w") as fOut: json.dump(self.get_config_dict(), fOut, indent=2) torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin")) @staticmethod def load(input_path): with open(os.path.join(input_path, "config.json")) as fIn: config = json.load(fIn) model = WeightedLayerPooling(**config) model.load_state_dict( torch.load(os.path.join(input_path, "pytorch_model.bin"), map_location=torch.device("cpu")) ) return model
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_dimension, num_hidden_layers: int = 12, layer_start: int = 4, layer_weights = None): super(WeightedLayerPooling, self).__init__() self.config_keys = ['word_embedding_dimension', 'layer_start', 'num_hidden_layers'] self.word_embedding_dimension = word_embedding_dimension self.layer_start = layer_start self.num_hidden_layers = num_hidden_layers self.layer_weights = layer_weights if layer_weights is not None else nn.Parameter(torch.tensor([1] * (num_hidden_layers+1 - layer_start), dtype=torch.float)) def forward(self, features: Dict[str, Tensor]): ft_all_layers = features['all_layer_embeddings'] all_layer_embedding = torch.stack(ft_all_layers) all_layer_embedding = all_layer_embedding[self.layer_start:, :, :, :] # Start from 4th layers output weight_factor = self.layer_weights.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).expand(all_layer_embedding.size()) weighted_average = (weight_factor*all_layer_embedding).sum(dim=0) / self.layer_weights.sum() features.update({'token_embeddings': weighted_average}) return features def get_word_embedding_dimension(self): return self.word_embedding_dimension def get_config_dict(self): return {key: self.__dict__[key] for key in self.config_keys} def save(self, output_path): with open(os.path.join(output_path, 'config.json'), 'w') as fOut: json.dump(self.get_config_dict(), fOut, indent=2) torch.save(self.state_dict(), os.path.join(output_path, 'pytorch_model.bin')) @staticmethod def load(input_path): with open(os.path.join(input_path, 'config.json')) as fIn: config = json.load(fIn) model = WeightedLayerPooling(**config) model.load_state_dict(torch.load(os.path.join(input_path, 'pytorch_model.bin'), map_location=torch.device('cpu'))) return model
# 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/output type to a FX node.""" return isinstance(val, torch.fx.node.base_types) def is_graphable_type(typ) -> bool: """Return whether the given type is graphable""" return issubclass(typ, torch.fx.node.base_types) def to_graphable(stuff): """Flattens stuff into a flat list of graphable types.""" # We can consider preserving things like List[int] to improve # perf and readability (right now that is all flattened out) flat_args, spec = pytree.tree_flatten(stuff) for arg in flat_args: if not is_graphable(arg): raise RuntimeError( f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found " f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as " f"via pytree.register_constant; otherwise, register it as a pytree." ) return flat_args, spec def from_graphable(flat_args, spec): """The inverse of to_graphable.""" stuff = pytree.tree_unflatten(flat_args, spec) return stuff def func_to_graphable(func): """ Pack and flatten a function type into graphable types. This is useful for legalizing the function argument of `flat_apply`. """ return pytree.tree_flatten(_ConstantFunction(func)) @dataclass(frozen=True) class _ConstantFunction: func: Callable def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) pytree.register_constant(_ConstantFunction) _op_types = ( torch._ops.OpOverload, torch._ops.OpOverloadPacket, torch._ops.HigherOrderOperator, ) class FlatApply(HigherOrderOperator): def __init__(self) -> None: super().__init__("flat_apply") def __call__(self, func, in_spec, *flat_args, **_unused): """ Functions that take in non-graphable types cannot directly be put into FX graph. Given func(*args, **kwargs), if all of the non-graphable types are pytrees, then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph. The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to: >>> def flat_apply_impl(func, in_spec, *flat_args): >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec) >>> output = func(*args, **kwargs) >>> return output flat_apply supports the following two cases: - an input type is a container type (e.g. of tensors) registered as a pytree. We'll tree_flatten the input type and store the spec. - an input type is a constant type (i.e. torch.compile will specialize on it) registered with pytree.register_constant. The constant type goes directly into the spec. """ assert isinstance(func, _op_types) or pytree._is_constant_holder(func) assert len(_unused) == 0 return impl(func, in_spec, *flat_args) def impl(func, in_spec, *flat_args): if not isinstance(func, _op_types): # assume _ConstantFunction func = pytree._retrieve_constant(func) assert isinstance(func, _ConstantFunction) args, kwargs = from_graphable(flat_args, in_spec) out = func(*args, **kwargs) # Right now, all outputs must either be graphable or lists/tuples of graphables. # # TODO: The following can be updated to support non-graphable outputs and pytrees. # For non-graphable constant outputs: the assumption would be that they are constant # (everytime the function runs those MUST be the same) # For pytree outputs: # I'm not sure if we need to return (flat_output, spec) or just (flat_output,): # in the latter case the tracers need to carry out the output specs # (they need to know how to reconstruct the object from just the flat_output). def is_valid_output(x): if isinstance(x, (tuple, list)): return all(map(is_valid_output, x)) return is_graphable(x) assert is_valid_output(out) return out flat_apply = FlatApply()
# 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/output type to a FX node.""" return isinstance(val, torch.fx.node.base_types) def is_graphable_type(typ) -> bool: """Return whether the given type is graphable""" return issubclass(typ, torch.fx.node.base_types) def to_graphable(stuff): """Flattens stuff into a flat list of graphable types.""" # We can consider preserving things like List[int] to improve # perf and readability (right now that is all flattened out) flat_args, spec = pytree.tree_flatten(stuff) for arg in flat_args: if not is_graphable(arg): raise RuntimeError( f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found " f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as " f"via pytree.register_constant; otherwise, register it as a pytree." ) return flat_args, spec def from_graphable(flat_args, spec): """The inverse of to_graphable.""" stuff = pytree.tree_unflatten(flat_args, spec) return stuff def func_to_graphable(func): """ Pack and flatten a function type into graphable types. This is useful for legalizing the function argument of `flat_apply`. """ return pytree.tree_flatten(_ConstantFunction(func)) @dataclass(frozen=True) class _ConstantFunction: func: Callable def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) pytree.register_constant(_ConstantFunction) _op_types = ( torch._ops.OpOverload, torch._ops.OpOverloadPacket, torch._ops.HigherOrderOperator, ) class FlatApply(HigherOrderOperator): def __init__(self) -> None: super().__init__("flat_apply") def __call__(self, func, in_spec, *flat_args, **_unused): """ Functions that take in non-graphable types cannot directly be put into FX graph. Given func(*args, **kwargs), if all of the non-graphable types are pytrees, then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph. The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to: >>> def flat_apply_impl(func, in_spec, *flat_args): >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec) >>> output = func(*args, **kwargs) >>> return output flat_apply supports the following two cases: - an input type is a container type (e.g. of tensors) registered as a pytree. We'll tree_flatten the input type and store the spec. - an input type is a constant type (i.e. torch.compile will specialize on it) registered with pytree.register_constant. The constant type goes directly into the spec. """ assert isinstance(func, _op_types) or pytree._is_constant_holder(func) assert len(_unused) == 0 return impl(func, in_spec, *flat_args) def impl(func, in_spec, *flat_args): if not isinstance(func, _op_types): # assume _ConstantFunction func = pytree._retrieve_constant(func) assert isinstance(func, _ConstantFunction) args, kwargs = from_graphable(flat_args, in_spec) out = func(*args, **kwargs) # Right now, all outputs must either be graphable or lists/tuples of graphables. # # TODO: The following can be updated to support non-graphable outputs and pytrees. # For non-graphable constant outputs: the assumption would be that they are constant # (every time the function runs those MUST be the same) # For pytree outputs: # I'm not sure if we need to return (flat_output, spec) or just (flat_output,): # in the latter case the tracers need to carry out the output specs # (they need to know how to reconstruct the object from just the flat_output). def is_valid_output(x): if isinstance(x, (tuple, list)): return all(map(is_valid_output, x)) return is_graphable(x) assert is_valid_output(out) return out flat_apply = FlatApply()
# 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 MMDataParallel, MMDistributedDataParallel from .setup_env import register_all_modules, setup_multi_processes from .split_batch import split_batch from .util_distribution import build_ddp, build_dp, get_device __all__ = [ 'get_root_logger', 'collect_env', 'find_latest_checkpoint', 'update_data_root', 'setup_multi_processes', 'get_caller_name', 'log_img_scale', 'compat_cfg', 'split_batch', 'build_ddp', 'build_dp', 'get_device', 'MMDataParallel', 'MMDistributedDataParallel', 'register_all_modules' ]
# 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 import replace_cfg_vals from .setup_env import setup_multi_processes from .split_batch import split_batch from .util_distribution import build_ddp, build_dp, get_device __all__ = [ 'get_root_logger', 'collect_env', 'find_latest_checkpoint', 'update_data_root', 'setup_multi_processes', 'get_caller_name', 'log_img_scale', 'compat_cfg', 'split_batch', 'build_ddp', 'build_dp', 'get_device', 'replace_cfg_vals', 'AvoidOOM', 'AvoidCUDAOOM' ]
# 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 file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import uuid import pytest import qdrant_client from docarray.index import QdrantDocumentIndex cur_dir = os.path.dirname(os.path.abspath(__file__)) qdrant_yml = os.path.abspath(os.path.join(cur_dir, "docker-compose.yml")) @pytest.fixture(scope="session", autouse=True) def start_storage(): os.system(f"docker compose -f {qdrant_yml} up -d --remove-orphans") time.sleep(1) yield os.system(f"docker compose -f {qdrant_yml} down --remove-orphans") @pytest.fixture(scope="function") def tmp_collection_name(): return uuid.uuid4().hex @pytest.fixture def qdrant() -> qdrant_client.QdrantClient: """This fixture takes care of removing the collection before each test case""" client = qdrant_client.QdrantClient(path="/tmp/qdrant-local") for collection in client.get_collections().collections: client.delete_collection(collection.name) return client @pytest.fixture def qdrant_config(qdrant) -> QdrantDocumentIndex.DBConfig: return QdrantDocumentIndex.DBConfig(path=qdrant._client.location)
# 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 file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import uuid import pytest import qdrant_client from docarray.index import QdrantDocumentIndex cur_dir = os.path.dirname(os.path.abspath(__file__)) qdrant_yml = os.path.abspath(os.path.join(cur_dir, 'docker-compose.yml')) @pytest.fixture(scope='session', autouse=True) def start_storage(): os.system(f"docker-compose -f {qdrant_yml} up -d --remove-orphans") time.sleep(1) yield os.system(f"docker-compose -f {qdrant_yml} down --remove-orphans") @pytest.fixture(scope='function') def tmp_collection_name(): return uuid.uuid4().hex @pytest.fixture def qdrant() -> qdrant_client.QdrantClient: """This fixture takes care of removing the collection before each test case""" client = qdrant_client.QdrantClient(path='/tmp/qdrant-local') for collection in client.get_collections().collections: client.delete_collection(collection.name) return client @pytest.fixture def qdrant_config(qdrant) -> QdrantDocumentIndex.DBConfig: return QdrantDocumentIndex.DBConfig(path=qdrant._client.location)
"""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 ( render_text_description, render_text_description_and_args, ) from langchain_core.utils.function_calling import ( format_tool_to_openai_function, format_tool_to_openai_tool, ) __all__ = [ "format_tool_to_openai_function", "format_tool_to_openai_tool", "render_text_description", "render_text_description_and_args", ]
"""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 ( render_text_description, render_text_description_and_args, ) from langchain_core.utils.function_calling import ( format_tool_to_openai_function, format_tool_to_openai_tool, ) __all__ = [ "render_text_description", "render_text_description_and_args", "format_tool_to_openai_tool", "format_tool_to_openai_function", ]
"""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. Please use " "<https://smith.langchain.com/hub> instead." ), ) def try_load_from_hub( *args: Any, **kwargs: Any, ) -> Any: """[DEPRECATED] Try to load from the old Hub.""" warnings.warn( "Loading from the deprecated github-based Hub is no longer supported. " "Please use the new LangChain Hub at https://smith.langchain.com/hub instead.", DeprecationWarning, stacklevel=2, ) # return None, which indicates that we shouldn't load from old hub # and might just be a filepath for e.g. load_chain return None
"""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. Please use " "<https://smith.langchain.com/hub> instead." ), ) def try_load_from_hub( *args: Any, **kwargs: Any, ) -> Any: warnings.warn( "Loading from the deprecated github-based Hub is no longer supported. " "Please use the new LangChain Hub at https://smith.langchain.com/hub instead.", DeprecationWarning, stacklevel=2, ) # return None, which indicates that we shouldn't load from old hub # and might just be a filepath for e.g. load_chain return None
_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), dict( type='MultiStepLR', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ] train_cfg = dict(max_epochs=max_epochs) optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2))
_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), dict( type='MultiStepLR', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ] train_cfg = dict(max_epochs=max_epochs) optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2))
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.getLogger(__name__) M = TypeVar("M", bound=BaseModel) class BaseRedisEventBus(Generic[M], ABC): Model: type[M] @property @abstractmethod def event_bus_name(self) -> str: pass @property def Message(self) -> type["_EventPayloadWrapper[M]"]: return _EventPayloadWrapper[self.Model] def _serialize_message(self, item: M, channel_key: str) -> tuple[str, str]: message = self.Message(payload=item).model_dump_json() channel_name = f"{self.event_bus_name}/{channel_key}" logger.debug(f"[{channel_name}] Publishing an event to Redis {message}") return message, channel_name def _deserialize_message(self, msg: Any, channel_key: str) -> M | None: message_type = "pmessage" if "*" in channel_key else "message" if msg["type"] != message_type: return None try: logger.debug(f"[{channel_key}] Consuming an event from Redis {msg['data']}") return self.Message.model_validate_json(msg["data"]).payload except Exception as e: logger.error(f"Failed to parse event result from Redis {msg} {e}") def _get_pubsub_channel( self, connection: redis.Redis | redis.AsyncRedis, channel_key: str ) -> tuple[PubSub | AsyncPubSub, str]: full_channel_name = f"{self.event_bus_name}/{channel_key}" pubsub = connection.pubsub() return pubsub, full_channel_name class _EventPayloadWrapper(BaseModel, Generic[M]): """ Wrapper model to allow `RedisEventBus.Model` to be a discriminated union of multiple event types. """ payload: M class RedisEventBus(BaseRedisEventBus[M], ABC): @property def connection(self) -> redis.Redis: return redis.get_redis() def publish_event(self, event: M, channel_key: str): message, full_channel_name = self._serialize_message(event, channel_key) self.connection.publish(full_channel_name, message) def listen_events(self, channel_key: str) -> Generator[M, None, None]: pubsub, full_channel_name = self._get_pubsub_channel( self.connection, channel_key ) assert isinstance(pubsub, PubSub) if "*" in channel_key: pubsub.psubscribe(full_channel_name) else: pubsub.subscribe(full_channel_name) for message in pubsub.listen(): if event := self._deserialize_message(message, channel_key): yield event class AsyncRedisEventBus(BaseRedisEventBus[M], ABC): @property async def connection(self) -> redis.AsyncRedis: return await redis.get_redis_async() async def publish_event(self, event: M, channel_key: str): message, full_channel_name = self._serialize_message(event, channel_key) connection = await self.connection await connection.publish(full_channel_name, message) async def listen_events(self, channel_key: str) -> AsyncGenerator[M, None]: pubsub, full_channel_name = self._get_pubsub_channel( await self.connection, channel_key ) assert isinstance(pubsub, AsyncPubSub) if "*" in channel_key: await pubsub.psubscribe(full_channel_name) else: await pubsub.subscribe(full_channel_name) async for message in pubsub.listen(): if event := self._deserialize_message(message, channel_key): yield event async def wait_for_event( self, channel_key: str, timeout: Optional[float] = None ) -> M | None: try: return await asyncio.wait_for( anext(aiter(self.listen_events(channel_key))), timeout ) except TimeoutError: return None
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.data import redis logger = logging.getLogger(__name__) class DateTimeEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime): return o.isoformat() return super().default(o) M = TypeVar("M", bound=BaseModel) class BaseRedisEventBus(Generic[M], ABC): Model: type[M] @property @abstractmethod def event_bus_name(self) -> str: pass def _serialize_message(self, item: M, channel_key: str) -> tuple[str, str]: message = json.dumps(item.model_dump(), cls=DateTimeEncoder) channel_name = f"{self.event_bus_name}/{channel_key}" logger.debug(f"[{channel_name}] Publishing an event to Redis {message}") return message, channel_name def _deserialize_message(self, msg: Any, channel_key: str) -> M | None: message_type = "pmessage" if "*" in channel_key else "message" if msg["type"] != message_type: return None try: data = json.loads(msg["data"]) logger.debug(f"Consuming an event from Redis {data}") return self.Model(**data) except Exception as e: logger.error(f"Failed to parse event result from Redis {msg} {e}") def _get_pubsub_channel( self, connection: redis.Redis | redis.AsyncRedis, channel_key: str ) -> tuple[PubSub | AsyncPubSub, str]: full_channel_name = f"{self.event_bus_name}/{channel_key}" pubsub = connection.pubsub() return pubsub, full_channel_name class RedisEventBus(BaseRedisEventBus[M], ABC): Model: type[M] @property def connection(self) -> redis.Redis: return redis.get_redis() def publish_event(self, event: M, channel_key: str): message, full_channel_name = self._serialize_message(event, channel_key) self.connection.publish(full_channel_name, message) def listen_events(self, channel_key: str) -> Generator[M, None, None]: pubsub, full_channel_name = self._get_pubsub_channel( self.connection, channel_key ) assert isinstance(pubsub, PubSub) if "*" in channel_key: pubsub.psubscribe(full_channel_name) else: pubsub.subscribe(full_channel_name) for message in pubsub.listen(): if event := self._deserialize_message(message, channel_key): yield event class AsyncRedisEventBus(BaseRedisEventBus[M], ABC): Model: type[M] @property async def connection(self) -> redis.AsyncRedis: return await redis.get_redis_async() async def publish_event(self, event: M, channel_key: str): message, full_channel_name = self._serialize_message(event, channel_key) connection = await self.connection await connection.publish(full_channel_name, message) async def listen_events(self, channel_key: str) -> AsyncGenerator[M, None]: pubsub, full_channel_name = self._get_pubsub_channel( await self.connection, channel_key ) assert isinstance(pubsub, AsyncPubSub) if "*" in channel_key: await pubsub.psubscribe(full_channel_name) else: await pubsub.subscribe(full_channel_name) async for message in pubsub.listen(): if event := self._deserialize_message(message, channel_key): yield event async def wait_for_event( self, channel_key: str, timeout: Optional[float] = None ) -> M | None: try: return await asyncio.wait_for( anext(aiter(self.listen_events(channel_key))), timeout ) except TimeoutError: return None
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 AudioBytes T = TypeVar('T', bound='AbstractAudioTensor') MAX_INT_16 = 2**15 class AbstractAudioTensor(AbstractTensor, ABC): def to_bytes(self) -> 'AudioBytes': """ Convert audio tensor to [`AudioBytes`][docarray.typrin.AudioBytes]. """ from docarray.typing.bytes.audio_bytes import AudioBytes tensor = self.get_comp_backend().to_numpy(self) tensor = (tensor * MAX_INT_16).astype('<h') return AudioBytes(tensor.tobytes()) def save( self: 'T', file_path: Union[str, BinaryIO], format: str = 'wav', frame_rate: int = 44100, sample_width: int = 2, pydub_args: Dict[str, Any] = {}, ) -> None: """ Save audio tensor to an audio file. Mono/stereo is preserved. :param file_path: path to an audio file. If file is a string, open the file by that name, otherwise treat it as a file-like object. :param format: format for the audio file ('mp3', 'wav', 'raw', 'ogg' or other ffmpeg/avconv supported files) :param frame_rate: sampling frequency :param sample_width: sample width in bytes :param pydub_args: dictionary of additional arguments for pydub.AudioSegment.export function """ pydub = import_library('pydub', raise_error=True) # noqa: F841 from pydub import AudioSegment comp_backend = self.get_comp_backend() channels = 2 if comp_backend.n_dim(array=self) > 1 else 1 # type: ignore segment = AudioSegment( self.to_bytes(), frame_rate=frame_rate, sample_width=sample_width, channels=channels, ) segment.export(file_path, format=format, **pydub_args) def display(self, rate=44100): """ Play audio data from tensor in notebook. """ if is_notebook(): from IPython.display import Audio, display audio_np = self.get_comp_backend().to_numpy(self) display(Audio(audio_np, rate=rate)) else: warnings.warn('Display of audio is only possible in a notebook.')
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 AudioBytes T = TypeVar('T', bound='AbstractAudioTensor') MAX_INT_16 = 2**15 class AbstractAudioTensor(AbstractTensor, ABC): def to_bytes(self) -> 'AudioBytes': """ Convert audio tensor to AudioBytes. """ from docarray.typing.bytes.audio_bytes import AudioBytes tensor = self.get_comp_backend().to_numpy(self) tensor = (tensor * MAX_INT_16).astype('<h') return AudioBytes(tensor.tobytes()) def save( self: 'T', file_path: Union[str, BinaryIO], format: str = 'wav', frame_rate: int = 44100, sample_width: int = 2, pydub_args: Dict[str, Any] = {}, ) -> None: """ Save audio tensor to an audio file. Mono/stereo is preserved. :param file_path: path to an audio file. If file is a string, open the file by that name, otherwise treat it as a file-like object. :param format: format for the audio file ('mp3', 'wav', 'raw', 'ogg' or other ffmpeg/avconv supported files) :param frame_rate: sampling frequency :param sample_width: sample width in bytes :param pydub_args: dictionary of additional arguments for pydub.AudioSegment.export function """ pydub = import_library('pydub', raise_error=True) # noqa: F841 from pydub import AudioSegment comp_backend = self.get_comp_backend() channels = 2 if comp_backend.n_dim(array=self) > 1 else 1 # type: ignore segment = AudioSegment( self.to_bytes(), frame_rate=frame_rate, sample_width=sample_width, channels=channels, ) segment.export(file_path, format=format, **pydub_args) def display(self, rate=44100): """ Play audio data from tensor in notebook. """ if is_notebook(): from IPython.display import Audio, display audio_np = self.get_comp_backend().to_numpy(self) display(Audio(audio_np, rate=rate)) else: warnings.warn('Display of audio is only possible in a notebook.')
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), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')))
_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), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')))
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 TOYDATA_DIR LOCAL_AUDIO_FILES = [ str(TOYDATA_DIR / 'hello.wav'), str(TOYDATA_DIR / 'olleh.wav'), ] REMOTE_AUDIO_FILE = 'https://github.com/docarray/docarray/blob/feat-rewrite-v2/tests/toydata/olleh.wav?raw=true' # noqa: E501 @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_audio(file_url): audio = Audio(url=file_url) audio.tensor = audio.url.load() assert isinstance(audio.tensor, np.ndarray) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_save_audio_ndarray(file_url, tmpdir): tmp_file = str(tmpdir / 'tmp.wav') audio = Audio(url=file_url) audio.tensor = audio.url.load() assert isinstance(audio.tensor, np.ndarray) assert isinstance(audio.tensor, AudioNdArray) audio.tensor.save_to_wav_file(tmp_file) assert os.path.isfile(tmp_file) audio_from_file = Audio(url=tmp_file) audio_from_file.tensor = audio_from_file.url.load() assert np.allclose(audio.tensor, audio_from_file.tensor) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_save_audio_torch_tensor(file_url, tmpdir): tmp_file = str(tmpdir / 'tmp.wav') audio = Audio(url=file_url) audio.tensor = parse_obj_as(AudioTorchTensor, torch.from_numpy(audio.url.load())) assert isinstance(audio.tensor, torch.Tensor) assert isinstance(audio.tensor, AudioTorchTensor) audio.tensor.save_to_wav_file(tmp_file) assert os.path.isfile(tmp_file) audio_from_file = Audio(url=tmp_file) audio_from_file.tensor = parse_obj_as( AudioTorchTensor, torch.from_numpy(audio_from_file.url.load()) ) assert torch.allclose(audio.tensor, audio_from_file.tensor) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE], ) def test_extend_audio(file_url): class MyAudio(Audio): title: str tensor: Optional[AudioNdArray] my_audio = MyAudio(title='my extended audio', url=file_url) my_audio.tensor = parse_obj_as(AudioNdArray, my_audio.url.load()) assert isinstance(my_audio.tensor, AudioNdArray) assert isinstance(my_audio.url, AudioUrl) def test_audio_np(): audio = parse_obj_as(Audio, np.zeros((10, 10, 3))) assert (audio.tensor == np.zeros((10, 10, 3))).all() def test_audio_torch(): audio = parse_obj_as(Audio, torch.zeros(10, 10, 3)) assert (audio.tensor == torch.zeros(10, 10, 3)).all() def test_audio_shortcut_doc(): class MyDoc(BaseDocument): audio: Audio audio2: Audio audio3: Audio doc = MyDoc( audio='http://myurl.wav', audio2=np.zeros((10, 10, 3)), audio3=torch.zeros(10, 10, 3), ) assert doc.audio.url == 'http://myurl.wav' assert (doc.audio2.tensor == np.zeros((10, 10, 3))).all() assert (doc.audio3.tensor == torch.zeros(10, 10, 3)).all()
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 = [ str(TOYDATA_DIR / 'hello.wav'), str(TOYDATA_DIR / 'olleh.wav'), ] REMOTE_AUDIO_FILE = 'https://github.com/docarray/docarray/blob/feat-rewrite-v2/tests/toydata/olleh.wav?raw=true' # noqa: E501 @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_audio(file_url): audio = Audio(url=file_url) audio.tensor = audio.url.load() assert isinstance(audio.tensor, np.ndarray) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_save_audio_ndarray(file_url, tmpdir): tmp_file = str(tmpdir / 'tmp.wav') audio = Audio(url=file_url) audio.tensor = audio.url.load() assert isinstance(audio.tensor, np.ndarray) assert isinstance(audio.tensor, AudioNdArray) audio.tensor.save_to_wav_file(tmp_file) assert os.path.isfile(tmp_file) audio_from_file = Audio(url=tmp_file) audio_from_file.tensor = audio_from_file.url.load() assert np.allclose(audio.tensor, audio_from_file.tensor) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize('file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE]) def test_save_audio_torch_tensor(file_url, tmpdir): tmp_file = str(tmpdir / 'tmp.wav') audio = Audio(url=file_url) audio.tensor = parse_obj_as(AudioTorchTensor, torch.from_numpy(audio.url.load())) assert isinstance(audio.tensor, torch.Tensor) assert isinstance(audio.tensor, AudioTorchTensor) audio.tensor.save_to_wav_file(tmp_file) assert os.path.isfile(tmp_file) audio_from_file = Audio(url=tmp_file) audio_from_file.tensor = parse_obj_as( AudioTorchTensor, torch.from_numpy(audio_from_file.url.load()) ) assert torch.allclose(audio.tensor, audio_from_file.tensor) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_url', [*LOCAL_AUDIO_FILES, REMOTE_AUDIO_FILE], ) def test_extend_audio(file_url): class MyAudio(Audio): title: str tensor: Optional[AudioNdArray] my_audio = MyAudio(title='my extended audio', url=file_url) my_audio.tensor = parse_obj_as(AudioNdArray, my_audio.url.load()) assert isinstance(my_audio.tensor, AudioNdArray) assert isinstance(my_audio.url, AudioUrl)
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={ "activation": "relu", }, input_shape=(2, 3), expected_output_shape=(2, 3), expected_num_trainable_weights=0, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=True, assert_built_after_instantiation=True, ) self.run_layer_test( layers.Activation, init_kwargs={ "activation": activations.gelu, }, input_shape=(2, 2), expected_output_shape=(2, 2), expected_num_trainable_weights=0, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=True, assert_built_after_instantiation=True, )
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={ "activation": "relu", }, input_shape=(2, 3), expected_output_shape=(2, 3), expected_num_trainable_weights=0, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=True, ) self.run_layer_test( layers.Activation, init_kwargs={ "activation": activations.gelu, }, input_shape=(2, 2), expected_output_shape=(2, 2), expected_num_trainable_weights=0, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=True, )
_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) audio_path = os.path.join(os.path.dirname(__file__), "jfk.flac") language = "en" if model_name.endswith(".en") else None result = model.transcribe( audio_path, language=language, temperature=0.0, word_timestamps=True ) assert result["language"] == "en" assert result["text"] == "".join([s["text"] for s in result["segments"]]) transcription = result["text"].lower() assert "my fellow americans" in transcription assert "your country" in transcription assert "do for you" in transcription tokenizer = get_tokenizer(model.is_multilingual, num_languages=model.num_languages) all_tokens = [t for s in result["segments"] for t in s["tokens"]] assert tokenizer.decode(all_tokens) == result["text"] assert tokenizer.decode_with_timestamps(all_tokens).startswith("<|0.00|>") timing_checked = False for segment in result["segments"]: for timing in segment["words"]: assert timing["start"] < timing["end"] if timing["word"].strip(" ,") == "Americans": assert timing["start"] <= 1.8 assert timing["end"] >= 1.8 timing_checked = True assert timing_checked
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) audio_path = os.path.join(os.path.dirname(__file__), "jfk.flac") language = "en" if model_name.endswith(".en") else None result = model.transcribe( audio_path, language=language, temperature=0.0, word_timestamps=True ) assert result["language"] == "en" assert result["text"] == "".join([s["text"] for s in result["segments"]]) transcription = result["text"].lower() assert "my fellow americans" in transcription assert "your country" in transcription assert "do for you" in transcription tokenizer = get_tokenizer(model.is_multilingual) all_tokens = [t for s in result["segments"] for t in s["tokens"]] assert tokenizer.decode(all_tokens) == result["text"] assert tokenizer.decode_with_timestamps(all_tokens).startswith("<|0.00|>") timing_checked = False for segment in result["segments"]: for timing in segment["words"]: assert timing["start"] < timing["end"] if timing["word"].strip(" ,") == "Americans": assert timing["start"] <= 1.8 assert timing["end"] >= 1.8 timing_checked = True assert timing_checked
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 " "calling the underlying implementation directly.", stacklevel=2, ) from . import _sox_io_backend return getattr(_sox_io_backend, name)
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 " "calling the udnerlying implementation directly.", stacklevel=2, ) from . import _sox_io_backend return getattr(_sox_io_backend, name)
_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 docarray.typing import NdArray, TorchTensor from tests.index.weaviate.fixture_weaviate import ( # noqa: F401 start_storage, weaviate_client, ) pytestmark = [pytest.mark.slow, pytest.mark.index] def test_find_torch(weaviate_client): class TorchDoc(BaseDoc): tens: TorchTensor[10] = Field(dims=10, is_embedding=True) index = WeaviateDocumentIndex[TorchDoc]() index_docs = [ TorchDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) ] index.index(index_docs) query = index_docs[-1] docs, scores = index.find(query, limit=5) assert len(docs) == 5 assert len(scores) == 5 for doc in docs: assert isinstance(doc.tens, TorchTensor) assert docs[0].id == index_docs[-1].id assert torch.allclose(docs[0].tens, index_docs[-1].tens) @pytest.mark.tensorflow def test_find_tensorflow(): from docarray.typing import TensorFlowTensor class TfDoc(BaseDoc): tens: TensorFlowTensor[10] = Field(dims=10, is_embedding=True) index = WeaviateDocumentIndex[TfDoc]() index_docs = [ TfDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) ] index.index(index_docs) query = index_docs[-1] docs, scores = index.find(query, limit=5) assert len(docs) == 5 assert len(scores) == 5 for doc in docs: assert isinstance(doc.tens, TensorFlowTensor) assert docs[0].id == index_docs[-1].id assert np.allclose( docs[0].tens.unwrap().numpy(), index_docs[-1].tens.unwrap().numpy() ) def test_contain(): class SimpleDoc(BaseDoc): tens: NdArray[10] = Field(dims=1000) class SimpleSchema(BaseDoc): tens: NdArray[10] index = WeaviateDocumentIndex[SimpleSchema]() index_docs = [SimpleDoc(tens=np.zeros(10)) for _ in range(10)] assert (index_docs[0] in index) is False index.index(index_docs) for doc in index_docs: assert (doc in index) is True index_docs_new = [SimpleDoc(tens=np.zeros(10)) for _ in range(10)] for doc in index_docs_new: assert (doc in index) is False
# 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 docarray.typing import TorchTensor from tests.index.weaviate.fixture_weaviate import ( # noqa: F401 start_storage, weaviate_client, ) pytestmark = [pytest.mark.slow, pytest.mark.index] def test_find_torch(weaviate_client): class TorchDoc(BaseDoc): tens: TorchTensor[10] = Field(dims=10, is_embedding=True) index = WeaviateDocumentIndex[TorchDoc]() index_docs = [ TorchDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) ] index.index(index_docs) query = index_docs[-1] docs, scores = index.find(query, limit=5) assert len(docs) == 5 assert len(scores) == 5 for doc in docs: assert isinstance(doc.tens, TorchTensor) assert docs[0].id == index_docs[-1].id assert torch.allclose(docs[0].tens, index_docs[-1].tens) @pytest.mark.tensorflow def test_find_tensorflow(): from docarray.typing import TensorFlowTensor class TfDoc(BaseDoc): tens: TensorFlowTensor[10] = Field(dims=10, is_embedding=True) index = WeaviateDocumentIndex[TfDoc]() index_docs = [ TfDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) ] index.index(index_docs) query = index_docs[-1] docs, scores = index.find(query, limit=5) assert len(docs) == 5 assert len(scores) == 5 for doc in docs: assert isinstance(doc.tens, TensorFlowTensor) assert docs[0].id == index_docs[-1].id assert np.allclose( docs[0].tens.unwrap().numpy(), index_docs[-1].tens.unwrap().numpy() )
# 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.00241 """ def __init__(self, backbone: ConfigType, rpn_head: ConfigType, roi_head: ConfigType, train_cfg: ConfigType, test_cfg: ConfigType, neck: OptConfigType = None, data_preprocessor: OptConfigType = None, init_cfg: OptMultiConfig = None) -> None: super().__init__( backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_cfg, test_cfg=test_cfg, data_preprocessor=data_preprocessor, init_cfg=init_cfg)
# 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, rpn_head, roi_head, train_cfg, test_cfg, neck=None, pretrained=None, init_cfg=None): super(MaskScoringRCNN, self).__init__( backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained, init_cfg=init_cfg)
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 optional imports. DEPRECATED_LOOKUP = { "GoogleSearchRun": "langchain_community.tools", "GoogleSearchResults": "langchain_community.tools", } _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "GoogleSearchResults", "GoogleSearchRun", ]
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 optional imports. DEPRECATED_LOOKUP = { "GoogleSearchRun": "langchain_community.tools", "GoogleSearchResults": "langchain_community.tools", } _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "GoogleSearchRun", "GoogleSearchResults", ]
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 + num_docs for j in range(num_docs): doc_id = str(start_id + j) d = Document(id=doc_id) d.text = text d.tags['id'] = f'myself id is: {doc_id}' if embedding: if sparse_embedding: from scipy.sparse import coo_matrix d.embedding = coo_matrix( (np.array([1, 1, 1]), (np.array([0, 1, 2]), np.array([1, 2, 1]))) ) else: d.embedding = np.random.random( [embed_dim + np.random.randint(0, jitter)] ) for _ in range(chunks_per_doc): chunk_doc_id = str(next_chunk_doc_id) c = Document(id=chunk_doc_id) c.text = 'i\'m chunk %s from doc %s' % (chunk_doc_id, doc_id) if embedding: c.embedding = np.random.random( [embed_dim + np.random.randint(0, jitter)] ) c.tags['parent_id'] = f'my parent is: {id}' c.tags['id'] = f'myself id is: {doc_id}' d.chunks.append(c) next_chunk_doc_id += 1 da.append(d) return da
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.transforms.utils import has_all, has_any IMAGE = make_image(color_space=datapoints.ColorSpace.RGB) BOUNDING_BOX = make_bounding_box(format=datapoints.BoundingBoxFormat.XYXY, spatial_size=IMAGE.spatial_size) MASK = make_detection_mask(size=IMAGE.spatial_size) @pytest.mark.parametrize( ("sample", "types", "expected"), [ ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.BoundingBox,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Mask,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.Mask), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.BoundingBox, datapoints.Mask), True), ((MASK,), (datapoints.Image, datapoints.BoundingBox), False), ((BOUNDING_BOX,), (datapoints.Image, datapoints.Mask), False), ((IMAGE,), (datapoints.BoundingBox, datapoints.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), True, ), ((), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda obj: isinstance(obj, datapoints.Image),), True), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: False,), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: True,), True), ((IMAGE,), (datapoints.Image, PIL.Image.Image, torchvision.prototype.transforms.utils.is_simple_tensor), True), ( (torch.Tensor(IMAGE),), (datapoints.Image, PIL.Image.Image, torchvision.prototype.transforms.utils.is_simple_tensor), True, ), ( (to_image_pil(IMAGE),), (datapoints.Image, PIL.Image.Image, torchvision.prototype.transforms.utils.is_simple_tensor), True, ), ], ) def test_has_any(sample, types, expected): assert has_any(sample, *types) is expected @pytest.mark.parametrize( ("sample", "types", "expected"), [ ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.BoundingBox,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Mask,), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.Mask), True), ((IMAGE, BOUNDING_BOX, MASK), (datapoints.BoundingBox, datapoints.Mask), True), ( (IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), True, ), ((BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox), False), ((BOUNDING_BOX, MASK), (datapoints.Image, datapoints.Mask), False), ((IMAGE, MASK), (datapoints.BoundingBox, datapoints.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), True, ), ((BOUNDING_BOX, MASK), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), False), ((IMAGE, MASK), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), False), ((IMAGE, BOUNDING_BOX), (datapoints.Image, datapoints.BoundingBox, datapoints.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (lambda obj: isinstance(obj, (datapoints.Image, datapoints.BoundingBox, datapoints.Mask)),), True, ), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: False,), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: True,), True), ], ) def test_has_all(sample, types, expected): assert has_all(sample, *types) is expected
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 = make_image(color_space=features.ColorSpace.RGB) BOUNDING_BOX = make_bounding_box(format=features.BoundingBoxFormat.XYXY, spatial_size=IMAGE.spatial_size) MASK = make_detection_mask(size=IMAGE.spatial_size) @pytest.mark.parametrize( ("sample", "types", "expected"), [ ((IMAGE, BOUNDING_BOX, MASK), (features.Image,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.BoundingBox,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Mask,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Image, features.BoundingBox), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Image, features.Mask), True), ((IMAGE, BOUNDING_BOX, MASK), (features.BoundingBox, features.Mask), True), ((MASK,), (features.Image, features.BoundingBox), False), ((BOUNDING_BOX,), (features.Image, features.Mask), False), ((IMAGE,), (features.BoundingBox, features.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (features.Image, features.BoundingBox, features.Mask), True, ), ((), (features.Image, features.BoundingBox, features.Mask), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda obj: isinstance(obj, features.Image),), True), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: False,), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: True,), True), ((IMAGE,), (features.Image, PIL.Image.Image, features.is_simple_tensor), True), ((torch.Tensor(IMAGE),), (features.Image, PIL.Image.Image, features.is_simple_tensor), True), ((to_image_pil(IMAGE),), (features.Image, PIL.Image.Image, features.is_simple_tensor), True), ], ) def test_has_any(sample, types, expected): assert has_any(sample, *types) is expected @pytest.mark.parametrize( ("sample", "types", "expected"), [ ((IMAGE, BOUNDING_BOX, MASK), (features.Image,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.BoundingBox,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Mask,), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Image, features.BoundingBox), True), ((IMAGE, BOUNDING_BOX, MASK), (features.Image, features.Mask), True), ((IMAGE, BOUNDING_BOX, MASK), (features.BoundingBox, features.Mask), True), ( (IMAGE, BOUNDING_BOX, MASK), (features.Image, features.BoundingBox, features.Mask), True, ), ((BOUNDING_BOX, MASK), (features.Image, features.BoundingBox), False), ((BOUNDING_BOX, MASK), (features.Image, features.Mask), False), ((IMAGE, MASK), (features.BoundingBox, features.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (features.Image, features.BoundingBox, features.Mask), True, ), ((BOUNDING_BOX, MASK), (features.Image, features.BoundingBox, features.Mask), False), ((IMAGE, MASK), (features.Image, features.BoundingBox, features.Mask), False), ((IMAGE, BOUNDING_BOX), (features.Image, features.BoundingBox, features.Mask), False), ( (IMAGE, BOUNDING_BOX, MASK), (lambda obj: isinstance(obj, (features.Image, features.BoundingBox, features.Mask)),), True, ), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: False,), False), ((IMAGE, BOUNDING_BOX, MASK), (lambda _: True,), True), ], ) def test_has_all(sample, types, expected): assert has_all(sample, *types) is expected
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 Image to a tensor of the same type - this does not scale values. .. v2betastatus:: PILToTensor transform This transform does not support torchscript. Converts a PIL Image (H x W x C) to a Tensor of shape (C x H x W). """ _transformed_types = (PIL.Image.Image,) def _transform(self, inpt: PIL.Image.Image, params: Dict[str, Any]) -> torch.Tensor: return F.pil_to_tensor(inpt) class ToImage(Transform): """[BETA] Convert a tensor, ndarray, or PIL Image to :class:`~torchvision.datapoints.Image` ; this does not scale values. .. v2betastatus:: ToImage transform This transform does not support torchscript. """ _transformed_types = (is_pure_tensor, PIL.Image.Image, np.ndarray) def _transform( self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: Dict[str, Any] ) -> datapoints.Image: return F.to_image(inpt) class ToPILImage(Transform): """[BETA] Convert a tensor or an ndarray to PIL Image - this does not scale values. .. v2betastatus:: ToPILImage transform This transform does not support torchscript. Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape H x W x C to a PIL Image while preserving the value range. Args: mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). If ``mode`` is ``None`` (default) there are some assumptions made about the input data: - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``). .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes """ _transformed_types = (is_pure_tensor, datapoints.Image, np.ndarray) def __init__(self, mode: Optional[str] = None) -> None: super().__init__() self.mode = mode def _transform( self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: Dict[str, Any] ) -> PIL.Image.Image: return F.to_pil_image(inpt, mode=self.mode) class ToPureTensor(Transform): """[BETA] Convert all datapoints to pure tensors, removing associated metadata (if any). .. v2betastatus:: ToPureTensor transform This doesn't scale or change the values, only the type. """ _transformed_types = (datapoints.Datapoint,) def _transform(self, inpt: Any, params: Dict[str, Any]) -> torch.Tensor: return inpt.as_subclass(torch.Tensor)
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 Image to a tensor of the same type - this does not scale values. .. v2betastatus:: PILToTensor transform This transform does not support torchscript. Converts a PIL Image (H x W x C) to a Tensor of shape (C x H x W). """ _transformed_types = (PIL.Image.Image,) def _transform(self, inpt: PIL.Image.Image, params: Dict[str, Any]) -> torch.Tensor: return F.pil_to_tensor(inpt) class ToImage(Transform): """[BETA] Convert a tensor, ndarray, or PIL Image to :class:`~torchvision.datapoints.Image` ; this does not scale values. .. v2betastatus:: ToImage transform This transform does not support torchscript. """ _transformed_types = (is_pure_tensor, PIL.Image.Image, np.ndarray) def _transform( self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: Dict[str, Any] ) -> datapoints.Image: return F.to_image(inpt) class ToPILImage(Transform): """[BETA] Convert a tensor or an ndarray to PIL Image - this does not scale values. .. v2betastatus:: ToPILImage transform This transform does not support torchscript. Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape H x W x C to a PIL Image while preserving the value range. Args: mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). If ``mode`` is ``None`` (default) there are some assumptions made about the input data: - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``). .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes """ _transformed_types = (is_pure_tensor, datapoints.Image, np.ndarray) def __init__(self, mode: Optional[str] = None) -> None: super().__init__() self.mode = mode def _transform( self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: Dict[str, Any] ) -> PIL.Image.Image: return F.to_pil_image(inpt, mode=self.mode) class ToPureTensor(Transform): """[BETA] Convert all datapoints to pure tensors, removing associated metadata (if any). .. v2betastatus:: ToPureTensor transform This doesn't scale or change the values, only the type. """ _transformed_types = (datapoints.Datapoint,) def _transform(self, inpt: Any, params: Dict[str, Any]) -> torch.Tensor: return inpt.as_subclass(torch.Tensor)
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(Path(__file__).parent, relative_to=HERE) old_path = "langchain." + here + "." + name new_path = "langchain_experimental." + here + "." + name msg = ( "This agent has been moved to langchain experiment. " "This agent relies on python REPL tool under the hood, so to use it " "safely please sandbox the python REPL. " "Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md " "and https://github.com/langchain-ai/langchain/discussions/11680" "To keep using this code as is, install langchain experimental and " f"update your import statement from:\n `{old_path}` to `{new_path}`." ) raise ImportError(msg) msg = f"{name} does not exist" raise AttributeError(msg)
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(Path(__file__).parent, relative_to=HERE) old_path = "langchain." + here + "." + name new_path = "langchain_experimental." + here + "." + name raise ImportError( "This agent has been moved to langchain experiment. " "This agent relies on python REPL tool under the hood, so to use it " "safely please sandbox the python REPL. " "Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md " "and https://github.com/langchain-ai/langchain/discussions/11680" "To keep using this code as is, install langchain experimental and " f"update your import statement from:\n `{old_path}` to `{new_path}`." ) raise AttributeError(f"{name} does not exist")
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['FlowBuildLevel']): """Annotate a function so that it requires certain build level to run. Example: .. highlight:: python .. code-block:: python @build_required(FlowBuildLevel.RUNTIME) def foo(): print(1) :param levels: required build level to run this function. :return: annotated function """ def __build_level(func): @wraps(func) def arg_wrapper(self, *args, **kwargs): if hasattr(self, '_build_level'): if self._build_level in levels: return func(self, *args, **kwargs) else: raise FlowBuildLevelError( f'build_level check failed for {func!r}, required level: {levels}, actual level: {self._build_level}' ) else: raise AttributeError(f'{self!r} has no attribute "_build_level"') return arg_wrapper return __build_level def _hanging_deployments(op_flow: 'Flow') -> List[str]: """ :param op_flow: the Flow we're operating on :return: names of floating Deployments (nobody recv from them) in the Flow. """ all_needs = {k for p, v in op_flow for k in v.needs} all_names = {p for p, v in op_flow if not v.args.floating} # all_names is always a superset of all_needs return list(all_names.difference(all_needs))
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']): """Annotate a function so that it requires certain build level to run. Example: .. highlight:: python .. code-block:: python @build_required(FlowBuildLevel.RUNTIME) def foo(): print(1) :param levels: required build level to run this function. :return: annotated function """ def __build_level(func): @wraps(func) def arg_wrapper(self, *args, **kwargs): if hasattr(self, '_build_level'): if self._build_level in levels: return func(self, *args, **kwargs) else: raise FlowBuildLevelError( f'build_level check failed for {func!r}, required level: {levels}, actual level: {self._build_level}' ) else: raise AttributeError(f'{self!r} has no attribute "_build_level"') return arg_wrapper return __build_level def _hanging_deployments(op_flow: 'Flow') -> List[str]: """ :param op_flow: the Flow we're operating on :return: names of floating Deployments (nobody recv from them) in the Flow. """ all_needs = {k for p, v in op_flow for k in v.needs} all_names = {p for p, v in op_flow if not v.args.floating} # all_names is always a superset of all_needs return list(all_names.difference(all_needs))
# 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_size_hook import SyncRandomSizeHook from .wandblogger_hook import MMDetWandbHook from .yolox_lrupdater_hook import YOLOXLrUpdaterHook from .yolox_mode_switch_hook import YOLOXModeSwitchHook __all__ = [ 'SyncRandomSizeHook', 'YOLOXModeSwitchHook', 'SyncNormHook', 'ExpMomentumEMAHook', 'LinearMomentumEMAHook', 'YOLOXLrUpdaterHook', 'CheckInvalidLossHook', 'SetEpochInfoHook', 'MemoryProfilerHook', 'MMDetWandbHook' ]
# 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_size_hook import SyncRandomSizeHook from .yolox_lrupdater_hook import YOLOXLrUpdaterHook from .yolox_mode_switch_hook import YOLOXModeSwitchHook __all__ = [ 'SyncRandomSizeHook', 'YOLOXModeSwitchHook', 'SyncNormHook', 'ExpMomentumEMAHook', 'LinearMomentumEMAHook', 'YOLOXLrUpdaterHook', 'CheckInvalidLossHook', 'SetEpochInfoHook', 'MemoryProfilerHook' ]
""" 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_graph(sys.getrecursionlimit, can_constant_fold_through=True) def getrecursionlimit() -> int: return sys.getrecursionlimit()
""" 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_graph(sys.getrecursionlimit, can_constant_fold_through=True) def getrecursionlimit() -> int: return sys.getrecursionlimit() @substitute_in_graph(sys.get_int_max_str_digits, can_constant_fold_through=True) def get_int_max_str_digits() -> int: return sys.get_int_max_str_digits()
_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=32, batch_augments=[ dict(type='BatchSyncRandomResize', random_size_range=(640, 1152)) ]), tracker=dict( weight_iou_with_det_scores=False, match_iou_thrs=dict(high=0.3), )) train_pipeline = [ dict( type='Mosaic', img_scale=img_scale, pad_val=114.0, bbox_clip_border=True), dict( type='RandomAffine', scaling_ratio_range=(0.1, 2), border=(-img_scale[0] // 2, -img_scale[1] // 2), bbox_clip_border=True), dict( type='MixUp', img_scale=img_scale, ratio_range=(0.8, 1.6), pad_val=114.0, bbox_clip_border=True), dict(type='YOLOXHSVRandomAug'), dict(type='RandomFlip', prob=0.5), dict( type='Resize', scale=img_scale, keep_ratio=True, clip_object_border=True), dict(type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False), dict(type='PackDetInputs') ] test_pipeline = [ dict( type='TransformBroadcaster', transforms=[ dict(type='LoadImageFromFile', backend_args=_base_.backend_args), dict(type='Resize', scale=img_scale, keep_ratio=True), dict( type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='LoadTrackAnnotations'), ]), dict(type='PackTrackInputs') ] train_dataloader = dict( dataset=dict( type='MultiImageMixDataset', dataset=dict( type='ConcatDataset', datasets=[ dict( type='CocoDataset', data_root='data/MOT20', ann_file='annotations/train_cocoformat.json', # TODO: mmdet use img as key, but img_path is needed data_prefix=dict(img='train'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict( type='LoadImageFromFile', backend_args=_base_.backend_args), dict(type='LoadAnnotations', with_bbox=True), ]), dict( type='CocoDataset', data_root='data/crowdhuman', ann_file='annotations/crowdhuman_train.json', data_prefix=dict(img='train'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict( type='LoadImageFromFile', backend_args=_base_.backend_args), dict(type='LoadAnnotations', with_bbox=True), ]), dict( type='CocoDataset', data_root='data/crowdhuman', ann_file='annotations/crowdhuman_val.json', data_prefix=dict(img='val'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict( type='LoadImageFromFile', backend_args=_base_.backend_args), dict(type='LoadAnnotations', with_bbox=True), ]), ]), pipeline=train_pipeline)) val_dataloader = dict( dataset=dict(ann_file='annotations/train_cocoformat.json')) test_dataloader = dict( dataset=dict( data_root='data/MOT20', ann_file='annotations/test_cocoformat.json')) test_evaluator = dict( type='MOTChallengeMetrics', postprocess_tracklet_cfg=[ dict(type='InterpolateTracklets', min_num_frames=5, max_num_frames=20) ], format_only=True, outfile_prefix='./mot_20_test_res')
_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=32, batch_augments=[ dict(type='BatchSyncRandomResize', random_size_range=(640, 1152)) ]), tracker=dict( weight_iou_with_det_scores=False, match_iou_thrs=dict(high=0.3), )) train_pipeline = [ dict( type='Mosaic', img_scale=img_scale, pad_val=114.0, bbox_clip_border=True), dict( type='RandomAffine', scaling_ratio_range=(0.1, 2), border=(-img_scale[0] // 2, -img_scale[1] // 2), bbox_clip_border=True), dict( type='MixUp', img_scale=img_scale, ratio_range=(0.8, 1.6), pad_val=114.0, bbox_clip_border=True), dict(type='YOLOXHSVRandomAug'), dict(type='RandomFlip', prob=0.5), dict( type='Resize', scale=img_scale, keep_ratio=True, clip_object_border=True), dict(type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False), dict(type='PackDetInputs') ] test_pipeline = [ dict( type='TransformBroadcaster', transforms=[ dict(type='LoadImageFromFile'), dict(type='Resize', scale=img_scale, keep_ratio=True), dict( type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='LoadTrackAnnotations'), ]), dict(type='PackTrackInputs') ] train_dataloader = dict( dataset=dict( type='MultiImageMixDataset', dataset=dict( type='ConcatDataset', datasets=[ dict( type='CocoDataset', data_root='data/MOT20', ann_file='annotations/train_cocoformat.json', # TODO: mmdet use img as key, but img_path is needed data_prefix=dict(img='train'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), ]), dict( type='CocoDataset', data_root='data/crowdhuman', ann_file='annotations/crowdhuman_train.json', data_prefix=dict(img='train'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), ]), dict( type='CocoDataset', data_root='data/crowdhuman', ann_file='annotations/crowdhuman_val.json', data_prefix=dict(img='val'), filter_cfg=dict(filter_empty_gt=True, min_size=32), metainfo=dict(classes=('pedestrian', )), pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), ]), ]), pipeline=train_pipeline)) val_dataloader = dict( dataset=dict(ann_file='annotations/train_cocoformat.json')) test_dataloader = dict( dataset=dict( data_root='data/MOT20', ann_file='annotations/test_cocoformat.json')) test_evaluator = dict( type='MOTChallengeMetrics', postprocess_tracklet_cfg=[ dict(type='InterpolateTracklets', min_num_frames=5, max_num_frames=20) ], format_only=True, outfile_prefix='./mot_20_test_res')
_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( type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w40')), neck=dict(type='HRFPN', in_channels=[40, 80, 160, 320], out_channels=256))
_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( type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w40')), neck=dict(type='HRFPN', in_channels=[40, 80, 160, 320], out_channels=256))
_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', teacher_ckpt=teacher_ckpt, backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5)) max_epochs = 24 param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ] train_cfg = dict(max_epochs=max_epochs) # multi-scale training train_pipeline = [ dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 800)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] train_dataloader = dict(dataset=dict(pipeline=train_pipeline))
_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', teacher_ckpt=teacher_ckpt, backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5)) max_epochs = 24 param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ] train_cfg = dict(max_epochs=max_epochs) # multi-scale training train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 800)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] train_dataloader = dict(dataset=dict(pipeline=train_pipeline))
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(FunctionalTestImpl, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu") class FunctionalFloat64OnlyCPUTest(Functional64OnlyTestImpl, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu")
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 FunctionalFloat64CPUTest(FunctionalTestImpl, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu") class FunctionalFloat64OnlyCPUTest(Functional64OnlyTestImpl, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu") class FunctionalCPUOnlyFloat32Test(FunctionalCPUOnlyTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class FunctionalCPUOnlyFloat64Test(FunctionalCPUOnlyTestImpl, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu")
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_arg, _setup_size from torchvision.transforms.v2.utils import has_any, is_simple_tensor, query_bounding_boxes, query_size class FixedSizeCrop(Transform): def __init__( self, size: Union[int, Sequence[int]], fill: Union[datapoints._FillType, Dict[Type, datapoints._FillType]] = 0, padding_mode: str = "constant", ) -> None: super().__init__() size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) self.crop_height = size[0] self.crop_width = size[1] self.fill = fill self._fill = _setup_fill_arg(fill) self.padding_mode = padding_mode def _check_inputs(self, flat_inputs: List[Any]) -> None: if not has_any( flat_inputs, PIL.Image.Image, datapoints.Image, is_simple_tensor, datapoints.Video, ): raise TypeError( f"{type(self).__name__}() requires input sample to contain an tensor or PIL image or a Video." ) if has_any(flat_inputs, datapoints.BoundingBoxes) and not has_any(flat_inputs, Label, OneHotLabel): raise TypeError( f"If a BoundingBoxes is contained in the input sample, " f"{type(self).__name__}() also requires it to contain a Label or OneHotLabel." ) def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]: height, width = query_size(flat_inputs) new_height = min(height, self.crop_height) new_width = min(width, self.crop_width) needs_crop = new_height != height or new_width != width offset_height = max(height - self.crop_height, 0) offset_width = max(width - self.crop_width, 0) r = torch.rand(1) top = int(offset_height * r) left = int(offset_width * r) bounding_boxes: Optional[torch.Tensor] try: bounding_boxes = query_bounding_boxes(flat_inputs) except ValueError: bounding_boxes = None if needs_crop and bounding_boxes is not None: format = bounding_boxes.format bounding_boxes, canvas_size = F.crop_bounding_boxes( bounding_boxes.as_subclass(torch.Tensor), format=format, top=top, left=left, height=new_height, width=new_width, ) bounding_boxes = F.clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size) height_and_width = F.convert_format_bounding_boxes( bounding_boxes, old_format=format, new_format=datapoints.BoundingBoxFormat.XYWH )[..., 2:] is_valid = torch.all(height_and_width > 0, dim=-1) else: is_valid = None pad_bottom = max(self.crop_height - new_height, 0) pad_right = max(self.crop_width - new_width, 0) needs_pad = pad_bottom != 0 or pad_right != 0 return dict( needs_crop=needs_crop, top=top, left=left, height=new_height, width=new_width, is_valid=is_valid, padding=[0, 0, pad_right, pad_bottom], needs_pad=needs_pad, ) def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any: if params["needs_crop"]: inpt = F.crop( inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"], ) if params["is_valid"] is not None: if isinstance(inpt, (Label, OneHotLabel, datapoints.Mask)): inpt = inpt.wrap_like(inpt, inpt[params["is_valid"]]) # type: ignore[arg-type] elif isinstance(inpt, datapoints.BoundingBoxes): inpt = datapoints.BoundingBoxes.wrap_like( inpt, F.clamp_bounding_boxes(inpt[params["is_valid"]], format=inpt.format, canvas_size=inpt.canvas_size), ) if params["needs_pad"]: fill = self._fill[type(inpt)] inpt = F.pad(inpt, params["padding"], fill=fill, padding_mode=self.padding_mode) return inpt
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_arg, _setup_size from torchvision.transforms.v2.utils import has_any, is_simple_tensor, query_bounding_boxes, query_spatial_size class FixedSizeCrop(Transform): def __init__( self, size: Union[int, Sequence[int]], fill: Union[datapoints._FillType, Dict[Type, datapoints._FillType]] = 0, padding_mode: str = "constant", ) -> None: super().__init__() size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) self.crop_height = size[0] self.crop_width = size[1] self.fill = fill self._fill = _setup_fill_arg(fill) self.padding_mode = padding_mode def _check_inputs(self, flat_inputs: List[Any]) -> None: if not has_any( flat_inputs, PIL.Image.Image, datapoints.Image, is_simple_tensor, datapoints.Video, ): raise TypeError( f"{type(self).__name__}() requires input sample to contain an tensor or PIL image or a Video." ) if has_any(flat_inputs, datapoints.BoundingBoxes) and not has_any(flat_inputs, Label, OneHotLabel): raise TypeError( f"If a BoundingBoxes is contained in the input sample, " f"{type(self).__name__}() also requires it to contain a Label or OneHotLabel." ) def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]: height, width = query_spatial_size(flat_inputs) new_height = min(height, self.crop_height) new_width = min(width, self.crop_width) needs_crop = new_height != height or new_width != width offset_height = max(height - self.crop_height, 0) offset_width = max(width - self.crop_width, 0) r = torch.rand(1) top = int(offset_height * r) left = int(offset_width * r) bounding_boxes: Optional[torch.Tensor] try: bounding_boxes = query_bounding_boxes(flat_inputs) except ValueError: bounding_boxes = None if needs_crop and bounding_boxes is not None: format = bounding_boxes.format bounding_boxes, spatial_size = F.crop_bounding_boxes( bounding_boxes.as_subclass(torch.Tensor), format=format, top=top, left=left, height=new_height, width=new_width, ) bounding_boxes = F.clamp_bounding_boxes(bounding_boxes, format=format, spatial_size=spatial_size) height_and_width = F.convert_format_bounding_boxes( bounding_boxes, old_format=format, new_format=datapoints.BoundingBoxFormat.XYWH )[..., 2:] is_valid = torch.all(height_and_width > 0, dim=-1) else: is_valid = None pad_bottom = max(self.crop_height - new_height, 0) pad_right = max(self.crop_width - new_width, 0) needs_pad = pad_bottom != 0 or pad_right != 0 return dict( needs_crop=needs_crop, top=top, left=left, height=new_height, width=new_width, is_valid=is_valid, padding=[0, 0, pad_right, pad_bottom], needs_pad=needs_pad, ) def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any: if params["needs_crop"]: inpt = F.crop( inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"], ) if params["is_valid"] is not None: if isinstance(inpt, (Label, OneHotLabel, datapoints.Mask)): inpt = inpt.wrap_like(inpt, inpt[params["is_valid"]]) # type: ignore[arg-type] elif isinstance(inpt, datapoints.BoundingBoxes): inpt = datapoints.BoundingBoxes.wrap_like( inpt, F.clamp_bounding_boxes( inpt[params["is_valid"]], format=inpt.format, spatial_size=inpt.spatial_size ), ) if params["needs_pad"]: fill = self._fill[type(inpt)] inpt = F.pad(inpt, params["padding"], fill=fill, padding_mode=self.padding_mode) return inpt
# 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', 'footwear', 'hair', 'skin', 'face') PALETTE = [(0, 192, 64), (0, 64, 96), (128, 192, 192), (0, 64, 64), (0, 192, 224), (0, 192, 192), (128, 192, 64), (0, 192, 96), (128, 32, 192), (0, 0, 224), (0, 0, 64), (0, 160, 192), (128, 0, 96), (128, 0, 192), (0, 32, 192)]
# 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', 'footwear', 'hair', 'skin', 'face') PALETTE = [(0, 192, 64), (0, 64, 96), (128, 192, 192), (0, 64, 64), (0, 192, 224), (0, 192, 192), (128, 192, 64), (0, 192, 96), (128, 32, 192), (0, 0, 224), (0, 0, 64), (0, 160, 192), (128, 0, 96), (128, 0, 192), (0, 32, 192)]
__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:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len`` after stripping will be discarded. """ def __init__( self, min_sent_len: int = 1, max_sent_len: int = 512, punct_chars: Optional[List[str]] = None, uniform_weight: bool = True, traversal_paths: Tuple[str] = ('r',), *args, **kwargs ): """ :param min_sent_len: the minimal number of characters, (including white spaces) of the sentence, by default 1. :param max_sent_len: the maximal number of characters, (including white spaces) of the sentence, by default 512. :param punct_chars: the punctuation characters to split on, whatever is in the list will be used, for example ['!', '.', '?'] will use '!', '.' and '?' :param uniform_weight: the definition of it should have uniform weight or should be calculated :param traversal_paths: traverse path on docs, e.g. ['r'], ['c'] """ super().__init__(*args, **kwargs) self.min_sent_len = min_sent_len self.max_sent_len = max_sent_len self.punct_chars = punct_chars self.uniform_weight = uniform_weight self.logger = JinaLogger(self.__class__.__name__) self.traversal_paths = traversal_paths if not punct_chars: self.punct_chars = [ '!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '‼', '‽', '⁇', '⁈', '⁉', '⸮', '﹖', '﹗', '!', '.', '?', '。', '。', '\n', ] if self.min_sent_len > self.max_sent_len: self.logger.warning( 'the min_sent_len (={}) should be smaller or equal to the max_sent_len (={})'.format( self.min_sent_len, self.max_sent_len ) ) self._slit_pat = re.compile( r'\s*([^{0}]+)(?<!\s)[{0}]*'.format(''.join(set(self.punct_chars))) ) @requests def segment(self, docs: Optional[DocumentArray], parameters: Dict, **kwargs): """ Split the text into sentences. :param docs: Documents that contain the text :param parameters: Dictionary of parameters :param kwargs: Additional keyword arguments :return: a list of chunk dicts with the split sentences """ if not docs: return traversal_path = parameters.get('traversal_paths', self.traversal_paths) flat_docs = docs.traverse_flat(traversal_path) for doc in flat_docs: text = doc.text ret = [ (m.group(0), m.start(), m.end()) for m in re.finditer(self._slit_pat, text) ] if not ret: ret = [(text, 0, len(text))] for ci, (r, s, e) in enumerate(ret): f = re.sub('\n+', ' ', r).strip() f = f[: self.max_sent_len] if len(f) > self.min_sent_len: doc.chunks.append( Document( text=f, offset=ci, weight=1.0 if self.uniform_weight else len(f) / len(text), location=[s, e], ) )
__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): """ :class:`Sentencizer` split the text on the doc-level into sentences on the chunk-level with a rule-base strategy. The text is split by the punctuation characters listed in ``punct_chars``. The sentences that are shorter than the ``min_sent_len`` or longer than the ``max_sent_len`` after stripping will be discarded. """ def __init__( self, min_sent_len: int = 1, max_sent_len: int = 512, punct_chars: Optional[List[str]] = None, uniform_weight: bool = True, traversal_paths: Iterable[str] = ('r',), *args, **kwargs ): """ :param min_sent_len: the minimal number of characters, (including white spaces) of the sentence, by default 1. :param max_sent_len: the maximal number of characters, (including white spaces) of the sentence, by default 512. :param punct_chars: the punctuation characters to split on, whatever is in the list will be used, for example ['!', '.', '?'] will use '!', '.' and '?' :param uniform_weight: the definition of it should have uniform weight or should be calculated :param traversal_paths: traverse path on docs, e.g. ['r'], ['c'] """ super().__init__(*args, **kwargs) self.min_sent_len = min_sent_len self.max_sent_len = max_sent_len self.punct_chars = punct_chars self.uniform_weight = uniform_weight self.logger = JinaLogger(self.__class__.__name__) self.traversal_paths = traversal_paths if not punct_chars: self.punct_chars = [ '!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '‼', '‽', '⁇', '⁈', '⁉', '⸮', '﹖', '﹗', '!', '.', '?', '。', '。', '\n', ] if self.min_sent_len > self.max_sent_len: self.logger.warning( 'the min_sent_len (={}) should be smaller or equal to the max_sent_len (={})'.format( self.min_sent_len, self.max_sent_len ) ) self._slit_pat = re.compile( r'\s*([^{0}]+)(?<!\s)[{0}]*'.format(''.join(set(self.punct_chars))) ) @requests def segment( self, docs: Optional[DocumentArray] = None, parameters: Dict = {}, **kwargs ): """ Split the text into sentences. :param docs: Documents that contain the text :param parameters: Dictionary of parameters :param kwargs: Additional keyword arguments :return: a list of chunk dicts with the split sentences """ if not docs: return traversal_path = parameters.get('traversal_paths', self.traversal_paths) flat_docs = docs.traverse_flat(traversal_path) for doc in flat_docs: text = doc.text ret = [ (m.group(0), m.start(), m.end()) for m in re.finditer(self._slit_pat, text) ] if not ret: ret = [(text, 0, len(text))] for ci, (r, s, e) in enumerate(ret): f = re.sub('\n+', ' ', r).strip() f = f[: self.max_sent_len] if len(f) > self.min_sent_len: doc.chunks.append( Document( text=f, offset=ci, weight=1.0 if self.uniform_weight else len(f) / len(text), location=[s, e], ) )
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_channels=3" if num_output_channels == 3 else "" replacement = "convert_color_space(..., color_space=datapoints.ColorSpace.GRAY)" if num_output_channels == 3: replacement = f"convert_color_space({replacement}, color_space=datapoints.ColorSpace.RGB)" warnings.warn( f"The function `to_grayscale(...{call})` is deprecated in will be removed in a future release. " f"Instead, please use `{replacement}`.", ) return _F.to_grayscale(inpt, num_output_channels=num_output_channels) @torch.jit.unused def to_tensor(inpt: Any) -> torch.Tensor: warnings.warn( "The function `to_tensor(...)` is deprecated and will be removed in a future release. " "Instead, please use `to_image_tensor(...)` followed by `convert_image_dtype(...)`." ) return _F.to_tensor(inpt) def get_image_size(inpt: Union[datapoints.ImageTypeJIT, datapoints.VideoTypeJIT]) -> List[int]: warnings.warn( "The function `get_image_size(...)` is deprecated and will be removed in a future release. " "Instead, please use `get_spatial_size(...)` which returns `[h, w]` instead of `[w, h]`." ) return _F.get_image_size(inpt)
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.Image.Image: call = ", num_output_channels=3" if num_output_channels == 3 else "" replacement = "convert_color_space(..., color_space=datapoints.ColorSpace.GRAY)" if num_output_channels == 3: replacement = f"convert_color_space({replacement}, color_space=datapoints.ColorSpace.RGB)" warnings.warn( f"The function `to_grayscale(...{call})` is deprecated in will be removed in a future release. " f"Instead, please use `{replacement}`.", ) return _F.to_grayscale(inpt, num_output_channels=num_output_channels) def rgb_to_grayscale( inpt: Union[datapoints.ImageTypeJIT, datapoints.VideoTypeJIT], num_output_channels: int = 1 ) -> Union[datapoints.ImageTypeJIT, datapoints.VideoTypeJIT]: old_color_space = None # TODO: remove when un-deprecating if not (torch.jit.is_scripting() or is_simple_tensor(inpt)) and isinstance( inpt, (datapoints.Image, datapoints.Video) ): inpt = inpt.as_subclass(torch.Tensor) call = ", num_output_channels=3" if num_output_channels == 3 else "" replacement = ( f"convert_color_space(..., color_space=datapoints.ColorSpace.GRAY" f"{f', old_color_space=datapoints.ColorSpace.{old_color_space}' if old_color_space is not None else ''})" ) if num_output_channels == 3: replacement = ( f"convert_color_space({replacement}, color_space=datapoints.ColorSpace.RGB" f"{f', old_color_space=datapoints.ColorSpace.GRAY' if old_color_space is not None else ''})" ) warnings.warn( f"The function `rgb_to_grayscale(...{call})` is deprecated in will be removed in a future release. " f"Instead, please use `{replacement}`.", ) return _F.rgb_to_grayscale(inpt, num_output_channels=num_output_channels) @torch.jit.unused def to_tensor(inpt: Any) -> torch.Tensor: warnings.warn( "The function `to_tensor(...)` is deprecated and will be removed in a future release. " "Instead, please use `to_image_tensor(...)` followed by `convert_image_dtype(...)`." ) return _F.to_tensor(inpt) def get_image_size(inpt: Union[datapoints.ImageTypeJIT, datapoints.VideoTypeJIT]) -> List[int]: warnings.warn( "The function `get_image_size(...)` is deprecated and will be removed in a future release. " "Instead, please use `get_spatial_size(...)` which returns `[h, w]` instead of `[w, h]`." ) return _F.get_image_size(inpt)
__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_version is_latest_version()
__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): """BuilderConfig for Parquet.""" batch_size: int = 10_000 columns: Optional[List[str]] = None features: Optional[datasets.Features] = None class Parquet(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = ParquetConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] # Infer features if they are stored in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(files): with open(file, "rb") as f: features = datasets.Features.from_arrow_schema(pq.read_schema(f)) if self.config.columns is not None: self.info.features = datasets.Features( {col: feat for col, feat in features.items() if col in self.config.columns} ) self.info.features = features break splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.info.features.arrow_schema) return pa_table def _generate_tables(self, files): if self.config.features is not None and self.config.columns is not None: if sorted(field.name for field in self.info.features.arrow_schema) != sorted(self.config.columns): raise ValueError( f"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: parquet_file = pq.ParquetFile(f) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size, columns=self.config.columns) ): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
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): """BuilderConfig for Parquet.""" batch_size: int = 10_000 columns: Optional[List[str]] = None features: Optional[datasets.Features] = None class Parquet(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = ParquetConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(files): with open(file, "rb") as f: self.info.features = datasets.Features.from_arrow_schema(pq.read_schema(f)) break splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.info.features.arrow_schema) return pa_table def _generate_tables(self, files): schema = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema) != sorted(self.config.columns): raise ValueError( f"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: parquet_file = pq.ParquetFile(f) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size, columns=self.config.columns) ): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
#!/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. """ def __init__(self, rir_path: str): super().__init__() rir, sample_rate = torchaudio.load(rir_path) self.register_buffer("rir", rir) self.rir_sample_rate: int = sample_rate def forward(self, input_path: str, output_path: str): torchaudio.sox_effects.init_sox_effects() # 1. load audio waveform, sample_rate = torchaudio.load(input_path) # 2. Add background noise alpha = 0.01 waveform = alpha * torch.randn_like(waveform) + (1 - alpha) * waveform # 3. Reample the RIR filter to much the audio sample rate rir, _ = torchaudio.sox_effects.apply_effects_tensor( self.rir, self.rir_sample_rate, effects=[["rate", str(sample_rate)]] ) rir = rir / torch.linalg.vector_norm(rir, ord=2) rir = torch.flip(rir, [1]) # 4. Apply RIR filter waveform = torch.nn.functional.pad(waveform, (rir.shape[1] - 1, 0)) waveform = torch.nn.functional.conv1d(waveform[None, ...], rir[None, ...])[0] # Save torchaudio.save(output_path, waveform, sample_rate) def _create_jit_pipeline(rir_path, output_path): module = torch.jit.script(Pipeline(rir_path)) print("*" * 40) print("* Pipeline code") print("*" * 40) print() print(module.code) print("*" * 40) module.save(output_path) def _get_path(*paths): return os.path.join(os.path.dirname(__file__), *paths) def _parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--rir-path", default=_get_path("..", "data", "rir.wav"), help="Audio dara for room impulse response." ) parser.add_argument("--output-path", default=_get_path("pipeline.zip"), help="Output JIT file.") return parser.parse_args() def _main(): args = _parse_args() _create_jit_pipeline(args.rir_path, args.output_path) if __name__ == "__main__": _main()
#!/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. """ def __init__(self, rir_path: str): super().__init__() rir, sample_rate = torchaudio.load(rir_path) self.register_buffer("rir", rir) self.rir_sample_rate: int = sample_rate def forward(self, input_path: str, output_path: str): torchaudio.sox_effects.init_sox_effects() # 1. load audio waveform, sample_rate = torchaudio.load(input_path) # 2. Add background noise alpha = 0.01 waveform = alpha * torch.randn_like(waveform) + (1 - alpha) * waveform # 3. Reample the RIR filter to much the audio sample rate rir, _ = torchaudio.sox_effects.apply_effects_tensor( self.rir, self.rir_sample_rate, effects=[["rate", str(sample_rate)]] ) rir = rir / torch.norm(rir, p=2) rir = torch.flip(rir, [1]) # 4. Apply RIR filter waveform = torch.nn.functional.pad(waveform, (rir.shape[1] - 1, 0)) waveform = torch.nn.functional.conv1d(waveform[None, ...], rir[None, ...])[0] # Save torchaudio.save(output_path, waveform, sample_rate) def _create_jit_pipeline(rir_path, output_path): module = torch.jit.script(Pipeline(rir_path)) print("*" * 40) print("* Pipeline code") print("*" * 40) print() print(module.code) print("*" * 40) module.save(output_path) def _get_path(*paths): return os.path.join(os.path.dirname(__file__), *paths) def _parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--rir-path", default=_get_path("..", "data", "rir.wav"), help="Audio dara for room impulse response." ) parser.add_argument("--output-path", default=_get_path("pipeline.zip"), help="Output JIT file.") return parser.parse_args() def _main(): args = _parse_args() _create_jit_pipeline(args.rir_path, args.output_path) if __name__ == "__main__": _main()
# 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from packaging import version from .. import __version__ from .constants import ( CONFIG_NAME, DEPRECATED_REVISION_ARGS, DIFFUSERS_DYNAMIC_MODULE_NAME, FLAX_WEIGHTS_NAME, GGUF_FILE_EXTENSION, HF_MODULES_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MIN_PEFT_VERSION, ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFETENSORS_FILE_EXTENSION, SAFETENSORS_WEIGHTS_NAME, USE_PEFT_BACKEND, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .deprecation_utils import deprecate from .doc_utils import replace_example_docstring from .dynamic_modules_utils import get_class_from_dynamic_module from .export_utils import export_to_gif, export_to_obj, export_to_ply, export_to_video from .hub_utils import ( PushToHubMixin, _add_variant, _get_checkpoint_shard_files, _get_model_file, extract_commit_hash, http_user_agent, ) from .import_utils import ( BACKENDS_MAPPING, DIFFUSERS_SLOW_IMPORT, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, get_objects_from_module, is_accelerate_available, is_accelerate_version, is_bitsandbytes_available, is_bitsandbytes_version, is_bs4_available, is_flax_available, is_ftfy_available, is_gguf_available, is_gguf_version, is_google_colab, is_hf_hub_version, is_hpu_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_matplotlib_available, is_note_seq_available, is_onnx_available, is_opencv_available, is_optimum_quanto_available, is_optimum_quanto_version, is_peft_available, is_peft_version, is_safetensors_available, is_scipy_available, is_sentencepiece_available, is_tensorboard_available, is_timm_available, is_torch_available, is_torch_npu_available, is_torch_version, is_torch_xla_available, is_torch_xla_version, is_torchao_available, is_torchao_version, is_torchsde_available, is_torchvision_available, is_transformers_available, is_transformers_version, is_unidecode_available, is_wandb_available, is_xformers_available, requires_backends, ) from .loading_utils import get_module_from_name, get_submodule_by_name, load_image, load_video from .logging import get_logger from .outputs import BaseOutput from .peft_utils import ( check_peft_version, delete_adapter_layers, get_adapter_name, get_peft_kwargs, recurse_remove_peft_layers, scale_lora_layers, set_adapter_layers, set_weights_and_activate_adapters, unscale_lora_layers, ) from .pil_utils import PIL_INTERPOLATION, make_image_grid, numpy_to_pil, pt_to_pil from .remote_utils import remote_decode from .state_dict_utils import ( convert_all_state_dict_to_peft, convert_state_dict_to_diffusers, convert_state_dict_to_kohya, convert_state_dict_to_peft, convert_unet_state_dict_to_peft, state_dict_all_zero, ) from .typing_utils import _get_detailed_type, _is_valid_type logger = get_logger(__name__) def check_min_version(min_version): if version.parse(__version__) < version.parse(min_version): if "dev" in min_version: error_message = ( "This example requires a source install from HuggingFace diffusers (see " "`https://huggingface.co/docs/diffusers/installation#install-from-source`)," ) else: error_message = f"This example requires a minimum version of {min_version}," error_message += f" but the version found is {__version__}.\n" raise ImportError(error_message)
# 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from packaging import version from .. import __version__ from .constants import ( CONFIG_NAME, DEPRECATED_REVISION_ARGS, DIFFUSERS_DYNAMIC_MODULE_NAME, FLAX_WEIGHTS_NAME, GGUF_FILE_EXTENSION, HF_MODULES_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MIN_PEFT_VERSION, ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFETENSORS_FILE_EXTENSION, SAFETENSORS_WEIGHTS_NAME, USE_PEFT_BACKEND, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .deprecation_utils import deprecate from .doc_utils import replace_example_docstring from .dynamic_modules_utils import get_class_from_dynamic_module from .export_utils import export_to_gif, export_to_obj, export_to_ply, export_to_video from .hub_utils import ( PushToHubMixin, _add_variant, _get_checkpoint_shard_files, _get_model_file, extract_commit_hash, http_user_agent, ) from .import_utils import ( BACKENDS_MAPPING, DIFFUSERS_SLOW_IMPORT, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, get_objects_from_module, is_accelerate_available, is_accelerate_version, is_bitsandbytes_available, is_bitsandbytes_version, is_bs4_available, is_flax_available, is_ftfy_available, is_gguf_available, is_gguf_version, is_google_colab, is_hf_hub_version, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_matplotlib_available, is_note_seq_available, is_onnx_available, is_opencv_available, is_optimum_quanto_available, is_optimum_quanto_version, is_peft_available, is_peft_version, is_safetensors_available, is_scipy_available, is_sentencepiece_available, is_tensorboard_available, is_timm_available, is_torch_available, is_torch_npu_available, is_torch_version, is_torch_xla_available, is_torch_xla_version, is_torchao_available, is_torchao_version, is_torchsde_available, is_torchvision_available, is_transformers_available, is_transformers_version, is_unidecode_available, is_wandb_available, is_xformers_available, requires_backends, ) from .loading_utils import get_module_from_name, get_submodule_by_name, load_image, load_video from .logging import get_logger from .outputs import BaseOutput from .peft_utils import ( check_peft_version, delete_adapter_layers, get_adapter_name, get_peft_kwargs, recurse_remove_peft_layers, scale_lora_layers, set_adapter_layers, set_weights_and_activate_adapters, unscale_lora_layers, ) from .pil_utils import PIL_INTERPOLATION, make_image_grid, numpy_to_pil, pt_to_pil from .remote_utils import remote_decode from .state_dict_utils import ( convert_all_state_dict_to_peft, convert_state_dict_to_diffusers, convert_state_dict_to_kohya, convert_state_dict_to_peft, convert_unet_state_dict_to_peft, state_dict_all_zero, ) from .typing_utils import _get_detailed_type, _is_valid_type logger = get_logger(__name__) def check_min_version(min_version): if version.parse(__version__) < version.parse(min_version): if "dev" in min_version: error_message = ( "This example requires a source install from HuggingFace diffusers (see " "`https://huggingface.co/docs/diffusers/installation#install-from-source`)," ) else: error_message = f"This example requires a minimum version of {min_version}," error_message += f" but the version found is {__version__}.\n" raise ImportError(error_message)
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.import_module("langchain_core." + module_name) all_ = getattr(module, "__all__", []) for cls_ in all_: getattr(module, cls_) def try_to_import(module_name: str) -> tuple[int, str]: """Try to import a module via subprocess.""" module = importlib.import_module("langchain_core." + module_name) all_ = getattr(module, "__all__", []) for cls_ in all_: getattr(module, cls_) result = subprocess.run( ["python", "-c", f"import langchain_core.{module_name}"], check=True ) return result.returncode, module_name def test_importable_all_via_subprocess() -> None: """Test import in isolation. Note: ImportErrors due to circular imports can be raised for one sequence of imports but not another. """ module_names = [] for path in Path("../core/langchain_core/").glob("*"): module_name = path.stem if not module_name.startswith(".") and path.suffix != ".typed": module_names.append(module_name) with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: futures = [ executor.submit(try_to_import, module_name) for module_name in module_names ] for future in concurrent.futures.as_completed(futures): result = future.result() # Will raise an exception if the callable raised code, module_name = result if code != 0: msg = f"Failed to import {module_name}." raise ValueError(msg)
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.import_module("langchain_core." + module_name) all_ = getattr(module, "__all__", []) for cls_ in all_: getattr(module, cls_) def try_to_import(module_name: str) -> tuple[int, str]: """Try to import a module via subprocess.""" module = importlib.import_module("langchain_core." + module_name) all_ = getattr(module, "__all__", []) for cls_ in all_: getattr(module, cls_) result = subprocess.run( ["python", "-c", f"import langchain_core.{module_name}"], ) return result.returncode, module_name def test_importable_all_via_subprocess() -> None: """Test import in isolation. Note: ImportErrors due to circular imports can be raised for one sequence of imports but not another. """ module_names = [] for path in Path("../core/langchain_core/").glob("*"): module_name = path.stem if not module_name.startswith(".") and path.suffix != ".typed": module_names.append(module_name) with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: futures = [ executor.submit(try_to_import, module_name) for module_name in module_names ] for future in concurrent.futures.as_completed(futures): result = future.result() # Will raise an exception if the callable raised code, module_name = result if code != 0: msg = f"Failed to import {module_name}." raise ValueError(msg)
# 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 SampleList from mmdet.utils import ConfigType, OptConfigType from .single_stage import SingleStageDetector @MODELS.register_module() class KnowledgeDistillationSingleStageDetector(SingleStageDetector): r"""Implementation of `Distilling the Knowledge in a Neural Network. <https://arxiv.org/abs/1503.02531>`_. Args: backbone (:obj:`ConfigDict` or dict): The backbone module. neck (:obj:`ConfigDict` or dict): The neck module. bbox_head (:obj:`ConfigDict` or dict): The bbox head module. teacher_config (:obj:`ConfigDict` | dict | str | Path): Config file path or the config object of teacher model. teacher_ckpt (str, optional): Checkpoint path of teacher model. If left as None, the model will not load any weights. Defaults to True. eval_teacher (bool): Set the train mode for teacher. Defaults to True. train_cfg (:obj:`ConfigDict` or dict, optional): The training config of ATSS. Defaults to None. test_cfg (:obj:`ConfigDict` or dict, optional): The testing config of ATSS. Defaults to None. data_preprocessor (:obj:`ConfigDict` or dict, optional): Config of :class:`DetDataPreprocessor` to process the input data. Defaults to None. """ def __init__( self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, teacher_config: Union[ConfigType, str, Path], teacher_ckpt: Optional[str] = None, eval_teacher: bool = True, train_cfg: OptConfigType = None, test_cfg: OptConfigType = None, data_preprocessor: OptConfigType = None, ) -> None: super().__init__( backbone=backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, data_preprocessor=data_preprocessor) self.eval_teacher = eval_teacher # Build teacher model if isinstance(teacher_config, (str, Path)): teacher_config = Config.fromfile(teacher_config) self.teacher_model = MODELS.build(teacher_config['model']) if teacher_ckpt is not None: load_checkpoint( self.teacher_model, teacher_ckpt, map_location='cpu') def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList) -> dict: """ Args: batch_inputs (Tensor): Input images of shape (N, C, H, W). These should usually be mean centered and std scaled. batch_data_samples (list[:obj:`DetDataSample`]): The batch data samples. It usually includes information such as `gt_instance` or `gt_panoptic_seg` or `gt_sem_seg`. Returns: dict[str, Tensor]: A dictionary of loss components. """ x = self.extract_feat(batch_inputs) with torch.no_grad(): teacher_x = self.teacher_model.extract_feat(batch_inputs) out_teacher = self.teacher_model.bbox_head(teacher_x) losses = self.bbox_head.loss(x, out_teacher, batch_data_samples) return losses def cuda(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to cuda when calling ``cuda`` function.""" self.teacher_model.cuda(device=device) return super().cuda(device=device) def to(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to other device when calling ``to`` function.""" self.teacher_model.to(device=device) return super().to(device=device) def train(self, mode: bool = True) -> None: """Set the same train mode for teacher and student model.""" if self.eval_teacher: self.teacher_model.train(False) else: self.teacher_model.train(mode) super().train(mode) def __setattr__(self, name: str, value: Any) -> None: """Set attribute, i.e. self.name = value This reloading prevent the teacher model from being registered as a nn.Module. The teacher module is registered as a plain object, so that the teacher parameters will not show up when calling ``self.parameters``, ``self.modules``, ``self.children`` methods. """ if name == 'teacher_model': object.__setattr__(self, name, value) else: super().__setattr__(name, value)
# 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 import MODELS from mmdet.utils import ConfigType, OptConfigType from .single_stage import SingleStageDetector @MODELS.register_module() class KnowledgeDistillationSingleStageDetector(SingleStageDetector): r"""Implementation of `Distilling the Knowledge in a Neural Network. <https://arxiv.org/abs/1503.02531>`_. Args: backbone (:obj:`ConfigDict` or dict): The backbone module. neck (:obj:`ConfigDict` or dict): The neck module. bbox_head (:obj:`ConfigDict` or dict): The bbox head module. teacher_config (:obj:`ConfigDict` | dict | str | Path): Config file path or the config object of teacher model. teacher_ckpt (str, optional): Checkpoint path of teacher model. If left as None, the model will not load any weights. Defaults to True. eval_teacher (bool): Set the train mode for teacher. Defaults to True. train_cfg (:obj:`ConfigDict` or dict, optional): The training config of ATSS. Defaults to None. test_cfg (:obj:`ConfigDict` or dict, optional): The testing config of ATSS. Defaults to None. data_preprocessor (:obj:`ConfigDict` or dict, optional): Config of :class:`DetDataPreprocessor` to process the input data. Defaults to None. """ def __init__( self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, teacher_config: Union[ConfigType, str, Path], teacher_ckpt: Optional[str] = None, eval_teacher: bool = True, train_cfg: OptConfigType = None, test_cfg: OptConfigType = None, data_preprocessor: OptConfigType = None, ) -> None: super().__init__( backbone=backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, data_preprocessor=data_preprocessor) self.eval_teacher = eval_teacher # Build teacher model if isinstance(teacher_config, (str, Path)): teacher_config = Config.fromfile(teacher_config) self.teacher_model = MODELS.build(teacher_config['model']) if teacher_ckpt is not None: load_checkpoint( self.teacher_model, teacher_ckpt, map_location='cpu') def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList) -> dict: """ Args: batch_inputs (Tensor): Input images of shape (N, C, H, W). These should usually be mean centered and std scaled. batch_data_samples (list[:obj:`DetDataSample`]): The batch data samples. It usually includes information such as `gt_instance` or `gt_panoptic_seg` or `gt_sem_seg`. Returns: dict[str, Tensor]: A dictionary of loss components. """ x = self.extract_feat(batch_inputs) with torch.no_grad(): teacher_x = self.teacher_model.extract_feat(batch_inputs) out_teacher = self.teacher_model.bbox_head(teacher_x) losses = self.bbox_head.loss(x, out_teacher, batch_data_samples) return losses def cuda(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to cuda when calling ``cuda`` function.""" self.teacher_model.cuda(device=device) return super().cuda(device=device) def to(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to other device when calling ``to`` function.""" self.teacher_model.to(device=device) return super().to(device=device) def train(self, mode: bool = True) -> None: """Set the same train mode for teacher and student model.""" if self.eval_teacher: self.teacher_model.train(False) else: self.teacher_model.train(mode) super().train(mode) def __setattr__(self, name: str, value: Any) -> None: """Set attribute, i.e. self.name = value This reloading prevent the teacher model from being registered as a nn.Module. The teacher module is registered as a plain object, so that the teacher parameters will not show up when calling ``self.parameters``, ``self.modules``, ``self.children`` methods. """ if name == 'teacher_model': object.__setattr__(self, name, value) else: super().__setattr__(name, value)
__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): """ Encode the Document text into embedding. """ def __init__( self, model_name: str = 'all-MiniLM-L6-v2', traversal_paths: Iterable[str] = ('r',), batch_size: int = 32, device: str = 'cpu', *args, **kwargs ): """ :param model_name: The name of the sentence transformer to be used :param device: Torch device to put the model on (e.g. 'cpu', 'cuda', 'cuda:1') :param traversal_paths: Default traversal paths :param batch_size: Batch size to be used in the encoder model """ super().__init__(*args, **kwargs) self.batch_size = batch_size self.traversal_paths = traversal_paths self.model = SentenceTransformer(model_name, device=device) @requests def encode( self, docs: Optional[DocumentArray] = None, parameters: Dict = {}, **kwargs ): """ Encode all docs with text and store the encodings in the ``embedding`` attribute of the docs. :param docs: Documents to send to the encoder. They need to have the ``text`` attribute get an embedding. :param parameters: Any additional parameters for the `encode` function. """ if docs is None: return for batch in docs.traverse_flat( traversal_paths=parameters.get('traversal_paths', self.traversal_paths), filter_fn=lambda doc: len(doc.text) > 0, ).batch( batch_size=parameters.get('batch_size', self.batch_size), ): texts = batch.get_attributes('text') with torch.inference_mode(): embeddings = self.model.encode(texts) for doc, embedding in zip(batch, embeddings): doc.embedding = embedding
__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): """ Encode the Document text into embedding. """ def __init__( self, model_name: str = 'all-MiniLM-L6-v2', traversal_paths: Iterable[str] = ('r',), batch_size: int = 32, device: str = 'cpu', *args, **kwargs ): """ :param model_name: The name of the sentence transformer to be used :param device: Torch device to put the model on (e.g. 'cpu', 'cuda', 'cuda:1') :param traversal_paths: Default traversal paths :param batch_size: Batch size to be used in the encoder model """ super().__init__(*args, **kwargs) self.batch_size = batch_size self.traversal_paths = traversal_paths self.model = SentenceTransformer(model_name, device=device) @requests def encode( self, docs: Optional[DocumentArray] = None, parameters: Dict = {}, **kwargs ): """ Encode all docs with text and store the encodings in the ``embedding`` attribute of the docs. :param docs: Documents to send to the encoder. They need to have the ``text`` attribute get an embedding. :param parameters: Any additional parameters for the `encode` function. """ if docs is None: return for batch in docs.traverse_flat( traversal_paths=parameters.get('traversal_paths', self.traversal_paths), filter_fn=lambda doc: len(doc.text)>0 ).batch( batch_size=parameters.get('batch_size', self.batch_size), ): texts = batch.get_attributes('text') with torch.inference_mode(): embeddings = self.model.encode(texts) for doc, embedding in zip(batch, embeddings): doc.embedding = embedding
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(CosineSimilarityLoss): def __init__( self, model: SparseEncoder, loss_fct: nn.Module = nn.MSELoss(), cos_score_transformation: nn.Module = nn.Identity(), ) -> None: """ SparseCosineSimilarityLoss expects that the InputExamples consists of two texts and a float label. It computes the vectors ``u = model(sentence_A)`` and ``v = model(sentence_B)`` and measures the cosine-similarity between the two. By default, it minimizes the following loss: ``||input_label - cos_score_transformation(cosine_sim(u,v))||_2``. Args: model: SparseEncoder model loss_fct: Which pytorch loss function should be used to compare the ``cosine_similarity(u, v)`` with the input_label? By default, MSE is used: ``||input_label - cosine_sim(u, v)||_2`` cos_score_transformation: The cos_score_transformation function is applied on top of cosine_similarity. By default, the identify function is used (i.e. no change). Requirements: - Need to be used in SpladeLoss or CSRLoss as a loss function. - Sentence pairs with corresponding similarity scores in range `[0, 1]` Inputs: +--------------------------------+------------------------+ | Texts | Labels | +================================+========================+ | (sentence_A, sentence_B) pairs | float similarity score | +--------------------------------+------------------------+ Relations: - :class:`SparseAnglELoss` is :class:`SparseCoSENTLoss` with ``pairwise_angle_sim`` as the metric, rather than ``pairwise_cos_sim``. Example: :: from datasets import Dataset from sentence_transformers.sparse_encoder import SparseEncoder, SparseEncoderTrainer, losses model = SparseEncoder("distilbert/distilbert-base-uncased") train_dataset = Dataset.from_dict( { "sentence1": ["It's nice weather outside today.", "He drove to work."], "sentence2": ["It's so sunny.", "She walked to the store."], "score": [1.0, 0.3], } ) loss = losses.SpladeLoss( model=model, loss=losses.SparseCosineSimilarityLoss(model), corpus_regularizer_weight=5e-5, use_corpus_regularizer_only=True, ) trainer = SparseEncoderTrainer(model=model, train_dataset=train_dataset, loss=loss) trainer.train() """ model.similarity_fn_name = "cosine" return super().__init__(model, loss_fct=loss_fct, cos_score_transformation=cos_score_transformation) def forward(self, sentence_features: Iterable[dict[str, Tensor]], labels: Tensor) -> Tensor: raise AttributeError("SparseCosineSimilarityLoss should not be used alone. Use it with SpladeLoss or CSRLoss.")
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(CosineSimilarityLoss): def __init__( self, model: SparseEncoder, loss_fct: nn.Module = nn.MSELoss(), cos_score_transformation: nn.Module = nn.Identity(), ) -> None: """ SparseCosineSimilarityLoss expects that the InputExamples consists of two texts and a float label. It computes the vectors ``u = model(sentence_A)`` and ``v = model(sentence_B)`` and measures the cosine-similarity between the two. By default, it minimizes the following loss: ``||input_label - cos_score_transformation(cosine_sim(u,v))||_2``. Args: model: SparseEncoder model loss_fct: Which pytorch loss function should be used to compare the ``cosine_similarity(u, v)`` with the input_label? By default, MSE is used: ``||input_label - cosine_sim(u, v)||_2`` cos_score_transformation: The cos_score_transformation function is applied on top of cosine_similarity. By default, the identify function is used (i.e. no change). Requirements: - Need to be used in SpladeLoss or CSRLoss as a loss function. - Sentence pairs with corresponding similarity scores in range `[0, 1]` Inputs: +--------------------------------+------------------------+ | Texts | Labels | +================================+========================+ | (sentence_A, sentence_B) pairs | float similarity score | +--------------------------------+------------------------+ Relations: - :class:`SparseAnglELoss` is :class:`SparseCoSENTLoss` with ``pairwise_angle_sim`` as the metric, rather than ``pairwise_cos_sim``. Example: :: from datasets import Dataset from sentence_transformers.sparse_encoder import SparseEncoder, SparseEncoderTrainer, losses model = SparseEncoder("distilbert/distilbert-base-uncased") train_dataset = Dataset.from_dict( { "sentence1": ["It's nice weather outside today.", "He drove to work."], "sentence2": ["It's so sunny.", "She walked to the store."], "score": [1.0, 0.3], } ) loss = losses.SpladeLoss(model=model, loss=losses.SparseCosineSimilarityLoss(model), lambda_corpus=5e-5, all_docs=True) trainer = SparseEncoderTrainer(model=model, train_dataset=train_dataset, loss=loss) trainer.train() """ model.similarity_fn_name = "cosine" return super().__init__(model, loss_fct=loss_fct, cos_score_transformation=cos_score_transformation) def forward(self, sentence_features: Iterable[dict[str, Tensor]], labels: Tensor) -> Tensor: raise AttributeError("SparseCosineSimilarityLoss should not be used alone. Use it with SpladeLoss or CSRLoss.")
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 TextModerationInput(BaseModel): query: str = Field(description="Text to moderate") class EdenAiTextModerationTool(EdenaiTool): """Tool that queries the Eden AI Explicit text detection. for api reference check edenai documentation: https://docs.edenai.co/reference/image_explicit_content_create. To use, you should have the environment variable ``EDENAI_API_KEY`` set with your API token. You can find your token here: https://app.edenai.run/admin/account/settings """ name: str = "edenai_explicit_content_detection_text" description: str = ( "A wrapper around edenai Services explicit content detection for text. " """Useful for when you have to scan text for offensive, sexually explicit or suggestive content, it checks also if there is any content of self-harm, violence, racist or hate speech.""" """the structure of the output is : 'the type of the explicit content : the likelihood of it being explicit' the likelihood is a number between 1 and 5, 1 being the lowest and 5 the highest. something is explicit if the likelihood is equal or higher than 3. for example : nsfw_likelihood: 1 this is not explicit. for example : nsfw_likelihood: 3 this is explicit. """ "Input should be a string." ) args_schema: Type[BaseModel] = TextModerationInput language: str feature: str = "text" subfeature: str = "moderation" def _parse_response(self, response: list) -> str: formatted_result = [] for result in response: if "nsfw_likelihood" in result.keys(): formatted_result.append( "nsfw_likelihood: " + str(result["nsfw_likelihood"]) ) for label, likelihood in zip(result["label"], result["likelihood"]): formatted_result.append(f'"{label}": {str(likelihood)}') return "\n".join(formatted_result) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" query_params = {"text": query, "language": self.language} return self._call_eden_ai(query_params)
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 TextModerationInput(BaseModel): query: str = Field(description="Text to moderate") class EdenAiTextModerationTool(EdenaiTool): # type: ignore[override, override, override] """Tool that queries the Eden AI Explicit text detection. for api reference check edenai documentation: https://docs.edenai.co/reference/image_explicit_content_create. To use, you should have the environment variable ``EDENAI_API_KEY`` set with your API token. You can find your token here: https://app.edenai.run/admin/account/settings """ name: str = "edenai_explicit_content_detection_text" description: str = ( "A wrapper around edenai Services explicit content detection for text. " """Useful for when you have to scan text for offensive, sexually explicit or suggestive content, it checks also if there is any content of self-harm, violence, racist or hate speech.""" """the structure of the output is : 'the type of the explicit content : the likelihood of it being explicit' the likelihood is a number between 1 and 5, 1 being the lowest and 5 the highest. something is explicit if the likelihood is equal or higher than 3. for example : nsfw_likelihood: 1 this is not explicit. for example : nsfw_likelihood: 3 this is explicit. """ "Input should be a string." ) args_schema: Type[BaseModel] = TextModerationInput language: str feature: str = "text" subfeature: str = "moderation" def _parse_response(self, response: list) -> str: formatted_result = [] for result in response: if "nsfw_likelihood" in result.keys(): formatted_result.append( "nsfw_likelihood: " + str(result["nsfw_likelihood"]) ) for label, likelihood in zip(result["label"], result["likelihood"]): formatted_result.append(f'"{label}": {str(likelihood)}') return "\n".join(formatted_result) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" query_params = {"text": query, "language": self.language} return self._call_eden_ai(query_params)
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 sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder from sentence_transformers.datasets import ParallelSentencesDataset, SentencesDataset from sentence_transformers.LoggingHandler import LoggingHandler from sentence_transformers.model_card import SentenceTransformerModelCardData from sentence_transformers.quantization import quantize_embeddings from sentence_transformers.readers import InputExample from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.similarity_functions import SimilarityFunction from sentence_transformers.trainer import SentenceTransformerTrainer from sentence_transformers.training_args import SentenceTransformerTrainingArguments # If codecarbon is installed and the log level is not defined, # automatically overwrite the default to "error" if importlib.util.find_spec("codecarbon") and "CODECARBON_LOG_LEVEL" not in os.environ: os.environ["CODECARBON_LOG_LEVEL"] = "error" __all__ = [ "LoggingHandler", "SentencesDataset", "ParallelSentencesDataset", "SentenceTransformer", "SimilarityFunction", "InputExample", "CrossEncoder", "SentenceTransformerTrainer", "SentenceTransformerTrainingArguments", "SentenceTransformerModelCardData", "quantize_embeddings", "export_optimized_onnx_model", "export_dynamic_quantized_onnx_model", "export_static_quantized_openvino_model", ]
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 CrossEncoder from sentence_transformers.datasets import ParallelSentencesDataset, SentencesDataset from sentence_transformers.LoggingHandler import LoggingHandler from sentence_transformers.model_card import SentenceTransformerModelCardData from sentence_transformers.quantization import quantize_embeddings from sentence_transformers.readers import InputExample from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.similarity_functions import SimilarityFunction from sentence_transformers.trainer import SentenceTransformerTrainer from sentence_transformers.training_args import SentenceTransformerTrainingArguments # If codecarbon is installed and the log level is not defined, # automatically overwrite the default to "error" if importlib.util.find_spec("codecarbon") and "CODECARBON_LOG_LEVEL" not in os.environ: os.environ["CODECARBON_LOG_LEVEL"] = "error" __all__ = [ "LoggingHandler", "SentencesDataset", "ParallelSentencesDataset", "SentenceTransformer", "SimilarityFunction", "InputExample", "CrossEncoder", "SentenceTransformerTrainer", "SentenceTransformerTrainingArguments", "SentenceTransformerModelCardData", "quantize_embeddings", "export_optimized_onnx_model", "export_dynamic_quantized_onnx_model", ]
""" 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", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[LoggingHandler()] ) # Important, you need to shield your code with if __name__. Otherwise, CUDA runs into issues when spawning new processes. if __name__ == "__main__": # Create a large list of 100k sentences sentences = [f"This is sentence {i}" for i in range(100000)] # Define the model model = SentenceTransformer("all-MiniLM-L6-v2") # Start the multi-process pool on all available CUDA devices pool = model.start_multi_process_pool() # Compute the embeddings using the multi-process pool emb = model.encode(sentences, pool=pool) print("Embeddings computed. Shape:", emb.shape) # Optional: Stop the processes in the pool model.stop_multi_process_pool(pool)
""" 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", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[LoggingHandler()] ) # Important, you need to shield your code with if __name__. Otherwise, CUDA runs into issues when spawning new processes. if __name__ == "__main__": # Create a large list of 100k sentences sentences = [f"This is sentence {i}" for i in range(100000)] # Define the model model = SentenceTransformer("all-MiniLM-L6-v2") # Start the multi-process pool on all available CUDA devices pool = model.start_multi_process_pool() # Compute the embeddings using the multi-process pool emb = model.encode_multi_process(sentences, pool) print("Embeddings computed. Shape:", emb.shape) # Optional: Stop the processes in the pool model.stop_multi_process_pool(pool)
# 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 into X.""" import scipy.sparse from sklearn.metrics import mean_squared_error from sklearn.model_selection import StratifiedGroupKFold, cross_val_score X, y, q, _ = tm.make_ltr(n_samples=128, n_features=2, n_query_groups=8, max_rel=3) # pack qid into x using dataframe df = impl.DataFrame(X) df["qid"] = q ranker = xgb.XGBRanker(n_estimators=3, eval_metric="ndcg", tree_method=tree_method) ranker.fit(df, y) s = ranker.score(df, y) assert s > 0.7 # works with validation datasets as well valid_df = df.copy() valid_df.iloc[0, 0] = 3.0 ranker.fit(df, y, eval_set=[(valid_df, y)]) # same as passing qid directly ranker = xgb.XGBRanker(n_estimators=3, eval_metric="ndcg", tree_method=tree_method) ranker.fit(X, y, qid=q) s1 = ranker.score(df, y) assert np.isclose(s, s1) # Works with standard sklearn cv if tree_method != "gpu_hist": # we need cuML for this. kfold = StratifiedGroupKFold(shuffle=False) results = cross_val_score(ranker, df, y, cv=kfold, groups=df.qid) assert len(results) == 5 # Works with custom metric def neg_mse(*args: Any, **kwargs: Any) -> float: return -float(mean_squared_error(*args, **kwargs)) ranker = xgb.XGBRanker( n_estimators=3, eval_metric=neg_mse, tree_method=tree_method, disable_default_eval_metric=True, ) ranker.fit(df, y, eval_set=[(valid_df, y)]) score = ranker.score(valid_df, y) assert np.isclose(score, ranker.evals_result()["validation_0"]["neg_mse"][-1]) # Works with sparse data if tree_method != "gpu_hist": # no sparse with cuDF X_csr = scipy.sparse.csr_matrix(X) df = impl.DataFrame.sparse.from_spmatrix( X_csr, columns=[str(i) for i in range(X.shape[1])] ) df["qid"] = q ranker = xgb.XGBRanker( n_estimators=3, eval_metric="ndcg", tree_method=tree_method ) ranker.fit(df, y) s2 = ranker.score(df, y) assert np.isclose(s2, s) with pytest.raises(ValueError, match="Either `group` or `qid`."): ranker.fit(df, y, eval_set=[(X, y)]) def run_ranking_categorical(device: str) -> None: """Test LTR with categorical features.""" from sklearn.model_selection import cross_val_score X, y = tm.make_categorical( n_samples=512, n_features=10, n_categories=3, onehot=False ) rng = np.random.default_rng(1994) qid = rng.choice(3, size=y.shape[0]) qid = np.sort(qid) X["qid"] = qid ltr = xgb.XGBRanker(enable_categorical=True, device=device) ltr.fit(X, y) score = ltr.score(X, y) assert score > 0.9 ltr = xgb.XGBRanker(enable_categorical=True, device=device) # test using the score function inside sklearn. scores = cross_val_score(ltr, X, y) for s in scores: assert s > 0.7 def run_normalization(device: str) -> None: """Test normalization.""" X, y, qid, _ = tm.make_ltr(2048, 4, 64, 3) ltr = xgb.XGBRanker(objective="rank:pairwise", n_estimators=4, device=device) ltr.fit(X, y, qid=qid, eval_set=[(X, y)], eval_qid=[qid]) e0 = ltr.evals_result() ltr = xgb.XGBRanker( objective="rank:pairwise", n_estimators=4, device=device, lambdarank_normalization=False, ) ltr.fit(X, y, qid=qid, eval_set=[(X, y)], eval_qid=[qid]) e1 = ltr.evals_result() assert e1["validation_0"]["ndcg@32"][-1] > e0["validation_0"]["ndcg@32"][-1]
# 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 into X.""" import scipy.sparse from sklearn.metrics import mean_squared_error from sklearn.model_selection import StratifiedGroupKFold, cross_val_score X, y, q, _ = tm.make_ltr(n_samples=128, n_features=2, n_query_groups=8, max_rel=3) # pack qid into x using dataframe df = impl.DataFrame(X) df["qid"] = q ranker = xgb.XGBRanker(n_estimators=3, eval_metric="ndcg", tree_method=tree_method) ranker.fit(df, y) s = ranker.score(df, y) assert s > 0.7 # works with validation datasets as well valid_df = df.copy() valid_df.iloc[0, 0] = 3.0 ranker.fit(df, y, eval_set=[(valid_df, y)]) # same as passing qid directly ranker = xgb.XGBRanker(n_estimators=3, eval_metric="ndcg", tree_method=tree_method) ranker.fit(X, y, qid=q) s1 = ranker.score(df, y) assert np.isclose(s, s1) # Works with standard sklearn cv if tree_method != "gpu_hist": # we need cuML for this. kfold = StratifiedGroupKFold(shuffle=False) results = cross_val_score(ranker, df, y, cv=kfold, groups=df.qid) assert len(results) == 5 # Works with custom metric def neg_mse(*args: Any, **kwargs: Any) -> float: return -float(mean_squared_error(*args, **kwargs)) ranker = xgb.XGBRanker( n_estimators=3, eval_metric=neg_mse, tree_method=tree_method, disable_default_eval_metric=True, ) ranker.fit(df, y, eval_set=[(valid_df, y)]) score = ranker.score(valid_df, y) assert np.isclose(score, ranker.evals_result()["validation_0"]["neg_mse"][-1]) # Works with sparse data if tree_method != "gpu_hist": # no sparse with cuDF X_csr = scipy.sparse.csr_matrix(X) df = impl.DataFrame.sparse.from_spmatrix( X_csr, columns=[str(i) for i in range(X.shape[1])] ) df["qid"] = q ranker = xgb.XGBRanker( n_estimators=3, eval_metric="ndcg", tree_method=tree_method ) ranker.fit(df, y) s2 = ranker.score(df, y) assert np.isclose(s2, s) with pytest.raises(ValueError, match="Either `group` or `qid`."): ranker.fit(df, y, eval_set=[(X, y)]) def run_ranking_categorical(device: str) -> None: """Test LTR with categorical features.""" from sklearn.model_selection import cross_val_score X, y = tm.make_categorical( n_samples=512, n_features=10, n_categories=3, onehot=False ) rng = np.random.default_rng(1994) qid = rng.choice(3, size=y.shape[0]) qid = np.sort(qid) X["qid"] = qid ltr = xgb.XGBRanker(enable_categorical=True, device=device) ltr.fit(X, y) score = ltr.score(X, y) assert score > 0.9 ltr = xgb.XGBRanker(enable_categorical=True, device=device) # test using the score function inside sklearn. scores = cross_val_score(ltr, X, y) for s in scores: assert s > 0.7
# 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, HOOKS, INFERENCERS, LOG_PROCESSORS, LOOPS, METRICS, MODEL_WRAPPERS, MODELS, OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS, PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, TASK_UTILS, TRANSFORMS, VISBACKENDS, VISUALIZERS, WEIGHT_INITIALIZERS) from .utils import (count_registered_modules, init_default_scope, traverse_registry_tree) __all__ = [ 'Registry', 'RUNNERS', 'RUNNER_CONSTRUCTORS', 'HOOKS', 'DATASETS', 'DATA_SAMPLERS', 'TRANSFORMS', 'MODELS', 'WEIGHT_INITIALIZERS', 'OPTIMIZERS', 'OPTIM_WRAPPER_CONSTRUCTORS', 'TASK_UTILS', 'PARAM_SCHEDULERS', 'METRICS', 'MODEL_WRAPPERS', 'OPTIM_WRAPPERS', 'LOOPS', 'VISBACKENDS', 'VISUALIZERS', 'LOG_PROCESSORS', 'EVALUATOR', 'INFERENCERS', 'DefaultScope', 'traverse_registry_tree', 'count_registered_modules', 'build_model_from_cfg', 'build_runner_from_cfg', 'build_from_cfg', 'build_scheduler_from_cfg', 'init_default_scope' ]
# 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, HOOKS, LOG_PROCESSORS, LOOPS, METRICS, MODEL_WRAPPERS, MODELS, OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS, PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, TASK_UTILS, TRANSFORMS, VISBACKENDS, VISUALIZERS, WEIGHT_INITIALIZERS) from .utils import (count_registered_modules, init_default_scope, traverse_registry_tree) __all__ = [ 'Registry', 'RUNNERS', 'RUNNER_CONSTRUCTORS', 'HOOKS', 'DATASETS', 'DATA_SAMPLERS', 'TRANSFORMS', 'MODELS', 'WEIGHT_INITIALIZERS', 'OPTIMIZERS', 'OPTIM_WRAPPER_CONSTRUCTORS', 'TASK_UTILS', 'PARAM_SCHEDULERS', 'METRICS', 'MODEL_WRAPPERS', 'OPTIM_WRAPPERS', 'LOOPS', 'VISBACKENDS', 'VISUALIZERS', 'LOG_PROCESSORS', 'EVALUATOR', 'DefaultScope', 'traverse_registry_tree', 'count_registered_modules', 'build_model_from_cfg', 'build_runner_from_cfg', 'build_from_cfg', 'build_scheduler_from_cfg', 'init_default_scope' ]
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, ) try: from .version import __version__, git_version # noqa: F401 except ImportError: pass __all__ = [ "io", "compliance", "datasets", "functional", "models", "pipelines", "kaldi_io", "utils", "sox_effects", "transforms", "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 .version import __version__, git_version # noqa: F401 except ImportError: pass __all__ = [ "compliance", "datasets", "functional", "models", "pipelines", "kaldi_io", "utils", "sox_effects", "transforms", "list_audio_backends", "get_audio_backend", "set_audio_backend", ]
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.array.mixins.find import FindMixin from docarray.array.mixins.getattr import GetAttributeMixin from docarray.array.mixins.getitem import GetItemMixin from docarray.array.mixins.group import GroupMixin from docarray.array.mixins.io.binary import BinaryIOMixin from docarray.array.mixins.io.common import CommonIOMixin from docarray.array.mixins.io.csv import CsvIOMixin from docarray.array.mixins.io.dataframe import DataframeIOMixin from docarray.array.mixins.io.from_gen import FromGeneratorMixin from docarray.array.mixins.io.json import JsonIOMixin from docarray.array.mixins.io.pushpull import PushPullMixin from docarray.array.mixins.match import MatchMixin from docarray.array.mixins.parallel import ParallelMixin from docarray.array.mixins.plot import PlotMixin from docarray.array.mixins.post import PostMixin from docarray.array.mixins.pydantic import PydanticMixin from docarray.array.mixins.reduce import ReduceMixin from docarray.array.mixins.sample import SampleMixin from docarray.array.mixins.setitem import SetItemMixin from docarray.array.mixins.strawberry import StrawberryMixin from docarray.array.mixins.text import TextToolsMixin from docarray.array.mixins.traverse import TraverseMixin from docarray.array.mixins.dataloader import DataLoaderMixin class AllMixins( GetAttributeMixin, GetItemMixin, SetItemMixin, DelItemMixin, ContentPropertyMixin, PydanticMixin, StrawberryMixin, GroupMixin, EmptyMixin, CsvIOMixin, JsonIOMixin, BinaryIOMixin, CommonIOMixin, EmbedMixin, PushPullMixin, FromGeneratorMixin, FindMixin, MatchMixin, TraverseMixin, PlotMixin, SampleMixin, PostMixin, TextToolsMixin, EvaluationMixin, ReduceMixin, ParallelMixin, DataframeIOMixin, DataLoaderMixin, ABC, ): """All plugins that can be used in :class:`DocumentArray`.""" ...
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 GroupMixin from .io.binary import BinaryIOMixin from .io.common import CommonIOMixin from .io.csv import CsvIOMixin from .io.dataframe import DataframeIOMixin from .io.from_gen import FromGeneratorMixin from .io.json import JsonIOMixin from .io.pushpull import PushPullMixin from .match import MatchMixin from .parallel import ParallelMixin from .plot import PlotMixin from .post import PostMixin from .pydantic import PydanticMixin from .reduce import ReduceMixin from .sample import SampleMixin from .setitem import SetItemMixin from .strawberry import StrawberryMixin from .text import TextToolsMixin from .traverse import TraverseMixin from .dataloader import DataLoaderMixin class AllMixins( GetAttributeMixin, GetItemMixin, SetItemMixin, DelItemMixin, ContentPropertyMixin, PydanticMixin, StrawberryMixin, GroupMixin, EmptyMixin, CsvIOMixin, JsonIOMixin, BinaryIOMixin, CommonIOMixin, EmbedMixin, PushPullMixin, FromGeneratorMixin, FindMixin, MatchMixin, TraverseMixin, PlotMixin, SampleMixin, PostMixin, TextToolsMixin, EvaluationMixin, ReduceMixin, ParallelMixin, DataframeIOMixin, DataLoaderMixin, ABC, ): """All plugins that can be used in :class:`DocumentArray`.""" ...
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, "Argument `beta_1` must be in the \\[0, 1\\] range. Otherwise, the " "optimizer degenerates to SignSGD. Received: beta_1=-0.1.", ): Lion(beta_1=-0.1) with self.assertRaisesRegex( ValueError, "Argument `beta_1` must be in the \\[0, 1\\] range. Otherwise, the " "optimizer degenerates to SignSGD. Received: beta_1=0.0.", ): Lion(beta_1=0.0) with self.assertRaisesRegex( ValueError, "Argument `beta_1` must be in the \\[0, 1\\] range. Otherwise, the " "optimizer degenerates to SignSGD. Received: beta_1=1.1.", ): Lion(beta_1=1.1) def test_config(self): optimizer = Lion( learning_rate=0.5, beta_1=0.5, beta_2=0.67, ) self.run_class_serialization_test(optimizer) def test_single_step(self): optimizer = Lion(learning_rate=0.5) grads = ops.array([1.0, 6.0, 7.0, 2.0]) vars = backend.Variable([1.0, 2.0, 3.0, 4.0]) optimizer.apply_gradients(zip([grads], [vars])) self.assertAllClose(vars, [0.5, 1.5, 2.5, 3.5], rtol=1e-4, atol=1e-4) def test_weight_decay(self): grads, var1, var2, var3 = ( ops.zeros(()), backend.Variable(2.0), backend.Variable(2.0, name="exclude"), backend.Variable(2.0), ) optimizer_1 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_1.apply_gradients(zip([grads], [var1])) optimizer_2 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_2.exclude_from_weight_decay(var_names=["exclude"]) optimizer_2.apply_gradients(zip([grads, grads], [var1, var2])) optimizer_3 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_3.exclude_from_weight_decay(var_list=[var3]) optimizer_3.apply_gradients(zip([grads, grads], [var1, var3])) self.assertAlmostEqual(var1.numpy(), 1.9760959, decimal=6) self.assertAlmostEqual(var2.numpy(), 2.0, decimal=6) self.assertAlmostEqual(var3.numpy(), 2.0, decimal=6) def test_correctness_with_golden(self): optimizer = Lion() x = backend.Variable(np.ones([10])) grads = ops.arange(0.1, 1.1, 0.1) first_grads = ops.full((10,), 0.01) golden = np.tile( [[0.999], [0.998], [0.997], [0.996], [0.995]], (1, 10), ) optimizer.apply_gradients(zip([first_grads], [x])) for i in range(5): self.assertAllClose(x, golden[i], rtol=5e-4, atol=5e-4) optimizer.apply_gradients(zip([grads], [x])) def test_clip_norm(self): optimizer = Lion(clipnorm=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [2**0.5 / 2, 2**0.5 / 2]) def test_clip_value(self): optimizer = Lion(clipvalue=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [1.0, 1.0]) @pytest.mark.requires_trainable_backend def test_ema(self): # TODO: test correctness model = keras.Sequential([keras.layers.Dense(10)]) model.compile(optimizer=Lion(use_ema=True), loss="mse") x = keras.ops.zeros((1, 5)) y = keras.ops.zeros((1, 10)) model.fit(x, y)
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, beta_2=0.67, ) self.run_class_serialization_test(optimizer) def test_single_step(self): optimizer = Lion(learning_rate=0.5) grads = ops.array([1.0, 6.0, 7.0, 2.0]) vars = backend.Variable([1.0, 2.0, 3.0, 4.0]) optimizer.apply_gradients(zip([grads], [vars])) self.assertAllClose(vars, [0.5, 1.5, 2.5, 3.5], rtol=1e-4, atol=1e-4) def test_weight_decay(self): grads, var1, var2, var3 = ( ops.zeros(()), backend.Variable(2.0), backend.Variable(2.0, name="exclude"), backend.Variable(2.0), ) optimizer_1 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_1.apply_gradients(zip([grads], [var1])) optimizer_2 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_2.exclude_from_weight_decay(var_names=["exclude"]) optimizer_2.apply_gradients(zip([grads, grads], [var1, var2])) optimizer_3 = Lion(learning_rate=1.0, weight_decay=0.004) optimizer_3.exclude_from_weight_decay(var_list=[var3]) optimizer_3.apply_gradients(zip([grads, grads], [var1, var3])) self.assertAlmostEqual(var1.numpy(), 1.9760959, decimal=6) self.assertAlmostEqual(var2.numpy(), 2.0, decimal=6) self.assertAlmostEqual(var3.numpy(), 2.0, decimal=6) def test_correctness_with_golden(self): optimizer = Lion() x = backend.Variable(np.ones([10])) grads = ops.arange(0.1, 1.1, 0.1) first_grads = ops.full((10,), 0.01) golden = np.tile( [[0.999], [0.998], [0.997], [0.996], [0.995]], (1, 10), ) optimizer.apply_gradients(zip([first_grads], [x])) for i in range(5): self.assertAllClose(x, golden[i], rtol=5e-4, atol=5e-4) optimizer.apply_gradients(zip([grads], [x])) def test_clip_norm(self): optimizer = Lion(clipnorm=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [2**0.5 / 2, 2**0.5 / 2]) def test_clip_value(self): optimizer = Lion(clipvalue=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [1.0, 1.0]) @pytest.mark.requires_trainable_backend def test_ema(self): # TODO: test correctness model = keras.Sequential([keras.layers.Dense(10)]) model.compile(optimizer=Lion(use_ema=True), loss="mse") x = keras.ops.zeros((1, 5)) y = keras.ops.zeros((1, 10)) model.fit(x, y)
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 average value over the window defined by `pool_size`. The window is shifted by `strides`. The resulting output when using "valid" padding option has a shape of: `output_shape = (input_shape - pool_size + 1) / strides)` The resulting output shape when using the "same" padding option is: `output_shape = input_shape / strides` Args: pool_size: int, size of the max pooling window. strides: int or None. Specifies how much the pooling window moves for each pooling step. If None, it will default to `pool_size`. padding: string, either `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, steps, features)` while `"channels_first"` corresponds to inputs with shape `(batch, features, steps)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `"channels_last"`. Input shape: - If `data_format="channels_last"`: 3D tensor with shape `(batch_size, steps, features)`. - If `data_format="channels_first"`: 3D tensor with shape `(batch_size, features, steps)`. Output shape: - If `data_format="channels_last"`: 3D tensor with shape `(batch_size, downsampled_steps, features)`. - If `data_format="channels_first"`: 3D tensor with shape `(batch_size, features, downsampled_steps)`. Examples: `strides=1` and `padding="valid"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding="valid") >>> avg_pool_1d(x) `strides=2` and `padding="valid"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=2, padding="valid") >>> avg_pool_1d(x) `strides=1` and `padding="same"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding="same") >>> avg_pool_1d(x) """ def __init__( self, pool_size, strides=None, padding="valid", data_format=None, name=None, **kwargs ): super().__init__( pool_size, strides, pool_dimensions=1, pool_mode="average", padding=padding, data_format=data_format, name=name, **kwargs, )
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 average value over the window defined by `pool_size`. The window is shifted by `strides`. The resulting output when using "valid" padding option has a shape of: `output_shape = (input_shape - pool_size + 1) / strides)` The resulting output shape when using the "same" padding option is: `output_shape = input_shape / strides` Args: pool_size: int, size of the max pooling window. strides: int or None. Specifies how much the pooling window moves for each pooling step. If None, it will default to `pool_size`. padding: string, either `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, steps, features)` while `"channels_first"` corresponds to inputs with shape `(batch, features, steps)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `"channels_last"`. Input shape: - If `data_format="channels_last"`: 3D tensor with shape `(batch_size, steps, features)`. - If `data_format="channels_first"`: 3D tensor with shape `(batch_size, features, steps)`. Output shape: - If `data_format="channels_last"`: 3D tensor with shape `(batch_size, downsampled_steps, features)`. - If `data_format="channels_first"`: 3D tensor with shape `(batch_size, features, downsampled_steps)`. Examples: `strides=1` and `padding="valid"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding="valid") >>> avg_pool_1d(x) `strides=2` and `padding="valid"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=2, padding="valid") >>> avg_pool_1d(x) `strides=1` and `padding="same"`: >>> x = np.array([1., 2., 3., 4., 5.]) >>> x = np.reshape(x, [1, 5, 1]) >>> avg_pool_1d = keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding="same") >>> avg_pool_1d(x) """ def __init__( self, pool_size, strides=None, padding="valid", data_format=None, name=None, **kwargs ): super().__init__( pool_size, strides, pool_dimensions=1, pool_mode="average", padding=padding, data_format=data_format, name=name, **kwargs, )
"""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 AutoContrast(BaseImagePreprocessingLayer): """Performs the auto-contrast operation on an image. Auto contrast stretches the values of an image across the entire available `value_range`. This makes differences between pixels more obvious. An example of this is if an image only has values `[0, 1]` out of the range `[0, 255]`, auto contrast will change the `1` values to be `255`. This layer is active at both training and inference time. Args: value_range: Range of values the incoming images will have. Represented as a two number tuple written `(low, high)`. This is typically either `(0, 1)` or `(0, 255)` depending on how your preprocessing pipeline is set up. Defaults to `(0, 255)`. """ _USE_BASE_FACTOR = False _VALUE_RANGE_VALIDATION_ERROR = ( "The `value_range` argument should be a list of two numbers. " ) def __init__( self, value_range=(0, 255), **kwargs, ): super().__init__(**kwargs) self._set_value_range(value_range) def _set_value_range(self, value_range): if not isinstance(value_range, (tuple, list)): raise ValueError( self._VALUE_RANGE_VALIDATION_ERROR + f"Received: value_range={value_range}" ) if len(value_range) != 2: raise ValueError( self._VALUE_RANGE_VALIDATION_ERROR + f"Received: value_range={value_range}" ) self.value_range = sorted(value_range) def transform_images(self, images, transformation=None, training=True): original_images = images images = self._transform_value_range( images, original_range=self.value_range, target_range=(0, 255), dtype=self.compute_dtype, ) images = self.backend.cast(images, self.compute_dtype) low = self.backend.numpy.min(images, axis=(1, 2), keepdims=True) high = self.backend.numpy.max(images, axis=(1, 2), keepdims=True) scale = 255.0 / (high - low) offset = -low * scale images = images * scale + offset results = self.backend.numpy.clip(images, 0.0, 255.0) results = self._transform_value_range( results, original_range=(0, 255), target_range=self.value_range, dtype=self.compute_dtype, ) # don't process NaN channels results = self.backend.numpy.where( self.backend.numpy.isnan(results), original_images, results ) if results.dtype == images.dtype: return results if backend.is_int_dtype(images.dtype): results = self.backend.numpy.round(results) return _saturate_cast(results, images.dtype, self.backend) def transform_labels(self, labels, transformation, training=True): return labels def transform_bounding_boxes( self, bounding_boxes, transformation, training=True, ): return bounding_boxes def transform_segmentation_masks( self, segmentation_masks, transformation, training=True ): return segmentation_masks def get_config(self): config = super().get_config() config.update({"value_range": self.value_range}) return config def compute_output_shape(self, input_shape): return input_shape
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 AutoContrast(BaseImagePreprocessingLayer): """Performs the auto-contrast operation on an image. Auto contrast stretches the values of an image across the entire available `value_range`. This makes differences between pixels more obvious. An example of this is if an image only has values `[0, 1]` out of the range `[0, 255]`, auto contrast will change the `1` values to be `255`. This layer is active at both training and inference time. Args: value_range: Range of values the incoming images will have. Represented as a two number tuple written `(low, high)`. This is typically either `(0, 1)` or `(0, 255)` depending on how your preprocessing pipeline is set up. Defaults to `(0, 255)`. """ _USE_BASE_FACTOR = False _VALUE_RANGE_VALIDATION_ERROR = ( "The `value_range` argument should be a list of two numbers. " ) def __init__( self, value_range=(0, 255), **kwargs, ): super().__init__(**kwargs) self._set_value_range(value_range) def _set_value_range(self, value_range): if not isinstance(value_range, (tuple, list)): raise ValueError( self._VALUE_RANGE_VALIDATION_ERROR + f"Received: value_range={value_range}" ) if len(value_range) != 2: raise ValueError( self._VALUE_RANGE_VALIDATION_ERROR + f"Received: value_range={value_range}" ) self.value_range = sorted(value_range) def transform_images(self, images, transformation=None, training=True): original_images = images images = self._transform_value_range( images, original_range=self.value_range, target_range=(0, 255), dtype=self.compute_dtype, ) images = self.backend.cast(images, self.compute_dtype) low = self.backend.numpy.min(images, axis=(1, 2), keepdims=True) high = self.backend.numpy.max(images, axis=(1, 2), keepdims=True) scale = 255.0 / (high - low) offset = -low * scale images = images * scale + offset results = self.backend.numpy.clip(images, 0.0, 255.0) results = self._transform_value_range( results, original_range=(0, 255), target_range=self.value_range, dtype=self.compute_dtype, ) # don't process NaN channels results = self.backend.numpy.where( self.backend.numpy.isnan(results), original_images, results ) if results.dtype == images.dtype: return results if backend.is_int_dtype(images.dtype): results = self.backend.numpy.round(results) return _saturate_cast(results, images.dtype, self.backend) def transform_labels(self, labels, transformation, training=True): return labels def transform_bounding_boxes( self, bounding_boxes, transformation, training=True ): return bounding_boxes def transform_segmentation_masks( self, segmentation_masks, transformation, training=True ): return segmentation_masks def get_config(self): config = super().get_config() config.update({"value_range": self.value_range}) return config def compute_output_shape(self, input_shape): return input_shape
"""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]: """ Get collection of nodes up to certain level including leaf nodes. Args: root (ET.Element): XML Root Element level (int): Levels to traverse in the tree Returns: List[ET.Element]: List of target nodes """ def traverse(current_node, current_level): if len(current_node) == 0 or level == current_level: # Keep leaf nodes and target level nodes nodes.append(current_node) elif current_level < level: # Move to the next level for child in current_node: traverse(child, current_level + 1) nodes = [] traverse(root, 0) return nodes class XMLReader(BaseReader): """ XML reader. Reads XML documents with options to help suss out relationships between nodes. Args: tree_level_split (int): From which level in the xml tree we split documents, the default level is the root which is level 0 """ def __init__(self, tree_level_split: Optional[int] = 0) -> None: """Initialize with arguments.""" super().__init__() self.tree_level_split = tree_level_split def _parse_xmlelt_to_document( self, root: ET.Element, extra_info: Optional[Dict] = None ) -> List[Document]: """ Parse the xml object into a list of Documents. Args: root: The XML Element to be converted. extra_info (Optional[Dict]): Additional information. Default is None. Returns: Document: The documents. """ nodes = _get_leaf_nodes_up_to_level(root, self.tree_level_split) documents = [] for node in nodes: content = ET.tostring(node, encoding="utf8").decode("utf-8") content = re.sub(r"^<\?xml.*", "", content) content = content.strip() documents.append(Document(text=content, extra_info=extra_info or {})) return documents def load_data( self, file: Path, extra_info: Optional[Dict] = None, ) -> List[Document]: """ Load data from the input file. Args: file (Path): Path to the input file. extra_info (Optional[Dict]): Additional information. Default is None. Returns: List[Document]: List of documents. """ if not isinstance(file, Path): file = Path(file) tree = ET.parse(file) return self._parse_xmlelt_to_document(tree.getroot(), extra_info)
"""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]: """Get collection of nodes up to certain level including leaf nodes. Args: root (ET.Element): XML Root Element level (int): Levels to traverse in the tree Returns: List[ET.Element]: List of target nodes """ def traverse(current_node, current_level): if len(current_node) == 0 or level == current_level: # Keep leaf nodes and target level nodes nodes.append(current_node) elif current_level < level: # Move to the next level for child in current_node: traverse(child, current_level + 1) nodes = [] traverse(root, 0) return nodes class XMLReader(BaseReader): """XML reader. Reads XML documents with options to help suss out relationships between nodes. Args: tree_level_split (int): From which level in the xml tree we split documents, the default level is the root which is level 0 """ def __init__(self, tree_level_split: Optional[int] = 0) -> None: """Initialize with arguments.""" super().__init__() self.tree_level_split = tree_level_split def _parse_xmlelt_to_document( self, root: ET.Element, extra_info: Optional[Dict] = None ) -> List[Document]: """Parse the xml object into a list of Documents. Args: root: The XML Element to be converted. extra_info (Optional[Dict]): Additional information. Default is None. Returns: Document: The documents. """ nodes = _get_leaf_nodes_up_to_level(root, self.tree_level_split) documents = [] for node in nodes: content = ET.tostring(node, encoding="utf8").decode("utf-8") content = re.sub(r"^<\?xml.*", "", content) content = content.strip() documents.append(Document(text=content, extra_info=extra_info or {})) return documents def load_data( self, file: Path, extra_info: Optional[Dict] = None, ) -> List[Document]: """Load data from the input file. Args: file (Path): Path to the input file. extra_info (Optional[Dict]): Additional information. Default is None. Returns: List[Document]: List of documents. """ if not isinstance(file, Path): file = Path(file) tree = ET.parse(file) return self._parse_xmlelt_to_document(tree.getroot(), extra_info)
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, reason="OPENAI_API_KEY not available to test Cognee integration", ) @pytest.mark.asyncio async def test_graph_rag_cognee(): documents = [ Document( text="Jessica Miller, Experienced Sales Manager with a strong track record in driving sales growth and building high-performing teams." ), Document( text="David Thompson, Creative Graphic Designer with over 8 years of experience in visual design and branding." ), ] # Instantiate cognee GraphRAG cogneeRAG = CogneeGraphRAG( llm_api_key=os.environ["OPENAI_API_KEY"], llm_provider="openai", llm_model="gpt-4o-mini", graph_db_provider="networkx", vector_db_provider="lancedb", relational_db_provider="sqlite", relational_db_name="cognee_db", ) # Add data to cognee await cogneeRAG.add(documents, "test") # Process data into a knowledge graph await cogneeRAG.process_data("test") # Answer prompt based on knowledge graph search_results = await cogneeRAG.search("Tell me who are the people mentioned?") assert len(search_results) > 0, "No search results found" print("\n\nAnswer based on knowledge graph:\n") for result in search_results: print(f"{result}\n") # Answer prompt based on RAG search_results = await cogneeRAG.rag_search("Tell me who are the people mentioned?") assert len(search_results) > 0, "No search results found" print("\n\nAnswer based on RAG:\n") for result in search_results: print(f"{result}\n") # Search for related nodes search_results = await cogneeRAG.get_related_nodes("person") print("\n\nRelated nodes are:\n") for result in search_results: print(f"{result}\n") assert len(search_results) > 0, "No search results found" # Clean all data from previous runs await cognee.prune.prune_data() await cognee.prune.prune_system(metadata=True)
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, reason="OPENAI_API_KEY not available to test Cognee integration", ) @pytest.mark.asyncio() async def test_graph_rag_cognee(): documents = [ Document( text="Jessica Miller, Experienced Sales Manager with a strong track record in driving sales growth and building high-performing teams." ), Document( text="David Thompson, Creative Graphic Designer with over 8 years of experience in visual design and branding." ), ] # Instantiate cognee GraphRAG cogneeRAG = CogneeGraphRAG( llm_api_key=os.environ["OPENAI_API_KEY"], llm_provider="openai", llm_model="gpt-4o-mini", graph_db_provider="networkx", vector_db_provider="lancedb", relational_db_provider="sqlite", relational_db_name="cognee_db", ) # Add data to cognee await cogneeRAG.add(documents, "test") # Process data into a knowledge graph await cogneeRAG.process_data("test") # Answer prompt based on knowledge graph search_results = await cogneeRAG.search("Tell me who are the people mentioned?") assert len(search_results) > 0, "No search results found" print("\n\nAnswer based on knowledge graph:\n") for result in search_results: print(f"{result}\n") # Answer prompt based on RAG search_results = await cogneeRAG.rag_search("Tell me who are the people mentioned?") assert len(search_results) > 0, "No search results found" print("\n\nAnswer based on RAG:\n") for result in search_results: print(f"{result}\n") # Search for related nodes search_results = await cogneeRAG.get_related_nodes("person") print("\n\nRelated nodes are:\n") for result in search_results: print(f"{result}\n") assert len(search_results) > 0, "No search results found" # Clean all data from previous runs await cognee.prune.prune_data() await cognee.prune.prune_system(metadata=True)
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 hard_shrink from keras.src.activations.activations import hard_sigmoid from keras.src.activations.activations import hard_silu from keras.src.activations.activations import hard_tanh from keras.src.activations.activations import leaky_relu from keras.src.activations.activations import linear from keras.src.activations.activations import log_sigmoid from keras.src.activations.activations import log_softmax from keras.src.activations.activations import mish from keras.src.activations.activations import relu from keras.src.activations.activations import relu6 from keras.src.activations.activations import selu from keras.src.activations.activations import sigmoid from keras.src.activations.activations import silu from keras.src.activations.activations import softmax from keras.src.activations.activations import softplus from keras.src.activations.activations import softsign from keras.src.activations.activations import tanh from keras.src.api_export import keras_export from keras.src.saving import object_registration from keras.src.saving import serialization_lib ALL_OBJECTS = { relu, leaky_relu, relu6, softmax, celu, elu, selu, softplus, softsign, silu, gelu, glu, tanh, sigmoid, exponential, hard_sigmoid, hard_silu, hard_tanh, hard_shrink, linear, mish, log_softmax, log_sigmoid, } ALL_OBJECTS_DICT = {fn.__name__: fn for fn in ALL_OBJECTS} # Additional aliases ALL_OBJECTS_DICT["swish"] = silu ALL_OBJECTS_DICT["hard_swish"] = hard_silu @keras_export("keras.activations.serialize") def serialize(activation): fn_config = serialization_lib.serialize_keras_object(activation) if "config" not in fn_config: raise ValueError( f"Unknown activation function '{activation}' cannot be " "serialized due to invalid function name. Make sure to use " "an activation name that matches the references defined in " "activations.py or use " "`@keras.saving.register_keras_serializable()`" "to register any custom activations. " f"config={fn_config}" ) if not isinstance(activation, types.FunctionType): # Case for additional custom activations represented by objects return fn_config if ( isinstance(fn_config["config"], str) and fn_config["config"] not in globals() ): # Case for custom activation functions from external activations modules fn_config["config"] = object_registration.get_registered_name( activation ) return fn_config # Case for keras.activations builtins (simply return name) return fn_config["config"] @keras_export("keras.activations.deserialize") def deserialize(config, custom_objects=None): """Return a Keras activation function via its config.""" return serialization_lib.deserialize_keras_object( config, module_objects=ALL_OBJECTS_DICT, custom_objects=custom_objects, ) @keras_export("keras.activations.get") def get(identifier): """Retrieve a Keras activation function via an identifier.""" if identifier is None: return linear if isinstance(identifier, dict): obj = deserialize(identifier) elif isinstance(identifier, str): obj = ALL_OBJECTS_DICT.get(identifier, None) else: obj = identifier if callable(obj): return obj raise ValueError( f"Could not interpret activation function identifier: {identifier}" )
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 hard_sigmoid from keras.src.activations.activations import hard_silu from keras.src.activations.activations import hard_tanh from keras.src.activations.activations import leaky_relu from keras.src.activations.activations import linear from keras.src.activations.activations import log_sigmoid from keras.src.activations.activations import log_softmax from keras.src.activations.activations import mish from keras.src.activations.activations import relu from keras.src.activations.activations import relu6 from keras.src.activations.activations import selu from keras.src.activations.activations import sigmoid from keras.src.activations.activations import silu from keras.src.activations.activations import softmax from keras.src.activations.activations import softplus from keras.src.activations.activations import softsign from keras.src.activations.activations import tanh from keras.src.api_export import keras_export from keras.src.saving import object_registration from keras.src.saving import serialization_lib ALL_OBJECTS = { relu, leaky_relu, relu6, softmax, celu, elu, selu, softplus, softsign, silu, gelu, glu, tanh, sigmoid, exponential, hard_sigmoid, hard_silu, hard_tanh, linear, mish, log_softmax, log_sigmoid, } ALL_OBJECTS_DICT = {fn.__name__: fn for fn in ALL_OBJECTS} # Additional aliases ALL_OBJECTS_DICT["swish"] = silu ALL_OBJECTS_DICT["hard_swish"] = hard_silu @keras_export("keras.activations.serialize") def serialize(activation): fn_config = serialization_lib.serialize_keras_object(activation) if "config" not in fn_config: raise ValueError( f"Unknown activation function '{activation}' cannot be " "serialized due to invalid function name. Make sure to use " "an activation name that matches the references defined in " "activations.py or use " "`@keras.saving.register_keras_serializable()`" "to register any custom activations. " f"config={fn_config}" ) if not isinstance(activation, types.FunctionType): # Case for additional custom activations represented by objects return fn_config if ( isinstance(fn_config["config"], str) and fn_config["config"] not in globals() ): # Case for custom activation functions from external activations modules fn_config["config"] = object_registration.get_registered_name( activation ) return fn_config # Case for keras.activations builtins (simply return name) return fn_config["config"] @keras_export("keras.activations.deserialize") def deserialize(config, custom_objects=None): """Return a Keras activation function via its config.""" return serialization_lib.deserialize_keras_object( config, module_objects=ALL_OBJECTS_DICT, custom_objects=custom_objects, ) @keras_export("keras.activations.get") def get(identifier): """Retrieve a Keras activation function via an identifier.""" if identifier is None: return linear if isinstance(identifier, dict): obj = deserialize(identifier) elif isinstance(identifier, str): obj = ALL_OBJECTS_DICT.get(identifier, None) else: obj = identifier if callable(obj): return obj raise ValueError( f"Could not interpret activation function identifier: {identifier}" )
""" 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 traceback from datasets import load_dataset from sentence_transformers import ( SparseEncoder, SparseEncoderModelCardData, SparseEncoderTrainer, SparseEncoderTrainingArguments, ) from sentence_transformers.sparse_encoder import evaluation, losses # Set the log level to INFO to get more information logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def main(): model_name = "distilbert/distilbert-base-uncased" train_batch_size = 12 num_epochs = 1 lambda_query = 5e-5 lambda_corpus = 3e-5 learning_rate = 2e-5 # 1. Define our SparseEncoder model model = SparseEncoder( model_name, model_card_data=SparseEncoderModelCardData( language="en", license="apache-2.0", model_name="splade-distilbert-base-uncased trained on Quora Duplicates Questions", ), ) model.max_seq_length = 256 # Set the max sequence length to 256 for the training logging.info("Model max length: %s", model.max_seq_length) # 2. Load the MS MARCO dataset: https://huggingface.co/datasets/sentence-transformers/msmarco-bm25 logging.info("Read the MS MARCO training dataset") full_dataset = load_dataset("sentence-transformers/quora-duplicates", "triplet", split="train").select( range(100000) ) dataset_dict = full_dataset.train_test_split(test_size=1_000, seed=12) train_dataset = dataset_dict["train"] eval_dataset = dataset_dict["test"] logging.info(train_dataset) logging.info(eval_dataset) # 3. Define our training loss loss = losses.SpladeLoss( model=model, loss=losses.SparseMultipleNegativesRankingLoss(model=model), lambda_query=lambda_query, # Weight for query loss lambda_corpus=lambda_corpus, # Weight for document loss ) # 4. Define the evaluator. We use the SparseNanoBEIREvaluator, which is a light-weight evaluator for English evaluator = evaluation.SparseNanoBEIREvaluator( dataset_names=["msmarco", "nfcorpus", "nq"], batch_size=train_batch_size ) # 5. Define the training arguments short_model_name = model_name if "/" not in model_name else model_name.split("/")[-1] run_name = f"splade-{short_model_name}-msmarco-mrl" args = SparseEncoderTrainingArguments( # Required parameter: output_dir=f"models/{run_name}", # Optional training parameters: num_train_epochs=num_epochs, per_device_train_batch_size=train_batch_size, per_device_eval_batch_size=train_batch_size, learning_rate=learning_rate, load_best_model_at_end=True, metric_for_best_model="eval_NanoBEIR_mean_dot_ndcg@10", fp16=False, # Set to False if you get an error that your GPU can't run on FP16 bf16=True, # Set to True if you have a GPU that supports BF16 # Optional tracking/debugging parameters: eval_strategy="steps", eval_steps=1650, save_strategy="steps", save_steps=1650, save_total_limit=2, logging_steps=200, run_name=run_name, # Will be used in W&B if `wandb` is installed seed=42, ) # 6. Create the trainer & start training trainer = SparseEncoderTrainer( model=model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, loss=loss, evaluator=evaluator, ) trainer.train() # 7. Evaluate the final model, using the complete NanoBEIR dataset test_evaluator = evaluation.SparseNanoBEIREvaluator(show_progress_bar=True, batch_size=train_batch_size) test_evaluator(model) # 8. Save the final model final_output_dir = f"models/{run_name}/final" model.save_pretrained(final_output_dir) # 9. (Optional) save the model to the Hugging Face Hub! # It is recommended to run `huggingface-cli login` to log into your Hugging Face account first try: model.push_to_hub(run_name) except Exception: logging.error( f"Error uploading model to the Hugging Face Hub:\n{traceback.format_exc()}To upload it manually, you can run " f"`huggingface-cli login`, followed by loading the model using `model = SparseEncoder({final_output_dir!r})` " f"and saving it using `model.push_to_hub('{run_name}')`." ) if __name__ == "__main__": main()
""" 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 traceback from datasets import load_dataset from sentence_transformers import ( SparseEncoder, SparseEncoderModelCardData, SparseEncoderTrainer, SparseEncoderTrainingArguments, ) from sentence_transformers.sparse_encoder import evaluation, losses # Set the log level to INFO to get more information logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def main(): model_name = "distilbert/distilbert-base-uncased" train_batch_size = 12 num_epochs = 1 lambda_query = 5e-5 lambda_corpus = 3e-5 learning_rate = 2e-5 # 1. Define our SparseEncoder model model = SparseEncoder( model_name, model_card_data=SparseEncoderModelCardData( language="en", license="apache-2.0", model_name="splade-distilbert-base-uncased trained on Quora Duplicates Questions", ), ) model.max_seq_length = 256 # Set the max sequence length to 256 for the training logging.info("Model max length:", model.max_seq_length) # 2. Load the MS MARCO dataset: https://huggingface.co/datasets/sentence-transformers/msmarco-bm25 logging.info("Read the MS MARCO training dataset") full_dataset = load_dataset("sentence-transformers/quora-duplicates", "triplet", split="train").select( range(100000) ) dataset_dict = full_dataset.train_test_split(test_size=1_000, seed=12) train_dataset = dataset_dict["train"] eval_dataset = dataset_dict["test"] logging.info(train_dataset) logging.info(eval_dataset) # 3. Define our training loss loss = losses.SpladeLoss( model=model, loss=losses.SparseMultipleNegativesRankingLoss(model=model), lambda_query=lambda_query, # Weight for query loss lambda_corpus=lambda_corpus, # Weight for document loss ) # 4. Define the evaluator. We use the SparseNanoBEIREvaluator, which is a light-weight evaluator for English evaluator = evaluation.SparseNanoBEIREvaluator( dataset_names=["msmarco", "nfcorpus", "nq"], batch_size=train_batch_size ) # 5. Define the training arguments short_model_name = model_name if "/" not in model_name else model_name.split("/")[-1] run_name = f"splade-{short_model_name}-msmarco-mrl" args = SparseEncoderTrainingArguments( # Required parameter: output_dir=f"models/{run_name}", # Optional training parameters: num_train_epochs=num_epochs, per_device_train_batch_size=train_batch_size, per_device_eval_batch_size=train_batch_size, learning_rate=learning_rate, load_best_model_at_end=True, metric_for_best_model="eval_NanoBEIR_mean_dot_ndcg@10", fp16=False, # Set to False if you get an error that your GPU can't run on FP16 bf16=True, # Set to True if you have a GPU that supports BF16 # Optional tracking/debugging parameters: eval_strategy="steps", eval_steps=1650, save_strategy="steps", save_steps=1650, save_total_limit=2, logging_steps=200, run_name=run_name, # Will be used in W&B if `wandb` is installed seed=42, ) # 6. Create the trainer & start training trainer = SparseEncoderTrainer( model=model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, loss=loss, evaluator=evaluator, ) trainer.train() # 7. Evaluate the final model, using the complete NanoBEIR dataset test_evaluator = evaluation.SparseNanoBEIREvaluator(show_progress_bar=True, batch_size=train_batch_size) test_evaluator(model) # 8. Save the final model final_output_dir = f"models/{run_name}/final" model.save_pretrained(final_output_dir) # 9. (Optional) save the model to the Hugging Face Hub! # It is recommended to run `huggingface-cli login` to log into your Hugging Face account first try: model.push_to_hub(run_name) except Exception: logging.error( f"Error uploading model to the Hugging Face Hub:\n{traceback.format_exc()}To upload it manually, you can run " f"`huggingface-cli login`, followed by loading the model using `model = SparseEncoder({final_output_dir!r})` " f"and saving it using `model.push_to_hub('{run_name}')`." ) if __name__ == "__main__": main()
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 ) -> Union[List, AbstractDocumentArray]: """Return all values of the fields from all docs this array contains :param field: name of the fields to extract :return: Returns a list of the field value for each document in the array like container """ field_type = self.__class__.document_type._get_nested_document_class(field) if issubclass(field_type, BaseDocument): # calling __class_getitem__ ourselves is a hack otherwise mypy complain # most likely a bug in mypy though # bug reported here https://github.com/python/mypy/issues/14111 return self.__class__.__class_getitem__(field_type)( (getattr(doc, field) for doc in self) ) else: return [getattr(doc, field) for doc in self]
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 this array contains :param field: name of the fields to extract :return: Returns a list of the field value for each document in the array like container """ return [getattr(doc, field) for doc in self]
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 def test_parse_gt_instance_info(): packed_inputs = demo_mm_inputs()['data_samples'] batch_gt_instances, batch_gt_instances_ignore, batch_img_metas \ = unpack_gt_instances(packed_inputs) assert len(batch_gt_instances) == len(packed_inputs) assert len(batch_gt_instances_ignore) == len(packed_inputs) assert len(batch_img_metas) == len(packed_inputs) def test_process_empty_roi(): batch_size = 2 batch_img_metas = [{'ori_shape': (10, 12)}] * batch_size device = torch.device('cpu') results_list = empty_instances(batch_img_metas, device, task_type='bbox') assert len(results_list) == batch_size for results in results_list: assert isinstance(results, InstanceData) assert len(results) == 0 assert torch.allclose(results.bboxes, torch.zeros(0, 4, device=device)) results_list = empty_instances( batch_img_metas, device, task_type='mask', instance_results=results_list, mask_thr_binary=0.5) assert len(results_list) == batch_size for results in results_list: assert isinstance(results, InstanceData) assert len(results) == 0 assert results.masks.shape == (0, 10, 12) # batch_img_metas and instance_results length must be the same with pytest.raises(AssertionError): empty_instances( batch_img_metas, device, task_type='mask', instance_results=[results_list[0]] * 3) def test_filter_gt_instances(): packed_inputs = demo_mm_inputs()['data_samples'] score_thr = 0.7 with pytest.raises(AssertionError): filter_gt_instances(packed_inputs, score_thr=score_thr) # filter no instances by score for inputs in packed_inputs: inputs.gt_instances.scores = torch.ones_like( inputs.gt_instances.labels).float() filtered_packed_inputs = filter_gt_instances( copy.deepcopy(packed_inputs), score_thr=score_thr) for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) # filter all instances for inputs in packed_inputs: inputs.gt_instances.scores = torch.zeros_like( inputs.gt_instances.labels).float() filtered_packed_inputs = filter_gt_instances( copy.deepcopy(packed_inputs), score_thr=score_thr) for filtered_inputs in filtered_packed_inputs: assert len(filtered_inputs.gt_instances) == 0 packed_inputs = demo_mm_inputs()['data_samples'] # filter no instances by size wh_thr = (0, 0) filtered_packed_inputs = filter_gt_instances( copy.deepcopy(packed_inputs), wh_thr=wh_thr) for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) # filter all instances by size for inputs in packed_inputs: img_shape = inputs.img_shape wh_thr = (max(wh_thr[0], img_shape[0]), max(wh_thr[1], img_shape[1])) filtered_packed_inputs = filter_gt_instances( copy.deepcopy(packed_inputs), wh_thr=wh_thr) for filtered_inputs in filtered_packed_inputs: assert len(filtered_inputs.gt_instances) == 0 def test_rename_loss_dict(): prefix = 'sup_' losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} sup_losses = rename_loss_dict(prefix, losses) for name in losses.keys(): assert sup_losses[prefix + name] == losses[name] def test_reweight_loss_dict(): weight = 4 losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} weighted_losses = reweight_loss_dict(copy.deepcopy(losses), weight) for name in losses.keys(): assert weighted_losses[name] == losses[name] * weight
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_ignore, batch_img_metas \ = unpack_gt_instances(packed_inputs) assert len(batch_gt_instances) == len(packed_inputs) assert len(batch_gt_instances_ignore) == len(packed_inputs) assert len(batch_img_metas) == len(packed_inputs) def test_process_empty_roi(): batch_size = 2 batch_img_metas = [{'ori_shape': (10, 12)}] * batch_size device = torch.device('cpu') results_list = empty_instances(batch_img_metas, device, task_type='bbox') assert len(results_list) == batch_size for results in results_list: assert isinstance(results, InstanceData) assert len(results) == 0 assert torch.allclose(results.bboxes, torch.zeros(0, 4, device=device)) results_list = empty_instances( batch_img_metas, device, task_type='mask', instance_results=results_list, mask_thr_binary=0.5) assert len(results_list) == batch_size for results in results_list: assert isinstance(results, InstanceData) assert len(results) == 0 assert results.masks.shape == (0, 10, 12) # batch_img_metas and instance_results length must be the same with pytest.raises(AssertionError): empty_instances( batch_img_metas, device, task_type='mask', instance_results=[results_list[0]] * 3)
"""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: Client) -> None: """Test init estimation for classsifier.""" from sklearn.datasets import make_classification X, y = make_classification(n_samples=4096 * 2, n_features=32, random_state=1994) clf = xgb.XGBClassifier(n_estimators=1, max_depth=1, tree_method=tree_method) clf.fit(X, y) base_score = get_basescore(clf) dx = da.from_array(X).rechunk(chunks=(32, None)) dy = da.from_array(y).rechunk(chunks=(32,)) dclf = xgb.dask.DaskXGBClassifier( n_estimators=1, max_depth=1, tree_method=tree_method ) dclf.client = client dclf.fit(dx, dy) dbase_score = get_basescore(dclf) np.testing.assert_allclose(base_score, dbase_score) def check_init_estimation_reg(tree_method: str, client: Client) -> None: """Test init estimation for regressor.""" from sklearn.datasets import make_regression # pylint: disable=unbalanced-tuple-unpacking X, y = make_regression(n_samples=4096 * 2, n_features=32, random_state=1994) reg = xgb.XGBRegressor(n_estimators=1, max_depth=1, tree_method=tree_method) reg.fit(X, y) base_score = get_basescore(reg) dx = da.from_array(X).rechunk(chunks=(32, None)) dy = da.from_array(y).rechunk(chunks=(32,)) dreg = xgb.dask.DaskXGBRegressor( n_estimators=1, max_depth=1, tree_method=tree_method ) dreg.client = client dreg.fit(dx, dy) dbase_score = get_basescore(dreg) np.testing.assert_allclose(base_score, dbase_score) def check_init_estimation(tree_method: str, client: Client) -> None: """Test init estimation.""" check_init_estimation_reg(tree_method, client) check_init_estimation_clf(tree_method, client) def check_uneven_nan(client: Client, tree_method: str, n_workers: int) -> None: """Issue #9271, not every worker has missing value.""" assert n_workers >= 2 with client.as_current(): clf = xgb.dask.DaskXGBClassifier(tree_method=tree_method) X = pd.DataFrame({"a": range(10000), "b": range(10000, 0, -1)}) y = pd.Series([*[0] * 5000, *[1] * 5000]) X["a"][:3000:1000] = np.nan client.wait_for_workers(n_workers=n_workers) clf.fit( dd.from_pandas(X, npartitions=n_workers), dd.from_pandas(y, npartitions=n_workers), )
"""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: Client) -> None: """Test init estimation for classsifier.""" from sklearn.datasets import make_classification X, y = make_classification(n_samples=4096 * 2, n_features=32, random_state=1994) clf = xgb.XGBClassifier(n_estimators=1, max_depth=1, tree_method=tree_method) clf.fit(X, y) base_score = get_basescore(clf) dx = da.from_array(X).rechunk(chunks=(32, None)) dy = da.from_array(y).rechunk(chunks=(32,)) dclf = xgb.dask.DaskXGBClassifier( n_estimators=1, max_depth=1, tree_method=tree_method ) dclf.client = client dclf.fit(dx, dy) dbase_score = get_basescore(dclf) np.testing.assert_allclose(base_score, dbase_score) def check_init_estimation_reg(tree_method: str, client: Client) -> None: """Test init estimation for regressor.""" from sklearn.datasets import make_regression # pylint: disable=unbalanced-tuple-unpacking X, y = make_regression(n_samples=4096 * 2, n_features=32, random_state=1994) reg = xgb.XGBRegressor(n_estimators=1, max_depth=1, tree_method=tree_method) reg.fit(X, y) base_score = get_basescore(reg) dx = da.from_array(X).rechunk(chunks=(32, None)) dy = da.from_array(y).rechunk(chunks=(32,)) dreg = xgb.dask.DaskXGBRegressor( n_estimators=1, max_depth=1, tree_method=tree_method ) dreg.client = client dreg.fit(dx, dy) dbase_score = get_basescore(dreg) np.testing.assert_allclose(base_score, dbase_score) def check_init_estimation(tree_method: str, client: Client) -> None: """Test init estimation.""" check_init_estimation_reg(tree_method, client) check_init_estimation_clf(tree_method, client) def check_uneven_nan(client: Client, tree_method: str, n_workers: int) -> None: """Issue #9271, not every worker has missing value.""" assert n_workers >= 2 with client.as_current(): clf = xgb.dask.DaskXGBClassifier(tree_method=tree_method) X = pd.DataFrame({"a": range(10000), "b": range(10000, 0, -1)}) y = pd.Series([*[0] * 5000, *[1] * 5000]) X["a"][:3000:1000] = np.NaN client.wait_for_workers(n_workers=n_workers) clf.fit( dd.from_pandas(X, npartitions=n_workers), dd.from_pandas(y, npartitions=n_workers), )
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 ( _FillType, _get_fill, _setup_fill_arg, _setup_size, get_bounding_boxes, has_any, is_pure_tensor, query_size, ) class FixedSizeCrop(Transform): def __init__( self, size: Union[int, Sequence[int]], fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, padding_mode: str = "constant", ) -> None: super().__init__() size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) self.crop_height = size[0] self.crop_width = size[1] self.fill = fill self._fill = _setup_fill_arg(fill) self.padding_mode = padding_mode def check_inputs(self, flat_inputs: list[Any]) -> None: if not has_any( flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor, tv_tensors.Video, ): raise TypeError( f"{type(self).__name__}() requires input sample to contain an tensor or PIL image or a Video." ) if has_any(flat_inputs, tv_tensors.BoundingBoxes) and not has_any(flat_inputs, Label, OneHotLabel): raise TypeError( f"If a BoundingBoxes is contained in the input sample, " f"{type(self).__name__}() also requires it to contain a Label or OneHotLabel." ) def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: height, width = query_size(flat_inputs) new_height = min(height, self.crop_height) new_width = min(width, self.crop_width) needs_crop = new_height != height or new_width != width offset_height = max(height - self.crop_height, 0) offset_width = max(width - self.crop_width, 0) r = torch.rand(1) top = int(offset_height * r) left = int(offset_width * r) bounding_boxes: Optional[torch.Tensor] try: bounding_boxes = get_bounding_boxes(flat_inputs) except ValueError: bounding_boxes = None if needs_crop and bounding_boxes is not None: format = bounding_boxes.format bounding_boxes, canvas_size = F.crop_bounding_boxes( bounding_boxes.as_subclass(torch.Tensor), format=format, top=top, left=left, height=new_height, width=new_width, ) bounding_boxes = F.clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size) height_and_width = F.convert_bounding_box_format( bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYWH )[..., 2:] is_valid = torch.all(height_and_width > 0, dim=-1) else: is_valid = None pad_bottom = max(self.crop_height - new_height, 0) pad_right = max(self.crop_width - new_width, 0) needs_pad = pad_bottom != 0 or pad_right != 0 return dict( needs_crop=needs_crop, top=top, left=left, height=new_height, width=new_width, is_valid=is_valid, padding=[0, 0, pad_right, pad_bottom], needs_pad=needs_pad, ) def transform(self, inpt: Any, params: dict[str, Any]) -> Any: if params["needs_crop"]: inpt = self._call_kernel( F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"], ) if params["is_valid"] is not None: if isinstance(inpt, (Label, OneHotLabel, tv_tensors.Mask)): inpt = tv_tensors.wrap(inpt[params["is_valid"]], like=inpt) elif isinstance(inpt, tv_tensors.BoundingBoxes): inpt = tv_tensors.wrap( F.clamp_bounding_boxes(inpt[params["is_valid"]], format=inpt.format, canvas_size=inpt.canvas_size), like=inpt, ) if params["needs_pad"]: fill = _get_fill(self._fill, type(inpt)) inpt = self._call_kernel(F.pad, inpt, params["padding"], fill=fill, padding_mode=self.padding_mode) return inpt
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 ( _FillType, _get_fill, _setup_fill_arg, _setup_size, get_bounding_boxes, has_any, is_pure_tensor, query_size, ) class FixedSizeCrop(Transform): def __init__( self, size: Union[int, Sequence[int]], fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0, padding_mode: str = "constant", ) -> None: super().__init__() size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) self.crop_height = size[0] self.crop_width = size[1] self.fill = fill self._fill = _setup_fill_arg(fill) self.padding_mode = padding_mode def check_inputs(self, flat_inputs: List[Any]) -> None: if not has_any( flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor, tv_tensors.Video, ): raise TypeError( f"{type(self).__name__}() requires input sample to contain an tensor or PIL image or a Video." ) if has_any(flat_inputs, tv_tensors.BoundingBoxes) and not has_any(flat_inputs, Label, OneHotLabel): raise TypeError( f"If a BoundingBoxes is contained in the input sample, " f"{type(self).__name__}() also requires it to contain a Label or OneHotLabel." ) def make_params(self, flat_inputs: List[Any]) -> Dict[str, Any]: height, width = query_size(flat_inputs) new_height = min(height, self.crop_height) new_width = min(width, self.crop_width) needs_crop = new_height != height or new_width != width offset_height = max(height - self.crop_height, 0) offset_width = max(width - self.crop_width, 0) r = torch.rand(1) top = int(offset_height * r) left = int(offset_width * r) bounding_boxes: Optional[torch.Tensor] try: bounding_boxes = get_bounding_boxes(flat_inputs) except ValueError: bounding_boxes = None if needs_crop and bounding_boxes is not None: format = bounding_boxes.format bounding_boxes, canvas_size = F.crop_bounding_boxes( bounding_boxes.as_subclass(torch.Tensor), format=format, top=top, left=left, height=new_height, width=new_width, ) bounding_boxes = F.clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size) height_and_width = F.convert_bounding_box_format( bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYWH )[..., 2:] is_valid = torch.all(height_and_width > 0, dim=-1) else: is_valid = None pad_bottom = max(self.crop_height - new_height, 0) pad_right = max(self.crop_width - new_width, 0) needs_pad = pad_bottom != 0 or pad_right != 0 return dict( needs_crop=needs_crop, top=top, left=left, height=new_height, width=new_width, is_valid=is_valid, padding=[0, 0, pad_right, pad_bottom], needs_pad=needs_pad, ) def transform(self, inpt: Any, params: Dict[str, Any]) -> Any: if params["needs_crop"]: inpt = self._call_kernel( F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"], ) if params["is_valid"] is not None: if isinstance(inpt, (Label, OneHotLabel, tv_tensors.Mask)): inpt = tv_tensors.wrap(inpt[params["is_valid"]], like=inpt) elif isinstance(inpt, tv_tensors.BoundingBoxes): inpt = tv_tensors.wrap( F.clamp_bounding_boxes(inpt[params["is_valid"]], format=inpt.format, canvas_size=inpt.canvas_size), like=inpt, ) if params["needs_pad"]: fill = _get_fill(self._fill, type(inpt)) inpt = self._call_kernel(F.pad, inpt, params["padding"], fill=fill, padding_mode=self.padding_mode) return inpt
# 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, register_all_modules # TODO: support fuse_conv_bn and format_only def parse_args(): parser = argparse.ArgumentParser( description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--work-dir', help='the directory to save the file containing evaluation metrics') parser.add_argument( '--out', type=str, help='dump predictions to a pickle file for offline evaluation') parser.add_argument( '--show', action='store_true', help='show prediction results') parser.add_argument( '--show-dir', help='directory where painted images will be saved. ' 'If specified, it will be automatically saved ' 'to the work_dir/timestamp/show_dir') parser.add_argument( '--wait-time', type=float, default=2, help='the interval of show (s)') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() # register all modules in mmdet into the registries # do not init the default scope here because it will be init in the runner register_all_modules(init_default_scope=False) # load config cfg = Config.fromfile(args.config) cfg.launcher = args.launcher if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) # work_dir is determined in this priority: CLI > segment in file > filename if args.work_dir is not None: # update configs according to CLI args if args.work_dir is not None cfg.work_dir = args.work_dir elif cfg.get('work_dir', None) is None: # use config filename as default work_dir if cfg.work_dir is None cfg.work_dir = osp.join('./work_dirs', osp.splitext(osp.basename(args.config))[0]) cfg.load_from = args.checkpoint if args.show or args.show_dir: cfg = trigger_visualization_hook(cfg, args) # Dump predictions if args.out is not None: assert args.out.endswith(('.pkl', '.pickle')), \ 'The dump file must be a pkl file.' add_dump_metric(args, cfg) # build the runner from config if 'runner_type' not in cfg: # build the default runner runner = Runner.from_cfg(cfg) else: # build customized runner from the registry # if 'runner_type' is set in the cfg runner = RUNNERS.build(cfg) # start testing runner.test() if __name__ == '__main__': main()
# 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_args(): parser = argparse.ArgumentParser( description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--work-dir', help='the directory to save the file containing evaluation metrics') parser.add_argument( '--show', action='store_true', help='show prediction results') parser.add_argument( '--show-dir', help='directory where painted images will be saved. ' 'If specified, it will be automatically saved ' 'to the work_dir/timestamp/show_dir') parser.add_argument( '--wait-time', type=float, default=2, help='the interval of show (s)') parser.add_argument( '--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair ' 'in xxx=yyy format will be merged into config file. If the value to ' 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' 'Note that the quotation marks are necessary and that no white space ' 'is allowed.') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def trigger_visualization_hook(cfg, args): default_hooks = cfg.default_hooks if 'visualization' in default_hooks: visualization_hook = default_hooks['visualization'] # Turn on visualization visualization_hook['draw'] = True if args.show: visualization_hook['show'] = True visualization_hook['wait_time'] = args.wait_time if args.show_dir: visualization_hook['test_out_dir'] = args.show_dir else: raise RuntimeError( 'VisualizationHook must be included in default_hooks.' 'refer to usage ' '"visualization=dict(type=\'VisualizationHook\')"') return cfg def main(): args = parse_args() # register all modules in mmdet into the registries # do not init the default scope here because it will be init in the runner register_all_modules(init_default_scope=False) # load config cfg = Config.fromfile(args.config) cfg.launcher = args.launcher if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) # work_dir is determined in this priority: CLI > segment in file > filename if args.work_dir is not None: # update configs according to CLI args if args.work_dir is not None cfg.work_dir = args.work_dir elif cfg.get('work_dir', None) is None: # use config filename as default work_dir if cfg.work_dir is None cfg.work_dir = osp.join('./work_dirs', osp.splitext(osp.basename(args.config))[0]) cfg.load_from = args.checkpoint if args.show or args.show_dir: cfg = trigger_visualization_hook(cfg, args) # build the runner from config if 'runner_type' not in cfg: # build the default runner runner = Runner.from_cfg(cfg) else: # build customized runner from the registry # if 'runner_type' is set in the cfg runner = RUNNERS.build(cfg) # start testing runner.test() if __name__ == '__main__': main()
# 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 compatibility. TODO: remove in 3.0.0
# 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.base.response.schema import Response # import global eval handler from llama_index.core.callbacks.global_handlers import set_global_handler from llama_index.core.data_structs.struct_type import IndexStructType from llama_index.core.embeddings.mock_embed_model import MockEmbedding # indices # loading from llama_index.core.indices import ( ComposableGraph, DocumentSummaryIndex, GPTDocumentSummaryIndex, GPTKeywordTableIndex, GPTListIndex, GPTRAKEKeywordTableIndex, GPTSimpleKeywordTableIndex, GPTTreeIndex, GPTVectorStoreIndex, KeywordTableIndex, KnowledgeGraphIndex, ListIndex, PropertyGraphIndex, RAKEKeywordTableIndex, SimpleKeywordTableIndex, SummaryIndex, TreeIndex, VectorStoreIndex, load_graph_from_storage, load_index_from_storage, load_indices_from_storage, ) # structured from llama_index.core.indices.common.struct_store.base import ( SQLDocumentContextBuilder, ) # prompt helper from llama_index.core.indices.prompt_helper import PromptHelper # prompts from llama_index.core.prompts import ( BasePromptTemplate, ChatPromptTemplate, # backwards compatibility Prompt, PromptTemplate, SelectorPromptTemplate, ) from llama_index.core.readers import SimpleDirectoryReader, download_loader # Response Synthesizer from llama_index.core.response_synthesizers.factory import get_response_synthesizer from llama_index.core.schema import Document, QueryBundle from llama_index.core.service_context import ( ServiceContext, set_global_service_context, ) # global settings from llama_index.core.settings import Settings # storage from llama_index.core.storage.storage_context import StorageContext # sql wrapper from llama_index.core.utilities.sql_wrapper import SQLDatabase # global tokenizer from llama_index.core.utils import get_tokenizer, set_global_tokenizer # best practices for library logging: # https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library logging.getLogger(__name__).addHandler(NullHandler()) __all__ = [ "StorageContext", "ServiceContext", "ComposableGraph", # indices "SummaryIndex", "VectorStoreIndex", "SimpleKeywordTableIndex", "KeywordTableIndex", "RAKEKeywordTableIndex", "TreeIndex", "DocumentSummaryIndex", "KnowledgeGraphIndex", "PropertyGraphIndex", # indices - legacy names "GPTKeywordTableIndex", "GPTKnowledgeGraphIndex", "GPTSimpleKeywordTableIndex", "GPTRAKEKeywordTableIndex", "GPTListIndex", "ListIndex", "GPTTreeIndex", "GPTVectorStoreIndex", "GPTDocumentSummaryIndex", "Prompt", "PromptTemplate", "BasePromptTemplate", "ChatPromptTemplate", "SelectorPromptTemplate", "SummaryPrompt", "TreeInsertPrompt", "TreeSelectPrompt", "TreeSelectMultiplePrompt", "RefinePrompt", "QuestionAnswerPrompt", "KeywordExtractPrompt", "QueryKeywordExtractPrompt", "Response", "Document", "SimpleDirectoryReader", "VellumPredictor", "VellumPromptRegistry", "MockEmbedding", "SQLDatabase", "SQLDocumentContextBuilder", "SQLContextBuilder", "PromptHelper", "IndexStructType", "download_loader", "load_graph_from_storage", "load_index_from_storage", "load_indices_from_storage", "QueryBundle", "get_response_synthesizer", "set_global_service_context", "set_global_handler", "set_global_tokenizer", "get_tokenizer", "Settings", ] # eval global toggle from llama_index.core.callbacks.base_handler import BaseCallbackHandler global_handler: Optional[BaseCallbackHandler] = None # NOTE: keep for backwards compatibility SQLContextBuilder = SQLDocumentContextBuilder # global tokenizer global_tokenizer: Optional[Callable[[str], list]] = None
"""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.response.schema import Response # import global eval handler from llama_index.core.callbacks.global_handlers import set_global_handler from llama_index.core.data_structs.struct_type import IndexStructType from llama_index.core.embeddings.mock_embed_model import MockEmbedding # indices # loading from llama_index.core.indices import ( ComposableGraph, DocumentSummaryIndex, GPTDocumentSummaryIndex, GPTKeywordTableIndex, GPTListIndex, GPTRAKEKeywordTableIndex, GPTSimpleKeywordTableIndex, GPTTreeIndex, GPTVectorStoreIndex, KeywordTableIndex, KnowledgeGraphIndex, ListIndex, PropertyGraphIndex, RAKEKeywordTableIndex, SimpleKeywordTableIndex, SummaryIndex, TreeIndex, VectorStoreIndex, load_graph_from_storage, load_index_from_storage, load_indices_from_storage, ) # structured from llama_index.core.indices.common.struct_store.base import ( SQLDocumentContextBuilder, ) # prompt helper from llama_index.core.indices.prompt_helper import PromptHelper # prompts from llama_index.core.prompts import ( BasePromptTemplate, ChatPromptTemplate, # backwards compatibility Prompt, PromptTemplate, SelectorPromptTemplate, ) from llama_index.core.readers import SimpleDirectoryReader, download_loader # Response Synthesizer from llama_index.core.response_synthesizers.factory import get_response_synthesizer from llama_index.core.schema import Document, QueryBundle from llama_index.core.service_context import ( ServiceContext, set_global_service_context, ) # global settings from llama_index.core.settings import Settings # storage from llama_index.core.storage.storage_context import StorageContext # sql wrapper from llama_index.core.utilities.sql_wrapper import SQLDatabase # global tokenizer from llama_index.core.utils import get_tokenizer, set_global_tokenizer # best practices for library logging: # https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library logging.getLogger(__name__).addHandler(NullHandler()) __all__ = [ "StorageContext", "ServiceContext", "ComposableGraph", # indices "SummaryIndex", "VectorStoreIndex", "SimpleKeywordTableIndex", "KeywordTableIndex", "RAKEKeywordTableIndex", "TreeIndex", "DocumentSummaryIndex", "KnowledgeGraphIndex", "PropertyGraphIndex", # indices - legacy names "GPTKeywordTableIndex", "GPTKnowledgeGraphIndex", "GPTSimpleKeywordTableIndex", "GPTRAKEKeywordTableIndex", "GPTListIndex", "ListIndex", "GPTTreeIndex", "GPTVectorStoreIndex", "GPTDocumentSummaryIndex", "Prompt", "PromptTemplate", "BasePromptTemplate", "ChatPromptTemplate", "SelectorPromptTemplate", "SummaryPrompt", "TreeInsertPrompt", "TreeSelectPrompt", "TreeSelectMultiplePrompt", "RefinePrompt", "QuestionAnswerPrompt", "KeywordExtractPrompt", "QueryKeywordExtractPrompt", "Response", "Document", "SimpleDirectoryReader", "VellumPredictor", "VellumPromptRegistry", "MockEmbedding", "SQLDatabase", "SQLDocumentContextBuilder", "SQLContextBuilder", "PromptHelper", "IndexStructType", "download_loader", "load_graph_from_storage", "load_index_from_storage", "load_indices_from_storage", "QueryBundle", "get_response_synthesizer", "set_global_service_context", "set_global_handler", "set_global_tokenizer", "get_tokenizer", "Settings", ] # eval global toggle from llama_index.core.callbacks.base_handler import BaseCallbackHandler global_handler: Optional[BaseCallbackHandler] = None # NOTE: keep for backwards compatibility SQLContextBuilder = SQLDocumentContextBuilder # global tokenizer global_tokenizer: Optional[Callable[[str], list]] = None
_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, 1333), keep_ratio=True, backend='pillow'), dict(type='LoadAnnotations', with_bbox=True), dict( type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'text', 'custom_entities', 'tokens_positive', 'phrase_ids', 'phrases')) ] dataset_Flickr30k_val = dict( type=dataset_type, data_root=data_root, ann_file='final_flickr_separateGT_val.json', data_prefix=dict(img='flickr30k_images/'), pipeline=test_pipeline, ) dataset_Flickr30k_test = dict( type=dataset_type, data_root=data_root, ann_file='final_flickr_separateGT_test.json', data_prefix=dict(img='flickr30k_images/'), pipeline=test_pipeline, ) val_evaluator_Flickr30k = dict(type='Flickr30kMetric') test_evaluator_Flickr30k = dict(type='Flickr30kMetric') # ----------Config---------- # dataset_prefixes = ['Flickr30kVal', 'Flickr30kTest'] datasets = [dataset_Flickr30k_val, dataset_Flickr30k_test] metrics = [val_evaluator_Flickr30k, test_evaluator_Flickr30k] val_dataloader = dict( dataset=dict(_delete_=True, type='ConcatDataset', datasets=datasets)) test_dataloader = val_dataloader val_evaluator = dict( _delete_=True, type='MultiDatasetsEvaluator', metrics=metrics, dataset_prefixes=dataset_prefixes) test_evaluator = val_evaluator
_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), keep_ratio=True, backend='pillow'), dict(type='LoadAnnotations', with_bbox=True), dict( type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'text', 'custom_entities', 'tokens_positive', 'phrase_ids', 'phrases')) ] dataset_Flickr30k_val = dict( type=dataset_type, data_root=data_root, ann_file='mdetr_annotations/final_flickr_separateGT_val.json', data_prefix=dict(img='flickr30k_images/'), pipeline=test_pipeline, ) dataset_Flickr30k_test = dict( type=dataset_type, data_root=data_root, ann_file='mdetr_annotations/final_flickr_separateGT_test.json', data_prefix=dict(img='flickr30k_images/'), pipeline=test_pipeline, ) val_evaluator_Flickr30k = dict(type='Flickr30kMetric') test_evaluator_Flickr30k = dict(type='Flickr30kMetric') # ----------Config---------- # dataset_prefixes = ['Flickr30kVal', 'Flickr30kTest'] datasets = [dataset_Flickr30k_val, dataset_Flickr30k_test] metrics = [val_evaluator_Flickr30k, test_evaluator_Flickr30k] val_dataloader = dict( dataset=dict(_delete_=True, type='ConcatDataset', datasets=datasets)) test_dataloader = val_dataloader val_evaluator = dict( _delete_=True, type='MultiDatasetsEvaluator', metrics=metrics, dataset_prefixes=dataset_prefixes) test_evaluator = val_evaluator
# 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 mmdet.registry import MODELS from .single_stage import SingleStageDetector @MODELS.register_module() class KnowledgeDistillationSingleStageDetector(SingleStageDetector): r"""Implementation of `Distilling the Knowledge in a Neural Network. <https://arxiv.org/abs/1503.02531>`_. Args: teacher_config (:obj:`ConfigDict` | dict | str | Path): Config file path or the config object of teacher model. teacher_ckpt (str, optional): Checkpoint path of teacher model. If left as None, the model will not load any weights. """ def __init__( self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, teacher_config: Union[ConfigType, str, Path], teacher_ckpt: Optional[str] = None, eval_teacher: bool = True, train_cfg: OptConfigType = None, test_cfg: OptConfigType = None, preprocess_cfg: OptConfigType = None, ) -> None: super().__init__( backbone=backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, preprocess_cfg=preprocess_cfg) self.eval_teacher = eval_teacher # Build teacher model if isinstance(teacher_config, (str, Path)): teacher_config = Config.fromfile(teacher_config) self.teacher_model = MODELS.build(teacher_config['model']) if teacher_ckpt is not None: load_checkpoint( self.teacher_model, teacher_ckpt, map_location='cpu') def forward_train(self, batch_inputs: Tensor, batch_data_samples: SampleList, **kwargs) -> dict: """ Args: batch_inputs (Tensor): Input images of shape (N, C, H, W). These should usually be mean centered and std scaled. batch_data_samples (list[:obj:`DetDataSample`]): The batch data samples. It usually includes information such as `gt_instance` or `gt_panoptic_seg` or `gt_sem_seg`. Returns: dict[str, Tensor]: A dictionary of loss components. """ x = self.extract_feat(batch_inputs) with torch.no_grad(): teacher_x = self.teacher_model.extract_feat(batch_inputs) out_teacher = self.teacher_model.bbox_head(teacher_x) losses = self.bbox_head.forward_train(x, out_teacher, batch_data_samples) return losses def cuda(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to cuda when calling ``cuda`` function.""" self.teacher_model.cuda(device=device) return super().cuda(device=device) def to(self, device: Optional[str] = None) -> nn.Module: """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to other device when calling ``to`` function.""" self.teacher_model.to(device=device) return super().to(device=device) def train(self, mode: bool = True) -> None: """Set the same train mode for teacher and student model.""" if self.eval_teacher: self.teacher_model.train(False) else: self.teacher_model.train(mode) super().train(mode) def __setattr__(self, name: str, value: Any) -> None: """Set attribute, i.e. self.name = value This reloading prevent the teacher model from being registered as a nn.Module. The teacher module is registered as a plain object, so that the teacher parameters will not show up when calling ``self.parameters``, ``self.modules``, ``self.children`` methods. """ if name == 'teacher_model': object.__setattr__(self, name, value) else: super().__setattr__(name, value)
# 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 KnowledgeDistillationSingleStageDetector(SingleStageDetector): r"""Implementation of `Distilling the Knowledge in a Neural Network. <https://arxiv.org/abs/1503.02531>`_. Args: teacher_config (str | dict): Config file path or the config object of teacher model. teacher_ckpt (str, optional): Checkpoint path of teacher model. If left as None, the model will not load any weights. """ def __init__(self, backbone, neck, bbox_head, teacher_config, teacher_ckpt=None, eval_teacher=True, train_cfg=None, test_cfg=None, pretrained=None): super().__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained) self.eval_teacher = eval_teacher # Build teacher model if isinstance(teacher_config, (str, Path)): teacher_config = mmcv.Config.fromfile(teacher_config) self.teacher_model = build_detector(teacher_config['model']) if teacher_ckpt is not None: load_checkpoint( self.teacher_model, teacher_ckpt, map_location='cpu') def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None): """ Args: img (Tensor): Input images of shape (N, C, H, W). Typically these should be mean centered and std scaled. img_metas (list[dict]): A List of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys see :class:`mmdet.datasets.pipelines.Collect`. gt_bboxes (list[Tensor]): Each item are the truth boxes for each image in [tl_x, tl_y, br_x, br_y] format. gt_labels (list[Tensor]): Class indices corresponding to each box gt_bboxes_ignore (None | list[Tensor]): Specify which bounding boxes can be ignored when computing the loss. Returns: dict[str, Tensor]: A dictionary of loss components. """ x = self.extract_feat(img) with torch.no_grad(): teacher_x = self.teacher_model.extract_feat(img) out_teacher = self.teacher_model.bbox_head(teacher_x) losses = self.bbox_head.forward_train(x, out_teacher, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore) return losses def cuda(self, device=None): """Since teacher_model is registered as a plain object, it is necessary to put the teacher model to cuda when calling cuda function.""" self.teacher_model.cuda(device=device) return super().cuda(device=device) def train(self, mode=True): """Set the same train mode for teacher and student model.""" if self.eval_teacher: self.teacher_model.train(False) else: self.teacher_model.train(mode) super().train(mode) def __setattr__(self, name, value): """Set attribute, i.e. self.name = value This reloading prevent the teacher model from being registered as a nn.Module. The teacher module is registered as a plain object, so that the teacher parameters will not show up when calling ``self.parameters``, ``self.modules``, ``self.children`` methods. """ if name == 'teacher_model': object.__setattr__(self, name, value) else: super().__setattr__(name, value)
# 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from transformers.image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torchvision_available, is_vision_available from ...test_video_processing_common import VideoProcessingTestMixin, prepare_video_inputs if is_vision_available(): if is_torchvision_available(): from transformers import LlavaOnevisionVideoProcessor class LlavaOnevisionVideoProcessingTester: def __init__( self, parent, batch_size=7, num_frames=8, num_channels=3, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=OPENAI_CLIP_MEAN, image_std=OPENAI_CLIP_STD, do_convert_rgb=True, ): size = size if size is not None else {"height": 20, "width": 20} self.parent = parent self.batch_size = batch_size self.num_frames = num_frames self.num_channels = num_channels self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_convert_rgb = do_convert_rgb def prepare_video_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def expected_output_video_shape(self, video): return self.num_frames, self.num_channels, self.size["height"], self.size["width"] def prepare_video_inputs(self, equal_resolution=False, return_tensors="pil"): videos = prepare_video_inputs( batch_size=self.batch_size, num_frames=self.num_frames, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, return_tensors=return_tensors, ) return videos @require_torch @require_vision class LlavaOnevisionVideoProcessingTest(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = LlavaOnevisionVideoProcessor if is_torchvision_available() else None def setUp(self): super().setUp() self.video_processor_tester = LlavaOnevisionVideoProcessingTester(self) @property def video_processor_dict(self): return self.video_processor_tester.prepare_video_processor_dict() def test_video_processor_properties(self): video_processing = self.fast_video_processing_class(**self.video_processor_dict) self.assertTrue(hasattr(video_processing, "do_resize")) self.assertTrue(hasattr(video_processing, "size")) self.assertTrue(hasattr(video_processing, "do_normalize")) self.assertTrue(hasattr(video_processing, "image_mean")) self.assertTrue(hasattr(video_processing, "image_std")) self.assertTrue(hasattr(video_processing, "do_convert_rgb")) def test_video_processor_from_dict_with_kwargs(self): video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict) self.assertEqual(video_processor.size, {"height": 20, "width": 20}) video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict, size=42) self.assertEqual(video_processor.size, {"shortest_edge": 42})
# 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from transformers.image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_video_processing_common import VideoProcessingTestMixin, prepare_video_inputs if is_torch_available(): pass if is_vision_available(): if is_torchvision_available(): from transformers import LlavaOnevisionVideoProcessor class LlavaOnevisionVideoProcessingTester: def __init__( self, parent, batch_size=7, num_frames=8, num_channels=3, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=OPENAI_CLIP_MEAN, image_std=OPENAI_CLIP_STD, do_convert_rgb=True, ): size = size if size is not None else {"height": 20, "width": 20} self.parent = parent self.batch_size = batch_size self.num_frames = num_frames self.num_channels = num_channels self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_convert_rgb = do_convert_rgb def prepare_video_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def expected_output_video_shape(self, video): return self.num_frames, self.num_channels, self.size["height"], self.size["width"] def prepare_video_inputs(self, equal_resolution=False, return_tensors="pil"): videos = prepare_video_inputs( batch_size=self.batch_size, num_frames=self.num_frames, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, return_tensors=return_tensors, ) return videos @require_torch @require_vision class LlavaOnevisionVideoProcessingTest(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = LlavaOnevisionVideoProcessor if is_torchvision_available() else None def setUp(self): super().setUp() self.video_processor_tester = LlavaOnevisionVideoProcessingTester(self) @property def video_processor_dict(self): return self.video_processor_tester.prepare_video_processor_dict() def test_video_processor_properties(self): video_processing = self.fast_video_processing_class(**self.video_processor_dict) self.assertTrue(hasattr(video_processing, "do_resize")) self.assertTrue(hasattr(video_processing, "size")) self.assertTrue(hasattr(video_processing, "do_normalize")) self.assertTrue(hasattr(video_processing, "image_mean")) self.assertTrue(hasattr(video_processing, "image_std")) self.assertTrue(hasattr(video_processing, "do_convert_rgb")) def test_video_processor_from_dict_with_kwargs(self): video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict) self.assertEqual(video_processor.size, {"height": 20, "width": 20}) video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict, size=42) self.assertEqual(video_processor.size, {"shortest_edge": 42})
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, get_num_frames, get_image_num_channels, get_num_channels_image, get_num_channels_video, get_num_channels, get_size_bounding_boxes, get_size_image, get_size_mask, get_size_video, get_size, ) # usort: skip from ._augment import erase, erase_image, erase_video, jpeg, jpeg_image, jpeg_video from ._color import ( adjust_brightness, adjust_brightness_image, adjust_brightness_video, adjust_contrast, adjust_contrast_image, adjust_contrast_video, adjust_gamma, adjust_gamma_image, adjust_gamma_video, adjust_hue, adjust_hue_image, adjust_hue_video, adjust_saturation, adjust_saturation_image, adjust_saturation_video, adjust_sharpness, adjust_sharpness_image, adjust_sharpness_video, autocontrast, autocontrast_image, autocontrast_video, equalize, equalize_image, equalize_video, grayscale_to_rgb, grayscale_to_rgb_image, invert, invert_image, invert_video, permute_channels, permute_channels_image, permute_channels_video, posterize, posterize_image, posterize_video, rgb_to_grayscale, rgb_to_grayscale_image, solarize, solarize_image, solarize_video, to_grayscale, ) from ._geometry import ( affine, affine_bounding_boxes, affine_image, affine_mask, affine_video, center_crop, center_crop_bounding_boxes, center_crop_image, center_crop_mask, center_crop_video, crop, crop_bounding_boxes, crop_image, crop_mask, crop_video, elastic, elastic_bounding_boxes, elastic_image, elastic_mask, elastic_transform, elastic_video, five_crop, five_crop_image, five_crop_video, hflip, # TODO: Consider moving all pure alias definitions at the bottom of the file horizontal_flip, horizontal_flip_bounding_boxes, horizontal_flip_image, horizontal_flip_mask, horizontal_flip_video, pad, pad_bounding_boxes, pad_image, pad_mask, pad_video, perspective, perspective_bounding_boxes, perspective_image, perspective_mask, perspective_video, resize, resize_bounding_boxes, resize_image, resize_mask, resize_video, resized_crop, resized_crop_bounding_boxes, resized_crop_image, resized_crop_mask, resized_crop_video, rotate, rotate_bounding_boxes, rotate_image, rotate_mask, rotate_video, ten_crop, ten_crop_image, ten_crop_video, vertical_flip, vertical_flip_bounding_boxes, vertical_flip_image, vertical_flip_mask, vertical_flip_video, vflip, ) from ._misc import ( convert_image_dtype, gaussian_blur, gaussian_blur_image, gaussian_blur_video, gaussian_noise, gaussian_noise_image, gaussian_noise_video, normalize, normalize_image, normalize_video, sanitize_bounding_boxes, to_dtype, to_dtype_image, to_dtype_video, ) from ._temporal import uniform_temporal_subsample, uniform_temporal_subsample_video from ._type_conversion import pil_to_tensor, to_image, to_pil_image from ._deprecated import get_image_size, to_tensor # usort: skip
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, get_num_frames, get_image_num_channels, get_num_channels_image, get_num_channels_video, get_num_channels, get_size_bounding_boxes, get_size_image, get_size_mask, get_size_video, get_size, ) # usort: skip from ._augment import erase, erase_image, erase_video, jpeg, jpeg_image, jpeg_video from ._color import ( adjust_brightness, adjust_brightness_image, adjust_brightness_video, adjust_contrast, adjust_contrast_image, adjust_contrast_video, adjust_gamma, adjust_gamma_image, adjust_gamma_video, adjust_hue, adjust_hue_image, adjust_hue_video, adjust_saturation, adjust_saturation_image, adjust_saturation_video, adjust_sharpness, adjust_sharpness_image, adjust_sharpness_video, autocontrast, autocontrast_image, autocontrast_video, equalize, equalize_image, equalize_video, grayscale_to_rgb, grayscale_to_rgb_image, invert, invert_image, invert_video, permute_channels, permute_channels_image, permute_channels_video, posterize, posterize_image, posterize_video, rgb_to_grayscale, rgb_to_grayscale_image, solarize, solarize_image, solarize_video, to_grayscale, ) from ._geometry import ( affine, affine_bounding_boxes, affine_image, affine_mask, affine_video, center_crop, center_crop_bounding_boxes, center_crop_image, center_crop_mask, center_crop_video, crop, crop_bounding_boxes, crop_image, crop_mask, crop_video, elastic, elastic_bounding_boxes, elastic_image, elastic_mask, elastic_transform, elastic_video, five_crop, five_crop_image, five_crop_video, hflip, # TODO: Consider moving all pure alias definitions at the bottom of the file horizontal_flip, horizontal_flip_bounding_boxes, horizontal_flip_image, horizontal_flip_mask, horizontal_flip_video, pad, pad_bounding_boxes, pad_image, pad_mask, pad_video, perspective, perspective_bounding_boxes, perspective_image, perspective_mask, perspective_video, resize, resize_bounding_boxes, resize_image, resize_mask, resize_video, resized_crop, resized_crop_bounding_boxes, resized_crop_image, resized_crop_mask, resized_crop_video, rotate, rotate_bounding_boxes, rotate_image, rotate_mask, rotate_video, ten_crop, ten_crop_image, ten_crop_video, vertical_flip, vertical_flip_bounding_boxes, vertical_flip_image, vertical_flip_mask, vertical_flip_video, vflip, ) from ._misc import ( convert_image_dtype, gaussian_blur, gaussian_blur_image, gaussian_blur_video, normalize, normalize_image, normalize_video, sanitize_bounding_boxes, to_dtype, to_dtype_image, to_dtype_video, ) from ._temporal import uniform_temporal_subsample, uniform_temporal_subsample_video from ._type_conversion import pil_to_tensor, to_image, to_pil_image from ._deprecated import get_image_size, to_tensor # usort: skip
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, query: str, ) -> list[Document]: if self.response_index >= len(self.sequential_responses): return [] else: self.response_index += 1 return self.sequential_responses[self.response_index - 1] async def _aget_relevant_documents( # type: ignore[override] self, query: str, ) -> list[Document]: return self._get_relevant_documents(query)
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[override] self, query: str, ) -> List[Document]: if self.response_index >= len(self.sequential_responses): return [] else: self.response_index += 1 return self.sequential_responses[self.response_index - 1] async def _aget_relevant_documents( # type: ignore[override] self, query: str, ) -> List[Document]: return self._get_relevant_documents(query)
__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 @pytest.mark.parametrize( 'arr_in', [ (np.ones((input_dim, input_dim, 3), dtype=np.float32)), ], ) def test_tf_no_batch(arr_in: np.ndarray): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=DocumentArray([Document(blob=arr_in)]), return_results=True, ) assert len(results[0].docs) == 1 assert results[0].docs[0].embedding.shape == (target_output_dim,) def test_tf_batch(): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=( Document(blob=np.ones((input_dim, input_dim, 3), dtype=np.float32)) for _ in range(25) ), return_results=True, ) assert len(results[0].docs.get_attributes('embedding')) == 25 assert results[0].docs.get_attributes('embedding')[0].shape == ( target_output_dim, ) @pytest.mark.parametrize( ['docs', 'docs_per_path', 'traversal_paths'], [ ( pytest.lazy_fixture('docs_with_blobs'), [[['r'], 10], [['c'], 0], [['cc'], 0]], ['r'], ), ( pytest.lazy_fixture('docs_with_chunk_blobs'), [[['r'], 0], [['c'], 10], [['cc'], 0]], ['c'], ), ( pytest.lazy_fixture('docs_with_chunk_chunk_blobs'), [[['r'], 0], [['c'], 0], [['cc'], 10]], ['cc'], ), ], ) def test_traversal_path( docs: DocumentArray, docs_per_path: List[List[str]], traversal_paths: List[str] ): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=docs, parameters={'traversal_paths': traversal_paths}, return_results=True, ) for path, count in docs_per_path: embeddings = ( DocumentArray(results[0].docs) .traverse_flat(path) .get_attributes('embedding') ) assert len([x for x in embeddings if x is not None]) == count @pytest.mark.docker def test_docker_runtime(build_docker_image: str): with pytest.raises(subprocess.TimeoutExpired): subprocess.run( ['jina', 'executor', f'--uses=docker://{build_docker_image}'], timeout=30, check=True, ) @pytest.mark.gpu @pytest.mark.docker def test_docker_runtime_gpu(build_docker_image_gpu: str): with pytest.raises(subprocess.TimeoutExpired): subprocess.run( [ 'jina', 'pea', f'--uses=docker://{build_docker_image_gpu}', '--gpus', 'all', '--uses-with', 'device:"/GPU:0"', ], timeout=30, check=True, )
__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.parametrize('arr_in', [ (np.ones((input_dim, input_dim, 3), dtype=np.float32)), ]) def test_tf_no_batch(arr_in: np.ndarray): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=DocumentArray([Document(blob=arr_in)]), return_results=True ) assert len(results[0].docs) == 1 assert results[0].docs[0].embedding.shape == (target_output_dim,) def test_tf_batch(): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=(Document(blob=np.ones((input_dim, input_dim, 3), dtype=np.float32)) for _ in range(25)), return_results=True ) assert len(results[0].docs.get_attributes('embedding')) == 25 assert results[0].docs.get_attributes('embedding')[0].shape == (target_output_dim,) @pytest.mark.parametrize( ['docs', 'docs_per_path', 'traversal_paths'], [ (pytest.lazy_fixture('docs_with_blobs'), [[['r'], 10], [['c'], 0], [['cc'], 0]], ['r']), (pytest.lazy_fixture('docs_with_chunk_blobs'), [[['r'], 0], [['c'], 10], [['cc'], 0]], ['c']), (pytest.lazy_fixture('docs_with_chunk_chunk_blobs'), [[['r'], 0], [['c'], 0], [['cc'], 10]], ['cc']) ] ) def test_traversal_path(docs: DocumentArray, docs_per_path: List[List[str]], traversal_paths: List[str]): flow = Flow().add(uses=ImageTFEncoder) with flow: results = flow.post( on='/test', inputs=docs, parameters={'traversal_paths': traversal_paths}, return_results=True ) for path, count in docs_per_path: assert len(DocumentArray(results[0].docs).traverse_flat(path).get_attributes('embedding')) == count
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 languages as described in our publication Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation. For an example, see `the distillation documentation <../../examples/training/distillation/README.html>`_ on extending language models to new languages. Args: model: SentenceTransformerModel References: - Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation: https://arxiv.org/abs/2004.09813 - `Training > Model Distillation <../../examples/training/distillation/README.html>`_ - `Training > Multilingual Models <../../examples/training/multilingual/README.html>`_ Requirements: 1. Usually uses a finetuned teacher M in a knowledge distillation setup Relations: - :class:`MarginMSELoss` is equivalent to this loss, but with a margin through a negative pair. Input: +-----------------------------------------+-----------------------------+ | Texts | Labels | +=========================================+=============================+ | sentence | model sentence embeddings | +-----------------------------------------+-----------------------------+ | sentence_1, sentence_2, ..., sentence_N | model sentence embeddings | +-----------------------------------------+-----------------------------+ Example: :: from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses from datasets import Dataset student_model = SentenceTransformer("microsoft/mpnet-base") teacher_model = SentenceTransformer("all-mpnet-base-v2") train_dataset = Dataset.from_dict({ "english": ["The first sentence", "The second sentence", "The third sentence", "The fourth sentence"], "french": ["La première phrase", "La deuxième phrase", "La troisième phrase", "La quatrième phrase"], }) def compute_labels(batch): return { "label": teacher_model.encode(batch["english"]) } train_dataset = train_dataset.map(compute_labels, batched=True) loss = losses.MSELoss(student_model) trainer = SentenceTransformerTrainer( model=student_model, train_dataset=train_dataset, loss=loss, ) trainer.train() """ super(MSELoss, self).__init__() self.model = model self.loss_fct = nn.MSELoss() def forward(self, sentence_features: Iterable[Dict[str, Tensor]], labels: Tensor): # Concatenate multiple inputs on the batch dimension if len(sentence_features) > 1: embeddings = torch.cat([self.model(inputs)["sentence_embedding"] for inputs in sentence_features], dim=0) # Repeat the labels for each input return self.loss_fct(embeddings, labels.repeat(len(sentence_features), 1)) embeddings = self.model(sentence_features[0])["sentence_embedding"] return self.loss_fct(embeddings, labels) @property def citation(self) -> str: return """ @inproceedings{reimers-2020-multilingual-sentence-bert, title = "Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation", author = "Reimers, Nils and Gurevych, Iryna", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing", month = "11", year = "2020", publisher = "Association for Computational Linguistics", url = "https://arxiv.org/abs/2004.09813", } """
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 described in our publication Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation. For an example, see `the distillation documentation <../../examples/training/distillation/README.html>`_ on extending language models to new languages. :param model: SentenceTransformerModel References: - Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation: https://arxiv.org/abs/2004.09813 - `Training > Model Distillation <../../examples/training/distillation/README.html>`_ - `Training > Multilingual Models <../../examples/training/multilingual/README.html>`_ Requirements: 1. Usually uses a finetuned teacher M in a knowledge distillation setup Relations: - :class:`MarginMSELoss` is equivalent to this loss, but with a margin through a negative pair. Input: +-------------------+-----------------------------+ | Texts | Labels | +===================+=============================+ | single sentences | model sentence embeddings | +-------------------+-----------------------------+ Example:: from sentence_transformers import SentenceTransformer, InputExample, losses from torch.utils.data import DataLoader model_en = SentenceTransformer('bert-base-cased') model_fr = SentenceTransformer('flaubert/flaubert_base_cased') examples_en = ['The first sentence', 'The second sentence', 'The third sentence', 'The fourth sentence'] examples_fr = ['La première phrase', 'La deuxième phrase', 'La troisième phrase', 'La quatrième phrase'] train_batch_size = 2 labels_en_en = model_en.encode(examples_en) examples_en_fr = [InputExample(texts=[x], label=labels_en_en[i]) for i, x in enumerate(examples_en)] loader_en_fr = DataLoader(examples_en_fr, batch_size=train_batch_size) examples_fr_fr = [InputExample(texts=[x], label=labels_en_en[i]) for i, x in enumerate(examples_fr)] loader_fr_fr = DataLoader(examples_fr_fr, batch_size=train_batch_size) train_loss = losses.MSELoss(model=model_fr) model_fr.fit( [(loader_en_fr, train_loss), (loader_fr_fr, train_loss)], epochs=10, ) """ super(MSELoss, self).__init__() self.model = model self.loss_fct = nn.MSELoss() def forward(self, sentence_features: Iterable[Dict[str, Tensor]], labels: Tensor): rep = self.model(sentence_features[0])["sentence_embedding"] return self.loss_fct(rep, labels)
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') for _ in range(50)] ) with Flow(return_results=True).add(uses=DPRTextEncoder) as flow: resp = flow.post( on='/index', inputs=docs, request_size=request_size, return_results=True, ) assert sum(len(resp_batch.docs) for resp_batch in resp) == 50 for r in resp: for doc in r.docs: assert doc.embedding.shape == (_EMBEDDING_DIM,) @pytest.mark.docker def test_docker_runtime(build_docker_image: str): with pytest.raises(subprocess.TimeoutExpired): subprocess.run( [ 'jina', 'executor', f'--uses=docker://{build_docker_image}', '--volumes=.cache:/workspace/.cache', ], timeout=30, check=True, )
__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 = DocumentArray( [Document(text='just some random text here') for _ in range(50)] ) with Flow(return_results=True).add(uses=DPRTextEncoder) as flow: resp = flow.post( on='/index', inputs=docs, request_size=request_size, return_results=True, ) assert sum(len(resp_batch.docs) for resp_batch in resp) == 50 for r in resp: for doc in r.docs: assert doc.embedding is not None assert doc.embedding.shape == (768,)
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') train_pipeline = [ dict(type='LoadImageFromFile', file_client_args=file_client_args), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='RandomResize', scale=[(1333, 640), (1333, 800)]), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] test_pipeline = [ dict(type='LoadImageFromFile', file_client_args=file_client_args), dict(type='Resize', scale=(1333, 800), keep_ratio=True), dict( type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor')) ] train_dataloader = dict( batch_size=2, num_workers=2, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), batch_sampler=dict(type='AspectRatioBatchSampler'), dataset=dict( type=dataset_type, data_root=data_root, ann_file='annotations/instances_train2017.json', data_prefix=dict(img='train2017/'), filter_cfg=dict(filter_empty_gt=True, min_size=32), pipeline=train_pipeline)) val_dataloader = dict( batch_size=2, num_workers=2, persistent_workers=True, drop_last=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='RepeatDataset', times=3, dataset=dict( type=dataset_type, data_root=data_root, ann_file='annotations/instances_val2017.json', data_prefix=dict(img='val2017/'), test_mode=True, pipeline=test_pipeline))) test_dataloader = val_dataloader val_evaluator = dict( type='CocoMetric', ann_file=data_root + 'annotations/instances_val2017.json', metric='bbox') test_evaluator = val_evaluator # training schedule for 3x with `RepeatDataset` train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1) val_cfg = dict(type='ValLoop') test_cfg = dict(type='TestLoop') # learning rate # Experiments show that using milestones=[9, 11] has higher performance param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=12, by_epoch=True, milestones=[9, 11], gamma=0.1) ] # optimizer optim_wrapper = dict( type='OptimWrapper', optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001))
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') train_pipeline = [ dict(type='LoadImageFromFile', file_client_args=file_client_args), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='RandomResize', scale=[(1333, 640), (1333, 800)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] test_pipeline = [ dict(type='LoadImageFromFile', file_client_args=file_client_args), dict(type='Resize', scale=(1333, 800), keep_ratio=True), dict( type='PackDetInputs', meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor')) ] train_dataloader = dict( batch_size=2, num_workers=2, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), batch_sampler=dict(type='AspectRatioBatchSampler'), dataset=dict( type=dataset_type, data_root=data_root, ann_file='annotations/instances_train2017.json', data_prefix=dict(img='train2017/'), filter_cfg=dict(filter_empty_gt=True, min_size=32), pipeline=train_pipeline)) val_dataloader = dict( batch_size=2, num_workers=2, persistent_workers=True, drop_last=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type=dataset_type, data_root=data_root, ann_file='annotations/instances_val2017.json', data_prefix=dict(img='val2017/'), test_mode=True, pipeline=test_pipeline)) test_dataloader = val_dataloader val_evaluator = dict( type='CocoMetric', ann_file=data_root + 'annotations/instances_val2017.json', metric='bbox') test_evaluator = val_evaluator # TODO: use repeat dataset wrapper # training schedule for 3x train_cfg = dict(by_epoch=True, max_epochs=36) val_cfg = dict(interval=3) test_cfg = dict() # learning rate # Experiments show that using milestones=[27, 33] has higher performance param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=36, by_epoch=True, milestones=[27, 33], gamma=0.1) ] # optimizer optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
"""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 import AbsMaxQuantizer as AbsMaxQuantizer from keras.src.quantizers.quantizers import Quantizer as Quantizer from keras.src.quantizers.quantizers import abs_max_quantize as abs_max_quantize from keras.src.quantizers.quantizers import ( compute_float8_amax_history as compute_float8_amax_history, ) from keras.src.quantizers.quantizers import ( compute_float8_scale as compute_float8_scale, ) from keras.src.quantizers.quantizers import ( fake_quant_with_min_max_vars as fake_quant_with_min_max_vars, ) from keras.src.quantizers.quantizers import ( quantize_and_dequantize as quantize_and_dequantize, )
"""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.src.quantizers.quantizers import Quantizer from keras.src.quantizers.quantizers import abs_max_quantize from keras.src.quantizers.quantizers import compute_float8_amax_history from keras.src.quantizers.quantizers import compute_float8_scale from keras.src.quantizers.quantizers import fake_quant_with_min_max_vars from keras.src.quantizers.quantizers import quantize_and_dequantize
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_with_post_processor() -> None: def add_the_end(text: str) -> str: return text + "THE END!" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") loader = UnstructuredFileLoader( file_path=file_path, post_processors=[add_the_end], strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 assert docs[0].page_content.endswith("THE END!") def test_unstructured_file_loader_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] loader = UnstructuredFileLoader( file_path=file_paths, strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader() -> None: """Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") loader = UnstructuredAPIFileLoader( file_path=file_path, api_key="FAKE_API_KEY", strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] loader = UnstructuredAPIFileLoader( file_path=file_paths, api_key="FAKE_API_KEY", strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_io_loader() -> None: """Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") with open(file_path, "rb") as f: loader = UnstructuredAPIFileIOLoader( file=f, api_key="FAKE_API_KEY", strategy="fast", mode="elements", file_filename=file_path, ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader_io_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] with ExitStack() as stack: files = [stack.enter_context(open(file_path, "rb")) for file_path in file_paths] loader = UnstructuredAPIFileIOLoader( file=files, api_key="FAKE_API_KEY", strategy="fast", mode="elements", file_filenames=file_paths, ) docs = loader.load() assert len(docs) > 1
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_with_post_processor() -> None: def add_the_end(text: str) -> str: return text + "THE END!" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") loader = UnstructuredFileLoader( file_path=file_path, post_processors=[add_the_end], strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 assert docs[0].page_content.endswith("THE END!") def test_unstructured_file_loader_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] loader = UnstructuredFileLoader( file_path=file_paths, strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader() -> None: """Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") loader = UnstructuredAPIFileLoader( file_path=file_path, api_key="FAKE_API_KEY", strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] loader = UnstructuredAPIFileLoader( file_path=file_paths, api_key="FAKE_API_KEY", strategy="fast", mode="elements", ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_io_loader() -> None: """Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf") with open(file_path, "rb") as f: loader = UnstructuredAPIFileIOLoader( file=f, api_key="FAKE_API_KEY", strategy="fast", mode="elements", file_filename=file_path, ) docs = loader.load() assert len(docs) > 1 def test_unstructured_api_file_loader_io_multiple_files() -> None: """Test unstructured loader.""" file_paths = [ os.path.join(EXAMPLE_DOCS_DIRECTORY, "layout-parser-paper.pdf"), os.path.join(EXAMPLE_DOCS_DIRECTORY, "whatsapp_chat.txt"), ] with ExitStack() as stack: files = [stack.enter_context(open(file_path, "rb")) for file_path in file_paths] loader = UnstructuredAPIFileIOLoader( file=files, # type: ignore api_key="FAKE_API_KEY", strategy="fast", mode="elements", file_filenames=file_paths, ) docs = loader.load() assert len(docs) > 1
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.to_dict(), TYPE_KEY: doc.get_type(), } def json_to_doc(doc_dict: dict) -> BaseNode: doc_type = doc_dict[TYPE_KEY] data_dict = doc_dict[DATA_KEY] doc: BaseNode if "extra_info" in data_dict: return legacy_json_to_doc(doc_dict) else: if doc_type == Document.get_type(): if data_dict["class_name"] == ImageDocument.class_name(): doc = ImageDocument.from_dict(data_dict) else: doc = Document.from_dict(data_dict) elif doc_type == TextNode.get_type(): doc = TextNode.from_dict(data_dict) elif doc_type == ImageNode.get_type(): doc = ImageNode.from_dict(data_dict) elif doc_type == IndexNode.get_type(): doc = IndexNode.from_dict(data_dict) elif doc_type == Node.get_type(): doc = Node.from_dict(data_dict) else: raise ValueError(f"Unknown doc type: {doc_type}") return doc def legacy_json_to_doc(doc_dict: dict) -> BaseNode: """Todo: Deprecated legacy support for old node versions.""" doc_type = doc_dict[TYPE_KEY] data_dict = doc_dict[DATA_KEY] doc: BaseNode text = data_dict.get("text", "") metadata = data_dict.get("extra_info", {}) or {} id_ = data_dict.get("doc_id", None) relationships = data_dict.get("relationships", {}) relationships = { NodeRelationship(k): RelatedNodeInfo(node_id=str(v)) for k, v in relationships.items() } if doc_type == Document.get_type(): doc = Document( text=text, metadata=metadata, id=id_, relationships=relationships ) elif doc_type == TextNode.get_type(): doc = TextNode( text=text, metadata=metadata, id=id_, relationships=relationships ) elif doc_type == ImageNode.get_type(): image = data_dict.get("image", None) doc = ImageNode( text=text, metadata=metadata, id=id_, relationships=relationships, image=image, ) elif doc_type == IndexNode.get_type(): index_id = data_dict.get("index_id", None) doc = IndexNode( text=text, metadata=metadata, id=id_, relationships=relationships, index_id=index_id, ) else: raise ValueError(f"Unknown doc type: {doc_type}") return doc
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(), TYPE_KEY: doc.get_type(), } def json_to_doc(doc_dict: dict) -> BaseNode: doc_type = doc_dict[TYPE_KEY] data_dict = doc_dict[DATA_KEY] doc: BaseNode if "extra_info" in data_dict: return legacy_json_to_doc(doc_dict) else: if doc_type == Document.get_type(): if data_dict["class_name"] == ImageDocument.class_name(): doc = ImageDocument.from_dict(data_dict) else: doc = Document.from_dict(data_dict) elif doc_type == TextNode.get_type(): doc = TextNode.from_dict(data_dict) elif doc_type == ImageNode.get_type(): doc = ImageNode.from_dict(data_dict) elif doc_type == IndexNode.get_type(): doc = IndexNode.from_dict(data_dict) else: raise ValueError(f"Unknown doc type: {doc_type}") return doc def legacy_json_to_doc(doc_dict: dict) -> BaseNode: """Todo: Deprecated legacy support for old node versions.""" doc_type = doc_dict[TYPE_KEY] data_dict = doc_dict[DATA_KEY] doc: BaseNode text = data_dict.get("text", "") metadata = data_dict.get("extra_info", {}) or {} id_ = data_dict.get("doc_id", None) relationships = data_dict.get("relationships", {}) relationships = { NodeRelationship(k): RelatedNodeInfo(node_id=str(v)) for k, v in relationships.items() } if doc_type == Document.get_type(): doc = Document( text=text, metadata=metadata, id=id_, relationships=relationships ) elif doc_type == TextNode.get_type(): doc = TextNode( text=text, metadata=metadata, id=id_, relationships=relationships ) elif doc_type == ImageNode.get_type(): image = data_dict.get("image", None) doc = ImageNode( text=text, metadata=metadata, id=id_, relationships=relationships, image=image, ) elif doc_type == IndexNode.get_type(): index_id = data_dict.get("index_id", None) doc = IndexNode( text=text, metadata=metadata, id=id_, relationships=relationships, index_id=index_id, ) else: raise ValueError(f"Unknown doc type: {doc_type}") return doc
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, resolve_embed_model def generate_strings(num_strings: int = 100, string_length: int = 10) -> List[str]: """ Generate random strings sliced from the paul graham essay. Has the following form: offset 0: [0:string_length], [string_length:2*string_length], ... offset 1: [1:1+string_length], [1+string_length:1+2*string_length],... ... """ # noqa: D415 content = ( SimpleDirectoryReader("../../examples/paul_graham_essay/data") .load_data()[0] .get_content() ) content_length = len(content) strings_per_loop = content_length / string_length num_loops_upper_bound = int(num_strings / strings_per_loop) + 1 strings = [] for offset in range(num_loops_upper_bound + 1): ptr = offset % string_length while ptr + string_length < content_length: strings.append(content[ptr : ptr + string_length]) ptr += string_length if len(strings) == num_strings: break return strings def create_open_ai_embedding(batch_size: int) -> Tuple[BaseEmbedding, str, int]: return ( OpenAIEmbedding(embed_batch_size=batch_size), "OpenAIEmbedding", 4096, ) def create_local_embedding( model_name: str, batch_size: int ) -> Tuple[BaseEmbedding, str, int]: model = resolve_embed_model(f"local:{model_name}") return ( model, "hf/" + model_name, model._langchain_embedding.client.max_seq_length, # type: ignore ) def bench_simple_vector_store( embed_models: List[Callable[[int], Tuple[BaseEmbedding, str, int]]], num_strings: List[int] = [100], string_lengths: List[int] = [64, 256], embed_batch_sizes: List[int] = [1, DEFAULT_EMBED_BATCH_SIZE], torch_num_threads: Optional[int] = None, ) -> None: """Benchmark embeddings.""" print("Benchmarking Embeddings\n---------------------------") results = [] if torch_num_threads is not None: import torch # pants: no-infer-dep torch.set_num_threads(torch_num_threads) max_num_strings = max(num_strings) for string_length in string_lengths: generated_strings = generate_strings( num_strings=max_num_strings, string_length=string_length ) for string_count in num_strings: strings = generated_strings[:string_count] for batch_size in embed_batch_sizes: models = [] for create_model in embed_models: models.append(create_model(batch_size=batch_size)) # type: ignore for model in models: time1 = time.time() _ = model[0].get_text_embedding_batch(strings, show_progress=True) time2 = time.time() print( f"Embedding with model {model[1]} with " f"batch size {batch_size} and max_seq_length {model[2]} for " f"{string_count} strings of length {string_length} took " f"{time2 - time1} seconds." ) results.append((model[1], batch_size, string_length, time2 - time1)) # TODO: async version # print final results print("\n\nFinal Results\n---------------------------") results_df = pd.DataFrame( results, columns=["model", "batch_size", "string_length", "time"] ) print(results_df) if __name__ == "__main__": bench_simple_vector_store( embed_models=[ # create_open_ai_embedding, partial( create_local_embedding, model_name="sentence-transformers/all-MiniLM-L6-v2", ), partial( create_local_embedding, model_name="sentence-transformers/all-MiniLM-L12-v2", ), partial( create_local_embedding, model_name="BAAI/bge-small-en", ), partial( create_local_embedding, model_name="sentence-transformers/all-mpnet-base-v2", ), ], torch_num_threads=None, )
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, resolve_embed_model def generate_strings(num_strings: int = 100, string_length: int = 10) -> List[str]: """ Generate random strings sliced from the paul graham essay of the following form: offset 0: [0:string_length], [string_length:2*string_length], ... offset 1: [1:1+string_length], [1+string_length:1+2*string_length],... ... """ # noqa: D415 content = ( SimpleDirectoryReader("../../examples/paul_graham_essay/data") .load_data()[0] .get_content() ) content_length = len(content) strings_per_loop = content_length / string_length num_loops_upper_bound = int(num_strings / strings_per_loop) + 1 strings = [] for offset in range(num_loops_upper_bound + 1): ptr = offset % string_length while ptr + string_length < content_length: strings.append(content[ptr : ptr + string_length]) ptr += string_length if len(strings) == num_strings: break return strings def create_open_ai_embedding(batch_size: int) -> Tuple[BaseEmbedding, str, int]: return ( OpenAIEmbedding(embed_batch_size=batch_size), "OpenAIEmbedding", 4096, ) def create_local_embedding( model_name: str, batch_size: int ) -> Tuple[BaseEmbedding, str, int]: model = resolve_embed_model(f"local:{model_name}") return ( model, "hf/" + model_name, model._langchain_embedding.client.max_seq_length, # type: ignore ) def bench_simple_vector_store( embed_models: List[Callable[[int], Tuple[BaseEmbedding, str, int]]], num_strings: List[int] = [100], string_lengths: List[int] = [64, 256], embed_batch_sizes: List[int] = [1, DEFAULT_EMBED_BATCH_SIZE], torch_num_threads: Optional[int] = None, ) -> None: """Benchmark embeddings.""" print("Benchmarking Embeddings\n---------------------------") results = [] if torch_num_threads is not None: import torch # pants: no-infer-dep torch.set_num_threads(torch_num_threads) max_num_strings = max(num_strings) for string_length in string_lengths: generated_strings = generate_strings( num_strings=max_num_strings, string_length=string_length ) for string_count in num_strings: strings = generated_strings[:string_count] for batch_size in embed_batch_sizes: models = [] for create_model in embed_models: models.append(create_model(batch_size=batch_size)) # type: ignore for model in models: time1 = time.time() _ = model[0].get_text_embedding_batch(strings, show_progress=True) time2 = time.time() print( f"Embedding with model {model[1]} with " f"batch size {batch_size} and max_seq_length {model[2]} for " f"{string_count} strings of length {string_length} took " f"{time2 - time1} seconds." ) results.append((model[1], batch_size, string_length, time2 - time1)) # TODO: async version # print final results print("\n\nFinal Results\n---------------------------") results_df = pd.DataFrame( results, columns=["model", "batch_size", "string_length", "time"] ) print(results_df) if __name__ == "__main__": bench_simple_vector_store( embed_models=[ # create_open_ai_embedding, partial( create_local_embedding, model_name="sentence-transformers/all-MiniLM-L6-v2", ), partial( create_local_embedding, model_name="sentence-transformers/all-MiniLM-L12-v2", ), partial( create_local_embedding, model_name="BAAI/bge-small-en", ), partial( create_local_embedding, model_name="sentence-transformers/all-mpnet-base-v2", ), ], torch_num_threads=None, )
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 = """Thought: agent thought here ``` { "action": "search", "action_input": "what is the temperature in SF?" } ``` """ output = parser.invoke(_input) expected_output = AgentAction( tool="search", tool_input="what is the temperature in SF?", log=_input, ) assert output == expected_output def test_finish() -> None: """Test standard parsing of agent finish.""" parser = ReActJsonSingleInputOutputParser() _input = """Thought: agent thought here Final Answer: The temperature is 100""" output = parser.invoke(_input) expected_output = AgentFinish( return_values={"output": "The temperature is 100"}, log=_input, ) assert output == expected_output
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 = """Thought: agent thought here ``` { "action": "search", "action_input": "what is the temperature in SF?" } ``` """ output = parser.invoke(_input) expected_output = AgentAction( tool="search", tool_input="what is the temperature in SF?", log=_input ) assert output == expected_output def test_finish() -> None: """Test standard parsing of agent finish.""" parser = ReActJsonSingleInputOutputParser() _input = """Thought: agent thought here Final Answer: The temperature is 100""" output = parser.invoke(_input) expected_output = AgentFinish( return_values={"output": "The temperature is 100"}, log=_input ) assert output == expected_output
"""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[BaseChatModel]: return ChatPerplexity @property def init_from_env_params(self) -> tuple[dict, dict, dict]: return ({"PPLX_API_KEY": "api_key"}, {}, {"pplx_api_key": "api_key"})
"""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_model_class(self) -> Type[BaseChatModel]: return ChatPerplexity @property def init_from_env_params(self) -> Tuple[dict, dict, dict]: return ({"PPLX_API_KEY": "api_key"}, {}, {"pplx_api_key": "api_key"})
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 compatibility with THD, we use an # extraordinarily high default timeout, given that THD did not have timeouts. default_pg_timeout: timedelta = _DEFAULT_PG_TIMEOUT # Separate timeout for PGNCCL mainly because it's always been that way in the C++ layer, but until recently # there was one default that applied across all backends in the python layer. # Later, we could consider merging them back together at the c++ layer if we can align on a same value. # (only if TORCH_NCCL_BLOCKING_WAIT or TORCH_NCCL_ASYNC_ERROR_HANDLING is set to 1). try: from torch._C._distributed_c10d import _DEFAULT_PG_NCCL_TIMEOUT default_pg_nccl_timeout: Optional[timedelta] = _DEFAULT_PG_NCCL_TIMEOUT except ImportError: # if C++ NCCL support is not compiled, we don't have access to the default nccl value. # if anyone is actually trying to use nccl in this state, it should error. default_pg_nccl_timeout = None
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 compatibility with THD, we use an # extraordinarily high default timeout, given that THD did not have timeouts. default_pg_timeout: timedelta = _DEFAULT_PG_TIMEOUT # Separate timeout for PGNCCL mainly becuase it's always been that way in the C++ layer, but until recently # there was one default that applied across all backends in the python layer. # Later, we could consider merging them back together at the c++ layer if we can align on a same value. # (only if TORCH_NCCL_BLOCKING_WAIT or TORCH_NCCL_ASYNC_ERROR_HANDLING is set to 1). try: from torch._C._distributed_c10d import _DEFAULT_PG_NCCL_TIMEOUT default_pg_nccl_timeout: Optional[timedelta] = _DEFAULT_PG_NCCL_TIMEOUT except ImportError: # if C++ NCCL support is not compiled, we don't have access to the default nccl value. # if anyone is actually trying to use nccl in this state, it should error. default_pg_nccl_timeout = None
# 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 default. Possibly the only difference between them with default settings is that `binary` may achieve a slight speed improvement by assuming that the labels are binary instead of probabilistic. """ import time import numpy as np import pandas as pd from scipy.special import expit import lightgbm as lgb ################# # Simulate some binary data with a single categorical and # single continuous predictor rng = np.random.default_rng(seed=0) N = 1000 X = pd.DataFrame({"continuous": range(N), "categorical": np.repeat([0, 1, 2, 3, 4], N / 5)}) CATEGORICAL_EFFECTS = [-1, -1, -2, -2, 2] LINEAR_TERM = np.array( [-0.5 + 0.01 * X["continuous"][k] + CATEGORICAL_EFFECTS[X["categorical"][k]] for k in range(X.shape[0])] ) + rng.normal(loc=0, scale=1, size=X.shape[0]) TRUE_PROB = expit(LINEAR_TERM) Y = rng.binomial(n=1, p=TRUE_PROB, size=N) DATA = { "X": X, "probability_labels": TRUE_PROB, "binary_labels": Y, "lgb_with_binary_labels": lgb.Dataset(X, Y), "lgb_with_probability_labels": lgb.Dataset(X, TRUE_PROB), } ################# # Set up a couple of utilities for our experiments def log_loss(preds, labels): """Logarithmic loss with non-necessarily-binary labels.""" log_likelihood = np.sum(labels * np.log(preds)) / len(preds) return -log_likelihood def experiment(objective, label_type, data): """Measure performance of an objective. Parameters ---------- objective : {'binary', 'xentropy'} Objective function. label_type : {'binary', 'probability'} Type of the label. data : dict Data for training. Returns ------- result : dict Experiment summary stats. """ nrounds = 5 lgb_data = data[f"lgb_with_{label_type}_labels"] params = {"objective": objective, "feature_fraction": 1, "bagging_fraction": 1, "verbose": -1, "seed": 123} time_zero = time.time() gbm = lgb.train(params, lgb_data, num_boost_round=nrounds) y_fitted = gbm.predict(data["X"]) y_true = data[f"{label_type}_labels"] duration = time.time() - time_zero return {"time": duration, "correlation": np.corrcoef(y_fitted, y_true)[0, 1], "logloss": log_loss(y_fitted, y_true)} ################# # Observe the behavior of `binary` and `xentropy` objectives print("Performance of `binary` objective with binary labels:") print(experiment("binary", label_type="binary", data=DATA)) print("Performance of `xentropy` objective with binary labels:") print(experiment("xentropy", label_type="binary", data=DATA)) print("Performance of `xentropy` objective with probability labels:") print(experiment("xentropy", label_type="probability", data=DATA)) # Trying this throws an error on non-binary values of y: # experiment('binary', label_type='probability', DATA) # The speed of `binary` is not drastically different than # `xentropy`. `xentropy` runs faster than `binary` in many cases, although # there are reasons to suspect that `binary` should run faster when the # label is an integer instead of a float K = 10 A = [experiment("binary", label_type="binary", data=DATA)["time"] for k in range(K)] B = [experiment("xentropy", label_type="binary", data=DATA)["time"] for k in range(K)] print(f"Best `binary` time: {min(A)}") print(f"Best `xentropy` time: {min(B)}")
# 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 default. Possibly the only difference between them with default settings is that `binary` may achieve a slight speed improvement by assuming that the labels are binary instead of probabilistic. """ import time import numpy as np import pandas as pd from scipy.special import expit import lightgbm as lgb ################# # Simulate some binary data with a single categorical and # single continuous predictor np.random.seed(0) N = 1000 X = pd.DataFrame({"continuous": range(N), "categorical": np.repeat([0, 1, 2, 3, 4], N / 5)}) CATEGORICAL_EFFECTS = [-1, -1, -2, -2, 2] LINEAR_TERM = np.array( [-0.5 + 0.01 * X["continuous"][k] + CATEGORICAL_EFFECTS[X["categorical"][k]] for k in range(X.shape[0])] ) + np.random.normal(0, 1, X.shape[0]) TRUE_PROB = expit(LINEAR_TERM) Y = np.random.binomial(1, TRUE_PROB, size=N) DATA = { "X": X, "probability_labels": TRUE_PROB, "binary_labels": Y, "lgb_with_binary_labels": lgb.Dataset(X, Y), "lgb_with_probability_labels": lgb.Dataset(X, TRUE_PROB), } ################# # Set up a couple of utilities for our experiments def log_loss(preds, labels): """Logarithmic loss with non-necessarily-binary labels.""" log_likelihood = np.sum(labels * np.log(preds)) / len(preds) return -log_likelihood def experiment(objective, label_type, data): """Measure performance of an objective. Parameters ---------- objective : {'binary', 'xentropy'} Objective function. label_type : {'binary', 'probability'} Type of the label. data : dict Data for training. Returns ------- result : dict Experiment summary stats. """ np.random.seed(0) nrounds = 5 lgb_data = data[f"lgb_with_{label_type}_labels"] params = {"objective": objective, "feature_fraction": 1, "bagging_fraction": 1, "verbose": -1} time_zero = time.time() gbm = lgb.train(params, lgb_data, num_boost_round=nrounds) y_fitted = gbm.predict(data["X"]) y_true = data[f"{label_type}_labels"] duration = time.time() - time_zero return {"time": duration, "correlation": np.corrcoef(y_fitted, y_true)[0, 1], "logloss": log_loss(y_fitted, y_true)} ################# # Observe the behavior of `binary` and `xentropy` objectives print("Performance of `binary` objective with binary labels:") print(experiment("binary", label_type="binary", data=DATA)) print("Performance of `xentropy` objective with binary labels:") print(experiment("xentropy", label_type="binary", data=DATA)) print("Performance of `xentropy` objective with probability labels:") print(experiment("xentropy", label_type="probability", data=DATA)) # Trying this throws an error on non-binary values of y: # experiment('binary', label_type='probability', DATA) # The speed of `binary` is not drastically different than # `xentropy`. `xentropy` runs faster than `binary` in many cases, although # there are reasons to suspect that `binary` should run faster when the # label is an integer instead of a float K = 10 A = [experiment("binary", label_type="binary", data=DATA)["time"] for k in range(K)] B = [experiment("xentropy", label_type="binary", data=DATA)["time"] for k in range(K)] print(f"Best `binary` time: {min(A)}") print(f"Best `xentropy` time: {min(B)}")
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 for sample in batch["questions"] for text in sample["text"]]}, batched=True, remove_columns=["questions", "is_duplicate"], ) max_corpus_size = 100_000 corpus = dataset["text"][:max_corpus_size] # 2. Come up with some queries queries = [ "How do I become a good programmer?", "How do I become a good data scientist?", ] # 3. Load the model model = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1") # 4. Choose a target precision for the corpus embeddings corpus_precision = "binary" # Valid options are: "float32", "uint8", "int8", "ubinary", and "binary" # But usearch only supports "float32", "int8", and "binary" # 5. Encode the corpus full_corpus_embeddings = model.encode(corpus, normalize_embeddings=True, show_progress_bar=True) corpus_embeddings = quantize_embeddings(full_corpus_embeddings, precision=corpus_precision) # NOTE: We can also pass "precision=..." to the encode method to quantize the embeddings directly, # but we want to keep the full precision embeddings to act as a calibration dataset for quantizing # the query embeddings. This is important only if you are using uint8 or int8 precision # Initially, we don't have a usearch index yet, we can use semantic_search_usearch to create it corpus_index = None while True: # 7. Encode the queries using the full precision start_time = time.time() query_embeddings = model.encode(queries, normalize_embeddings=True) print(f"Encoding time: {time.time() - start_time:.6f} seconds") # 8. Perform semantic search using usearch results, search_time, corpus_index = semantic_search_usearch( query_embeddings, corpus_index=corpus_index, corpus_embeddings=corpus_embeddings if corpus_index is None else None, corpus_precision=corpus_precision, top_k=10, calibration_embeddings=full_corpus_embeddings, rescore=corpus_precision != "float32", rescore_multiplier=4, exact=True, output_index=True, ) # This is a helper function to showcase how usearch can be used with quantized embeddings. # You must either provide the `corpus_embeddings` or the `corpus_index` usearch index, but not both. # In the first call we'll provide the `corpus_embeddings` and get the `corpus_index` back, which # we'll use in the next call. In practice, the index is stored in RAM or saved to disk, and not # recalculated for every query. # This function will 1) quantize the query embeddings to the same precision as the corpus embeddings, # 2) perform the semantic search using usearch, 3) rescore the results using the full precision embeddings, # and 4) return the results and the search time (and perhaps the usearch index). # `corpus_precision` must be the same as the precision used to quantize the corpus embeddings. # It is used to convert the query embeddings to the same precision as the corpus embeddings. # `top_k` determines how many results are returned for each query. # `rescore_multiplier` is a parameter for the rescoring step. Rather than searching for the top_k results, # we search for top_k * rescore_multiplier results and rescore the top_k results using the full precision embeddings. # So, higher values of rescore_multiplier will give better results, but will be slower. # `calibration_embeddings` is a set of embeddings used to calibrate the quantization of the query embeddings. # This is important only if you are using uint8 or int8 precision. In practice, this is used to calculate # the minimum and maximum values of each of the embedding dimensions, which are then used to determine the # quantization thresholds. # `rescore` determines whether to rescore the results using the full precision embeddings, if False & the # corpus is quantized, the results will be very poor. `exact` determines whether to use the exact search # or the approximate search method in usearch. # 9. Output the results print(f"Search time: {search_time:.6f} seconds") for query, result in zip(queries, results): print(f"Query: {query}") for entry in result: print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}") print("") # 10. Prompt for more queries queries = [input("Please enter a question: ")]
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 for sample in batch["questions"] for text in sample["text"]]}, batched=True, remove_columns=["questions", "is_duplicate"], ) max_corpus_size = 100_000 corpus = dataset["text"][:max_corpus_size] # 2. Come up with some queries queries = [ "How do I become a good programmer?", "How do I become a good data scientist?", ] # 3. Load the model model = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1") # 4. Choose a target precision for the corpus embeddings corpus_precision = "binary" # Valid options are: "float32", "uint8", "int8", "ubinary", and "binary" # But usearch only supports "float32", "int8", and "binary" # 5. Encode the corpus full_corpus_embeddings = model.encode(corpus, normalize_embeddings=True, show_progress_bar=True) corpus_embeddings = quantize_embeddings(full_corpus_embeddings, precision=corpus_precision) # NOTE: We can also pass "precision=..." to the encode method to quantize the embeddings directly, # but we want to keep the full precision embeddings to act as a calibration dataset for quantizing # the query embeddings. This is important only if you are using uint8 or int8 precision # Initially, we don't have a usearch index yet, we can use semantic_search_usearch to create it corpus_index = None while True: # 7. Encode the queries using the full precision start_time = time.time() query_embeddings = model.encode(queries, normalize_embeddings=True) print(f"Encoding time: {time.time() - start_time:.6f} seconds") # 8. Perform semantic search using usearch results, search_time, corpus_index = semantic_search_usearch( query_embeddings, corpus_index=corpus_index, corpus_embeddings=corpus_embeddings if corpus_index is None else None, corpus_precision=corpus_precision, top_k=10, calibration_embeddings=full_corpus_embeddings, rescore=corpus_precision != "float32", rescore_multiplier=4, exact=True, output_index=True, ) # This is a helper function to showcase how usearch can be used with quantized embeddings. # You must either provide the `corpus_embeddings` or the `corpus_index` usearch index, but not both. # In the first call we'll provide the `corpus_embeddings` and get the `corpus_index` back, which # we'll use in the next call. In practice, the index is stored in RAM or saved to disk, and not # recalculated for every query. # This function will 1) quantize the query embeddings to the same precision as the corpus embeddings, # 2) perform the semantic search using usearch, 3) rescore the results using the full precision embeddings, # and 4) return the results and the search time (and perhaps the usearch index). # `corpus_precision` must be the same as the precision used to quantize the corpus embeddings. # It is used to convert the query embeddings to the same precision as the corpus embeddings. # `top_k` determines how many results are returned for each query. # `rescore_multiplier` is a parameter for the rescoring step. Rather than searching for the top_k results, # we search for top_k * rescore_multiplier results and rescore the top_k results using the full precision embeddings. # So, higher values of rescore_multiplier will give better results, but will be slower. # `calibration_embeddings` is a set of embeddings used to calibrate the quantization of the query embeddings. # This is important only if you are using uint8 or int8 precision. In practice, this is used to calculate # the minimum and maximum values of each of the embedding dimensions, which are then used to determine the # quantization thresholds. # `rescore` determines whether to rescore the results using the full precision embeddings, if False & the # corpus is quantized, the results will be very poor. `exact` determines whether to use the exact search # or the approximate search method in usearch. # 9. Output the results print(f"Search time: {search_time:.6f} seconds") for query, result in zip(queries, results): print(f"Query: {query}") for entry in result: print(f"(Score: {entry['score']:.4f}) {corpus[entry['corpus_id']]}") print("") # 10. Prompt for more queries queries = [input("Please enter a question: ")]
"""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.finetuning.types import BaseEmbeddingFinetuneEngine class SentenceTransformersFinetuneEngine(BaseEmbeddingFinetuneEngine): """Sentence Transformers Finetune Engine.""" def __init__( self, dataset: EmbeddingQAFinetuneDataset, model_id: str = "BAAI/bge-small-en", model_output_path: str = "exp_finetune", batch_size: int = 10, val_dataset: Optional[EmbeddingQAFinetuneDataset] = None, loss: Optional[Any] = None, epochs: int = 2, show_progress_bar: bool = True, evaluation_steps: int = 50, use_all_docs: bool = False, trust_remote_code: bool = False, device: Optional[Any] = None, save_checkpoints: bool = False, resume_from_checkpoint: bool = False, checkpoint_save_steps: int = 500, checkpoint_save_total_limit: int = 0, ) -> None: """Init params.""" from sentence_transformers import InputExample, SentenceTransformer, losses from torch.utils.data import DataLoader self.dataset = dataset self.model_id = model_id self.model_output_path = model_output_path self.model = SentenceTransformer( model_id, trust_remote_code=trust_remote_code, device=device ) self.use_all_docs = use_all_docs examples: Any = [] for query_id, query in dataset.queries.items(): if use_all_docs: for node_id in dataset.relevant_docs[query_id]: text = dataset.corpus[node_id] example = InputExample(texts=[query, text]) examples.append(example) else: node_id = dataset.relevant_docs[query_id][0] text = dataset.corpus[node_id] example = InputExample(texts=[query, text]) examples.append(example) self.examples = examples self.loader: DataLoader = DataLoader(examples, batch_size=batch_size) # define evaluator from sentence_transformers.evaluation import InformationRetrievalEvaluator evaluator: Optional[InformationRetrievalEvaluator] = None if val_dataset is not None: evaluator = InformationRetrievalEvaluator( val_dataset.queries, val_dataset.corpus, val_dataset.relevant_docs ) self.evaluator = evaluator # define loss self.loss = loss or losses.MultipleNegativesRankingLoss(self.model) self.epochs = epochs self.show_progress_bar = show_progress_bar self.evaluation_steps = evaluation_steps self.warmup_steps = int(len(self.loader) * epochs * 0.1) self.checkpoint_path = ( os.path.join("checkpoints", model_output_path) if save_checkpoints else None ) self.resume_from_checkpoint = resume_from_checkpoint self.checkpoint_save_steps = checkpoint_save_steps self.checkpoint_save_total_limit = checkpoint_save_total_limit def finetune(self, **train_kwargs: Any) -> None: """Finetune model.""" self.model.fit( train_objectives=[(self.loader, self.loss)], epochs=self.epochs, warmup_steps=self.warmup_steps, output_path=self.model_output_path, show_progress_bar=self.show_progress_bar, evaluator=self.evaluator, evaluation_steps=self.evaluation_steps, checkpoint_path=self.checkpoint_path, resume_from_checkpoint=self.resume_from_checkpoint, checkpoint_save_steps=self.checkpoint_save_steps, checkpoint_save_total_limit=self.checkpoint_save_total_limit, ) def get_finetuned_model(self, **model_kwargs: Any) -> BaseEmbedding: """Gets finetuned model.""" embed_model_str = "local:" + self.model_output_path return resolve_embed_model(embed_model_str)
"""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.finetuning.types import BaseEmbeddingFinetuneEngine class SentenceTransformersFinetuneEngine(BaseEmbeddingFinetuneEngine): """Sentence Transformers Finetune Engine.""" def __init__( self, dataset: EmbeddingQAFinetuneDataset, model_id: str = "BAAI/bge-small-en", model_output_path: str = "exp_finetune", batch_size: int = 10, val_dataset: Optional[EmbeddingQAFinetuneDataset] = None, loss: Optional[Any] = None, epochs: int = 2, show_progress_bar: bool = True, evaluation_steps: int = 50, use_all_docs: bool = False, trust_remote_code: bool = False, device: Optional[Any] = None, save_checkpoints: bool = False, resume_from_checkpoint: bool = False, checkpoint_save_steps: int = 500, checkpoint_save_total_limit: int = 0, ) -> None: """Init params.""" from sentence_transformers import InputExample, SentenceTransformer, losses from torch.utils.data import DataLoader self.dataset = dataset self.model_id = model_id self.model_output_path = model_output_path self.model = SentenceTransformer( model_id, trust_remote_code=trust_remote_code, device=device ) self.use_all_docs = use_all_docs examples: Any = [] for query_id, query in dataset.queries.items(): if use_all_docs: for node_id in dataset.relevant_docs[query_id]: text = dataset.corpus[node_id] example = InputExample(texts=[query, text]) examples.append(example) else: node_id = dataset.relevant_docs[query_id][0] text = dataset.corpus[node_id] example = InputExample(texts=[query, text]) examples.append(example) self.examples = examples self.loader: DataLoader = DataLoader(examples, batch_size=batch_size) # define evaluator from sentence_transformers.evaluation import InformationRetrievalEvaluator evaluator: Optional[InformationRetrievalEvaluator] = None if val_dataset is not None: evaluator = InformationRetrievalEvaluator( val_dataset.queries, val_dataset.corpus, val_dataset.relevant_docs ) self.evaluator = evaluator # define loss self.loss = loss or losses.MultipleNegativesRankingLoss(self.model) self.epochs = epochs self.show_progress_bar = show_progress_bar self.evaluation_steps = evaluation_steps self.warmup_steps = int(len(self.loader) * epochs * 0.1) self.checkpoint_path = ( os.path.join("checkpoints", model_output_path) if save_checkpoints else None ) self.resume_from_checkpoint = resume_from_checkpoint self.checkpoint_save_steps = checkpoint_save_steps self.checkpoint_save_total_limit = checkpoint_save_total_limit def finetune(self, **train_kwargs: Any) -> None: """Finetune model.""" self.model.fit( train_objectives=[(self.loader, self.loss)], epochs=self.epochs, warmup_steps=self.warmup_steps, output_path=self.model_output_path, show_progress_bar=self.show_progress_bar, evaluator=self.evaluator, evaluation_steps=self.evaluation_steps, checkpoint_path=self.checkpoint_path, resume_from_checkpoint=self.resume_from_checkpoint, checkpoint_save_steps=self.checkpoint_save_steps, checkpoint_save_total_limit=self.checkpoint_save_total_limit, ) def get_finetuned_model(self, **model_kwargs: Any) -> BaseEmbedding: """Gets finetuned model.""" embed_model_str = "local:" + self.model_output_path return resolve_embed_model(embed_model_str)
"""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 keras.src.ops.nn import celu from keras.src.ops.nn import conv from keras.src.ops.nn import conv_transpose from keras.src.ops.nn import ctc_decode from keras.src.ops.nn import ctc_loss from keras.src.ops.nn import depthwise_conv from keras.src.ops.nn import dot_product_attention from keras.src.ops.nn import elu from keras.src.ops.nn import gelu from keras.src.ops.nn import glu from keras.src.ops.nn import hard_shrink from keras.src.ops.nn import hard_sigmoid from keras.src.ops.nn import hard_silu from keras.src.ops.nn import hard_silu as hard_swish from keras.src.ops.nn import hard_tanh from keras.src.ops.nn import leaky_relu from keras.src.ops.nn import log_sigmoid from keras.src.ops.nn import log_softmax from keras.src.ops.nn import max_pool from keras.src.ops.nn import moments from keras.src.ops.nn import multi_hot from keras.src.ops.nn import normalize from keras.src.ops.nn import one_hot from keras.src.ops.nn import polar from keras.src.ops.nn import psnr from keras.src.ops.nn import relu from keras.src.ops.nn import relu6 from keras.src.ops.nn import rms_normalization from keras.src.ops.nn import selu from keras.src.ops.nn import separable_conv from keras.src.ops.nn import sigmoid from keras.src.ops.nn import silu from keras.src.ops.nn import silu as swish from keras.src.ops.nn import soft_shrink from keras.src.ops.nn import softmax from keras.src.ops.nn import softplus from keras.src.ops.nn import softsign from keras.src.ops.nn import sparse_categorical_crossentropy from keras.src.ops.nn import sparse_plus from keras.src.ops.nn import sparse_sigmoid from keras.src.ops.nn import sparsemax from keras.src.ops.nn import squareplus from keras.src.ops.nn import tanh_shrink from keras.src.ops.nn import threshold
"""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 keras.src.ops.nn import celu from keras.src.ops.nn import conv from keras.src.ops.nn import conv_transpose from keras.src.ops.nn import ctc_decode from keras.src.ops.nn import ctc_loss from keras.src.ops.nn import depthwise_conv from keras.src.ops.nn import dot_product_attention from keras.src.ops.nn import elu from keras.src.ops.nn import gelu from keras.src.ops.nn import glu from keras.src.ops.nn import hard_shrink from keras.src.ops.nn import hard_sigmoid from keras.src.ops.nn import hard_silu from keras.src.ops.nn import hard_silu as hard_swish from keras.src.ops.nn import hard_tanh from keras.src.ops.nn import leaky_relu from keras.src.ops.nn import log_sigmoid from keras.src.ops.nn import log_softmax from keras.src.ops.nn import max_pool from keras.src.ops.nn import moments from keras.src.ops.nn import multi_hot from keras.src.ops.nn import normalize from keras.src.ops.nn import one_hot from keras.src.ops.nn import polar from keras.src.ops.nn import psnr from keras.src.ops.nn import relu from keras.src.ops.nn import relu6 from keras.src.ops.nn import rms_normalization from keras.src.ops.nn import selu from keras.src.ops.nn import separable_conv from keras.src.ops.nn import sigmoid from keras.src.ops.nn import silu from keras.src.ops.nn import silu as swish from keras.src.ops.nn import soft_shrink from keras.src.ops.nn import softmax from keras.src.ops.nn import softplus from keras.src.ops.nn import softsign from keras.src.ops.nn import sparse_categorical_crossentropy from keras.src.ops.nn import sparse_plus from keras.src.ops.nn import sparsemax from keras.src.ops.nn import squareplus from keras.src.ops.nn import tanh_shrink from keras.src.ops.nn import threshold
"""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( api_key: Optional[str] = None, api_url: Optional[str] = None, ) -> Any: try: from langsmith import Client as LangSmithClient ls_client = LangSmithClient(api_url, api_key=api_key) if hasattr(ls_client, "push_prompt") and hasattr(ls_client, "pull_prompt"): return ls_client else: from langchainhub import Client as LangChainHubClient return LangChainHubClient(api_url, api_key=api_key) except ImportError: try: from langchainhub import Client as LangChainHubClient return LangChainHubClient(api_url, api_key=api_key) except ImportError as e: raise ImportError( "Could not import langsmith or langchainhub (deprecated)," "please install with `pip install langsmith`." ) from e def push( repo_full_name: str, object: Any, *, api_url: Optional[str] = None, api_key: Optional[str] = None, parent_commit_hash: Optional[str] = None, new_repo_is_public: bool = False, new_repo_description: Optional[str] = None, readme: Optional[str] = None, tags: Optional[Sequence[str]] = None, ) -> str: """ Push an object to the hub and returns the URL it can be viewed at in a browser. :param repo_full_name: The full name of the prompt to push to in the format of `owner/prompt_name` or `prompt_name`. :param object: The LangChain to serialize and push to the hub. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. :param parent_commit_hash: The commit hash of the parent commit to push to. Defaults to the latest commit automatically. :param new_repo_is_public: Whether the prompt should be public. Defaults to False (Private by default). :param new_repo_description: The description of the prompt. Defaults to an empty string. """ client = _get_client(api_key=api_key, api_url=api_url) # Then it's langsmith if hasattr(client, "push_prompt"): return client.push_prompt( repo_full_name, object=object, parent_commit_hash=parent_commit_hash, is_public=new_repo_is_public, description=new_repo_description, readme=readme, tags=tags, ) # Then it's langchainhub manifest_json = dumps(object) message = client.push( repo_full_name, manifest_json, parent_commit_hash=parent_commit_hash, new_repo_is_public=new_repo_is_public, new_repo_description=new_repo_description, ) return message def pull( owner_repo_commit: str, *, include_model: Optional[bool] = None, api_url: Optional[str] = None, api_key: Optional[str] = None, ) -> Any: """ Pull an object from the hub and returns it as a LangChain object. :param owner_repo_commit: The full name of the prompt to pull from in the format of `owner/prompt_name:commit_hash` or `owner/prompt_name` or just `prompt_name` if it's your own prompt. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. """ client = _get_client(api_key=api_key, api_url=api_url) # Then it's langsmith if hasattr(client, "pull_prompt"): response = client.pull_prompt(owner_repo_commit, include_model=include_model) return response # Then it's langchainhub if hasattr(client, "pull_repo"): # >= 0.1.15 res_dict = client.pull_repo(owner_repo_commit) obj = loads(json.dumps(res_dict["manifest"])) if isinstance(obj, BasePromptTemplate): if obj.metadata is None: obj.metadata = {} obj.metadata["lc_hub_owner"] = res_dict["owner"] obj.metadata["lc_hub_repo"] = res_dict["repo"] obj.metadata["lc_hub_commit_hash"] = res_dict["commit_hash"] return obj # Then it's < 0.1.15 langchainhub resp: str = client.pull(owner_repo_commit) return loads(resp)
"""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] = None, api_url: Optional[str] = None, ) -> Any: try: from langsmith import Client as LangSmithClient ls_client = LangSmithClient(api_url, api_key=api_key) if hasattr(ls_client, "push_prompt") and hasattr(ls_client, "pull_prompt"): return ls_client else: from langchainhub import Client as LangChainHubClient return LangChainHubClient(api_url, api_key=api_key) except ImportError: try: from langchainhub import Client as LangChainHubClient return LangChainHubClient(api_url, api_key=api_key) except ImportError as e: raise ImportError( "Could not import langsmith or langchainhub (deprecated)," "please install with `pip install langsmith`." ) from e def push( repo_full_name: str, object: Any, *, api_url: Optional[str] = None, api_key: Optional[str] = None, parent_commit_hash: Optional[str] = None, new_repo_is_public: bool = False, new_repo_description: Optional[str] = None, readme: Optional[str] = None, tags: Optional[Sequence[str]] = None, ) -> str: """ Push an object to the hub and returns the URL it can be viewed at in a browser. :param repo_full_name: The full name of the prompt to push to in the format of `owner/prompt_name` or `prompt_name`. :param object: The LangChain to serialize and push to the hub. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. :param parent_commit_hash: The commit hash of the parent commit to push to. Defaults to the latest commit automatically. :param new_repo_is_public: Whether the prompt should be public. Defaults to False (Private by default). :param new_repo_description: The description of the prompt. Defaults to an empty string. """ client = _get_client(api_key=api_key, api_url=api_url) # Then it's langsmith if hasattr(client, "push_prompt"): return client.push_prompt( repo_full_name, object=object, parent_commit_hash=parent_commit_hash, is_public=new_repo_is_public, description=new_repo_description, readme=readme, tags=tags, ) # Then it's langchainhub manifest_json = dumps(object) message = client.push( repo_full_name, manifest_json, parent_commit_hash=parent_commit_hash, new_repo_is_public=new_repo_is_public, new_repo_description=new_repo_description, ) return message def pull( owner_repo_commit: str, *, include_model: Optional[bool] = None, api_url: Optional[str] = None, api_key: Optional[str] = None, ) -> Any: """ Pull an object from the hub and returns it as a LangChain object. :param owner_repo_commit: The full name of the prompt to pull from in the format of `owner/prompt_name:commit_hash` or `owner/prompt_name` or just `prompt_name` if it's your own prompt. :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service if you have an api key set, or a localhost instance if not. :param api_key: The API key to use to authenticate with the LangChain Hub API. """ client = _get_client(api_key=api_key, api_url=api_url) # Then it's langsmith if hasattr(client, "pull_prompt"): response = client.pull_prompt(owner_repo_commit, include_model=include_model) return response # Then it's langchainhub if hasattr(client, "pull_repo"): # >= 0.1.15 res_dict = client.pull_repo(owner_repo_commit) obj = loads(json.dumps(res_dict["manifest"])) if isinstance(obj, BasePromptTemplate): if obj.metadata is None: obj.metadata = {} obj.metadata["lc_hub_owner"] = res_dict["owner"] obj.metadata["lc_hub_repo"] = res_dict["repo"] obj.metadata["lc_hub_commit_hash"] = res_dict["commit_hash"] return obj # Then it's < 0.1.15 langchainhub resp: str = client.pull(owner_repo_commit) return loads(resp)
# 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 like `EpochBasedRunner` and `IterBasedRunner` RUNNERS = Registry('runner', build_func=build_runner_from_cfg) # manage runner constructors that define how to initialize runners RUNNER_CONSTRUCTORS = Registry('runner constructor') # manage all kinds of loops like `EpochBasedTrainLoop` LOOPS = Registry('loop') # manage all kinds of hooks like `CheckpointHook` HOOKS = Registry('hook') # manage data-related modules DATASETS = Registry('dataset') DATA_SAMPLERS = Registry('data sampler') TRANSFORMS = Registry('transform') # mangage all kinds of modules inheriting `nn.Module` MODELS = Registry('model') # mangage all kinds of model wrappers like 'MMDistributedDataParallel' MODEL_WRAPPERS = Registry('model_wrapper') # mangage all kinds of weight initialization modules like `Uniform` WEIGHT_INITIALIZERS = Registry('weight initializer') # mangage all kinds of optimizers like `SGD` and `Adam` OPTIMIZERS = Registry('optimizer') # manage constructors that customize the optimization hyperparameters. OPTIM_WRAPPER_CONSTRUCTORS = Registry('optimizer wrapper constructor') # mangage all kinds of parameter schedulers like `MultiStepLR` PARAM_SCHEDULERS = Registry('parameter scheduler') # manage all kinds of metrics METRICS = Registry('metric') # manage task-specific modules like anchor generators and box coders TASK_UTILS = Registry('task util') # manage visualizer VISUALIZERS = Registry('visualizer') # manage visualizer backend VISBACKENDS = Registry('vis_backend') # manage logprocessor LOG_PROCESSORS = Registry('log_processor') # manage optimizer wrapper OPTIM_WRAPPERS = Registry('optim_wrapper')
# 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` and `IterBasedRunner` RUNNERS = Registry('runner') # manage runner constructors that define how to initialize runners RUNNER_CONSTRUCTORS = Registry('runner constructor') # manage all kinds of loops like `EpochBasedTrainLoop` LOOPS = Registry('loop') # manage all kinds of hooks like `CheckpointHook` HOOKS = Registry('hook') # manage data-related modules DATASETS = Registry('dataset') DATA_SAMPLERS = Registry('data sampler') TRANSFORMS = Registry('transform') # mangage all kinds of modules inheriting `nn.Module` MODELS = Registry('model') # mangage all kinds of model wrappers like 'MMDistributedDataParallel' MODEL_WRAPPERS = Registry('model_wrapper') # mangage all kinds of weight initialization modules like `Uniform` WEIGHT_INITIALIZERS = Registry('weight initializer') # mangage all kinds of optimizers like `SGD` and `Adam` OPTIMIZERS = Registry('optimizer') # manage constructors that customize the optimization hyperparameters. OPTIM_WRAPPER_CONSTRUCTORS = Registry('optimizer wrapper constructor') # mangage all kinds of parameter schedulers like `MultiStepLR` PARAM_SCHEDULERS = Registry('parameter scheduler') # manage all kinds of metrics METRICS = Registry('metric') # manage task-specific modules like anchor generators and box coders TASK_UTILS = Registry('task util') # manage visualizer VISUALIZERS = Registry('visualizer') # manage visualizer backend VISBACKENDS = Registry('vis_backend') # manage logprocessor LOG_PROCESSORS = Registry('log_processor') # manage optimizer wrapper OPTIM_WRAPPERS = Registry('optim_wrapper')
# 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 interface changes, the current class # functions incorrectly @HOOKS.register_module() class NaiveVisualizationHook(Hook): """Show or Write the predicted results during the process of testing. Args: interval (int): Visualization interval. Default: 1. draw_gt (bool): Whether to draw the ground truth. Default to True. draw_pred (bool): Whether to draw the predicted result. Default to True. """ priority = 'NORMAL' def __init__(self, interval: int = 1, draw_gt: bool = True, draw_pred: bool = True): self.draw_gt = draw_gt self.draw_pred = draw_pred self._interval = interval def _unpad(self, input: np.ndarray, unpad_shape: Tuple[int, int]) -> np.ndarray: unpad_width, unpad_height = unpad_shape unpad_image = input[:unpad_height, :unpad_width] return unpad_image def after_test_iter( self, runner, batch_idx: int, data_batch: Optional[Sequence[dict]] = None, outputs: Optional[Sequence[BaseDataElement]] = None) -> None: """Show or Write the predicted results. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the test loop. data_batch (Sequence[dict], optional): Data from dataloader. Defaults to None. outputs (Sequence[BaseDataElement], optional): Outputs from model. Defaults to None. """ if self.every_n_iters(runner, self._interval): for data, output in zip(data_batch, outputs): # type: ignore input = data['inputs'] data_sample = data['data_sample'] input = tensor2imgs(input, **data_sample.get('img_norm_cfg', dict()))[0] # TODO We will implement a function to revert the augmentation # in the future. ori_shape = (data_sample.ori_width, data_sample.ori_height) if 'pad_shape' in data_sample: input = self._unpad(input, data_sample.get('scale', ori_shape)) origin_image = cv2.resize(input, ori_shape) name = osp.basename(data_sample.img_path) runner.visualizer.add_datasample(name, origin_image, data_sample, output, self.draw_gt, self.draw_pred)
# 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.register_module() class NaiveVisualizationHook(Hook): """Show or Write the predicted results during the process of testing. Args: interval (int): Visualization interval. Default: 1. draw_gt (bool): Whether to draw the ground truth. Default to True. draw_pred (bool): Whether to draw the predicted result. Default to True. """ priority = 'NORMAL' def __init__(self, interval: int = 1, draw_gt: bool = True, draw_pred: bool = True): self.draw_gt = draw_gt self.draw_pred = draw_pred self._interval = interval def _unpad(self, input: np.ndarray, unpad_shape: Tuple[int, int]) -> np.ndarray: unpad_width, unpad_height = unpad_shape unpad_image = input[:unpad_height, :unpad_width] return unpad_image def after_test_iter( self, runner, batch_idx: int, data_batch: Optional[Sequence[Tuple[Any, BaseDataElement]]] = None, outputs: Optional[Sequence[BaseDataElement]] = None) -> None: """Show or Write the predicted results. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the test loop. data_batch (Sequence[Tuple[Any, BaseDataElement]], optional): Data from dataloader. Defaults to None. outputs (Sequence[BaseDataElement], optional): Outputs from model. Defaults to None. """ if self.every_n_iters(runner, self._interval): inputs, data_samples = data_batch # type: ignore inputs = tensor2imgs(inputs, **data_samples[0].get('img_norm_cfg', dict())) for input, data_sample, output in zip( inputs, data_samples, # type: ignore outputs): # type: ignore # TODO We will implement a function to revert the augmentation # in the future. ori_shape = (data_sample.ori_width, data_sample.ori_height) if 'pad_shape' in data_sample: input = self._unpad(input, data_sample.get('scale', ori_shape)) origin_image = cv2.resize(input, ori_shape) name = osp.basename(data_sample.img_path) runner.writer.add_image(name, origin_image, data_sample, output, self.draw_gt, self.draw_pred)
_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', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ]
_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', begin=0, end=max_epochs, by_epoch=True, milestones=[16, 22], gamma=0.1) ]
_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=max_epochs, by_epoch=True, milestones=[20, 23], gamma=0.1) ]
_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=max_epochs, by_epoch=True, milestones=[20, 23], gamma=0.1) ]
# 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]] # TODO: Due to interface changes, the current class # functions incorrectly @HOOKS.register_module() class NaiveVisualizationHook(Hook): """Show or Write the predicted results during the process of testing. Args: interval (int): Visualization interval. Defaults to 1. draw_gt (bool): Whether to draw the ground truth. Default to True. draw_pred (bool): Whether to draw the predicted result. Default to True. """ priority = 'NORMAL' def __init__(self, interval: int = 1, draw_gt: bool = True, draw_pred: bool = True): self.draw_gt = draw_gt self.draw_pred = draw_pred self._interval = interval def _unpad(self, input: np.ndarray, unpad_shape: Tuple[int, int]) -> np.ndarray: """Unpad the input image. Args: input (np.ndarray): The image to unpad. unpad_shape (tuple): The shape of image before padding. Returns: np.ndarray: The image before padding. """ unpad_width, unpad_height = unpad_shape unpad_image = input[:unpad_height, :unpad_width] return unpad_image def before_train(self, runner) -> None: """Call add_graph method of visualizer. Args: runner (Runner): The runner of the training process. """ runner.visualizer.add_graph(runner.model, None) def after_test_iter(self, runner, batch_idx: int, data_batch: DATA_BATCH = None, outputs: Optional[Sequence] = None) -> None: """Show or Write the predicted results. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the test loop. data_batch (dict or tuple or list, optional): Data from dataloader. outputs (Sequence, optional): Outputs from model. """ if self.every_n_inner_iters(batch_idx, self._interval): for data, output in zip(data_batch, outputs): # type: ignore input = data['inputs'] data_sample = data['data_sample'] input = tensor2imgs(input, **data_sample.get('img_norm_cfg', dict()))[0] # TODO We will implement a function to revert the augmentation # in the future. ori_shape = (data_sample.ori_width, data_sample.ori_height) if 'pad_shape' in data_sample: input = self._unpad(input, data_sample.get('scale', ori_shape)) origin_image = cv2.resize(input, ori_shape) name = osp.basename(data_sample.img_path) runner.visualizer.add_datasample(name, origin_image, data_sample, output, self.draw_gt, self.draw_pred)
# 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]] # TODO: Due to interface changes, the current class # functions incorrectly @HOOKS.register_module() class NaiveVisualizationHook(Hook): """Show or Write the predicted results during the process of testing. Args: interval (int): Visualization interval. Defaults to 1. draw_gt (bool): Whether to draw the ground truth. Default to True. draw_pred (bool): Whether to draw the predicted result. Default to True. """ priority = 'NORMAL' def __init__(self, interval: int = 1, draw_gt: bool = True, draw_pred: bool = True): self.draw_gt = draw_gt self.draw_pred = draw_pred self._interval = interval def _unpad(self, input: np.ndarray, unpad_shape: Tuple[int, int]) -> np.ndarray: """Unpad the input image. Args: input (np.ndarray): The image to unpad. unpad_shape (tuple): The shape of image before padding. Returns: np.ndarray: The image before padding. """ unpad_width, unpad_height = unpad_shape unpad_image = input[:unpad_height, :unpad_width] return unpad_image def after_test_iter(self, runner, batch_idx: int, data_batch: DATA_BATCH = None, outputs: Optional[Sequence] = None) -> None: """Show or Write the predicted results. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the test loop. data_batch (dict or tuple or list, optional): Data from dataloader. outputs (Sequence, optional): Outputs from model. """ if self.every_n_inner_iters(batch_idx, self._interval): for data, output in zip(data_batch, outputs): # type: ignore input = data['inputs'] data_sample = data['data_sample'] input = tensor2imgs(input, **data_sample.get('img_norm_cfg', dict()))[0] # TODO We will implement a function to revert the augmentation # in the future. ori_shape = (data_sample.ori_width, data_sample.ori_height) if 'pad_shape' in data_sample: input = self._unpad(input, data_sample.get('scale', ori_shape)) origin_image = cv2.resize(input, ori_shape) name = osp.basename(data_sample.img_path) runner.visualizer.add_datasample(name, origin_image, data_sample, output, self.draw_gt, self.draw_pred)
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_accelerator, slow, torch_device, ) from .single_file_testing_utils import SDXLSingleFileTesterMixin enable_full_determinism() @slow @require_torch_accelerator class StableDiffusionXLImg2ImgPipelineSingleFileSlowTests(unittest.TestCase, SDXLSingleFileTesterMixin): pipeline_class = StableDiffusionXLImg2ImgPipeline ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors" repo_id = "stabilityai/stable-diffusion-xl-base-1.0" original_config = ( "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml" ) def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device) def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device) def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0): generator = torch.Generator(device=generator_device).manual_seed(seed) init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) inputs = { "prompt": "a fantasy landscape, concept art, high resolution", "image": init_image, "generator": generator, "num_inference_steps": 3, "strength": 0.75, "guidance_scale": 7.5, "output_type": "np", } return inputs def test_single_file_format_inference_is_same_as_pretrained(self): super().test_single_file_format_inference_is_same_as_pretrained(expected_max_diff=1e-3) @slow @require_torch_accelerator class StableDiffusionXLImg2ImgRefinerPipelineSingleFileSlowTests(unittest.TestCase): pipeline_class = StableDiffusionXLImg2ImgPipeline ckpt_path = ( "https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/blob/main/sd_xl_refiner_1.0.safetensors" ) repo_id = "stabilityai/stable-diffusion-xl-refiner-1.0" original_config = ( "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml" ) def test_single_file_format_inference_is_same_as_pretrained(self): init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) pipe = self.pipeline_class.from_pretrained(self.repo_id, torch_dtype=torch.float16) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe.unet.set_default_attn_processor() pipe.enable_model_cpu_offload() generator = torch.Generator(device="cpu").manual_seed(0) image = pipe( prompt="mountains", image=init_image, num_inference_steps=5, generator=generator, output_type="np" ).images[0] pipe_single_file = self.pipeline_class.from_single_file(self.ckpt_path, torch_dtype=torch.float16) pipe_single_file.scheduler = DDIMScheduler.from_config(pipe_single_file.scheduler.config) pipe_single_file.unet.set_default_attn_processor() pipe_single_file.enable_model_cpu_offload() generator = torch.Generator(device="cpu").manual_seed(0) image_single_file = pipe_single_file( prompt="mountains", image=init_image, num_inference_steps=5, generator=generator, output_type="np" ).images[0] max_diff = numpy_cosine_similarity_distance(image.flatten(), image_single_file.flatten()) assert max_diff < 5e-4
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 .single_file_testing_utils import SDXLSingleFileTesterMixin enable_full_determinism() @slow @require_torch_gpu class StableDiffusionXLImg2ImgPipelineSingleFileSlowTests(unittest.TestCase, SDXLSingleFileTesterMixin): pipeline_class = StableDiffusionXLImg2ImgPipeline ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors" repo_id = "stabilityai/stable-diffusion-xl-base-1.0" original_config = ( "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml" ) def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0): generator = torch.Generator(device=generator_device).manual_seed(seed) init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) inputs = { "prompt": "a fantasy landscape, concept art, high resolution", "image": init_image, "generator": generator, "num_inference_steps": 3, "strength": 0.75, "guidance_scale": 7.5, "output_type": "np", } return inputs def test_single_file_format_inference_is_same_as_pretrained(self): super().test_single_file_format_inference_is_same_as_pretrained(expected_max_diff=1e-3) @slow @require_torch_gpu class StableDiffusionXLImg2ImgRefinerPipelineSingleFileSlowTests(unittest.TestCase): pipeline_class = StableDiffusionXLImg2ImgPipeline ckpt_path = ( "https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/blob/main/sd_xl_refiner_1.0.safetensors" ) repo_id = "stabilityai/stable-diffusion-xl-refiner-1.0" original_config = ( "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml" ) def test_single_file_format_inference_is_same_as_pretrained(self): init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) pipe = self.pipeline_class.from_pretrained(self.repo_id, torch_dtype=torch.float16) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe.unet.set_default_attn_processor() pipe.enable_model_cpu_offload() generator = torch.Generator(device="cpu").manual_seed(0) image = pipe( prompt="mountains", image=init_image, num_inference_steps=5, generator=generator, output_type="np" ).images[0] pipe_single_file = self.pipeline_class.from_single_file(self.ckpt_path, torch_dtype=torch.float16) pipe_single_file.scheduler = DDIMScheduler.from_config(pipe_single_file.scheduler.config) pipe_single_file.unet.set_default_attn_processor() pipe_single_file.enable_model_cpu_offload() generator = torch.Generator(device="cpu").manual_seed(0) image_single_file = pipe_single_file( prompt="mountains", image=init_image, num_inference_steps=5, generator=generator, output_type="np" ).images[0] max_diff = numpy_cosine_similarity_distance(image.flatten(), image_single_file.flatten()) assert max_diff < 5e-4
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 = TypeVar('T', bound='Tensor') class Tensor(np.ndarray, AbstractType): @classmethod def __get_validators__(cls): # one or more validators may be yielded which will be called in the # order to validate the input, each validator will receive as an input # the value returned from the previous validator yield cls.validate @classmethod def validate( cls: Type[T], value: Union[T, np.ndarray, List[Any], Tuple[Any], Any], field: 'ModelField', config: 'BaseConfig', ) -> T: if isinstance(value, np.ndarray): return cls.from_ndarray(value) elif isinstance(value, Tensor): return cast(T, value) elif isinstance(value, list) or isinstance(value, tuple): try: arr_from_list: np.ndarray = np.asarray(value) return cls.from_ndarray(arr_from_list) except Exception: pass # handled below else: try: arr: np.ndarray = np.ndarray(value) return cls.from_ndarray(arr) except Exception: pass # handled below raise ValueError(f'Expected a numpy.ndarray compatible type, got {type(value)}') @classmethod def from_ndarray(cls: Type[T], value: np.ndarray) -> T: return value.view(cls) @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: # this is needed to dump to json field_schema.update(type='string', format='tensor') def _to_json_compatible(self) -> np.ndarray: """ Convert tensor into a json compatible object :return: a list representation of the tensor """ return self.unwrap() def unwrap(self) -> np.ndarray: """ Return the original ndarray without any memory copy. The original view rest intact and is still a Document Tensor but the return object is a pure np.ndarray but both object share the same memory layout. EXAMPLE USAGE .. code-block:: python from docarray.typing import Tensor import numpy as np t1 = Tensor.validate(np.zeros((3, 224, 224)), None, None) # here t is a docarray Tensor t2 = t.unwrap() # here t2 is a pure np.ndarray but t1 is still a Docarray Tensor # But both share the same underlying memory :return: a numpy ndarray """ return self.view(np.ndarray) def _to_node_protobuf(self: T, field: str = 'tensor') -> NodeProto: """Convert itself into a NodeProto protobuf message. This function should be called when the Document is nested into another Document that need to be converted into a protobuf :param field: field in which to store the content in the node proto :return: the nested item protobuf message """ nd_proto = NdArrayProto() self._flush_tensor_to_proto(nd_proto, value=self) return NodeProto(**{field: nd_proto}) @classmethod def from_protobuf(cls: Type[T], pb_msg: 'NdArrayProto') -> 'T': """ read ndarray from a proto msg :param pb_msg: :return: a numpy array """ source = pb_msg.dense if source.buffer: x = np.frombuffer(source.buffer, dtype=source.dtype) return cls.from_ndarray(x.reshape(source.shape)) elif len(source.shape) > 0: return cls.from_ndarray(np.zeros(source.shape)) else: raise ValueError(f'proto message {pb_msg} cannot be cast to a Tensor') @staticmethod def _flush_tensor_to_proto(pb_msg: 'NdArrayProto', value: 'Tensor'): pb_msg.dense.buffer = value.tobytes() pb_msg.dense.ClearField('shape') pb_msg.dense.shape.extend(list(value.shape)) pb_msg.dense.dtype = value.dtype.str
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', bound='Tensor') class Tensor(np.ndarray, BaseNode): @classmethod def __get_validators__(cls): # one or more validators may be yielded which will be called in the # order to validate the input, each validator will receive as an input # the value returned from the previous validator yield cls.validate @classmethod def validate( cls: Type[T], value: Union[T, np.ndarray, List[Any], Tuple[Any], Any], field: 'ModelField', config: 'BaseConfig', ) -> T: if isinstance(value, np.ndarray): return cls.from_ndarray(value) elif isinstance(value, Tensor): return cast(T, value) elif isinstance(value, list) or isinstance(value, tuple): try: arr_from_list: np.ndarray = np.asarray(value) return cls.from_ndarray(arr_from_list) except Exception: pass # handled below else: try: arr: np.ndarray = np.ndarray(value) return cls.from_ndarray(arr) except Exception: pass # handled below raise ValueError(f'Expected a numpy.ndarray compatible type, got {type(value)}') @classmethod def from_ndarray(cls: Type[T], value: np.ndarray) -> T: return value.view(cls) @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: # this is needed to dump to json field_schema.update(type='string', format='tensor') def _to_json_compatible(self) -> np.ndarray: """ Convert tensor into a json compatible object :return: a list representation of the tensor """ return self.unwrap() def unwrap(self) -> np.ndarray: """ Return the original ndarray without any memory copy. The original view rest intact and is still a Document Tensor but the return object is a pure np.ndarray but both object share the same memory layout. EXAMPLE USAGE .. code-block:: python from docarray.typing import Tensor import numpy as np t1 = Tensor.validate(np.zeros((3, 224, 224)), None, None) # here t is a docarray Tensor t2 = t.unwrap() # here t2 is a pure np.ndarray but t1 is still a Docarray Tensor # But both share the same underlying memory :return: a numpy ndarray """ return self.view(np.ndarray) def _to_node_protobuf(self: T, field: str = 'tensor') -> NodeProto: """Convert itself into a NodeProto protobuf message. This function should be called when the Document is nested into another Document that need to be converted into a protobuf :param field: field in which to store the content in the node proto :return: the nested item protobuf message """ nd_proto = NdArrayProto() self._flush_tensor_to_proto(nd_proto, value=self) return NodeProto(**{field: nd_proto}) @classmethod def from_protobuf(cls: Type[T], pb_msg: 'NdArrayProto') -> 'T': """ read ndarray from a proto msg :param pb_msg: :return: a numpy array """ source = pb_msg.dense if source.buffer: x = np.frombuffer(source.buffer, dtype=source.dtype) return cls.from_ndarray(x.reshape(source.shape)) elif len(source.shape) > 0: return cls.from_ndarray(np.zeros(source.shape)) else: raise ValueError(f'proto message {pb_msg} cannot be cast to a Tensor') @staticmethod def _flush_tensor_to_proto(pb_msg: 'NdArrayProto', value: 'Tensor'): pb_msg.dense.buffer = value.tobytes() pb_msg.dense.ClearField('shape') pb_msg.dense.shape.extend(list(value.shape)) pb_msg.dense.dtype = value.dtype.str
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=Colors) # Test valid inputs result = parser.parse("red") assert result == Colors.RED result = parser.parse("green") assert result == Colors.GREEN result = parser.parse("blue") assert result == Colors.BLUE # Test invalid input with pytest.raises(OutputParserException): parser.parse("INVALID") def test_enum_output_parser_output_type() -> None: """Test the output type of the enum output parser is the expected enum.""" assert EnumOutputParser(enum=Colors).OutputType is Colors
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 valid inputs result = parser.parse("red") assert result == Colors.RED result = parser.parse("green") assert result == Colors.GREEN result = parser.parse("blue") assert result == Colors.BLUE # Test invalid input try: parser.parse("INVALID") assert False, "Should have raised OutputParserException" except OutputParserException: pass def test_enum_output_parser_output_type() -> None: """Test the output type of the enum output parser is the expected enum.""" assert EnumOutputParser(enum=Colors).OutputType is Colors
__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 import get_docs_batch_generator class ImageTFEncoder(Executor): """ :class:`ImageTFEncoder` encodes ``Document`` content from a ndarray, potentially B x (Height x Width x Channel) into a ndarray of `B x D`. Where `B` is the batch size and `D` is the Dimension. The :class:`ImageTFEncoder` wraps the models from `tensorflow.keras.applications`. <https://www.tensorflow.org/api_docs/python/tf/keras/applications>`_ :param model_name: the name of the model. Supported models include ``DenseNet121``, ``DenseNet169``, ``DenseNet201``, ``InceptionResNetV2``, ``InceptionV3``, ``MobileNet``, ``MobileNetV2``, ``NASNetLarge``, ``NASNetMobile``, ``ResNet101``, ``ResNet152``, ``ResNet50``, ``ResNet101V2``, ``ResNet152V2``, ``ResNet50V2``, ``VGG16``, ``VGG19``, ``Xception`` and etc. A full list can be find at <https://www.tensorflow.org/api_docs/python/tf/keras/applications#functions>`_ :param img_shape: The shape of the image to be encoded. :param pool_strategy: the pooling strategy. Options are: - `None`: Means that the output of the model will be the 4D tensor output of the last convolutional block. - `avg`: ;eans that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor. - `max`: Means that global max pooling will be applied. :param default_batch_size: size of each batch :param default_traversal_paths: traversal path of the Documents, (e.g. 'r', 'c') :param device: Device ('/CPU:0', '/GPU:0', '/GPU:X') :param args: additional positional arguments. :param kwargs: additional positional arguments. """ def __init__( self, model_name: str = 'MobileNetV2', img_shape: int = 336, pool_strategy: str = 'max', default_batch_size: int = 32, default_traversal_paths: Union[List[str], str] = None, device: str = '/CPU:0', *args, **kwargs, ): super().__init__(*args, **kwargs) if default_traversal_paths is None: default_traversal_paths = ['r'] self.model_name = model_name self.pool_strategy = pool_strategy self.img_shape = img_shape self.default_batch_size = default_batch_size self.default_traversal_paths = default_traversal_paths self.logger = JinaLogger(self.__class__.__name__) gpus = tf.config.experimental.list_physical_devices(device_type='GPU') if 'GPU' in device: gpu_index = 0 if 'GPU:' not in device else int(device.split(':')[-1]) if len(gpus) < gpu_index + 1: raise RuntimeError(f'Device {device} not found on your system!') self.device = tf.device(device) with self.device: model = getattr(tf.keras.applications, self.model_name)( input_shape=(self.img_shape, self.img_shape, 3), include_top=False, pooling=self.pool_strategy, weights='imagenet', ) model.trainable = False self.model = model @requests def encode(self, docs: DocumentArray, parameters: Dict, **kwargs): """ Encode document content into a ndarray of `B x D`. ` B` is the batch size and `D` is the Dimension. :param docs: DocumentArray containing blob as image data. :param args: additional positional arguments. :param kwargs: additional positional arguments. :return: Encoded result as a `BatchSize x D` numpy ``ndarray``, `D` is the output dimension """ if docs: document_batches_generator = get_docs_batch_generator( docs, traversal_path=parameters.get( 'traversal_paths', self.default_traversal_paths ), batch_size=parameters.get('batch_size', self.default_batch_size), needs_attr='blob', ) self._create_embeddings(document_batches_generator) def _create_embeddings(self, document_batches_generator: Iterable): for document_batch in document_batches_generator: blob_batch = np.stack([d.blob for d in document_batch]) with self.device: embedding_batch = self.model(blob_batch) for document, embedding in zip(document_batch, embedding_batch): document.embedding = np.array(embedding)
__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 class ImageTFEncoder(Executor): """ :class:`ImageTFEncoder` encodes ``Document`` content from a ndarray, potentially B x (Height x Width x Channel) into a ndarray of `B x D`. Where `B` is the batch size and `D` is the Dimension. The :class:`ImageTFEncoder` wraps the models from `tensorflow.keras.applications`. <https://www.tensorflow.org/api_docs/python/tf/keras/applications>`_ :param model_name: the name of the model. Supported models include ``DenseNet121``, ``DenseNet169``, ``DenseNet201``, ``InceptionResNetV2``, ``InceptionV3``, ``MobileNet``, ``MobileNetV2``, ``NASNetLarge``, ``NASNetMobile``, ``ResNet101``, ``ResNet152``, ``ResNet50``, ``ResNet101V2``, ``ResNet152V2``, ``ResNet50V2``, ``VGG16``, ``VGG19``, ``Xception`` and etc. A full list can be find at <https://www.tensorflow.org/api_docs/python/tf/keras/applications#functions>`_ :param img_shape: The shape of the image to be encoded. :param pool_strategy: the pooling strategy. Options are: - `None`: Means that the output of the model will be the 4D tensor output of the last convolutional block. - `avg`: ;eans that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor. - `max`: Means that global max pooling will be applied. :param default_batch_size: size of each batch :param default_traversal_paths: traversal path of the Documents, (e.g. 'r', 'c') :param on_gpu: set to True if using GPU :param args: additional positional arguments. :param kwargs: additional positional arguments. """ def __init__(self, model_name: str = 'MobileNetV2', img_shape: int = 336, pool_strategy: str = 'max', default_batch_size: int = 32, default_traversal_paths: List[str] = None, on_gpu: bool = True, *args, **kwargs): super().__init__(*args, **kwargs) if default_traversal_paths is None: default_traversal_paths = ['r'] self.model_name = model_name self.pool_strategy = pool_strategy self.img_shape = img_shape self.default_batch_size = default_batch_size self.default_traversal_paths = default_traversal_paths self.on_gpu = on_gpu self.logger = JinaLogger(self.__class__.__name__) import tensorflow as tf cpus = tf.config.experimental.list_physical_devices(device_type='CPU') gpus = tf.config.experimental.list_physical_devices(device_type='GPU') if self.on_gpu and len(gpus) > 0: cpus.append(gpus[0]) if self.on_gpu and len(gpus) == 0: self.logger.warning('You tried to use a GPU but no GPU was found on' ' your system. Defaulting to CPU!') tf.config.experimental.set_visible_devices(devices=cpus) model = getattr(tf.keras.applications, self.model_name)( input_shape=(self.img_shape, self.img_shape, 3), include_top=False, pooling=self.pool_strategy, weights='imagenet') model.trainable = False self.model = model @requests def encode(self, docs: DocumentArray, parameters: Dict, **kwargs): """ Encode document content into a ndarray of `B x D`. ` B` is the batch size and `D` is the Dimension. :param docs: DocumentArray containing blob as image data. :param args: additional positional arguments. :param kwargs: additional positional arguments. :return: Encoded result as a `BatchSize x D` numpy ``ndarray``, `D` is the output dimension """ if docs: document_batches_generator = get_docs_batch_generator( docs, traversal_path=parameters.get('traversal_paths', self.default_traversal_paths), batch_size=parameters.get('batch_size', self.default_batch_size), needs_attr='blob' ) self._create_embeddings(document_batches_generator) def _create_embeddings(self, document_batches_generator: Iterable): for document_batch in document_batches_generator: blob_batch = np.stack([d.blob for d in document_batch]) embedding_batch = self.model(blob_batch) for document, embedding in zip(document_batch, embedding_batch): document.embedding = np.array(embedding)
# 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, upsampling will be applied after each layer of convolution. The number of upsampling must be no more than the number of ConvModule layers. Args: in_channels (int): Number of channels in the input feature map. inner_channels (int): Number of channels produced by the convolution. num_layers (int): Number of convolution layers. num_upsample (int | optional): Number of upsampling layer. Must be no more than num_layers. Upsampling will be applied after the first ``num_upsample`` layers of convolution. Default: ``num_layers``. conv_cfg (dict): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: None. init_cfg (dict): Config dict for initialization. Default: None. kwargs (key word augments): Other augments used in ConvModule. """ def __init__(self, in_channels, inner_channels, num_layers=1, num_upsample=None, conv_cfg=None, norm_cfg=None, init_cfg=None, **kwargs): super(ConvUpsample, self).__init__(init_cfg) if num_upsample is None: num_upsample = num_layers assert num_upsample <= num_layers, \ f'num_upsample({num_upsample})must be no more than ' \ f'num_layers({num_layers})' self.num_layers = num_layers self.num_upsample = num_upsample self.conv = ModuleList() for i in range(num_layers): self.conv.append( ConvModule( in_channels, inner_channels, 3, padding=1, stride=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, **kwargs)) in_channels = inner_channels def forward(self, x): num_upsample = self.num_upsample for i in range(self.num_layers): x = self.conv[i](x) if num_upsample > 0: num_upsample -= 1 x = F.interpolate( x, scale_factor=2, mode='bilinear', align_corners=False) return x
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 convolution. The number of upsampling must be no more than the number of ConvModule layers. Args: in_channels (int): Number of channels in the input feature map. inner_channels (int): Number of channels produced by the convolution. num_layers (int): Number of convolution layers. num_upsample (int | optional): Number of upsampling layer. Must be no more than num_layers. Upsampling will be applied after the first ``num_upsample`` layers of convolution. Default: ``num_layers``. conv_cfg (dict): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: None. init_cfg (dict): Config dict for initialization. Default: None. kwargs (key word augments): Other augments used in ConvModule. """ def __init__(self, in_channels, inner_channels, num_layers=1, num_upsample=None, conv_cfg=None, norm_cfg=None, init_cfg=None, **kwargs): super(ConvUpsample, self).__init__(init_cfg) if num_upsample is None: num_upsample = num_layers assert num_upsample <= num_layers, \ f'num_upsample({num_upsample})must be no more than ' \ f'num_layers({num_layers})' self.num_layers = num_layers self.num_upsample = num_upsample self.conv = ModuleList() for i in range(num_layers): self.conv.append( ConvModule( in_channels, inner_channels, 3, padding=1, stride=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, **kwargs)) in_channels = inner_channels def forward(self, x): num_upsample = self.num_upsample for i in range(self.num_layers): x = self.conv[i](x) if num_upsample > 0: num_upsample -= 1 x = F.interpolate( x, scale_factor=2, mode='bilinear', align_corners=False) return x
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 import _RandomApplyTransform from .utils import query_chw class ToTensor(Transform): _transformed_types = (PIL.Image.Image, np.ndarray) def __init__(self) -> None: warnings.warn( "The transform `ToTensor()` is deprecated and will be removed in a future release. " "Instead, please use `transforms.Compose([transforms.ToImageTensor(), transforms.ConvertImageDtype()])`." ) super().__init__() def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor: return _F.to_tensor(inpt) class Grayscale(Transform): _transformed_types = (features.Image, PIL.Image.Image, features.is_simple_tensor, features.Video) def __init__(self, num_output_channels: Literal[1, 3] = 1) -> None: deprecation_msg = ( f"The transform `Grayscale(num_output_channels={num_output_channels})` " f"is deprecated and will be removed in a future release." ) if num_output_channels == 1: replacement_msg = ( "transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY)" ) else: replacement_msg = ( "transforms.Compose(\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY),\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.GRAY, color_space=ColorSpace.RGB),\n" ")" ) warnings.warn(f"{deprecation_msg} Instead, please use\n\n{replacement_msg}") super().__init__() self.num_output_channels = num_output_channels def _transform( self, inpt: Union[features.ImageType, features.VideoType], params: Dict[str, Any] ) -> Union[features.ImageType, features.VideoType]: output = _F.rgb_to_grayscale(inpt, num_output_channels=self.num_output_channels) if isinstance(inpt, (features.Image, features.Video)): output = inpt.wrap_like(inpt, output, color_space=features.ColorSpace.GRAY) # type: ignore[arg-type] return output class RandomGrayscale(_RandomApplyTransform): _transformed_types = (features.Image, PIL.Image.Image, features.is_simple_tensor, features.Video) def __init__(self, p: float = 0.1) -> None: warnings.warn( "The transform `RandomGrayscale(p=...)` is deprecated and will be removed in a future release. " "Instead, please use\n\n" "transforms.RandomApply(\n" " transforms.Compose(\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY),\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.GRAY, color_space=ColorSpace.RGB),\n" " )\n" " p=...,\n" ")" ) super().__init__(p=p) def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]: num_input_channels, *_ = query_chw(flat_inputs) return dict(num_input_channels=num_input_channels) def _transform( self, inpt: Union[features.ImageType, features.VideoType], params: Dict[str, Any] ) -> Union[features.ImageType, features.VideoType]: output = _F.rgb_to_grayscale(inpt, num_output_channels=params["num_input_channels"]) if isinstance(inpt, (features.Image, features.Video)): output = inpt.wrap_like(inpt, output, color_space=features.ColorSpace.GRAY) # type: ignore[arg-type] return output
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 import _RandomApplyTransform from ._utils import query_chw class ToTensor(Transform): _transformed_types = (PIL.Image.Image, np.ndarray) def __init__(self) -> None: warnings.warn( "The transform `ToTensor()` is deprecated and will be removed in a future release. " "Instead, please use `transforms.Compose([transforms.ToImageTensor(), transforms.ConvertImageDtype()])`." ) super().__init__() def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor: return _F.to_tensor(inpt) class Grayscale(Transform): _transformed_types = (features.Image, PIL.Image.Image, features.is_simple_tensor, features.Video) def __init__(self, num_output_channels: Literal[1, 3] = 1) -> None: deprecation_msg = ( f"The transform `Grayscale(num_output_channels={num_output_channels})` " f"is deprecated and will be removed in a future release." ) if num_output_channels == 1: replacement_msg = ( "transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY)" ) else: replacement_msg = ( "transforms.Compose(\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY),\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.GRAY, color_space=ColorSpace.RGB),\n" ")" ) warnings.warn(f"{deprecation_msg} Instead, please use\n\n{replacement_msg}") super().__init__() self.num_output_channels = num_output_channels def _transform( self, inpt: Union[features.ImageType, features.VideoType], params: Dict[str, Any] ) -> Union[features.ImageType, features.VideoType]: output = _F.rgb_to_grayscale(inpt, num_output_channels=self.num_output_channels) if isinstance(inpt, (features.Image, features.Video)): output = inpt.wrap_like(inpt, output, color_space=features.ColorSpace.GRAY) # type: ignore[arg-type] return output class RandomGrayscale(_RandomApplyTransform): _transformed_types = (features.Image, PIL.Image.Image, features.is_simple_tensor, features.Video) def __init__(self, p: float = 0.1) -> None: warnings.warn( "The transform `RandomGrayscale(p=...)` is deprecated and will be removed in a future release. " "Instead, please use\n\n" "transforms.RandomApply(\n" " transforms.Compose(\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.RGB, color_space=ColorSpace.GRAY),\n" " transforms.ConvertImageColorSpace(old_color_space=ColorSpace.GRAY, color_space=ColorSpace.RGB),\n" " )\n" " p=...,\n" ")" ) super().__init__(p=p) def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]: num_input_channels, *_ = query_chw(flat_inputs) return dict(num_input_channels=num_input_channels) def _transform( self, inpt: Union[features.ImageType, features.VideoType], params: Dict[str, Any] ) -> Union[features.ImageType, features.VideoType]: output = _F.rgb_to_grayscale(inpt, num_output_channels=params["num_input_channels"]) if isinstance(inpt, (features.Image, features.Video)): output = inpt.wrap_like(inpt, output, color_space=features.ColorSpace.GRAY) # type: ignore[arg-type] return output