input
stringlengths
33
5k
output
stringlengths
32
5k
from argparse import Namespace from copy import deepcopy from typing import TYPE_CHECKING, Type from hubble.executor.helper import is_valid_huburi from hubble.executor.hubio import HubIO from jina.enums import PodRoleType from jina.orchestrate.pods import Pod from jina.orchestrate.pods.container import ContainerPod if TYPE_CHECKING: # pragma: no cover from jina.orchestrate.pods import BasePod class PodFactory: """ A PodFactory is a factory class, abstracting the Pod creation """ @staticmethod def build_pod(args: 'Namespace', gateway_load_balancer: bool = False) -> Type['BasePod']: """Build an implementation of a `BasePod` interface :param args: deployment arguments parsed from the CLI. :param gateway_load_balancer: flag indicating if this Pod is supposed to be a Gateway Load Balancer :return: the created Deployment """ # copy to update but forward original cargs = deepcopy(args) cargs.gateway_load_balancer = gateway_load_balancer if is_valid_huburi(cargs.uses): _hub_args = deepcopy(args) _hub_args.uri = args.uses _hub_args.no_usage = True cargs.uses = HubIO(_hub_args).pull() if ( cargs.pod_role != PodRoleType.HEAD and cargs.uses and cargs.uses.startswith('docker://') ): return ContainerPod(cargs) else: return Pod(cargs)
from argparse import Namespace from copy import deepcopy from typing import TYPE_CHECKING, Type from hubble.executor.helper import is_valid_huburi from hubble.executor.hubio import HubIO from jina.enums import PodRoleType from jina.orchestrate.pods import Pod from jina.orchestrate.pods.container import ContainerPod if TYPE_CHECKING: # pragma: no cover from jina.orchestrate.pods import BasePod class PodFactory: """ A PodFactory is a factory class, abstracting the Pod creation """ @staticmethod def build_pod(args: 'Namespace') -> Type['BasePod']: """Build an implementation of a `BasePod` interface :param args: deployment arguments parsed from the CLI. :return: the created Deployment """ # copy to update but forward original cargs = deepcopy(args) if is_valid_huburi(cargs.uses): _hub_args = deepcopy(args) _hub_args.uri = args.uses _hub_args.no_usage = True cargs.uses = HubIO(_hub_args).pull() if ( cargs.pod_role != PodRoleType.HEAD and cargs.uses and cargs.uses.startswith('docker://') ): return ContainerPod(cargs) else: return Pod(args)
__version__ = '0.14.5' import os from docarray.document import Document from docarray.array import DocumentArray from docarray.dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
__version__ = '0.14.4' import os from docarray.document import Document from docarray.array import DocumentArray from docarray.dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
# 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 pytest from typing import Dict, List from docarray import BaseDoc, DocList from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDoc): embedding: NdArray text: str image: ImageDoc class MySimpleDoc(BaseDoc): title: str class MyComplexDoc(BaseDoc): content_dict_doclist: Dict[str, DocList[MySimpleDoc]] content_dict_list: Dict[str, List[MySimpleDoc]] aux_dict: Dict[str, int] @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_bytes(protocol, compress): d = MyDoc(embedding=[1, 2, 3, 4, 5], text='hello', image=ImageDoc(url='aux.png')) assert d.text == 'hello' assert d.embedding.tolist() == [1, 2, 3, 4, 5] assert d.image.url == 'aux.png' bstr = d.to_bytes(protocol=protocol, compress=compress) d2 = MyDoc.from_bytes(bstr, protocol=protocol, compress=compress) assert d2.text == 'hello' assert d2.embedding.tolist() == [1, 2, 3, 4, 5] assert d2.image.url == 'aux.png' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_base64(protocol, compress): d = MyDoc(embedding=[1, 2, 3, 4, 5], text='hello', image=ImageDoc(url='aux.png')) assert d.text == 'hello' assert d.embedding.tolist() == [1, 2, 3, 4, 5] assert d.image.url == 'aux.png' bstr = d.to_base64(protocol=protocol, compress=compress) d2 = MyDoc.from_base64(bstr, protocol=protocol, compress=compress) assert d2.text == 'hello' assert d2.embedding.tolist() == [1, 2, 3, 4, 5] assert d2.image.url == 'aux.png' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_bytes_complex(protocol, compress): d = MyComplexDoc( content_dict_doclist={ 'test1': DocList[MySimpleDoc]( [MySimpleDoc(title='123'), MySimpleDoc(title='456')] ) }, content_dict_list={ 'test1': [MySimpleDoc(title='123'), MySimpleDoc(title='456')] }, aux_dict={'a': 0}, ) bstr = d.to_bytes(protocol=protocol, compress=compress) d2 = MyComplexDoc.from_bytes(bstr, protocol=protocol, compress=compress) assert d2.aux_dict == {'a': 0} assert len(d2.content_dict_doclist['test1']) == 2 assert d2.content_dict_doclist['test1'][0].title == '123' assert d2.content_dict_doclist['test1'][1].title == '456' assert len(d2.content_dict_list['test1']) == 2 assert d2.content_dict_list['test1'][0].title == '123' assert d2.content_dict_list['test1'][1].title == '456' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_base64_complex(protocol, compress): d = MyComplexDoc( content_dict_doclist={ 'test1': DocList[MySimpleDoc]( [MySimpleDoc(title='123'), MySimpleDoc(title='456')] ) }, content_dict_list={ 'test1': [MySimpleDoc(title='123'), MySimpleDoc(title='456')] }, aux_dict={'a': 0}, ) bstr = d.to_base64(protocol=protocol, compress=compress) d2 = MyComplexDoc.from_base64(bstr, protocol=protocol, compress=compress) assert d2.aux_dict == {'a': 0} assert len(d2.content_dict_doclist['test1']) == 2 assert d2.content_dict_doclist['test1'][0].title == '123' assert d2.content_dict_doclist['test1'][1].title == '456' assert len(d2.content_dict_list['test1']) == 2 assert d2.content_dict_list['test1'][0].title == '123' assert d2.content_dict_list['test1'][1].title == '456'
import pytest from typing import Dict, List from docarray import BaseDoc, DocList from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDoc): embedding: NdArray text: str image: ImageDoc class MySimpleDoc(BaseDoc): title: str class MyComplexDoc(BaseDoc): content_dict_doclist: Dict[str, DocList[MySimpleDoc]] content_dict_list: Dict[str, List[MySimpleDoc]] aux_dict: Dict[str, int] @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_bytes(protocol, compress): d = MyDoc(embedding=[1, 2, 3, 4, 5], text='hello', image=ImageDoc(url='aux.png')) assert d.text == 'hello' assert d.embedding.tolist() == [1, 2, 3, 4, 5] assert d.image.url == 'aux.png' bstr = d.to_bytes(protocol=protocol, compress=compress) d2 = MyDoc.from_bytes(bstr, protocol=protocol, compress=compress) assert d2.text == 'hello' assert d2.embedding.tolist() == [1, 2, 3, 4, 5] assert d2.image.url == 'aux.png' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_base64(protocol, compress): d = MyDoc(embedding=[1, 2, 3, 4, 5], text='hello', image=ImageDoc(url='aux.png')) assert d.text == 'hello' assert d.embedding.tolist() == [1, 2, 3, 4, 5] assert d.image.url == 'aux.png' bstr = d.to_base64(protocol=protocol, compress=compress) d2 = MyDoc.from_base64(bstr, protocol=protocol, compress=compress) assert d2.text == 'hello' assert d2.embedding.tolist() == [1, 2, 3, 4, 5] assert d2.image.url == 'aux.png' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_bytes_complex(protocol, compress): d = MyComplexDoc( content_dict_doclist={ 'test1': DocList[MySimpleDoc]( [MySimpleDoc(title='123'), MySimpleDoc(title='456')] ) }, content_dict_list={ 'test1': [MySimpleDoc(title='123'), MySimpleDoc(title='456')] }, aux_dict={'a': 0}, ) bstr = d.to_bytes(protocol=protocol, compress=compress) d2 = MyComplexDoc.from_bytes(bstr, protocol=protocol, compress=compress) assert d2.aux_dict == {'a': 0} assert len(d2.content_dict_doclist['test1']) == 2 assert d2.content_dict_doclist['test1'][0].title == '123' assert d2.content_dict_doclist['test1'][1].title == '456' assert len(d2.content_dict_list['test1']) == 2 assert d2.content_dict_list['test1'][0].title == '123' assert d2.content_dict_list['test1'][1].title == '456' @pytest.mark.parametrize('protocol', ['protobuf', 'pickle']) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) def test_to_from_base64_complex(protocol, compress): d = MyComplexDoc( content_dict_doclist={ 'test1': DocList[MySimpleDoc]( [MySimpleDoc(title='123'), MySimpleDoc(title='456')] ) }, content_dict_list={ 'test1': [MySimpleDoc(title='123'), MySimpleDoc(title='456')] }, aux_dict={'a': 0}, ) bstr = d.to_base64(protocol=protocol, compress=compress) d2 = MyComplexDoc.from_base64(bstr, protocol=protocol, compress=compress) assert d2.aux_dict == {'a': 0} assert len(d2.content_dict_doclist['test1']) == 2 assert d2.content_dict_doclist['test1'][0].title == '123' assert d2.content_dict_doclist['test1'][1].title == '456' assert len(d2.content_dict_list['test1']) == 2 assert d2.content_dict_list['test1'][0].title == '123' assert d2.content_dict_list['test1'][1].title == '456'
"""Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format. """ import logging from torch.nn import Module from ..model import wav2vec2_model, Wav2Vec2Model _LG = logging.getLogger(__name__) def _get_config(cfg): config = { "extractor_mode": f"{cfg.feat_extract_norm}_norm", "extractor_conv_layer_config": list(zip(cfg.conv_dim, cfg.conv_kernel, cfg.conv_stride)), "extractor_conv_bias": cfg.conv_bias, "encoder_embed_dim": cfg.hidden_size, "encoder_projection_dropout": cfg.feat_proj_dropout, "encoder_pos_conv_kernel": cfg.num_conv_pos_embeddings, "encoder_pos_conv_groups": cfg.num_conv_pos_embedding_groups, "encoder_num_layers": cfg.num_hidden_layers, "encoder_num_heads": cfg.num_attention_heads, "encoder_attention_dropout": cfg.attention_dropout, "encoder_ff_interm_features": cfg.intermediate_size, "encoder_ff_interm_dropout": cfg.activation_dropout, "encoder_dropout": cfg.hidden_dropout, "encoder_layer_norm_first": cfg.do_stable_layer_norm, "encoder_layer_drop": cfg.layerdrop, } return config def _build(config, original): if original.__class__.__name__ == "Wav2Vec2ForCTC": aux_num_out = original.config.vocab_size wav2vec2 = original.wav2vec2 else: _LG.warning("The model is not an instance of Wav2Vec2ForCTC. " '"lm_head" module is not imported.') aux_num_out = None wav2vec2 = original imported = wav2vec2_model(**config, aux_num_out=aux_num_out) imported.feature_extractor.load_state_dict(wav2vec2.feature_extractor.state_dict()) imported.encoder.feature_projection.load_state_dict(wav2vec2.feature_projection.state_dict()) imported.encoder.transformer.load_state_dict(wav2vec2.encoder.state_dict()) if original.__class__.__name__ == "Wav2Vec2ForCTC": imported.aux.load_state_dict(original.lm_head.state_dict()) return imported def import_huggingface_model(original: Module) -> Wav2Vec2Model: """Build Wav2Vec2Model from the corresponding model object of Hugging Face's `Transformers`_. Args: original (torch.nn.Module): An instance of ``Wav2Vec2ForCTC`` from ``transformers``. Returns: Wav2Vec2Model: Imported model. Example >>> from torchaudio.models.wav2vec2.utils import import_huggingface_model >>> >>> original = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") >>> model = import_huggingface_model(original) >>> >>> waveforms, _ = torchaudio.load("audio.wav") >>> logits, _ = model(waveforms) .. _Transformers: https://huggingface.co/transformers/ """ _LG.info("Importing model.") _LG.info("Loading model configuration.") config = _get_config(original.config) _LG.debug(" - config: %s", config) _LG.info("Building model.") imported = _build(config, original) return imported
"""Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format. """ import logging from torch.nn import Module from ..model import wav2vec2_model, Wav2Vec2Model _LG = logging.getLogger(__name__) def _get_config(cfg): config = { "extractor_mode": f"{cfg.feat_extract_norm}_norm", "extractor_conv_layer_config": list(zip(cfg.conv_dim, cfg.conv_kernel, cfg.conv_stride)), "extractor_conv_bias": cfg.conv_bias, "encoder_embed_dim": cfg.hidden_size, "encoder_projection_dropout": cfg.feat_proj_dropout, "encoder_pos_conv_kernel": cfg.num_conv_pos_embeddings, "encoder_pos_conv_groups": cfg.num_conv_pos_embedding_groups, "encoder_num_layers": cfg.num_hidden_layers, "encoder_num_heads": cfg.num_attention_heads, "encoder_attention_dropout": cfg.attention_dropout, "encoder_ff_interm_features": cfg.intermediate_size, "encoder_ff_interm_dropout": cfg.activation_dropout, "encoder_dropout": cfg.hidden_dropout, "encoder_layer_norm_first": cfg.do_stable_layer_norm, "encoder_layer_drop": cfg.layerdrop, } return config def _build(config, original): if original.__class__.__name__ == "Wav2Vec2ForCTC": aux_num_out = original.config.vocab_size wav2vec2 = original.wav2vec2 else: _LG.warning("The model is not an instance of Wav2Vec2ForCTC. " '"lm_head" module is not imported.') aux_num_out = None wav2vec2 = original imported = wav2vec2_model(**config, aux_num_out=aux_num_out) imported.feature_extractor.load_state_dict(wav2vec2.feature_extractor.state_dict()) imported.encoder.feature_projection.load_state_dict(wav2vec2.feature_projection.state_dict()) imported.encoder.transformer.load_state_dict(wav2vec2.encoder.state_dict()) if original.__class__.__name__ == "Wav2Vec2ForCTC": imported.aux.load_state_dict(original.lm_head.state_dict()) return imported def import_huggingface_model(original: Module) -> Wav2Vec2Model: """import_huggingface_model(original: torch.nn.Module) -> torchaudio.models.Wav2Vec2Model Build Wav2Vec2Model from the corresponding model object of Hugging Face's `Transformers`_. Args: original (torch.nn.Module): An instance of ``Wav2Vec2ForCTC`` from ``transformers``. Returns: Wav2Vec2Model: Imported model. Example >>> from torchaudio.models.wav2vec2.utils import import_huggingface_model >>> >>> original = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") >>> model = import_huggingface_model(original) >>> >>> waveforms, _ = torchaudio.load("audio.wav") >>> logits, _ = model(waveforms) .. _Transformers: https://huggingface.co/transformers/ """ _LG.info("Importing model.") _LG.info("Loading model configuration.") config = _get_config(original.config) _LG.debug(" - config: %s", config) _LG.info("Building model.") imported = _build(config, original) return imported
import asyncio from typing import AsyncIterator, Iterator, Optional, Union from jina.helper import get_or_reuse_loop class _RequestsCounter: """Class used to wrap a count integer so that it can be updated inside methods. .. code-block:: python def count_increment(i: int, rc: _RequestsCounter): i += 1 rc.count += 1 c_int = 0 c_rc = _RequestsCounter() count_increment(c_int, c_rc) assert c_int == 0 assert c_rc.count == 1 """ count = 0 class AsyncRequestsIterator: """Iterator to allow async iteration of blocking/non-blocking iterator from the Client""" def __init__( self, iterator: Union[Iterator, AsyncIterator], request_counter: Optional[_RequestsCounter] = None, prefetch: int = 0, iterate_sync_in_thread: bool = True, ) -> None: """Async request iterator :param iterator: request iterator :param request_counter: counter of the numbers of request being handled at a given moment :param prefetch: The max amount of requests to be handled at a given moment (0 disables feature) :param iterate_sync_in_thread: if True, blocking iterators will call __next__ in a Thread. """ self.iterator = iterator self._request_counter = request_counter self._prefetch = prefetch self._iterate_sync_in_thread = iterate_sync_in_thread def iterator__next__(self): """ Executed inside a `ThreadPoolExecutor` via `loop.run_in_executor` to avoid following exception. "StopIteration interacts badly with generators and cannot be raised into a Future" :return: next request or None """ try: return self.iterator.__next__() except StopIteration: return None def __aiter__(self): return self async def __anext__(self): if isinstance(self.iterator, Iterator): """ An `Iterator` indicates "blocking" code, which might block all tasks in the event loop. Hence we iterate in the default executor provided by asyncio. """ if not self._iterate_sync_in_thread: async def _get_next(): try: req = self.iterator.__next__() except StopIteration: req = None return req request = await asyncio.create_task(_get_next()) else: request = await get_or_reuse_loop().run_in_executor( None, self.iterator__next__ ) """ `iterator.__next__` can be executed directly and that'd raise `StopIteration` in the executor, which raises the following exception while chaining states in futures. "StopIteration interacts badly with generators and cannot be raised into a Future" To avoid that, we handle the raise by a `return None` """ if request is None: raise StopAsyncIteration elif isinstance(self.iterator, AsyncIterator): # we assume that `AsyncIterator` doesn't block the event loop request = await self.iterator.__anext__() if self._prefetch > 0: while self._request_counter.count >= self._prefetch: await asyncio.sleep(0) return request
import asyncio from typing import AsyncIterator, Iterator, Optional, Union from jina.helper import get_or_reuse_loop class _RequestsCounter: """Class used to wrap a count integer so that it can be updated inside methods. .. code-block:: python def count_increment(i: int, rc: _RequestsCounter): i += 1 rc.count += 1 c_int = 0 c_rc = _RequestsCounter() count_increment(c_int, c_rc) assert c_int == 0 assert c_rc.count == 1 """ count = 0 class AsyncRequestsIterator: """Iterator to allow async iteration of blocking/non-blocking iterator from the Client""" def __init__( self, iterator: Union[Iterator, AsyncIterator], request_counter: Optional[_RequestsCounter] = None, prefetch: int = 0, iterate_sync_in_thread: bool = True, ) -> None: """Async request iterator :param iterator: request iterator :param request_counter: counter of the numbers of request being handled at a given moment :param prefetch: The max amount of requests to be handled at a given moment (0 disables feature) :param iterate_sync_in_thread: if True, blocking iterators will call __next__ in a Thread. """ self.iterator = iterator self._request_counter = request_counter self._prefetch = prefetch self._iterate_sync_in_thread = iterate_sync_in_thread def iterator__next__(self): """ Executed inside a `ThreadPoolExecutor` via `loop.run_in_executor` to avoid following exception. "StopIteration interacts badly with generators and cannot be raised into a Future" :return: next request or None """ try: return self.iterator.__next__() except StopIteration: return None def __aiter__(self): return self async def __anext__(self): if isinstance(self.iterator, Iterator): """ An `Iterator` indicates "blocking" code, which might block all tasks in the event loop. Hence we iterate in the default executor provided by asyncio. """ if not self._iterate_sync_in_thread: async def _get_next(): try: req = self.iterator.__next__() except StopIteration: req = None return req request = await asyncio.create_task(_get_next()) else: request = await get_or_reuse_loop().run_in_executor( None, self.iterator__next__ ) """ `iterator.__next__` can be executed directly and that'd raise `StopIteration` in the executor, which raises the following exception while chaining states in futures. "StopIteration interacts badly with generators and cannot be raised into a Future" To avoid that, we handle the raise by a `return None` """ if request is None: raise StopAsyncIteration elif isinstance(self.iterator, AsyncIterator): # we assume that `AsyncIterator` doesn't block the event loop request = await self.iterator.__anext__() if self._prefetch > 0: while self._request_counter.count >= self._prefetch: await asyncio.sleep(0) return request
_base_ = '../faster_rcnn/faster-rcnn_r50-caffe_fpn_1x_coco.py' rpn_weight = 0.7 model = dict( rpn_head=dict( _delete_=True, type='CascadeRPNHead', num_stages=2, stages=[ dict( type='StageCascadeRPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[1.0], strides=[4, 8, 16, 32, 64]), adapt_cfg=dict(type='dilation', dilation=3), bridged_feature=True, with_cls=False, reg_decoded_bbox=True, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=(.0, .0, .0, .0), target_stds=(0.1, 0.1, 0.5, 0.5)), loss_bbox=dict( type='IoULoss', linear=True, loss_weight=10.0 * rpn_weight)), dict( type='StageCascadeRPNHead', in_channels=256, feat_channels=256, adapt_cfg=dict(type='offset'), bridged_feature=False, with_cls=True, reg_decoded_bbox=True, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=(.0, .0, .0, .0), target_stds=(0.05, 0.05, 0.1, 0.1)), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0 * rpn_weight), loss_bbox=dict( type='IoULoss', linear=True, loss_weight=10.0 * rpn_weight)) ]), roi_head=dict( bbox_head=dict( bbox_coder=dict(target_stds=[0.04, 0.04, 0.08, 0.08]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.5), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=[ dict( assigner=dict( type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), allowed_border=-1, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False) ], rpn_proposal=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), rcnn=dict( assigner=dict( pos_iou_thr=0.65, neg_iou_thr=0.65, min_pos_iou=0.65), sampler=dict(type='RandomSampler', num=256))), test_cfg=dict( rpn=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), rcnn=dict(score_thr=1e-3))) optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2))
_base_ = '../faster_rcnn/faster_rcnn_r50_caffe_fpn_1x_coco.py' rpn_weight = 0.7 model = dict( rpn_head=dict( _delete_=True, type='CascadeRPNHead', num_stages=2, stages=[ dict( type='StageCascadeRPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[1.0], strides=[4, 8, 16, 32, 64]), adapt_cfg=dict(type='dilation', dilation=3), bridged_feature=True, with_cls=False, reg_decoded_bbox=True, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=(.0, .0, .0, .0), target_stds=(0.1, 0.1, 0.5, 0.5)), loss_bbox=dict( type='IoULoss', linear=True, loss_weight=10.0 * rpn_weight)), dict( type='StageCascadeRPNHead', in_channels=256, feat_channels=256, adapt_cfg=dict(type='offset'), bridged_feature=False, with_cls=True, reg_decoded_bbox=True, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=(.0, .0, .0, .0), target_stds=(0.05, 0.05, 0.1, 0.1)), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0 * rpn_weight), loss_bbox=dict( type='IoULoss', linear=True, loss_weight=10.0 * rpn_weight)) ]), roi_head=dict( bbox_head=dict( bbox_coder=dict(target_stds=[0.04, 0.04, 0.08, 0.08]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.5), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=[ dict( assigner=dict( type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), allowed_border=-1, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False) ], rpn_proposal=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), rcnn=dict( assigner=dict( pos_iou_thr=0.65, neg_iou_thr=0.65, min_pos_iou=0.65), sampler=dict(type='RandomSampler', num=256))), test_cfg=dict( rpn=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), rcnn=dict(score_thr=1e-3))) optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2))
from typing import Union, Dict, Any import google.ai.generativelanguage as glm import google.generativeai as genai from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ImageBlock, TextBlock, ) from llama_index.core.multi_modal_llms.base import ChatMessage from llama_index.core.utilities.gemini_utils import ROLES_FROM_GEMINI, ROLES_TO_GEMINI # These are the shortened model names # Any model that contains one of these names will not support function calling MODELS_WITHOUT_FUNCTION_CALLING_SUPPORT = [ "gemini-2.0-flash-thinking", "gemini-2.0-flash-lite", ] def _error_if_finished_early(candidate: "glm.Candidate") -> None: # type: ignore[name-defined] # only until release if (finish_reason := candidate.finish_reason) > 1: # 1=STOP (normally) reason = finish_reason.name # Safety reasons have more detail, so include that if we can. if finish_reason == 3: # 3=Safety relevant_safety = list( filter( lambda sr: sr.probability > 1, # 1=Negligible candidate.safety_ratings, ) ) reason += f" {relevant_safety}" raise RuntimeError(f"Response was terminated early: {reason}") def completion_from_gemini_response( response: Union[ "genai.types.GenerateContentResponse", "genai.types.AsyncGenerateContentResponse", ], ) -> CompletionResponse: top_candidate = response.candidates[0] _error_if_finished_early(top_candidate) raw = { **(type(top_candidate).to_dict(top_candidate)), # type: ignore **(type(response.prompt_feedback).to_dict(response.prompt_feedback)), # type: ignore } if response.usage_metadata: raw["usage_metadata"] = type(response.usage_metadata).to_dict( response.usage_metadata ) return CompletionResponse(text=response.text, raw=raw) def chat_from_gemini_response( response: Union[ "genai.types.GenerateContentResponse", "genai.types.AsyncGenerateContentResponse", ], ) -> ChatResponse: top_candidate = response.candidates[0] _error_if_finished_early(top_candidate) raw = { **(type(top_candidate).to_dict(top_candidate)), # type: ignore **(type(response.prompt_feedback).to_dict(response.prompt_feedback)), # type: ignore } if response.usage_metadata: raw["usage_metadata"] = type(response.usage_metadata).to_dict( response.usage_metadata ) role = ROLES_FROM_GEMINI[top_candidate.content.role] try: # When the response contains only a function call, the library # raises an exception. # The easiest way to detect this is to try access the text attribute and # catch the exception. # https://github.com/google-gemini/generative-ai-python/issues/670 text = response.text except (ValueError, AttributeError): text = None additional_kwargs: Dict[str, Any] = {} for part in response.parts: if fn := part.function_call: if "tool_calls" not in additional_kwargs: additional_kwargs["tool_calls"] = [] additional_kwargs["tool_calls"].append(fn) return ChatResponse( message=ChatMessage( role=role, content=text, additional_kwargs=additional_kwargs ), raw=raw, additional_kwargs=additional_kwargs, ) def chat_message_to_gemini(message: ChatMessage) -> "genai.types.ContentDict": """Convert ChatMessages to Gemini-specific history, including ImageDocuments.""" parts = [] for block in message.blocks: if isinstance(block, TextBlock): if block.text: parts.append({"text": block.text}) elif isinstance(block, ImageBlock): base64_bytes = block.resolve_image(as_base64=False).read() parts.append( { "mime_type": block.image_mimetype, "data": base64_bytes, } ) else: msg = f"Unsupported content block type: {type(block).__name__}" raise ValueError(msg) for tool_call in message.additional_kwargs.get("tool_calls", []): parts.append(tool_call) return { "role": ROLES_TO_GEMINI[message.role], "parts": parts, } def is_function_calling_model(model: str) -> bool: for model_name in MODELS_WITHOUT_FUNCTION_CALLING_SUPPORT: if model_name in model: return False return True
from typing import Union, Dict, Any import google.ai.generativelanguage as glm import google.generativeai as genai from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, CompletionResponse, ImageBlock, TextBlock, ) from llama_index.core.multi_modal_llms.base import ChatMessage from llama_index.core.utilities.gemini_utils import ROLES_FROM_GEMINI, ROLES_TO_GEMINI def _error_if_finished_early(candidate: "glm.Candidate") -> None: # type: ignore[name-defined] # only until release if (finish_reason := candidate.finish_reason) > 1: # 1=STOP (normally) reason = finish_reason.name # Safety reasons have more detail, so include that if we can. if finish_reason == 3: # 3=Safety relevant_safety = list( filter( lambda sr: sr.probability > 1, # 1=Negligible candidate.safety_ratings, ) ) reason += f" {relevant_safety}" raise RuntimeError(f"Response was terminated early: {reason}") def completion_from_gemini_response( response: Union[ "genai.types.GenerateContentResponse", "genai.types.AsyncGenerateContentResponse", ], ) -> CompletionResponse: top_candidate = response.candidates[0] _error_if_finished_early(top_candidate) raw = { **(type(top_candidate).to_dict(top_candidate)), # type: ignore **(type(response.prompt_feedback).to_dict(response.prompt_feedback)), # type: ignore } if response.usage_metadata: raw["usage_metadata"] = type(response.usage_metadata).to_dict( response.usage_metadata ) return CompletionResponse(text=response.text, raw=raw) def chat_from_gemini_response( response: Union[ "genai.types.GenerateContentResponse", "genai.types.AsyncGenerateContentResponse", ], ) -> ChatResponse: top_candidate = response.candidates[0] _error_if_finished_early(top_candidate) raw = { **(type(top_candidate).to_dict(top_candidate)), # type: ignore **(type(response.prompt_feedback).to_dict(response.prompt_feedback)), # type: ignore } if response.usage_metadata: raw["usage_metadata"] = type(response.usage_metadata).to_dict( response.usage_metadata ) role = ROLES_FROM_GEMINI[top_candidate.content.role] try: # When the response contains only a function call, the library # raises an exception. # The easiest way to detect this is to try access the text attribute and # catch the exception. # https://github.com/google-gemini/generative-ai-python/issues/670 text = response.text except (ValueError, AttributeError): text = None additional_kwargs: Dict[str, Any] = {} for part in response.parts: if fn := part.function_call: if "tool_calls" not in additional_kwargs: additional_kwargs["tool_calls"] = [] additional_kwargs["tool_calls"].append(fn) return ChatResponse( message=ChatMessage( role=role, content=text, additional_kwargs=additional_kwargs ), raw=raw, additional_kwargs=additional_kwargs, ) def chat_message_to_gemini(message: ChatMessage) -> "genai.types.ContentDict": """Convert ChatMessages to Gemini-specific history, including ImageDocuments.""" parts = [] for block in message.blocks: if isinstance(block, TextBlock): if block.text: parts.append({"text": block.text}) elif isinstance(block, ImageBlock): base64_bytes = block.resolve_image(as_base64=False).read() parts.append( { "mime_type": block.image_mimetype, "data": base64_bytes, } ) else: msg = f"Unsupported content block type: {type(block).__name__}" raise ValueError(msg) for tool_call in message.additional_kwargs.get("tool_calls", []): parts.append(tool_call) return { "role": ROLES_TO_GEMINI[message.role], "parts": parts, }
import numpy as np import orjson import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import NdArray from docarray.typing.tensor import NdArrayEmbedding def test_proto_tensor(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) tensor._to_node_protobuf() def test_from_list(): tensor = parse_obj_as(NdArray, [[0.0, 0.0], [0.0, 0.0]]) assert (tensor == np.zeros((2, 2))).all() def test_json_schema(): schema_json_of(NdArray) def test_dump_json(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) orjson_dumps(tensor) def test_load_json(): tensor = parse_obj_as(NdArray, np.zeros((2, 2))) json = orjson_dumps(tensor) print(json) print(type(json)) new_tensor = orjson.loads(json) assert (new_tensor == tensor).all() def test_unwrap(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) ndarray = tensor.unwrap() assert not isinstance(ndarray, NdArray) assert isinstance(ndarray, np.ndarray) assert isinstance(tensor, NdArray) assert (ndarray == np.zeros((3, 224, 224))).all() def test_parametrized(): # correct shape, single axis tensor = parse_obj_as(NdArray[128], np.zeros(128)) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (128,) # correct shape, multiple axis tensor = parse_obj_as(NdArray[3, 224, 224], np.zeros((3, 224, 224))) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (3, 224, 224) # wrong but reshapable shape tensor = parse_obj_as(NdArray[3, 224, 224], np.zeros((3, 224, 224))) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (3, 224, 224) # wrong and not reshapable shape with pytest.raises(ValueError): parse_obj_as(NdArray[3, 224, 224], np.zeros((224, 224))) def test_np_embedding(): # correct shape tensor = parse_obj_as(NdArrayEmbedding[128], np.zeros((128,))) assert isinstance(tensor, NdArrayEmbedding) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (128,) # wrong shape at data setting time with pytest.raises(ValueError): parse_obj_as(NdArrayEmbedding[128], np.zeros((256,))) # illegal shape at class creation time with pytest.raises(ValueError): parse_obj_as(NdArrayEmbedding[128, 128], np.zeros((128, 128)))
import numpy as np import orjson import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import NdArray def test_proto_tensor(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) tensor._to_node_protobuf() def test_from_list(): tensor = parse_obj_as(NdArray, [[0.0, 0.0], [0.0, 0.0]]) assert (tensor == np.zeros((2, 2))).all() def test_json_schema(): schema_json_of(NdArray) def test_dump_json(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) orjson_dumps(tensor) def test_load_json(): tensor = parse_obj_as(NdArray, np.zeros((2, 2))) json = orjson_dumps(tensor) print(json) print(type(json)) new_tensor = orjson.loads(json) assert (new_tensor == tensor).all() def test_unwrap(): tensor = parse_obj_as(NdArray, np.zeros((3, 224, 224))) ndarray = tensor.unwrap() assert not isinstance(ndarray, NdArray) assert isinstance(ndarray, np.ndarray) assert isinstance(tensor, NdArray) assert (ndarray == np.zeros((3, 224, 224))).all() def test_parametrized(): # correct shape, single axis tensor = parse_obj_as(NdArray[128], np.zeros(128)) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (128,) # correct shape, multiple axis tensor = parse_obj_as(NdArray[3, 224, 224], np.zeros((3, 224, 224))) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (3, 224, 224) # wrong but reshapable shape tensor = parse_obj_as(NdArray[3, 224, 224], np.zeros((3, 224, 224))) assert isinstance(tensor, NdArray) assert isinstance(tensor, np.ndarray) assert tensor.shape == (3, 224, 224) # wrong and not reshapable shape with pytest.raises(ValueError): parse_obj_as(NdArray[3, 224, 224], np.zeros((224, 224)))
"""Example of analytics tests with improved error handling and assertions.""" import json from unittest.mock import AsyncMock, Mock import fastapi import fastapi.testclient import pytest_mock from pytest_snapshot.plugin import Snapshot import backend.server.routers.analytics as analytics_routes from backend.server.conftest import TEST_USER_ID from backend.server.test_helpers import ( assert_error_response_structure, assert_mock_called_with_partial, assert_response_status, safe_parse_json, ) from backend.server.utils import get_user_id app = fastapi.FastAPI() app.include_router(analytics_routes.router) client = fastapi.testclient.TestClient(app) def override_get_user_id() -> str: """Override get_user_id for testing""" return TEST_USER_ID app.dependency_overrides[get_user_id] = override_get_user_id def test_log_raw_metric_success_improved( mocker: pytest_mock.MockFixture, configured_snapshot: Snapshot, ) -> None: """Test successful raw metric logging with improved assertions.""" # Mock the analytics function mock_result = Mock(id="metric-123-uuid") mock_log_metric = mocker.patch( "backend.data.analytics.log_raw_metric", new_callable=AsyncMock, return_value=mock_result, ) request_data = { "metric_name": "page_load_time", "metric_value": 2.5, "data_string": "/dashboard", } response = client.post("/log_raw_metric", json=request_data) # Improved assertions with better error messages assert_response_status(response, 200, "Metric logging should succeed") response_data = safe_parse_json(response, "Metric response parsing") assert response_data == "metric-123-uuid", f"Unexpected response: {response_data}" # Verify the function was called with correct parameters assert_mock_called_with_partial( mock_log_metric, user_id=TEST_USER_ID, metric_name="page_load_time", metric_value=2.5, data_string="/dashboard", ) # Snapshot test the response configured_snapshot.assert_match( json.dumps({"metric_id": response_data}, indent=2, sort_keys=True), "analytics_log_metric_success_improved", ) def test_log_raw_metric_invalid_request_improved() -> None: """Test invalid metric request with improved error assertions.""" # Test missing required fields response = client.post("/log_raw_metric", json={}) error_data = assert_error_response_structure( response, expected_status=422, expected_error_fields=["loc", "msg", "type"] ) # Verify specific error details detail = error_data["detail"] assert isinstance(detail, list), "Error detail should be a list" assert len(detail) > 0, "Should have at least one error" # Check that required fields are mentioned in errors error_fields = [error["loc"][-1] for error in detail if "loc" in error] assert "metric_name" in error_fields, "Should report missing metric_name" assert "metric_value" in error_fields, "Should report missing metric_value" assert "data_string" in error_fields, "Should report missing data_string" def test_log_raw_metric_type_validation_improved( mocker: pytest_mock.MockFixture, ) -> None: """Test metric type validation with improved assertions.""" # Mock the analytics function to avoid event loop issues mocker.patch( "backend.data.analytics.log_raw_metric", new_callable=AsyncMock, return_value=Mock(id="test-id"), ) invalid_requests = [ { "data": { "metric_name": "test", "metric_value": "not_a_number", # Invalid type "data_string": "test", }, "expected_error": "Input should be a valid number", }, { "data": { "metric_name": "", # Empty string "metric_value": 1.0, "data_string": "test", }, "expected_error": "String should have at least 1 character", }, { "data": { "metric_name": "test", "metric_value": 123, # Valid number "data_string": "", # Empty data_string }, "expected_error": "String should have at least 1 character", }, ] for test_case in invalid_requests: response = client.post("/log_raw_metric", json=test_case["data"]) error_data = assert_error_response_structure(response, expected_status=422) # Check that expected error is in the response error_text = json.dumps(error_data) assert ( test_case["expected_error"] in error_text or test_case["expected_error"].lower() in error_text.lower() ), f"Expected error '{test_case['expected_error']}' not found in: {error_text}"
"""Example of analytics tests with improved error handling and assertions.""" import json from unittest.mock import AsyncMock, Mock import fastapi import fastapi.testclient import pytest_mock from pytest_snapshot.plugin import Snapshot import backend.server.routers.analytics as analytics_routes from backend.server.conftest import TEST_USER_ID from backend.server.test_helpers import ( assert_error_response_structure, assert_mock_called_with_partial, assert_response_status, safe_parse_json, ) from backend.server.utils import get_user_id app = fastapi.FastAPI() app.include_router(analytics_routes.router) client = fastapi.testclient.TestClient(app) def override_get_user_id() -> str: """Override get_user_id for testing""" return TEST_USER_ID app.dependency_overrides[get_user_id] = override_get_user_id def test_log_raw_metric_success_improved( mocker: pytest_mock.MockFixture, configured_snapshot: Snapshot, ) -> None: """Test successful raw metric logging with improved assertions.""" # Mock the analytics function mock_result = Mock(id="metric-123-uuid") mock_log_metric = mocker.patch( "backend.data.analytics.log_raw_metric", new_callable=AsyncMock, return_value=mock_result, ) request_data = { "metric_name": "page_load_time", "metric_value": 2.5, "data_string": "/dashboard", } response = client.post("/log_raw_metric", json=request_data) # Improved assertions with better error messages assert_response_status(response, 200, "Metric logging should succeed") response_data = safe_parse_json(response, "Metric response parsing") assert response_data == "metric-123-uuid", f"Unexpected response: {response_data}" # Verify the function was called with correct parameters assert_mock_called_with_partial( mock_log_metric, user_id=TEST_USER_ID, metric_name="page_load_time", metric_value=2.5, data_string="/dashboard", ) # Snapshot test the response configured_snapshot.assert_match( json.dumps({"metric_id": response_data}, indent=2, sort_keys=True), "analytics_log_metric_success_improved", ) def test_log_raw_metric_invalid_request_improved() -> None: """Test invalid metric request with improved error assertions.""" # Test missing required fields response = client.post("/log_raw_metric", json={}) error_data = assert_error_response_structure( response, expected_status=422, expected_error_fields=["loc", "msg", "type"] ) # Verify specific error details detail = error_data["detail"] assert isinstance(detail, list), "Error detail should be a list" assert len(detail) > 0, "Should have at least one error" # Check that required fields are mentioned in errors error_fields = [error["loc"][-1] for error in detail if "loc" in error] assert "metric_name" in error_fields, "Should report missing metric_name" assert "metric_value" in error_fields, "Should report missing metric_value" assert "data_string" in error_fields, "Should report missing data_string" def test_log_raw_metric_type_validation_improved() -> None: """Test metric type validation with improved assertions.""" invalid_requests = [ { "data": { "metric_name": "test", "metric_value": "not_a_number", # Invalid type "data_string": "test", }, "expected_error": "Input should be a valid number", }, { "data": { "metric_name": "", # Empty string "metric_value": 1.0, "data_string": "test", }, "expected_error": "String should have at least 1 character", }, { "data": { "metric_name": "test", "metric_value": float("inf"), # Infinity "data_string": "test", }, "expected_error": "ensure this value is finite", }, ] for test_case in invalid_requests: response = client.post("/log_raw_metric", json=test_case["data"]) error_data = assert_error_response_structure(response, expected_status=422) # Check that expected error is in the response error_text = json.dumps(error_data) assert ( test_case["expected_error"] in error_text or test_case["expected_error"].lower() in error_text.lower() ), f"Expected error '{test_case['expected_error']}' not found in: {error_text}"
import datetime import json import typing import prisma.models import pydantic import backend.data.block import backend.data.graph import backend.server.model class LibraryAgent(pydantic.BaseModel): id: str # Changed from agent_id to match GraphMeta agent_id: str agent_version: int # Changed from agent_version to match GraphMeta preset_id: str | None updated_at: datetime.datetime name: str description: str # Made input_schema and output_schema match GraphMeta's type input_schema: dict[str, typing.Any] # Should be BlockIOObjectSubSchema in frontend output_schema: dict[str, typing.Any] # Should be BlockIOObjectSubSchema in frontend is_favorite: bool is_created_by_user: bool is_latest_version: bool @staticmethod def from_db(agent: prisma.models.LibraryAgent): if not agent.Agent: raise ValueError("AgentGraph is required") graph = backend.data.graph.GraphModel.from_db(agent.Agent) agent_updated_at = agent.Agent.updatedAt lib_agent_updated_at = agent.updatedAt # Take the latest updated_at timestamp either when the graph was updated or the library agent was updated updated_at = ( max(agent_updated_at, lib_agent_updated_at) if agent_updated_at else lib_agent_updated_at ) return LibraryAgent( id=agent.id, agent_id=agent.agentId, agent_version=agent.agentVersion, updated_at=updated_at, name=graph.name, description=graph.description, input_schema=graph.input_schema, output_schema=graph.output_schema, is_favorite=agent.isFavorite, is_created_by_user=agent.isCreatedByUser, is_latest_version=graph.is_active, preset_id=agent.AgentPreset.id if agent.AgentPreset else None, ) class LibraryAgentPreset(pydantic.BaseModel): id: str updated_at: datetime.datetime agent_id: str agent_version: int name: str description: str is_active: bool inputs: dict[str, typing.Union[backend.data.block.BlockInput, typing.Any]] @staticmethod def from_db(preset: prisma.models.AgentPreset): input_data = {} for data in preset.InputPresets or []: input_data[data.name] = json.loads(data.data) return LibraryAgentPreset( id=preset.id, updated_at=preset.updatedAt, agent_id=preset.agentId, agent_version=preset.agentVersion, name=preset.name, description=preset.description, is_active=preset.isActive, inputs=input_data, ) class LibraryAgentPresetResponse(pydantic.BaseModel): presets: list[LibraryAgentPreset] pagination: backend.server.model.Pagination class CreateLibraryAgentPresetRequest(pydantic.BaseModel): name: str description: str inputs: dict[str, typing.Union[backend.data.block.BlockInput, typing.Any]] agent_id: str agent_version: int is_active: bool
import typing import pydantic class LibraryAgent(pydantic.BaseModel): id: str # Changed from agent_id to match GraphMeta version: int # Changed from agent_version to match GraphMeta is_active: bool # Added to match GraphMeta name: str description: str isCreatedByUser: bool # Made input_schema and output_schema match GraphMeta's type input_schema: dict[str, typing.Any] # Should be BlockIOObjectSubSchema in frontend output_schema: dict[str, typing.Any] # Should be BlockIOObjectSubSchema in frontend
from typing import Dict, Type from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding RECOGNIZED_EMBEDDINGS: Dict[str, Type[BaseEmbedding]] = { MockEmbedding.class_name(): MockEmbedding, } # conditionals for llama-cloud support try: from llama_index.embeddings.openai import OpenAIEmbedding # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[OpenAIEmbedding.class_name()] = OpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.azure_openai import ( AzureOpenAIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[AzureOpenAIEmbedding.class_name()] = AzureOpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.huggingface_api import ( HuggingFaceInferenceAPIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[HuggingFaceInferenceAPIEmbedding.class_name()] = ( HuggingFaceInferenceAPIEmbedding ) except ImportError: pass def load_embed_model(data: dict) -> BaseEmbedding: """Load Embedding by name.""" if isinstance(data, BaseEmbedding): return data name = data.get("class_name") if name is None: raise ValueError("Embedding loading requires a class_name") if name not in RECOGNIZED_EMBEDDINGS: raise ValueError(f"Invalid Embedding name: {name}") return RECOGNIZED_EMBEDDINGS[name].from_dict(data)
from typing import Dict, Type from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding RECOGNIZED_EMBEDDINGS: Dict[str, Type[BaseEmbedding]] = { MockEmbedding.class_name(): MockEmbedding, } # conditionals for llama-cloud support try: from llama_index.embeddings.openai import OpenAIEmbedding # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[OpenAIEmbedding.class_name()] = OpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.azure_openai import ( AzureOpenAIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[AzureOpenAIEmbedding.class_name()] = AzureOpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.huggingface_api import ( HuggingFaceInferenceAPIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[ HuggingFaceInferenceAPIEmbedding.class_name() ] = HuggingFaceInferenceAPIEmbedding except ImportError: pass def load_embed_model(data: dict) -> BaseEmbedding: """Load Embedding by name.""" if isinstance(data, BaseEmbedding): return data name = data.get("class_name") if name is None: raise ValueError("Embedding loading requires a class_name") if name not in RECOGNIZED_EMBEDDINGS: raise ValueError(f"Invalid Embedding name: {name}") return RECOGNIZED_EMBEDDINGS[name].from_dict(data)
import functools import sys from io import StringIO from typing import Any, Dict, List, Optional, Tuple from llama_index.core.agent import ReActAgent from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.llms.openai import OpenAI from llama_index.tools.arxiv import ArxivToolSpec from llama_index.tools.wikipedia import WikipediaToolSpec SUPPORTED_TOOLS = { "arxiv_search_tool": ArxivToolSpec, "wikipedia": WikipediaToolSpec, } class Capturing(list): """ To capture the stdout from ReActAgent.chat with verbose=True. Taken from https://stackoverflow.com/questions/16571150/\ how-to-capture-stdout-output-from-a-python-function-call. """ def __enter__(self) -> Any: self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args) -> None: self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout class GradioReActAgentPack(BaseLlamaPack): """Gradio chatbot to chat with a ReActAgent pack.""" def __init__( self, tools_list: Optional[List[str]] = list(SUPPORTED_TOOLS.keys()), **kwargs: Any, ) -> None: """Init params.""" try: from ansi2html import Ansi2HTMLConverter except ImportError: raise ImportError("Please install ansi2html via `pip install ansi2html`") tools = [] for t in tools_list: try: tools.append(SUPPORTED_TOOLS[t]()) except KeyError: raise KeyError(f"Tool {t} is not supported.") self.tools = tools self.llm = OpenAI(model="gpt-4-1106-preview", max_tokens=2000) self.agent = ReActAgent.from_tools( tools=functools.reduce( lambda x, y: x.to_tool_list() + y.to_tool_list(), self.tools ), llm=self.llm, verbose=True, ) self.thoughts = "" self.conv = Ansi2HTMLConverter() def get_modules(self) -> Dict[str, Any]: """Get modules.""" return {"agent": self.agent, "llm": self.llm, "tools": self.tools} def _handle_user_message(self, user_message, history): """ Handle the user submitted message. Clear message box, and append to the history. """ return "", [*history, (user_message, "")] def _generate_response( self, chat_history: List[Tuple[str, str]] ) -> Tuple[str, List[Tuple[str, str]]]: """ Generate the response from agent, and capture the stdout of the ReActAgent's thoughts. """ with Capturing() as output: response = self.agent.stream_chat(chat_history[-1][0]) ansi = "\n========\n".join(output) html_output = self.conv.convert(ansi) for token in response.response_gen: chat_history[-1][1] += token yield chat_history, str(html_output) def _reset_chat(self) -> Tuple[str, str]: """Reset the agent's chat history. And clear all dialogue boxes.""" # clear agent history self.agent.reset() return "", "", "" # clear textboxes def run(self, *args: Any, **kwargs: Any) -> Any: """Run the pipeline.""" import gradio as gr demo = gr.Blocks( theme="gstaff/xkcd", css="#box { height: 420px; overflow-y: scroll !important}", ) with demo: gr.Markdown( "# Gradio ReActAgent Powered by LlamaIndex and LlamaHub 🦙\n" "This Gradio app is powered by LlamaIndex's `ReActAgent` with\n" "OpenAI's GPT-4-Turbo as the LLM. The tools are listed below.\n" "## Tools\n" "- [ArxivToolSpec](https://llamahub.ai/l/tools-arxiv)\n" "- [WikipediaToolSpec](https://llamahub.ai/l/tools-wikipedia)" ) with gr.Row(): chat_window = gr.Chatbot( label="Message History", scale=3, ) console = gr.HTML(elem_id="box") with gr.Row(): message = gr.Textbox(label="Write A Message", scale=4) clear = gr.ClearButton() message.submit( self._handle_user_message, [message, chat_window], [message, chat_window], queue=False, ).then( self._generate_response, chat_window, [chat_window, console], ) clear.click(self._reset_chat, None, [message, chat_window, console]) demo.launch(server_name="0.0.0.0", server_port=8080) if __name__ == "__main__": GradioReActAgentPack(run_from_main=True).run()
import functools import sys from io import StringIO from typing import Any, Dict, List, Optional, Tuple from llama_index.core.agent import ReActAgent from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.llms.openai import OpenAI from llama_index.tools.arxiv import ArxivToolSpec from llama_index.tools.wikipedia import WikipediaToolSpec SUPPORTED_TOOLS = { "arxiv_search_tool": ArxivToolSpec, "wikipedia": WikipediaToolSpec, } class Capturing(list): """To capture the stdout from ReActAgent.chat with verbose=True. Taken from https://stackoverflow.com/questions/16571150/\ how-to-capture-stdout-output-from-a-python-function-call. """ def __enter__(self) -> Any: self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args) -> None: self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout class GradioReActAgentPack(BaseLlamaPack): """Gradio chatbot to chat with a ReActAgent pack.""" def __init__( self, tools_list: Optional[List[str]] = list(SUPPORTED_TOOLS.keys()), **kwargs: Any, ) -> None: """Init params.""" try: from ansi2html import Ansi2HTMLConverter except ImportError: raise ImportError("Please install ansi2html via `pip install ansi2html`") tools = [] for t in tools_list: try: tools.append(SUPPORTED_TOOLS[t]()) except KeyError: raise KeyError(f"Tool {t} is not supported.") self.tools = tools self.llm = OpenAI(model="gpt-4-1106-preview", max_tokens=2000) self.agent = ReActAgent.from_tools( tools=functools.reduce( lambda x, y: x.to_tool_list() + y.to_tool_list(), self.tools ), llm=self.llm, verbose=True, ) self.thoughts = "" self.conv = Ansi2HTMLConverter() def get_modules(self) -> Dict[str, Any]: """Get modules.""" return {"agent": self.agent, "llm": self.llm, "tools": self.tools} def _handle_user_message(self, user_message, history): """Handle the user submitted message. Clear message box, and append to the history. """ return "", [*history, (user_message, "")] def _generate_response( self, chat_history: List[Tuple[str, str]] ) -> Tuple[str, List[Tuple[str, str]]]: """Generate the response from agent, and capture the stdout of the ReActAgent's thoughts. """ with Capturing() as output: response = self.agent.stream_chat(chat_history[-1][0]) ansi = "\n========\n".join(output) html_output = self.conv.convert(ansi) for token in response.response_gen: chat_history[-1][1] += token yield chat_history, str(html_output) def _reset_chat(self) -> Tuple[str, str]: """Reset the agent's chat history. And clear all dialogue boxes.""" # clear agent history self.agent.reset() return "", "", "" # clear textboxes def run(self, *args: Any, **kwargs: Any) -> Any: """Run the pipeline.""" import gradio as gr demo = gr.Blocks( theme="gstaff/xkcd", css="#box { height: 420px; overflow-y: scroll !important}", ) with demo: gr.Markdown( "# Gradio ReActAgent Powered by LlamaIndex and LlamaHub 🦙\n" "This Gradio app is powered by LlamaIndex's `ReActAgent` with\n" "OpenAI's GPT-4-Turbo as the LLM. The tools are listed below.\n" "## Tools\n" "- [ArxivToolSpec](https://llamahub.ai/l/tools-arxiv)\n" "- [WikipediaToolSpec](https://llamahub.ai/l/tools-wikipedia)" ) with gr.Row(): chat_window = gr.Chatbot( label="Message History", scale=3, ) console = gr.HTML(elem_id="box") with gr.Row(): message = gr.Textbox(label="Write A Message", scale=4) clear = gr.ClearButton() message.submit( self._handle_user_message, [message, chat_window], [message, chat_window], queue=False, ).then( self._generate_response, chat_window, [chat_window, console], ) clear.click(self._reset_chat, None, [message, chat_window, console]) demo.launch(server_name="0.0.0.0", server_port=8080) if __name__ == "__main__": GradioReActAgentPack(run_from_main=True).run()
from .config import Settings from .depends import requires_admin_user, requires_user from .jwt_utils import parse_jwt_token from .middleware import APIKeyValidator, auth_middleware from .models import User __all__ = [ "Settings", "parse_jwt_token", "requires_user", "requires_admin_user", "APIKeyValidator", "auth_middleware", "User", ]
from .config import Settings from .depends import requires_admin_user, requires_user from .jwt_utils import parse_jwt_token from .middleware import auth_middleware from .models import User __all__ = [ "Settings", "parse_jwt_token", "requires_user", "requires_admin_user", "auth_middleware", "User", ]
from typing import Optional, Type from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from pydantic import BaseModel from langchain_community.utilities.polygon import PolygonAPIWrapper class Inputs(BaseModel): """Inputs for Polygon's Last Quote API""" query: str class PolygonLastQuote(BaseTool): """Tool that gets the last quote of a ticker from Polygon""" mode: str = "get_last_quote" name: str = "polygon_last_quote" description: str = ( "A wrapper around Polygon's Last Quote API. " "This tool is useful for fetching the latest price of a stock. " "Input should be the ticker that you want to query the last price quote for." ) args_schema: Type[BaseModel] = Inputs api_wrapper: PolygonAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Polygon API tool.""" return self.api_wrapper.run(self.mode, ticker=query)
from typing import Optional, Type from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from pydantic import BaseModel from langchain_community.utilities.polygon import PolygonAPIWrapper class Inputs(BaseModel): """Inputs for Polygon's Last Quote API""" query: str class PolygonLastQuote(BaseTool): # type: ignore[override, override] """Tool that gets the last quote of a ticker from Polygon""" mode: str = "get_last_quote" name: str = "polygon_last_quote" description: str = ( "A wrapper around Polygon's Last Quote API. " "This tool is useful for fetching the latest price of a stock. " "Input should be the ticker that you want to query the last price quote for." ) args_schema: Type[BaseModel] = Inputs api_wrapper: PolygonAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Polygon API tool.""" return self.api_wrapper.run(self.mode, ticker=query)
"""SingleStore reader.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.database import DatabaseReader class SingleStoreReader(BaseReader): """ SingleStore reader. Args: scheme (str): Database Scheme. host (str): Database Host. port (str): Database Port. user (str): Database User. password (str): Database Password. dbname (str): Database Name. table_name (str): Table Name. content_field (str): Content Field. vector_field (str): Vector Field. """ def __init__( self, scheme: str, host: str, port: str, user: str, password: str, dbname: str, table_name: str, content_field: str = "text", vector_field: str = "embedding", ): """Initialize with parameters.""" self.scheme = scheme self.host = host self.port = port self.user = user self.password = password self.dbname = dbname self.table_name = table_name self.content_field = content_field self.vector_field = vector_field try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass self.DatabaseReader = DatabaseReader self.reader = self.DatabaseReader( scheme=self.scheme, host=self.host, port=self.port, user=self.user, password=self.password, dbname=self.dbname, ) def load_data(self, search_embedding: str, top_k: int = 5) -> List[Document]: """ Load data from SingleStore. Args: search_embedding (str): The embedding to search. top_k (int): Number of results to return. Returns: List[Document]: A list of documents. """ query = f""" SELECT {self.content_field}, DOT_PRODUCT_F64({self.vector_field}, JSON_ARRAY_PACK_F64(\'{search_embedding}\')) AS score FROM {self.table_name} ORDER BY score DESC LIMIT {top_k} """ return self.reader.load_data(query=query)
"""SingleStore reader.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document from llama_index.readers.database import DatabaseReader class SingleStoreReader(BaseReader): """SingleStore reader. Args: scheme (str): Database Scheme. host (str): Database Host. port (str): Database Port. user (str): Database User. password (str): Database Password. dbname (str): Database Name. table_name (str): Table Name. content_field (str): Content Field. vector_field (str): Vector Field. """ def __init__( self, scheme: str, host: str, port: str, user: str, password: str, dbname: str, table_name: str, content_field: str = "text", vector_field: str = "embedding", ): """Initialize with parameters.""" self.scheme = scheme self.host = host self.port = port self.user = user self.password = password self.dbname = dbname self.table_name = table_name self.content_field = content_field self.vector_field = vector_field try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass self.DatabaseReader = DatabaseReader self.reader = self.DatabaseReader( scheme=self.scheme, host=self.host, port=self.port, user=self.user, password=self.password, dbname=self.dbname, ) def load_data(self, search_embedding: str, top_k: int = 5) -> List[Document]: """Load data from SingleStore. Args: search_embedding (str): The embedding to search. top_k (int): Number of results to return. Returns: List[Document]: A list of documents. """ query = f""" SELECT {self.content_field}, DOT_PRODUCT_F64({self.vector_field}, JSON_ARRAY_PACK_F64(\'{search_embedding}\')) AS score FROM {self.table_name} ORDER BY score DESC LIMIT {top_k} """ return self.reader.load_data(query=query)
from __future__ import annotations from collections.abc import Iterable import torch.nn.functional as F from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from .ContrastiveLoss import SiameseDistanceMetric class OnlineContrastiveLoss(nn.Module): def __init__( self, model: SentenceTransformer, distance_metric=SiameseDistanceMetric.COSINE_DISTANCE, margin: float = 0.5 ) -> None: """ This Online Contrastive loss is similar to :class:`ConstrativeLoss`, but it selects hard positive (positives that are far apart) and hard negative pairs (negatives that are close) and computes the loss only for these pairs. This loss often yields better performances than ContrastiveLoss. Args: model: SentenceTransformer model distance_metric: Function that returns a distance between two embeddings. The class SiameseDistanceMetric contains pre-defined metrics that can be used margin: Negative samples (label == 0) should have a distance of at least the margin value. References: - `Training Examples > Quora Duplicate Questions <../../../examples/sentence_transformer/training/quora_duplicate_questions/README.html>`_ Requirements: 1. (anchor, positive/negative) pairs 2. Data should include hard positives and hard negatives Inputs: +-----------------------------------------------+------------------------------+ | Texts | Labels | +===============================================+==============================+ | (anchor, positive/negative) pairs | 1 if positive, 0 if negative | +-----------------------------------------------+------------------------------+ Relations: - :class:`ContrastiveLoss` is similar, but does not use hard positive and hard negative pairs. :class:`OnlineContrastiveLoss` often yields better results. Example: :: from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses from datasets import Dataset model = SentenceTransformer("microsoft/mpnet-base") 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."], "label": [1, 0], }) loss = losses.OnlineContrastiveLoss(model) trainer = SentenceTransformerTrainer( model=model, train_dataset=train_dataset, loss=loss, ) trainer.train() """ super().__init__() self.model = model self.margin = margin self.distance_metric = distance_metric def forward(self, sentence_features: Iterable[dict[str, Tensor]], labels: Tensor, size_average=False) -> Tensor: embeddings = [self.model(sentence_feature)["sentence_embedding"] for sentence_feature in sentence_features] distance_matrix = self.distance_metric(embeddings[0], embeddings[1]) negs = distance_matrix[labels == 0] poss = distance_matrix[labels == 1] # select hard positive and hard negative pairs negative_pairs = negs[negs < (poss.max() if len(poss) > 1 else negs.mean())] positive_pairs = poss[poss > (negs.min() if len(negs) > 1 else poss.mean())] positive_loss = positive_pairs.pow(2).sum() negative_loss = F.relu(self.margin - negative_pairs).pow(2).sum() loss = positive_loss + negative_loss return loss
from __future__ import annotations from collections.abc import Iterable import torch.nn.functional as F from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from .ContrastiveLoss import SiameseDistanceMetric class OnlineContrastiveLoss(nn.Module): def __init__( self, model: SentenceTransformer, distance_metric=SiameseDistanceMetric.COSINE_DISTANCE, margin: float = 0.5 ) -> None: """ This Online Contrastive loss is similar to :class:`ConstrativeLoss`, but it selects hard positive (positives that are far apart) and hard negative pairs (negatives that are close) and computes the loss only for these pairs. This loss often yields better performances than ContrastiveLoss. Args: model: SentenceTransformer model distance_metric: Function that returns a distance between two embeddings. The class SiameseDistanceMetric contains pre-defined metrics that can be used margin: Negative samples (label == 0) should have a distance of at least the margin value. References: - `Training Examples > Quora Duplicate Questions <../../examples/training/quora_duplicate_questions/README.html>`_ Requirements: 1. (anchor, positive/negative) pairs 2. Data should include hard positives and hard negatives Inputs: +-----------------------------------------------+------------------------------+ | Texts | Labels | +===============================================+==============================+ | (anchor, positive/negative) pairs | 1 if positive, 0 if negative | +-----------------------------------------------+------------------------------+ Relations: - :class:`ContrastiveLoss` is similar, but does not use hard positive and hard negative pairs. :class:`OnlineContrastiveLoss` often yields better results. Example: :: from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses from datasets import Dataset model = SentenceTransformer("microsoft/mpnet-base") 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."], "label": [1, 0], }) loss = losses.OnlineContrastiveLoss(model) trainer = SentenceTransformerTrainer( model=model, train_dataset=train_dataset, loss=loss, ) trainer.train() """ super().__init__() self.model = model self.margin = margin self.distance_metric = distance_metric def forward(self, sentence_features: Iterable[dict[str, Tensor]], labels: Tensor, size_average=False) -> Tensor: embeddings = [self.model(sentence_feature)["sentence_embedding"] for sentence_feature in sentence_features] distance_matrix = self.distance_metric(embeddings[0], embeddings[1]) negs = distance_matrix[labels == 0] poss = distance_matrix[labels == 1] # select hard positive and hard negative pairs negative_pairs = negs[negs < (poss.max() if len(poss) > 1 else negs.mean())] positive_pairs = poss[poss > (negs.min() if len(negs) > 1 else poss.mean())] positive_loss = positive_pairs.pow(2).sum() negative_loss = F.relu(self.margin - negative_pairs).pow(2).sum() loss = positive_loss + negative_loss return loss
from .spacy_text_encoder import SpacyTextEncoder
from .spacy_text_encoder import SpacyTextEncoder
from langchain_cli.namespaces.migrate.generate.utils import PKGS_ROOT def test_root() -> None: if PKGS_ROOT.name != "libs": msg = "Expected PKGS_ROOT.name to be 'libs'." raise ValueError(msg)
from langchain_cli.namespaces.migrate.generate.utils import PKGS_ROOT def test_root() -> None: assert PKGS_ROOT.name == "libs"
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn from sentence_transformers.sparse_encoder.losses.ReconstructionLoss import ReconstructionLoss from sentence_transformers.sparse_encoder.losses.SparseMultipleNegativesRankingLoss import ( SparseMultipleNegativesRankingLoss, ) from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class CSRLoss(nn.Module): """ CSR Loss module that combines Reconstruction Loss and Sparse Multiple Negatives Ranking Loss. Based on the paper: Beyond Matryoshka: Revisiting Sparse Coding for Adaptive Representation, https://arxiv.org/abs/2503.01776 This module computes the combined loss according to the formula: L_CSR = L_recon + γ * L_MRL where: - L_recon = L(k) + L(4k)/8 + β*L_aux - L_MRL is the Multiple Negatives Ranking Loss """ def __init__( self, model: SparseEncoder, beta: float = 0.1, gamma: float = 1.0, scale: float = 20.0, ): super().__init__() self.model = model self.beta = beta self.gamma = gamma self.scale = scale # Initialize the component losses self.reconstruction_loss = ReconstructionLoss(model, beta) self.ranking_loss = SparseMultipleNegativesRankingLoss(model, scale) def forward( self, sentence_features: Iterable[dict[str, torch.Tensor]], labels: torch.Tensor = None, ) -> dict[str, torch.Tensor]: """ Forward pass of the CSR Loss module. This method is used when the loss is computed as part of the model's forward pass. Args: sentence_features: Iterable of dictionaries containing sentence embeddings labels: Optional tensor of labels (not used in this implementation) Returns: Dictionary containing the total loss and individual loss components """ # Compute embeddings using the model outputs = [self.model(sentence_feature) for sentence_feature in sentence_features] sparse_embeddings = [output["sparse_embedding"] for output in outputs] recon_loss = self.reconstruction_loss.compute_loss_from_embeddings(outputs) ranking_loss = self.ranking_loss.compute_loss_from_embeddings(sparse_embeddings) # Compute total loss: L_CSR = L_recon + γ * L_MRL total_loss = recon_loss + self.gamma * ranking_loss return total_loss def get_config_dict(self): """ Get the configuration dictionary. Returns: Dictionary containing the configuration parameters """ return { "beta": self.beta, "gamma": self.gamma, "scale": self.scale, }
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn from sentence_transformers.sparse_encoder.losses.ReconstructionLoss import ReconstructionLoss from sentence_transformers.sparse_encoder.losses.SparseMultipleNegativesRankingLoss import ( SparseMultipleNegativesRankingLoss, ) from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class CSRLoss(nn.Module): """ CSR Loss module that combines Reconstruction Loss and Sparse Multiple Negatives Ranking Loss. This module computes the combined loss according to the formula: L_CSR = L_recon + γ * L_MRL where: - L_recon = L(k) + L(4k)/8 + β*L_aux - L_MRL is the Multiple Negatives Ranking Loss """ def __init__( self, model: SparseEncoder, beta: float = 0.1, gamma: float = 1.0, scale: float = 20.0, ): super().__init__() self.model = model self.beta = beta self.gamma = gamma self.scale = scale # Initialize the component losses self.reconstruction_loss = ReconstructionLoss(model, beta) self.ranking_loss = SparseMultipleNegativesRankingLoss(model, scale) def forward( self, sentence_features: Iterable[dict[str, torch.Tensor]], labels: torch.Tensor = None, ) -> dict[str, torch.Tensor]: """ Forward pass of the CSR Loss module. This method is used when the loss is computed as part of the model's forward pass. Args: sentence_features: Iterable of dictionaries containing sentence embeddings labels: Optional tensor of labels (not used in this implementation) Returns: Dictionary containing the total loss and individual loss components """ # Compute embeddings using the model outputs = [self.model(sentence_feature) for sentence_feature in sentence_features] sparse_embeddings = [output["sparse_embedding"] for output in outputs] recon_loss = self.reconstruction_loss.compute_loss_from_embeddings(outputs) ranking_loss = self.ranking_loss.compute_loss_from_embeddings(sparse_embeddings) # Compute total loss: L_CSR = L_recon + γ * L_MRL total_loss = recon_loss + self.gamma * ranking_loss return total_loss def get_config_dict(self): """ Get the configuration dictionary. Returns: Dictionary containing the configuration parameters """ return { "beta": self.beta, "gamma": self.gamma, "scale": self.scale, }
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( data_preprocessor=dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], bgr_to_rgb=False), backbone=dict( norm_cfg=norm_cfg, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron/resnet50_gn')), neck=dict(norm_cfg=norm_cfg), roi_head=dict( bbox_head=dict( type='Shared4Conv1FCBBoxHead', conv_out_channels=256, norm_cfg=norm_cfg), mask_head=dict(norm_cfg=norm_cfg))) # 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=[16, 22], gamma=0.1) ]
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( backbone=dict( norm_cfg=norm_cfg, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron/resnet50_gn')), neck=dict(norm_cfg=norm_cfg), roi_head=dict( bbox_head=dict( type='Shared4Conv1FCBBoxHead', conv_out_channels=256, norm_cfg=norm_cfg), mask_head=dict(norm_cfg=norm_cfg))) img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline)) # learning policy lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
from urllib.parse import urlparse, urlunparse import pytest from requests_mock import Mocker from llama_index.postprocessor.nvidia_rerank import NVIDIARerank as Interface @pytest.fixture() def mock_v1_local_models2(requests_mock: Mocker, base_url: str) -> None: parsed = urlparse(base_url) normalized_path = parsed.path.rstrip("/") if not normalized_path.endswith("/v1"): normalized_path += "/v1" base_url = urlunparse( (parsed.scheme, parsed.netloc, normalized_path, None, None, None) ) requests_mock.get( f"{base_url}/models", json={ "data": [ { "id": "model1", "object": "model", "created": 1234567890, "owned_by": "OWNER", "root": "model1", }, ] }, ) # test case for invalid base_url @pytest.mark.parametrize( "base_url", [ "http://0.0.0.0:8888/rankings", "http://0.0.0.0:8888/ranking", "http://test_url/.../v1", "https://test_url/.../v1", ], ) def test_base_url_invalid_not_hosted( base_url: str, mock_v1_local_models2: None ) -> None: Interface(base_url=base_url) @pytest.mark.parametrize( "base_url", [ "http://0.0.0.0:8888/v1", ], ) def test_base_url_valid_not_hosted(base_url: str, mock_v1_local_models2: None) -> None: with pytest.warns(UserWarning) as record: Interface(base_url=base_url) assert "Default model is set" in str(record[0].message) @pytest.mark.parametrize( "base_url", ["https://ai.api.nvidia.com/v1"], ) def test_base_url_valid_hosted(base_url: str, mock_v1_local_models2: None) -> None: Interface(base_url=base_url, api_key="BOGUS") @pytest.mark.parametrize( "base_url", [ "bogus", "http:/", "http://", "http:/oops", ], ) def test_param_base_url_negative(base_url: str, monkeypatch) -> None: monkeypatch.setenv("NVIDIA_API_KEY", "valid_api_key") with pytest.raises(ValueError) as e: Interface(model="model1", base_url=base_url) assert "Invalid base_url" in str(e.value) @pytest.mark.parametrize( "base_url", [ "http://host/path0/path1/path2/v1", "http://host:123/path0/path1/path2/v1", ], ) def test_proxy_base_url(base_url: str, mock_v1_local_models2: None) -> None: client = Interface(api_key="NO_API_KEY_PROVIDED", base_url=base_url) assert not client._is_hosted assert base_url.startswith(client.base_url)
from urllib.parse import urlparse, urlunparse import pytest from requests_mock import Mocker from llama_index.postprocessor.nvidia_rerank import NVIDIARerank as Interface @pytest.fixture() def mock_v1_local_models2(requests_mock: Mocker, base_url: str) -> None: result = urlparse(base_url) base_url = urlunparse((result.scheme, result.netloc, "v1", "", "", "")) requests_mock.get( f"{base_url}/models", json={ "data": [ { "id": "model1", "object": "model", "created": 1234567890, "owned_by": "OWNER", "root": "model1", }, ] }, ) # test case for invalid base_url @pytest.mark.parametrize( "base_url", [ "localhost", "localhost:8888", "http://0.0.0.0:8888/rankings", "http://0.0.0.0:8888/ranking", "http://test_url/.../v1", "https://test_url/.../v1", ], ) def test_base_url_invalid_not_hosted( base_url: str, mock_v1_local_models2: None ) -> None: with pytest.raises(ValueError): Interface(base_url=base_url) @pytest.mark.parametrize( "base_url", [ "http://0.0.0.0:8888/v1", ], ) def test_base_url_valid_not_hosted(base_url: str, mock_v1_local_models2: None) -> None: with pytest.warns(UserWarning): Interface(base_url=base_url) @pytest.mark.parametrize( "base_url", ["https://ai.api.nvidia.com/v1"], ) def test_base_url_valid_hosted(base_url: str, mock_v1_local_models2: None) -> None: Interface(base_url=base_url, api_key="BOGUS")
from typing import Dict MISTRALAI_MODELS: Dict[str, int] = { "mistral-tiny": 32000, "mistral-small": 32000, "mistral-medium": 32000, "mistral-large": 131000, "mistral-saba-latest": 32000, "open-mixtral-8x7b": 32000, "open-mistral-7b": 32000, "open-mixtral-8x22b": 64000, "mistral-small-latest": 32000, "mistral-medium-latest": 32000, "mistral-large-latest": 32000, "codestral-latest": 256000, "open-mistral-nemo-latest": 131000, "ministral-8b-latest": 131000, "ministral-3b-latest": 131000, "pixtral-large-latest": 131000, "pixtral-12b-2409": 131000, } MISTRALAI_FUNCTION_CALLING_MODELS = ( "mistral-large-latest", "open-mixtral-8x22b", "ministral-8b-latest", "ministral-3b-latest", "mistral-small-latest", "codestral-latest", "open-mistral-nemo-latest", "pixtral-large-latest", "pixtral-12b-2409", ) MISTRALAI_CODE_MODELS = "codestral-latest" def mistralai_modelname_to_contextsize(modelname: str) -> int: # handling finetuned models if modelname.startswith("ft:"): modelname = modelname.split(":")[1] if modelname not in MISTRALAI_MODELS: raise ValueError( f"Unknown model: {modelname}. Please provide a valid MistralAI model name." "Known models are: " + ", ".join(MISTRALAI_MODELS.keys()) ) return MISTRALAI_MODELS[modelname] def is_mistralai_function_calling_model(modelname: str) -> bool: return modelname in MISTRALAI_FUNCTION_CALLING_MODELS def is_mistralai_code_model(modelname: str) -> bool: return modelname in MISTRALAI_CODE_MODELS
from typing import Dict MISTRALAI_MODELS: Dict[str, int] = { "mistral-tiny": 32000, "mistral-small": 32000, "mistral-medium": 32000, "mistral-large": 131000, "mistral-saba-latest": 32000, "open-mixtral-8x7b": 32000, "open-mistral-7b": 32000, "open-mixtral-8x22b": 64000, "mistral-small-latest": 32000, "mistral-medium-latest": 32000, "mistral-large-latest": 32000, "codestral-latest": 256000, "open-mistral-nemo-latest": 131000, "ministral-8b-latest": 131000, "ministral-3b-latest": 131000, } MISTRALAI_FUNCTION_CALLING_MODELS = ( "mistral-large-latest", "open-mixtral-8x22b", "ministral-8b-latest", "ministral-3b-latest", "mistral-small-latest", "codestral-latest", "open-mistral-nemo-latest", ) MISTRALAI_CODE_MODELS = "codestral-latest" def mistralai_modelname_to_contextsize(modelname: str) -> int: # handling finetuned models if modelname.startswith("ft:"): modelname = modelname.split(":")[1] if modelname not in MISTRALAI_MODELS: raise ValueError( f"Unknown model: {modelname}. Please provide a valid MistralAI model name." "Known models are: " + ", ".join(MISTRALAI_MODELS.keys()) ) return MISTRALAI_MODELS[modelname] def is_mistralai_function_calling_model(modelname: str) -> bool: return modelname in MISTRALAI_FUNCTION_CALLING_MODELS def is_mistralai_code_model(modelname: str) -> bool: return modelname in MISTRALAI_CODE_MODELS
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from pathlib import Path import numpy as np import pytest from jina import Document, DocumentArray, Executor from jina.executors.metas import get_default_metas from jina_commons.indexers.dump import import_vectors from ..annoy_searcher import AnnoySearcher # fix the seed here np.random.seed(500) docs = DocumentArray([Document(embedding=np.random.random(10)) for i in range(10)]) search_doc = DocumentArray([Document(embedding=np.random.random(10))]) DUMP_PATH = 'tests/dump1' TOP_K = 5 @pytest.fixture(scope='function', autouse=True) def metas(tmpdir): os.environ['TEST_WORKSPACE'] = str(tmpdir) metas = get_default_metas() metas['workspace'] = os.environ['TEST_WORKSPACE'] yield metas del os.environ['TEST_WORKSPACE'] def test_config(): ex = Executor.load_config(str(Path(__file__).parents[1] / 'config.yml')) assert ex.metric == 'cosine' def test_simple_annoy(): from annoy import AnnoyIndex _index = AnnoyIndex(5, 'angular') for j in range(3): _index.add_item(j, np.random.random((5,))) _index.build(4) idx1, _ = _index.get_nns_by_vector( np.random.random((5,)), 3, include_distances=True ) assert len(idx1) == 3 @pytest.mark.parametrize( ['metric', 'is_distance'], [ ('cosine', True), ('euclidean', True), ('inner_product', True), ('cosine', False), ('euclidean', False), ('inner_product', False), ], ) def test_metric(tmpdir, metric, is_distance): metas = { 'workspace': str(tmpdir), 'name': 'searcher', } runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, metric=metric, is_distance=is_distance, runtime_args=runtime_args, ) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) assert len(docs[0].matches) == TOP_K for i in range(len(docs[0].matches) - 1): if not is_distance: assert ( docs[0].matches[i].scores[metric].value >= docs[0].matches[i + 1].scores[metric].value ) else: assert ( docs[0].matches[i].scores[metric].value <= docs[0].matches[i + 1].scores[metric].value ) def test_query_vector(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, runtime_args=runtime_args ) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) ids, vecs = import_vectors(DUMP_PATH, str(0)) ids = np.array(list(ids)) vecs = np.array(list(vecs)) assert len(docs) == 1 assert len(docs[0].matches) == TOP_K assert docs[0].matches[0].id in ids assert len(docs[0].matches[0].embedding) == 7 assert docs[0].matches[0].embedding in vecs da = DocumentArray([Document(id=0), Document(id=1), Document(id=2)]) indexer.fill_embedding(da) for i, doc in enumerate(da): assert list(doc.embedding) def test_fill_embeddings(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, runtime_args=runtime_args ) da = DocumentArray([Document(id=0), Document(id=1), Document(id=20)]) indexer.fill_embedding(da) assert da['0'].embedding is not None assert da['1'].embedding is not None assert da['20'].embedding is None def test_query_vector_empty(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher(default_top_k=TOP_K, metas=metas, runtime_args=runtime_args) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) assert len(docs[0].matches) == 0
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from pathlib import Path import numpy as np import pytest from jina import Document, DocumentArray, Executor from jina.executors.metas import get_default_metas from jina_commons.indexers.dump import import_vectors from ..annoy_searcher import AnnoySearcher # fix the seed here np.random.seed(500) docs = DocumentArray([Document(embedding=np.random.random(10)) for i in range(10)]) search_doc = DocumentArray([Document(embedding=np.random.random(10))]) DUMP_PATH = 'tests/dump1' TOP_K = 5 @pytest.fixture(scope='function', autouse=True) def metas(tmpdir): os.environ['TEST_WORKSPACE'] = str(tmpdir) metas = get_default_metas() metas['workspace'] = os.environ['TEST_WORKSPACE'] yield metas del os.environ['TEST_WORKSPACE'] def test_config(): ex = Executor.load_config(str(Path(__file__).parents[1] / 'config.yml')) assert ex.metric == 'euclidean' def test_simple_annoy(): from annoy import AnnoyIndex _index = AnnoyIndex(5, 'angular') for j in range(3): _index.add_item(j, np.random.random((5,))) _index.build(4) idx1, _ = _index.get_nns_by_vector( np.random.random((5,)), 3, include_distances=True ) assert len(idx1) == 3 @pytest.mark.parametrize( ['metric', 'is_distance'], [ ('cosine', True), ('euclidean', True), ('inner_product', True), ('cosine', False), ('euclidean', False), ('inner_product', False), ], ) def test_metric(tmpdir, metric, is_distance): metas = { 'workspace': str(tmpdir), 'name': 'searcher', } runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, metric=metric, is_distance=is_distance, runtime_args=runtime_args, ) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) assert len(docs[0].matches) == TOP_K for i in range(len(docs[0].matches) - 1): if not is_distance: assert ( docs[0].matches[i].scores[metric].value >= docs[0].matches[i + 1].scores[metric].value ) else: assert ( docs[0].matches[i].scores[metric].value <= docs[0].matches[i + 1].scores[metric].value ) def test_query_vector(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, runtime_args=runtime_args ) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) ids, vecs = import_vectors(DUMP_PATH, str(0)) ids = np.array(list(ids)) vecs = np.array(list(vecs)) assert len(docs) == 1 assert len(docs[0].matches) == TOP_K assert docs[0].matches[0].id in ids assert len(docs[0].matches[0].embedding) == 7 assert docs[0].matches[0].embedding in vecs da = DocumentArray([Document(id=0), Document(id=1), Document(id=2)]) indexer.fill_embedding(da) for i, doc in enumerate(da): assert list(doc.embedding) def test_fill_embeddings(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher( dump_path=DUMP_PATH, default_top_k=TOP_K, metas=metas, runtime_args=runtime_args ) da = DocumentArray([Document(id=0), Document(id=1), Document(id=20)]) indexer.fill_embedding(da) assert da['0'].embedding is not None assert da['1'].embedding is not None assert da['20'].embedding is None def test_query_vector_empty(tmpdir): metas = {'workspace': str(tmpdir), 'name': 'searcher'} runtime_args = {'pea_id': 0, 'replica_id': 0} indexer = AnnoySearcher(default_top_k=TOP_K, metas=metas, runtime_args=runtime_args) docs = DocumentArray([Document(embedding=np.random.random(7))]) indexer.search(docs, {}) assert len(docs[0].matches) == 0
from collections.abc import Sequence from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser class SelfAskOutputParser(AgentOutputParser): """Parses self-ask style LLM calls. Expects output to be in one of two formats. If the output signals that an action should be taken, should be in the below format. This will result in an AgentAction being returned. ``` Thoughts go here... Follow up: what is the temperature in SF? ``` If the output signals that a final answer should be given, should be in the below format. This will result in an AgentFinish being returned. ``` Thoughts go here... So the final answer is: The temperature is 100 degrees ``` """ followups: Sequence[str] = ("Follow up:", "Followup:") finish_string: str = "So the final answer is: " def parse(self, text: str) -> Union[AgentAction, AgentFinish]: last_line = text.split("\n")[-1] if not any([follow in last_line for follow in self.followups]): if self.finish_string not in last_line: raise OutputParserException(f"Could not parse output: {text}") return AgentFinish({"output": last_line[len(self.finish_string) :]}, text) after_colon = text.split(":")[-1].strip() return AgentAction("Intermediate Answer", after_colon, text) @property def _type(self) -> str: return "self_ask"
from typing import Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser class SelfAskOutputParser(AgentOutputParser): """Parses self-ask style LLM calls. Expects output to be in one of two formats. If the output signals that an action should be taken, should be in the below format. This will result in an AgentAction being returned. ``` Thoughts go here... Follow up: what is the temperature in SF? ``` If the output signals that a final answer should be given, should be in the below format. This will result in an AgentFinish being returned. ``` Thoughts go here... So the final answer is: The temperature is 100 degrees ``` """ followups: Sequence[str] = ("Follow up:", "Followup:") finish_string: str = "So the final answer is: " def parse(self, text: str) -> Union[AgentAction, AgentFinish]: last_line = text.split("\n")[-1] if not any([follow in last_line for follow in self.followups]): if self.finish_string not in last_line: raise OutputParserException(f"Could not parse output: {text}") return AgentFinish({"output": last_line[len(self.finish_string) :]}, text) after_colon = text.split(":")[-1].strip() return AgentAction("Intermediate Answer", after_colon, text) @property def _type(self) -> str: return "self_ask"
import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import AnyUrl @pytest.mark.proto def test_proto_any_url(): uri = parse_obj_as(AnyUrl, 'http://jina.ai/img.png') uri._to_node_protobuf() def test_json_schema(): schema_json_of(AnyUrl) def test_dump_json(): url = parse_obj_as(AnyUrl, 'http://jina.ai/img.png') orjson_dumps(url) @pytest.mark.parametrize( 'relative_path', [ 'data/05978.jpg', '../../data/05978.jpg', ], ) def test_relative_path(relative_path): # see issue: https://github.com/docarray/docarray/issues/978 url = parse_obj_as(AnyUrl, relative_path) assert url == relative_path def test_operators(): url = parse_obj_as(AnyUrl, 'data/05978.jpg') assert url == 'data/05978.jpg' assert url != 'aljdñjd' assert 'data' in url assert 'docarray' not in url
import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import AnyUrl @pytest.mark.proto def test_proto_any_url(): uri = parse_obj_as(AnyUrl, 'http://jina.ai/img.png') uri._to_node_protobuf() def test_json_schema(): schema_json_of(AnyUrl) def test_dump_json(): url = parse_obj_as(AnyUrl, 'http://jina.ai/img.png') orjson_dumps(url) def test_relative_path(): # see issue: https://github.com/docarray/docarray/issues/978 url = parse_obj_as(AnyUrl, 'data/05978.jpg') assert url == 'data/05978.jpg' def test_operators(): url = parse_obj_as(AnyUrl, 'data/05978.jpg') assert url == 'data/05978.jpg' assert url != 'aljdñjd' assert 'data' in url assert 'docarray' not in url
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files", [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ], ) def test_from_dir(files, tmp_path_factory): dataset_infos_dir = tmp_path_factory.mktemp("dset_infos_dir") if "full:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("---\ndataset_info:\n dataset_size: 42\n---") if "empty:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("") # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json", "w") as f: f.write('{"default": {"dataset_size": 42}}') dataset_infos = DatasetInfosDict.from_directory(dataset_infos_dir) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info", [ DatasetInfo(), DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ), ], ) def test_dataset_info_dump_and_reload(tmp_path, dataset_info: DatasetInfo): tmp_path = str(tmp_path) dataset_info.write_to_directory(tmp_path) reloaded = DatasetInfo.from_directory(tmp_path) assert dataset_info == reloaded assert os.path.exists(os.path.join(tmp_path, "dataset_info.json")) def test_dataset_info_to_yaml_dict(): dataset_info = DatasetInfo( description="foo", citation="bar", homepage="https://foo.bar", license="CC0", features=Features({"a": Value("int32")}), post_processed={}, supervised_keys=(), task_templates=[], builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train", "num_examples": 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, ) dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert sorted(dataset_info_yaml_dict) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str)) dataset_info_yaml = yaml.safe_dump(dataset_info_yaml_dict) reloaded = yaml.safe_load(dataset_info_yaml) assert dataset_info_yaml_dict == reloaded def test_dataset_info_to_yaml_dict_empty(): dataset_info = DatasetInfo() dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict", [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()}), DatasetInfosDict({"my_config_name": DatasetInfo()}), DatasetInfosDict( { "default": DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42), "v2": DatasetInfo(dataset_size=1337), } ), ], ) def test_dataset_infos_dict_dump_and_reload(tmp_path, dataset_infos_dict: DatasetInfosDict): tmp_path = str(tmp_path) dataset_infos_dict.write_to_directory(tmp_path) reloaded = DatasetInfosDict.from_directory(tmp_path) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): dataset_info.config_name = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml dataset_infos_dict[config_name] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(tmp_path, "README.md"))
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files", [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ], ) def test_from_dir(files, tmp_path_factory): dataset_infos_dir = tmp_path_factory.mktemp("dset_infos_dir") if "full:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("---\ndataset_info:\n dataset_size: 42\n---") if "empty:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("") # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json", "w") as f: f.write('{"default": {"dataset_size": 42}}') dataset_infos = DatasetInfosDict.from_directory(dataset_infos_dir) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info", [ DatasetInfo(), DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ), ], ) def test_dataset_info_dump_and_reload(tmp_path, dataset_info: DatasetInfo): tmp_path = str(tmp_path) dataset_info.write_to_directory(tmp_path) reloaded = DatasetInfo.from_directory(tmp_path) assert dataset_info == reloaded assert os.path.exists(os.path.join(tmp_path, "dataset_info.json")) def test_dataset_info_to_yaml_dict(): dataset_info = DatasetInfo( description="foo", citation="bar", homepage="https://foo.bar", license="CC0", features=Features({"a": Value("int32")}), post_processed={}, supervised_keys=tuple(), task_templates=[], builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train", "num_examples": 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, ) dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert sorted(dataset_info_yaml_dict) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str)) dataset_info_yaml = yaml.safe_dump(dataset_info_yaml_dict) reloaded = yaml.safe_load(dataset_info_yaml) assert dataset_info_yaml_dict == reloaded def test_dataset_info_to_yaml_dict_empty(): dataset_info = DatasetInfo() dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict", [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()}), DatasetInfosDict({"my_config_name": DatasetInfo()}), DatasetInfosDict( { "default": DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42), "v2": DatasetInfo(dataset_size=1337), } ), ], ) def test_dataset_infos_dict_dump_and_reload(tmp_path, dataset_infos_dict: DatasetInfosDict): tmp_path = str(tmp_path) dataset_infos_dict.write_to_directory(tmp_path) reloaded = DatasetInfosDict.from_directory(tmp_path) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): dataset_info.config_name = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml dataset_infos_dict[config_name] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(tmp_path, "README.md"))
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess import pytest from executor.audioclip_text import AudioCLIPTextEncoder from jina import Document, DocumentArray, Flow _EMBEDDING_DIM = 1024 @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=AudioCLIPTextEncoder) 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 subprocess import pytest from jina import Document, DocumentArray, Flow from ...audioclip_text import AudioCLIPTextEncoder _EMBEDDING_DIM = 1024 @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=AudioCLIPTextEncoder) 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, )
"""!!!DO NOT USE!!! Distribution related class for Tensorflow backend. This is just a prototype and we might want to unify it with other backends in the future. """ import tensorflow as tf from tensorflow.experimental import dtensor def list_devices(device_type=None): """Return all the available devices based on the device type. Note that this should return the global devices in a distributed setting. Args: device_type: string of `"cpu"`, `"gpu"` or `"tpu"`. Default to `gpu` or `tpu` if available when device_type is not provided. Otherwise will return the `cpu` devices. Return: List of devices that are available for distribute computation. """ device_type = device_type.upper() if device_type else None # DTensor doesn't support getting global devices, even when knowing the # Mesh. Use TF API instead to get global devices. Coordinator service is # enabled by default with DTensor, so that list_logical_devices() returns # a list of global devices. More context can be found in b/254911601. tf_devices = tf.config.list_logical_devices(device_type=device_type) cpu_devices = [] other_devices = [] for device in tf_devices: if device.device_type.lower() == "cpu": cpu_devices.append(device) else: other_devices.append(device) if device_type is None: tf_devices = other_devices if len(other_devices) > 0 else cpu_devices return [ f"{device.device_type.lower()}:{device.name.split(':')[-1]}" for device in tf_devices ] def distribute_value(value, tensor_layout): # TODO pass def _to_backend_mesh(device_mesh): """Convert the DeviceMesh to Tensorflow backend specific Mesh. Args: device_mesh: DeviceMesh instance to convert. Returns: A `tf.dtensor.Mesh` instance. """ mesh_dims = list(zip(device_mesh.axis_names, device_mesh.shape)) return dtensor.create_distributed_mesh( mesh_dims=mesh_dims, local_devices=device_mesh.devices.flatten() ) def _to_backend_layout(tensor_layout): """Convert the TensorLayout to Tensorflow backend specific Sharding. Args: tensor_layout: TensorLayout instance to convert. Returns: A `tf.dtensor.Layout` instance. """ if tensor_layout.device_mesh is None: raise ValueError( "Cannot create sharding when device mesh is not set for " "TensorLayout." ) sharding_specs = [ axis if axis else dtensor.UNSHARDED for axis in tensor_layout.axes ] dtensor_mesh = tensor_layout.device_mesh.backend_mesh return dtensor.Layout(sharding_specs=sharding_specs, mesh=dtensor_mesh)
"""!!!DO NOT USE!!! Distribution related class for Tensorflow backend. This is just a prototype and we might want to unify it with other backends in the future. """ import tensorflow as tf from tensorflow.experimental import dtensor def list_devices(device_type=None): """Return all the available devices based on the device type. Note that this should return the global devices in a distributed setting. Args: device_type: string of `"cpu"`, `"gpu"` or `"tpu"`. Default to `gpu` or `tpu` if available when device_type is not provided. Otherwise will return the `cpu` devices. Return: List of devices that are available for distribute computation. """ device_type = device_type.upper() if device_type else None # DTensor doesn't support getting global devices, even when knowing the # Mesh. Use TF API instead to get global devices. Coordinator service is # enabled by default with DTensor, so that list_logical_devices() returns # a list of global devices. More context can be found in b/254911601. tf_devices = tf.config.list_logical_devices(device_type=device_type) cpu_devices = [] other_devices = [] for device in tf_devices: if device.device_type.lower() == "cpu": cpu_devices.append(device) else: other_devices.append(device) if device_type is None: tf_devices = other_devices if len(other_devices) > 0 else cpu_devices return [ f"{device.device_type.lower()}:{device.name.split(':')[-1]}" for device in tf_devices ] def distribute_value(value, tensor_layout): # TODO pass def _to_dtensor_mesh(device_mesh): """Convert the DeviceMesh to Tensorflow backend specific Mesh. Args: device_mesh: DeviceMesh instance to convert. Returns: A `tf.dtensor.Mesh` instance. """ mesh_dims = list(zip(device_mesh.axis_names, device_mesh.shape)) return dtensor.create_distributed_mesh( mesh_dims=mesh_dims, local_devices=device_mesh.devices.flatten() ) def _to_dtensor_layout(tensor_layout): """Convert the TensorLayout to Tensorflow backend specific Sharding. Args: tensor_layout: TensorLayout instance to convert. Returns: A `tf.dtensor.Layout` instance. """ if tensor_layout.device_mesh is None: raise ValueError( "Cannot create sharding when device mesh is not set for " "TensorLayout." ) sharding_specs = [ axis if axis else dtensor.UNSHARDED for axis in tensor_layout.axes ] dtensor_mesh = _to_dtensor_mesh(tensor_layout.device_mesh) return dtensor.Layout(sharding_specs=sharding_specs, mesh=dtensor_mesh)
# Copyright (c) OpenMMLab. All rights reserved. import torch.utils.checkpoint as cp from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from .se_layer import SELayer class InvertedResidual(BaseModule): """Inverted Residual Block. Args: in_channels (int): The input channels of this Module. out_channels (int): The output channels of this Module. mid_channels (int): The input channels of the depthwise convolution. kernel_size (int): The kernel size of the depthwise convolution. Default: 3. stride (int): The stride of the depthwise convolution. Default: 1. se_cfg (dict): Config dict for se layer. Default: None, which means no se layer. with_expand_conv (bool): Use expand conv or not. If set False, mid_channels must be the same with in_channels. Default: True. conv_cfg (dict): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='BN'). act_cfg (dict): Config dict for activation layer. Default: dict(type='ReLU'). with_cp (bool): Use checkpoint or not. Using checkpoint will save some memory while slowing down the training speed. Default: False. init_cfg (dict or list[dict], optional): Initialization config dict. Default: None Returns: Tensor: The output tensor. """ def __init__(self, in_channels, out_channels, mid_channels, kernel_size=3, stride=1, se_cfg=None, with_expand_conv=True, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), with_cp=False, init_cfg=None): super(InvertedResidual, self).__init__(init_cfg) self.with_res_shortcut = (stride == 1 and in_channels == out_channels) assert stride in [1, 2], f'stride must in [1, 2]. ' \ f'But received {stride}.' self.with_cp = with_cp self.with_se = se_cfg is not None self.with_expand_conv = with_expand_conv if self.with_se: assert isinstance(se_cfg, dict) if not self.with_expand_conv: assert mid_channels == in_channels if self.with_expand_conv: self.expand_conv = ConvModule( in_channels=in_channels, out_channels=mid_channels, kernel_size=1, stride=1, padding=0, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.depthwise_conv = ConvModule( in_channels=mid_channels, out_channels=mid_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=mid_channels, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) if self.with_se: self.se = SELayer(**se_cfg) self.linear_conv = ConvModule( in_channels=mid_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=None) def forward(self, x): def _inner_forward(x): out = x if self.with_expand_conv: out = self.expand_conv(out) out = self.depthwise_conv(out) if self.with_se: out = self.se(out) out = self.linear_conv(out) if self.with_res_shortcut: return x + out else: return out if self.with_cp and x.requires_grad: out = cp.checkpoint(_inner_forward, x) else: out = _inner_forward(x) return out
# Copyright (c) OpenMMLab. All rights reserved. import torch.utils.checkpoint as cp from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from .se_layer import SELayer class InvertedResidual(BaseModule): """Inverted Residual Block. Args: in_channels (int): The input channels of this Module. out_channels (int): The output channels of this Module. mid_channels (int): The input channels of the depthwise convolution. kernel_size (int): The kernal size of the depthwise convolution. Default: 3. stride (int): The stride of the depthwise convolution. Default: 1. se_cfg (dict): Config dict for se layer. Defaul: None, which means no se layer. with_expand_conv (bool): Use expand conv or not. If set False, mid_channels must be the same with in_channels. Default: True. conv_cfg (dict): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='BN'). act_cfg (dict): Config dict for activation layer. Default: dict(type='ReLU'). with_cp (bool): Use checkpoint or not. Using checkpoint will save some memory while slowing down the training speed. Default: False. init_cfg (dict or list[dict], optional): Initialization config dict. Default: None Returns: Tensor: The output tensor. """ def __init__(self, in_channels, out_channels, mid_channels, kernel_size=3, stride=1, se_cfg=None, with_expand_conv=True, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), with_cp=False, init_cfg=None): super(InvertedResidual, self).__init__(init_cfg) self.with_res_shortcut = (stride == 1 and in_channels == out_channels) assert stride in [1, 2], f'stride must in [1, 2]. ' \ f'But received {stride}.' self.with_cp = with_cp self.with_se = se_cfg is not None self.with_expand_conv = with_expand_conv if self.with_se: assert isinstance(se_cfg, dict) if not self.with_expand_conv: assert mid_channels == in_channels if self.with_expand_conv: self.expand_conv = ConvModule( in_channels=in_channels, out_channels=mid_channels, kernel_size=1, stride=1, padding=0, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.depthwise_conv = ConvModule( in_channels=mid_channels, out_channels=mid_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=mid_channels, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) if self.with_se: self.se = SELayer(**se_cfg) self.linear_conv = ConvModule( in_channels=mid_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=None) def forward(self, x): def _inner_forward(x): out = x if self.with_expand_conv: out = self.expand_conv(out) out = self.depthwise_conv(out) if self.with_se: out = self.se(out) out = self.linear_conv(out) if self.with_res_shortcut: return x + out else: return out if self.with_cp and x.requires_grad: out = cp.checkpoint(_inner_forward, x) else: out = _inner_forward(x) return out
from abc import abstractmethod from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, TypeVar, Union from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore from qdrant_client.http import models as rest from qdrant_client.http.models.models import Distance if TYPE_CHECKING: # pragma: no cover import numpy as np import tensorflow import torch from qdrant_client import QdrantClient QdrantArrayType = TypeVar( 'QdrantArrayType', np.ndarray, tensorflow.Tensor, torch.Tensor, Sequence[float], ) class FindMixin: @property @abstractmethod def client(self) -> 'QdrantClient': raise NotImplementedError() @property @abstractmethod def collection_name(self) -> str: raise NotImplementedError() @property @abstractmethod def serialize_config(self) -> dict: raise NotImplementedError() @property @abstractmethod def distance(self) -> 'Distance': raise NotImplementedError() def _find_similar_vectors( self, q: 'QdrantArrayType', limit: int = 10, filter: Optional[Dict] = None, search_params: Optional[Dict] = None, **kwargs, ): query_vector = self._map_embedding(q) search_result = self.client.search( self.collection_name, query_vector=query_vector, query_filter=filter, search_params=None if not search_params else rest.SearchParams(**search_params), top=limit, append_payload=['_serialized'], ) docs = [] for hit in search_result: doc = Document.from_base64( hit.payload['_serialized'], **self.serialize_config ) doc.scores[f'{self.distance.lower()}_similarity'] = NamedScore( value=hit.score ) docs.append(doc) return DocumentArray(docs) def _find( self, query: 'QdrantArrayType', limit: int = 10, filter: Optional[Dict] = None, search_params: Optional[Dict] = None, **kwargs, ) -> List['DocumentArray']: """Returns approximate nearest neighbors given a batch of input queries. :param query: input supported to be used in Qdrant. :param limit: number of retrieved items :param filter: filter query used for pre-filtering :param search_params: additional parameters of the search :return: a list of DocumentArrays containing the closest Document objects for each of the queries in `query`. """ num_rows, _ = ndarray.get_array_rows(query) if num_rows == 1: return [ self._find_similar_vectors( query, limit=limit, filter=filter, search_params=search_params ) ] else: closest_docs = [] for q in query: da = self._find_similar_vectors( q, limit=limit, filter=filter, search_params=search_params ) closest_docs.append(da) return closest_docs def _find_with_filter( self, filter: Optional[Dict], limit: Optional[Union[int, float]] = 10 ): list_of_points, _offset = self.client.scroll( collection_name=self.collection_name, scroll_filter=filter, with_payload=True, limit=limit, ) da = DocumentArray() for result in list_of_points[:limit]: doc = Document.from_base64( result.payload['_serialized'], **self.serialize_config ) da.append(doc) return da def _filter( self, filter: Optional[Dict], limit: Optional[Union[int, float]] = 10 ) -> 'DocumentArray': """Returns a subset of documents by filtering by the given filter (`Qdrant` filter).. :param limit: number of retrieved items :param filter: filter query used for filtering. For more information: https://docarray.jina.ai/advanced/document-store/qdrant/#qdrant :return: a `DocumentArray` containing the `Document` objects that verify the filter. """ return self._find_with_filter(filter, limit=limit)
from abc import abstractmethod from typing import ( TYPE_CHECKING, TypeVar, Sequence, List, Union, Optional, Dict, ) from qdrant_client.http.models.models import Distance from docarray import Document, DocumentArray from docarray.math import ndarray from docarray.score import NamedScore if TYPE_CHECKING: # pragma: no cover import tensorflow import torch import numpy as np from qdrant_client import QdrantClient QdrantArrayType = TypeVar( 'QdrantArrayType', np.ndarray, tensorflow.Tensor, torch.Tensor, Sequence[float], ) class FindMixin: @property @abstractmethod def client(self) -> 'QdrantClient': raise NotImplementedError() @property @abstractmethod def collection_name(self) -> str: raise NotImplementedError() @property @abstractmethod def serialize_config(self) -> dict: raise NotImplementedError() @property @abstractmethod def distance(self) -> 'Distance': raise NotImplementedError() def _find_similar_vectors( self, q: 'QdrantArrayType', limit: int = 10, filter: Optional[Dict] = None ): query_vector = self._map_embedding(q) search_result = self.client.search( self.collection_name, query_vector=query_vector, query_filter=filter, search_params=None, top=limit, append_payload=['_serialized'], ) docs = [] for hit in search_result: doc = Document.from_base64( hit.payload['_serialized'], **self.serialize_config ) doc.scores[f'{self.distance.lower()}_similarity'] = NamedScore( value=hit.score ) docs.append(doc) return DocumentArray(docs) def _find( self, query: 'QdrantArrayType', limit: int = 10, filter: Optional[Dict] = None, **kwargs, ) -> List['DocumentArray']: """Returns approximate nearest neighbors given a batch of input queries. :param query: input supported to be used in Qdrant. :param limit: number of retrieved items :param filter: filter query used for pre-filtering :return: a list of DocumentArrays containing the closest Document objects for each of the queries in `query`. """ num_rows, _ = ndarray.get_array_rows(query) if num_rows == 1: return [self._find_similar_vectors(query, limit=limit, filter=filter)] else: closest_docs = [] for q in query: da = self._find_similar_vectors(q, limit=limit, filter=filter) closest_docs.append(da) return closest_docs def _find_with_filter( self, filter: Optional[Dict], limit: Optional[Union[int, float]] = 10 ): list_of_points, _offset = self.client.scroll( collection_name=self.collection_name, scroll_filter=filter, with_payload=True, limit=limit, ) da = DocumentArray() for result in list_of_points[:limit]: doc = Document.from_base64( result.payload['_serialized'], **self.serialize_config ) da.append(doc) return da def _filter( self, filter: Optional[Dict], limit: Optional[Union[int, float]] = 10 ) -> 'DocumentArray': """Returns a subset of documents by filtering by the given filter (`Qdrant` filter).. :param limit: number of retrieved items :param filter: filter query used for filtering. For more information: https://docarray.jina.ai/advanced/document-store/qdrant/#qdrant :return: a `DocumentArray` containing the `Document` objects that verify the filter. """ return self._find_with_filter(filter, limit=limit)
from typing import TYPE_CHECKING from .github import GithubWebhooksManager from .slant3d import Slant3DWebhooksManager if TYPE_CHECKING: from .base import BaseWebhooksManager # --8<-- [start:WEBHOOK_MANAGERS_BY_NAME] WEBHOOK_MANAGERS_BY_NAME: dict[str, type["BaseWebhooksManager"]] = { handler.PROVIDER_NAME: handler for handler in [ GithubWebhooksManager, Slant3DWebhooksManager, ] } # --8<-- [end:WEBHOOK_MANAGERS_BY_NAME] __all__ = ["WEBHOOK_MANAGERS_BY_NAME"]
from typing import TYPE_CHECKING from .github import GithubWebhooksManager if TYPE_CHECKING: from .base import BaseWebhooksManager # --8<-- [start:WEBHOOK_MANAGERS_BY_NAME] WEBHOOK_MANAGERS_BY_NAME: dict[str, type["BaseWebhooksManager"]] = { handler.PROVIDER_NAME: handler for handler in [ GithubWebhooksManager, ] } # --8<-- [end:WEBHOOK_MANAGERS_BY_NAME] __all__ = ["WEBHOOK_MANAGERS_BY_NAME"]
from __future__ import annotations from typing import Any, Optional, Union import torch from ._datapoint import Datapoint class Video(Datapoint): """[BETA] :class:`torch.Tensor` subclass for videos. Args: data (tensor-like): Any data that can be turned into a tensor with :func:`torch.as_tensor`. dtype (torch.dtype, optional): Desired data type of the bounding box. If omitted, will be inferred from ``data``. device (torch.device, optional): Desired device of the bounding box. If omitted and ``data`` is a :class:`torch.Tensor`, the device is taken from it. Otherwise, the bounding box is constructed on the CPU. requires_grad (bool, optional): Whether autograd should record operations on the bounding box. If omitted and ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. """ def __new__( cls, data: Any, *, dtype: Optional[torch.dtype] = None, device: Optional[Union[torch.device, str, int]] = None, requires_grad: Optional[bool] = None, ) -> Video: tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) if data.ndim < 4: raise ValueError return cls._wrap(tensor) def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] return self._make_repr() _VideoType = Union[torch.Tensor, Video] _VideoTypeJIT = torch.Tensor _TensorVideoType = Union[torch.Tensor, Video] _TensorVideoTypeJIT = torch.Tensor
from __future__ import annotations from typing import Any, Optional, Union import torch from ._datapoint import Datapoint class Video(Datapoint): """[BETA] :class:`torch.Tensor` subclass for videos. Args: data (tensor-like): Any data that can be turned into a tensor with :func:`torch.as_tensor`. dtype (torch.dtype, optional): Desired data type of the bounding box. If omitted, will be inferred from ``data``. device (torch.device, optional): Desired device of the bounding box. If omitted and ``data`` is a :class:`torch.Tensor`, the device is taken from it. Otherwise, the bounding box is constructed on the CPU. requires_grad (bool, optional): Whether autograd should record operations on the bounding box. If omitted and ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. """ @classmethod def _wrap(cls, tensor: torch.Tensor) -> Video: video = tensor.as_subclass(cls) return video def __new__( cls, data: Any, *, dtype: Optional[torch.dtype] = None, device: Optional[Union[torch.device, str, int]] = None, requires_grad: Optional[bool] = None, ) -> Video: tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) if data.ndim < 4: raise ValueError return cls._wrap(tensor) @classmethod def wrap_like(cls, other: Video, tensor: torch.Tensor) -> Video: return cls._wrap(tensor) def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] return self._make_repr() _VideoType = Union[torch.Tensor, Video] _VideoTypeJIT = torch.Tensor _TensorVideoType = Union[torch.Tensor, Video] _TensorVideoTypeJIT = torch.Tensor
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It generates sentence embeddings that can be compared using cosine-similarity to measure the similarity. Usage: python training_nli.py OR python training_nli.py pretrained_transformer_model_name """ from torch.utils.data import DataLoader import math from sentence_transformers import SentenceTransformer, LoggingHandler, losses, models, util from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator from sentence_transformers.readers import InputExample import logging from datetime import datetime import sys import os import gzip import csv #### Just some code to print debug information to stdout logging.basicConfig( format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[LoggingHandler()] ) #### /print debug information to stdout # Check if dataset exists. If not, download and extract it sts_dataset_path = "datasets/stsbenchmark.tsv.gz" if not os.path.exists(sts_dataset_path): util.http_get("https://sbert.net/datasets/stsbenchmark.tsv.gz", sts_dataset_path) # You can specify any huggingface/transformers pre-trained model here, for example, bert-base-uncased, roberta-base, xlm-roberta-base model_name = sys.argv[1] if len(sys.argv) > 1 else "distilbert-base-uncased" # Read the dataset train_batch_size = 16 num_epochs = 4 model_save_path = ( "output/training_stsbenchmark_" + model_name.replace("/", "-") + "-" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") ) # Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings word_embedding_model = models.Transformer(model_name) # Apply mean pooling to get one fixed sized sentence vector pooling_model = models.Pooling( word_embedding_model.get_word_embedding_dimension(), pooling_mode_mean_tokens=True, pooling_mode_cls_token=False, pooling_mode_max_tokens=False, ) model = SentenceTransformer(modules=[word_embedding_model, pooling_model]) # Convert the dataset to a DataLoader ready for training logging.info("Read STSbenchmark train dataset") train_samples = [] dev_samples = [] test_samples = [] with gzip.open(sts_dataset_path, "rt", encoding="utf8") as fIn: reader = csv.DictReader(fIn, delimiter="\t", quoting=csv.QUOTE_NONE) for row in reader: score = float(row["score"]) / 5.0 # Normalize score to range 0 ... 1 inp_example = InputExample(texts=[row["sentence1"], row["sentence2"]], label=score) if row["split"] == "dev": dev_samples.append(inp_example) elif row["split"] == "test": test_samples.append(inp_example) else: train_samples.append(inp_example) train_dataloader = DataLoader(train_samples, shuffle=True, batch_size=train_batch_size) train_loss = losses.CosineSimilarityLoss(model=model) logging.info("Read STSbenchmark dev dataset") evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name="sts-dev") # Configure the training. We skip evaluation in this example warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) # 10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the model model.fit( train_objectives=[(train_dataloader, train_loss)], evaluator=evaluator, epochs=num_epochs, evaluation_steps=1000, warmup_steps=warmup_steps, output_path=model_save_path, ) ############################################################################## # # Load the stored model and evaluate its performance on STS benchmark dataset # ############################################################################## model = SentenceTransformer(model_save_path) test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name="sts-test") test_evaluator(model, output_path=model_save_path)
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It generates sentence embeddings that can be compared using cosine-similarity to measure the similarity. Usage: python training_nli.py OR python training_nli.py pretrained_transformer_model_name """ from torch.utils.data import DataLoader import math from sentence_transformers import SentenceTransformer, LoggingHandler, losses, models, util from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator from sentence_transformers.readers import InputExample import logging from datetime import datetime import sys import os import gzip import csv #### Just some code to print debug information to stdout logging.basicConfig( format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[LoggingHandler()] ) #### /print debug information to stdout # Check if dataset exists. If not, download and extract it sts_dataset_path = "datasets/stsbenchmark.tsv.gz" if not os.path.exists(sts_dataset_path): util.http_get("https://sbert.net/datasets/stsbenchmark.tsv.gz", sts_dataset_path) # You can specify any huggingface/transformers pre-trained model here, for example, bert-base-uncased, roberta-base, xlm-roberta-base model_name = sys.argv[1] if len(sys.argv) > 1 else "distilbert-base-uncased" # Read the dataset train_batch_size = 16 num_epochs = 4 model_save_path = ( "output/training_stsbenchmark_" + model_name.replace("/", "-") + "-" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") ) # Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings word_embedding_model = models.Transformer(model_name) # Apply mean pooling to get one fixed sized sentence vector pooling_model = models.Pooling( word_embedding_model.get_word_embedding_dimension(), pooling_mode_mean_tokens=True, pooling_mode_cls_token=False, pooling_mode_max_tokens=False, ) model = SentenceTransformer(modules=[word_embedding_model, pooling_model]) # Convert the dataset to a DataLoader ready for training logging.info("Read STSbenchmark train dataset") train_samples = [] dev_samples = [] test_samples = [] with gzip.open(sts_dataset_path, "rt", encoding="utf8") as fIn: reader = csv.DictReader(fIn, delimiter="\t", quoting=csv.QUOTE_NONE) for row in reader: score = float(row["score"]) / 5.0 # Normalize score to range 0 ... 1 inp_example = InputExample(texts=[row["sentence1"], row["sentence2"]], label=score) if row["split"] == "dev": dev_samples.append(inp_example) elif row["split"] == "test": test_samples.append(inp_example) else: train_samples.append(inp_example) train_dataloader = DataLoader(train_samples, shuffle=True, batch_size=train_batch_size) train_loss = losses.CosineSimilarityLoss(model=model) logging.info("Read STSbenchmark dev dataset") evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name="sts-dev") # Configure the training. We skip evaluation in this example warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) # 10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the model model.fit( train_objectives=[(train_dataloader, train_loss)], evaluator=evaluator, epochs=num_epochs, evaluation_steps=1000, warmup_steps=warmup_steps, output_path=model_save_path, ) ############################################################################## # # Load the stored model and evaluate its performance on STS benchmark dataset # ############################################################################## model = SentenceTransformer(model_save_path) test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name="sts-test") test_evaluator(model, output_path=model_save_path)
"""langchain-core version information and utilities.""" VERSION = "0.3.67"
"""langchain-core version information and utilities.""" VERSION = "0.3.66"
import itertools import numpy as np from absl.testing import parameterized from torch.utils.data import Dataset as TorchDataset from keras.src.testing import test_case from keras.src.testing.test_utils import named_product from keras.src.utils.dataset_utils import split_dataset from keras.src.utils.module_utils import tensorflow as tf class MyTorchDataset(TorchDataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.x) def __getitem__(self, index): return self.x[index], self.y[index] class DatasetUtilsTest(test_case.TestCase): @parameterized.named_parameters( named_product( dataset_type=["list", "tuple", "tensorflow", "torch"], features_shape=[(2,), (100, 2), (10, 10, 2)], ) ) def test_split_dataset(self, dataset_type, features_shape): n_sample, left_size, right_size = 100, 0.2, 0.8 features = np.random.sample((n_sample,) + features_shape) labels = np.random.sample((n_sample, 1)) if dataset_type == "list": dataset = [features, labels] elif dataset_type == "tuple": dataset = (features, labels) elif dataset_type == "tensorflow": dataset = tf.data.Dataset.from_tensor_slices((features, labels)) elif dataset_type == "torch": dataset = MyTorchDataset(features, labels) dataset_left, dataset_right = split_dataset( dataset, left_size=left_size, right_size=right_size ) self.assertEqual( int(dataset_left.cardinality()), int(n_sample * left_size) ) self.assertEqual( int(dataset_right.cardinality()), int(n_sample * right_size) ) for sample in itertools.chain(dataset_left, dataset_right): self.assertEqual(sample[0].shape, features_shape) self.assertEqual(sample[1].shape, (1,)) @parameterized.named_parameters( named_product(structure_type=["dict", "tuple"]) ) def test_split_dataset_nested_structures(self, structure_type): n_sample, left_size, right_size = 100, 0.2, 0.8 features1 = np.random.sample((n_sample, 2)) features2 = np.random.sample((n_sample, 10, 2)) labels = np.random.sample((n_sample, 1)) if structure_type == "dict": dataset = tf.data.Dataset.from_tensor_slices( {"x1": features1, "x2": features2, "labels": labels} ) elif structure_type == "tuple": dataset = tf.data.Dataset.from_tensor_slices( ((features1, features2), labels) ) dataset_left, dataset_right = split_dataset( dataset, left_size=left_size, right_size=right_size ) self.assertEqual( int(dataset_left.cardinality()), int(n_sample * left_size) ) self.assertEqual( int(dataset_right.cardinality()), int(n_sample * right_size) ) for sample in itertools.chain(dataset_left, dataset_right): if structure_type == "dict": x1, x2, labels = sample["x1"], sample["x2"], sample["labels"] elif structure_type == "tuple": (x1, x2), labels = sample self.assertEqual(x1.shape, (2,)) self.assertEqual(x2.shape, (10, 2)) self.assertEqual(labels.shape, (1,))
import itertools import numpy as np from absl.testing import parameterized from torch.utils.data import Dataset as TorchDataset from keras.src.testing import test_case from keras.src.testing.test_utils import named_product from keras.src.utils.dataset_utils import split_dataset from keras.src.utils.module_utils import tensorflow as tf class MyTorchDataset(TorchDataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.x) def __getitem__(self, index): return self.x[index], self.y[index] class DatasetUtilsTest(test_case.TestCase): @parameterized.named_parameters( named_product( dataset_type=["list", "tuple", "tensorflow", "torch"], features_shape=[(2,), (100, 2), (10, 10, 2)], ) ) def test_split_dataset(self, dataset_type, features_shape): n_sample, left_size, right_size = 100, 0.2, 0.8 features = np.random.sample((n_sample,) + features_shape) labels = np.random.sample((n_sample, 1)) if dataset_type == "list": dataset = [features, labels] elif dataset_type == "tuple": dataset = (features, labels) elif dataset_type == "tensorflow": dataset = tf.data.Dataset.from_tensor_slices((features, labels)) elif dataset_type == "torch": dataset = MyTorchDataset(features, labels) dataset_left, dataset_right = split_dataset( dataset, left_size=left_size, right_size=right_size ) self.assertEqual( int(dataset_left.cardinality()), int(n_sample * left_size) ) self.assertEqual( int(dataset_right.cardinality()), int(n_sample * right_size) ) for sample in itertools.chain(dataset_left, dataset_right): self.assertEqual(sample[0].shape, features_shape) self.assertEqual(sample[1].shape, (1,)) @parameterized.named_parameters( named_product(structure_type=["dict", "tuple"]) ) def test_split_dataset_nested_structures(self, structure_type): n_sample, left_size, right_size = 100, 0.2, 0.8 features1 = np.random.sample((n_sample, 2)) features2 = np.random.sample((n_sample, 10, 2)) labels = np.random.sample((n_sample, 1)) if structure_type == "dict": dataset = tf.data.Dataset.from_tensor_slices( {"x1": features1, "x2": features2, "labels": labels} ) elif structure_type == "tuple": dataset = tf.data.Dataset.from_tensor_slices( ((features1, features2), labels) ) dataset_left, dataset_right = split_dataset( dataset, left_size=left_size, right_size=right_size ) self.assertEqual( int(dataset_left.cardinality()), int(n_sample * left_size) ) self.assertEqual( int(dataset_right.cardinality()), int(n_sample * right_size) ) for sample in itertools.chain(dataset_left, dataset_right): if structure_type == "dict": x1, x2, labels = sample["x1"], sample["x2"], sample["labels"] elif structure_type == "tuple": (x1, x2), labels = sample self.assertEqual(x1.shape, (2,)) self.assertEqual(x2.shape, (10, 2)) self.assertEqual(labels.shape, (1,))
import subprocess import pytest import os from typing import List, Generator from llama_index.core.schema import BaseNode, Document from llama_index.storage.docstore.gel import ( GelDocumentStore, ) from llama_index.storage.kvstore.gel import GelKVStore try: import gel # noqa no_packages = False except ImportError: no_packages = True skip_in_cicd = os.environ.get("CI") is not None try: if not skip_in_cicd: subprocess.run(["gel", "project", "init", "--non-interactive"], check=True) except subprocess.CalledProcessError as e: print(e) @pytest.fixture() def documents() -> List[Document]: return [ Document(text="doc_1"), Document(text="doc_2"), ] @pytest.fixture() def gel_kvstore() -> Generator[GelKVStore, None, None]: kvstore = None try: kvstore = GelKVStore() yield kvstore finally: if kvstore: keys = kvstore.get_all().keys() for key in keys: kvstore.delete(key) @pytest.fixture() def gel_docstore(gel_kvstore: GelKVStore) -> Generator[GelDocumentStore, None, None]: docstore = None try: docstore = GelDocumentStore(gel_kvstore=gel_kvstore) for id_ in docstore.docs: docstore.delete_document(id_) yield docstore finally: if docstore: for id_ in docstore.docs: docstore.delete_document(id_) @pytest.mark.skipif(no_packages or skip_in_cicd, reason="gel not installed") def test_gel_docstore( gel_docstore: GelDocumentStore, documents: List[Document] ) -> None: ds = gel_docstore assert len(ds.docs) == 0 # test adding documents ds.add_documents(documents) assert len(ds.docs) == 2 assert all(isinstance(doc, BaseNode) for doc in ds.docs.values()) # test updating documents ds.add_documents(documents) print(ds.docs) assert len(ds.docs) == 2 # test getting documents doc0 = ds.get_document(documents[0].get_doc_id()) assert doc0 is not None assert documents[0].get_content() == doc0.get_content() # test deleting documents ds.delete_document(documents[0].get_doc_id()) assert len(ds.docs) == 1 @pytest.mark.skipif(no_packages or skip_in_cicd, reason="gel not installed") def test_gel_docstore_hash( gel_docstore: GelDocumentStore, documents: List[Document] ) -> None: ds = gel_docstore # Test setting hash ds.set_document_hash("test_doc_id", "test_doc_hash") doc_hash = ds.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash" # Test updating hash ds.set_document_hash("test_doc_id", "test_doc_hash_new") doc_hash = ds.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash_new" # Test getting non-existent doc_hash = ds.get_document_hash("test_not_exist") assert doc_hash is None
from typing import List, Generator import subprocess import pytest from llama_index.core.schema import BaseNode, Document from llama_index.storage.docstore.gel import ( GelDocumentStore, ) from llama_index.storage.kvstore.gel import GelKVStore try: import gel # noqa no_packages = False except ImportError: no_packages = True try: subprocess.run(["gel", "project", "init", "--non-interactive"], check=True) except subprocess.CalledProcessError as e: print(e) @pytest.fixture() def documents() -> List[Document]: return [ Document(text="doc_1"), Document(text="doc_2"), ] @pytest.fixture() def gel_kvstore() -> Generator[GelKVStore, None, None]: kvstore = None try: kvstore = GelKVStore() yield kvstore finally: if kvstore: keys = kvstore.get_all().keys() for key in keys: kvstore.delete(key) @pytest.fixture() def gel_docstore(gel_kvstore: GelKVStore) -> Generator[GelDocumentStore, None, None]: docstore = None try: docstore = GelDocumentStore(gel_kvstore=gel_kvstore) for id_ in docstore.docs: docstore.delete_document(id_) yield docstore finally: if docstore: for id_ in docstore.docs: docstore.delete_document(id_) @pytest.mark.skipif(no_packages, reason="gel not installed") def test_gel_docstore( gel_docstore: GelDocumentStore, documents: List[Document] ) -> None: ds = gel_docstore assert len(ds.docs) == 0 # test adding documents ds.add_documents(documents) assert len(ds.docs) == 2 assert all(isinstance(doc, BaseNode) for doc in ds.docs.values()) # test updating documents ds.add_documents(documents) print(ds.docs) assert len(ds.docs) == 2 # test getting documents doc0 = ds.get_document(documents[0].get_doc_id()) assert doc0 is not None assert documents[0].get_content() == doc0.get_content() # test deleting documents ds.delete_document(documents[0].get_doc_id()) assert len(ds.docs) == 1 @pytest.mark.skipif(no_packages, reason="gel not installed") def test_gel_docstore_hash( gel_docstore: GelDocumentStore, documents: List[Document] ) -> None: ds = gel_docstore # Test setting hash ds.set_document_hash("test_doc_id", "test_doc_hash") doc_hash = ds.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash" # Test updating hash ds.set_document_hash("test_doc_id", "test_doc_hash_new") doc_hash = ds.get_document_hash("test_doc_id") assert doc_hash == "test_doc_hash_new" # Test getting non-existent doc_hash = ds.get_document_hash("test_not_exist") assert doc_hash is None
from pydantic import BaseModel from inspect import Signature, Parameter from typing import Any, Dict, Optional, List, Callable from llama_index.core.llms import ChatMessage, AudioBlock, TextBlock, MessageRole from llama_index.core.tools import BaseTool def make_function_from_tool_model( model_cls: type[BaseModel], tool: BaseTool ) -> Callable: fields = model_cls.model_fields parameters = [ Parameter(name, Parameter.POSITIONAL_OR_KEYWORD, annotation=field.annotation) for name, field in fields.items() ] sig = Signature(parameters) def func_template(*args, **kwargs): bound = func_template.__signature__.bind(*args, **kwargs) bound.apply_defaults() return tool(**bound.arguments).raw_output func_template.__signature__ = sig return func_template def callback_user_message( messages: Dict[int, List[ChatMessage]], message_id: int, text: Optional[str] = None, audio: Optional[Any] = None, ) -> None: if messages.get(message_id) is None: if text: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.USER, blocks=[TextBlock(text=text)]) ) else: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.USER, blocks=[AudioBlock(audio=audio)]) ) else: last_user_messages = [ message for message in messages[message_id] if message.role == MessageRole.USER ] if len(last_user_messages) > 0: last_user_message = last_user_messages[-1] else: messages[message_id].append(ChatMessage(role=MessageRole.USER, blocks=[])) last_user_message = [ message for message in messages[message_id] if message.role == MessageRole.USER ][-1] if text: last_user_message.blocks.append(TextBlock(text=text)) else: last_user_message.blocks.append(AudioBlock(audio=audio)) def callback_agent_message( messages: Dict[int, List[ChatMessage]], message_id: int, text: Optional[str] = None, audio: Optional[Any] = None, ) -> None: if messages.get(message_id) is None: if text: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.ASSISTANT, blocks=[TextBlock(text=text)]) ) else: messages[message_id] = [] messages[message_id].append( ChatMessage( role=MessageRole.ASSISTANT, blocks=[AudioBlock(audio=audio)] ) ) else: last_agent_messages = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ] if len(last_agent_messages) > 0: last_agent_message = last_agent_messages[-1] else: messages[message_id].append( ChatMessage(role=MessageRole.ASSISTANT, blocks=[]) ) last_agent_message = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ][-1] if text: last_agent_message.blocks.append(TextBlock(text=text)) else: last_agent_message.blocks.append(AudioBlock(audio=audio)) def callback_agent_message_correction( messages: Dict[int, List[ChatMessage]], message_id: int, text: str ) -> None: last_agent_message = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ][-1] last_block = [ block for block in last_agent_message.blocks if block.block_type == "text" ][-1] last_block.text = text def callback_latency_measurement(latencies: List[int], latency: int) -> None: latencies.append(latency) def get_messages_from_chat(chat: Dict[int, List[ChatMessage]]) -> List[ChatMessage]: messages: List[ChatMessage] = [] for msgs in chat.values(): for msg in msgs: messages.append(msg) return messages
from pydantic import BaseModel from inspect import Signature, Parameter from typing import Any, Dict, Optional, List, Callable from llama_index.core.llms import ChatMessage, AudioBlock, TextBlock, MessageRole from llama_index.core.tools import BaseTool def make_function_from_tool_model( model_cls: type[BaseModel], tool: BaseTool ) -> Callable: fields = model_cls.model_fields parameters = [ Parameter(name, Parameter.POSITIONAL_OR_KEYWORD, annotation=field.annotation) for name, field in fields.items() ] sig = Signature(parameters) def func_template(*args, **kwargs): bound = func_template.__signature__.bind(*args, **kwargs) bound.apply_defaults() return tool(**bound.arguments).raw_output func_template.__signature__ = sig return func_template def callback_user_message( messages: Dict[int, List[ChatMessage]], message_id: int, text: Optional[str] = None, audio: Optional[Any] = None, ) -> None: if messages.get(message_id) is None: if text: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.USER, blocks=[TextBlock(text=text)]) ) else: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.USER, blocks=[AudioBlock(audio=audio)]) ) else: last_user_messages = [ message for message in messages[message_id] if message.role == MessageRole.USER ] if len(last_user_messages) > 0: last_user_message = last_user_messages[-1] else: messages[message_id].append(ChatMessage(role=MessageRole.USER, blocks=[])) last_user_message = [ message for message in messages[message_id] if message.role == MessageRole.USER ][-1] if text: last_user_message.blocks.append(TextBlock(text=text)) else: last_user_message.blocks.append(AudioBlock(audio=audio)) def callback_agent_message( messages: Dict[int, List[ChatMessage]], message_id: int, text: Optional[str] = None, audio: Optional[Any] = None, ) -> None: if messages.get(message_id) is None: if text: messages[message_id] = [] messages[message_id].append( ChatMessage(role=MessageRole.ASSISTANT, blocks=[TextBlock(text=text)]) ) else: messages[message_id] = [] messages[message_id].append( ChatMessage( role=MessageRole.ASSISTANT, blocks=[AudioBlock(audio=audio)] ) ) else: last_agent_messages = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ] if len(last_agent_messages) > 0: last_agent_message = last_agent_messages[-1] else: messages[message_id].append( ChatMessage(role=MessageRole.ASSISTANT, blocks=[]) ) last_agent_message = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ][-1] if text: last_agent_message.blocks.append(TextBlock(text=text)) else: last_agent_message.blocks.append(AudioBlock(audio=audio)) def callback_agent_message_correction( messages: Dict[int, List[ChatMessage]], message_id: int, text: str ) -> None: last_agent_message = [ message for message in messages[message_id] if message.role == MessageRole.ASSISTANT ][-1] last_block = [ block for block in last_agent_message.blocks if block.block_type == "text" ][-1] last_block.text = text def callback_latency_measurement(latencies: List[int], latency: int) -> None: latencies.append(latency)
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .kaldi_compatibility_test_impl import Kaldi class TestKaldiFloat32(Kaldi, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class TestKaldiFloat64(Kaldi, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu")
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .kaldi_compatibility_test_impl import Kaldi, KaldiCPUOnly class TestKaldiCPUOnly(KaldiCPUOnly, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class TestKaldiFloat32(Kaldi, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class TestKaldiFloat64(Kaldi, PytorchTestCase): dtype = torch.float64 device = torch.device("cpu")
_base_ = 'faster-rcnn_regnetx-3.2GF_fpn_ms-3x_coco.py' model = dict( backbone=dict( type='RegNet', arch='regnetx_1.6gf', 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='open-mmlab://regnetx_1.6gf')), neck=dict( type='FPN', in_channels=[72, 168, 408, 912], out_channels=256, num_outs=5))
_base_ = 'faster_rcnn_regnetx-3.2GF_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( type='RegNet', arch='regnetx_1.6gf', 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='open-mmlab://regnetx_1.6gf')), neck=dict( type='FPN', in_channels=[72, 168, 408, 912], out_channels=256, num_outs=5))
# 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 gc import unittest import torch from diffusers import StableCascadeUNet from diffusers.utils import logging from diffusers.utils.testing_utils import ( backend_empty_cache, enable_full_determinism, require_torch_accelerator, slow, torch_device, ) logger = logging.get_logger(__name__) enable_full_determinism() @slow @require_torch_accelerator class StableCascadeUNetSingleFileTest(unittest.TestCase): 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 test_single_file_components_stage_b(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade", variant="bf16", subfolder="decoder", use_safetensors=True ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_b_lite(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_lite_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade", variant="bf16", subfolder="decoder_lite" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_c(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_c_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade-prior", variant="bf16", subfolder="prior" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_c_lite(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_c_lite_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade-prior", variant="bf16", subfolder="prior_lite" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" )
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 gc import unittest import torch from diffusers import StableCascadeUNet from diffusers.utils import logging from diffusers.utils.testing_utils import ( backend_empty_cache, enable_full_determinism, require_torch_accelerator, slow, torch_device, ) logger = logging.get_logger(__name__) enable_full_determinism() @slow @require_torch_accelerator class StableCascadeUNetSingleFileTest(unittest.TestCase): 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 test_single_file_components_stage_b(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade", variant="bf16", subfolder="decoder", use_safetensors=True ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_b_lite(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_lite_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade", variant="bf16", subfolder="decoder_lite" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_c(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_c_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade-prior", variant="bf16", subfolder="prior" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" ) def test_single_file_components_stage_c_lite(self): model_single_file = StableCascadeUNet.from_single_file( "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_c_lite_bf16.safetensors", torch_dtype=torch.bfloat16, ) model = StableCascadeUNet.from_pretrained( "stabilityai/stable-cascade-prior", variant="bf16", subfolder="prior_lite" ) PARAMS_TO_IGNORE = ["torch_dtype", "_name_or_path", "_use_default_values", "_diffusers_version"] for param_name, param_value in model_single_file.config.items(): if param_name in PARAMS_TO_IGNORE: continue assert model.config[param_name] == param_value, ( f"{param_name} differs between single file loading and pretrained loading" )
import enum from typing import Any, List, Optional, Union import pydantic import backend.data.graph from backend.data.api_key import APIKeyPermission, APIKeyWithoutHash class Methods(enum.Enum): SUBSCRIBE = "subscribe" UNSUBSCRIBE = "unsubscribe" EXECUTION_EVENT = "execution_event" ERROR = "error" HEARTBEAT = "heartbeat" class WsMessage(pydantic.BaseModel): method: Methods data: Optional[Union[dict[str, Any], list[Any], str]] = None success: bool | None = None channel: str | None = None error: str | None = None class ExecutionSubscription(pydantic.BaseModel): graph_id: str class SubscriptionDetails(pydantic.BaseModel): event_type: str channel: str graph_id: str class CreateGraph(pydantic.BaseModel): template_id: str | None = None template_version: int | None = None graph: backend.data.graph.Graph | None = None class CreateAPIKeyRequest(pydantic.BaseModel): name: str permissions: List[APIKeyPermission] description: Optional[str] = None class CreateAPIKeyResponse(pydantic.BaseModel): api_key: APIKeyWithoutHash plain_text_key: str class SetGraphActiveVersion(pydantic.BaseModel): active_graph_version: int class UpdatePermissionsRequest(pydantic.BaseModel): permissions: List[APIKeyPermission]
import enum from typing import Any, List, Optional, Union import pydantic import backend.data.graph from backend.data.api_key import APIKeyPermission, APIKeyWithoutHash class Methods(enum.Enum): SUBSCRIBE = "subscribe" UNSUBSCRIBE = "unsubscribe" EXECUTION_EVENT = "execution_event" ERROR = "error" HEARTBEAT = "heartbeat" class WsMessage(pydantic.BaseModel): method: Methods data: Optional[Union[dict[str, Any], list[Any], str]] = None success: bool | None = None channel: str | None = None error: str | None = None class ExecutionSubscription(pydantic.BaseModel): graph_id: str class SubscriptionDetails(pydantic.BaseModel): event_type: str channel: str graph_id: str class CreateGraph(pydantic.BaseModel): template_id: str | None = None template_version: int | None = None graph: backend.data.graph.Graph | None = None class CreateAPIKeyRequest(pydantic.BaseModel): name: str permissions: List[APIKeyPermission] description: Optional[str] = None class CreateAPIKeyResponse(pydantic.BaseModel): api_key: APIKeyWithoutHash plain_text_key: str class SetGraphActiveVersion(pydantic.BaseModel): active_graph_version: int class UpdatePermissionsRequest(pydantic.BaseModel): permissions: List[APIKeyPermission] class Pagination(pydantic.BaseModel): total_items: int = pydantic.Field( description="Total number of items.", examples=[42] ) total_pages: int = pydantic.Field( description="Total number of pages.", examples=[2] ) current_page: int = pydantic.Field( description="Current_page page number.", examples=[1] ) page_size: int = pydantic.Field( description="Number of items per page.", examples=[25] )
# Copyright (c) OpenMMLab. All rights reserved. from .backbones import * # noqa: F401,F403 from .data_preprocessors import * # noqa: F401,F403 from .dense_heads import * # noqa: F401,F403 from .detectors import * # noqa: F401,F403 from .layers import * # noqa: F401,F403 from .losses import * # noqa: F401,F403 from .mot import * # noqa: F401,F403 from .necks import * # noqa: F401,F403 from .reid import * # noqa: F401,F403 from .roi_heads import * # noqa: F401,F403 from .seg_heads import * # noqa: F401,F403 from .task_modules import * # noqa: F401,F403 from .test_time_augs import * # noqa: F401,F403 from .trackers import * # noqa: F401,F403 from .tracking_heads import * # noqa: F401,F403 from .vis import * # noqa: F401,F403
# Copyright (c) OpenMMLab. All rights reserved. from .backbones import * # noqa: F401,F403 from .data_preprocessors import * # noqa: F401,F403 from .dense_heads import * # noqa: F401,F403 from .detectors import * # noqa: F401,F403 from .layers import * # noqa: F401,F403 from .losses import * # noqa: F401,F403 from .mot import * # noqa: F401,F403 from .necks import * # noqa: F401,F403 from .reid import * # noqa: F401,F403 from .roi_heads import * # noqa: F401,F403 from .seg_heads import * # noqa: F401,F403 from .task_modules import * # noqa: F401,F403 from .test_time_augs import * # noqa: F401,F403 from .trackers import * # noqa: F401,F403 from .tracking_heads import * # noqa: F401,F403
"""Utility functions for validating Ollama models.""" from httpx import ConnectError from ollama import Client, ResponseError def validate_model(client: Client, model_name: str) -> None: """Validate that a model exists in the Ollama instance. Args: client: The Ollama client. model_name: The name of the model to validate. Raises: ValueError: If the model is not found or if there's a connection issue. """ try: response = client.list() model_names: list[str] = [model["model"] for model in response["models"]] if not any( model_name == m or m.startswith(f"{model_name}:") for m in model_names ): msg = ( f"Model `{model_name}` not found in Ollama. Please pull the " f"model (using `ollama pull {model_name}`) or specify a valid " f"model name. Available local models: {', '.join(model_names)}" ) raise ValueError(msg) except ConnectError as e: msg = "Failed to connect to Ollama. Please check that Ollama is downloaded, running and accessible. https://ollama.com/download" # noqa: E501 raise ValueError(msg) from e except ResponseError as e: msg = ( "Received an error from the Ollama API. " "Please check your Ollama server logs." ) raise ValueError(msg) from e
"""Utility functions for validating Ollama models.""" from httpx import ConnectError from ollama import Client, ResponseError def validate_model(client: Client, model_name: str) -> None: """Validate that a model exists in the Ollama instance. Args: client: The Ollama client. model_name: The name of the model to validate. Raises: ValueError: If the model is not found or if there's a connection issue. """ try: response = client.list() model_names: list[str] = [model["name"] for model in response["models"]] if not any( model_name == m or m.startswith(f"{model_name}:") for m in model_names ): msg = ( f"Model `{model_name}` not found in Ollama. Please pull the " f"model (using `ollama pull {model_name}`) or specify a valid " f"model name. Available local models: {', '.join(model_names)}" ) raise ValueError(msg) except ConnectError as e: msg = ( "Connection to Ollama failed. Please make sure Ollama is running " f"and accessible at {client._client.base_url}. " ) raise ValueError(msg) from e except ResponseError as e: msg = ( "Received an error from the Ollama API. " "Please check your Ollama server logs." ) raise ValueError(msg) from e
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.wandb_callback import WandbCallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "WandbCallbackHandler": "langchain_community.callbacks.wandb_callback", } _import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "WandbCallbackHandler", ]
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.wandb_callback import WandbCallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "WandbCallbackHandler": "langchain_community.callbacks.wandb_callback" } _import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "WandbCallbackHandler", ]
from typing import AsyncGenerator, Generator, Optional import pytest from jina import Client, Executor, requests from jina._docarray import Document, DocumentArray from jina.helper import random_port class MyDocument(Document): text: str number: Optional[int] class OutputDocument(Document): text: str class MyExecutor(Executor): @requests(on='/hello') async def task(self, doc: MyDocument, **kwargs) -> MyDocument: for i in range(100): yield MyDocument(text=f'{doc.text} {doc.number + i}') class CustomResponseExecutor(Executor): @requests(on='/task1') async def task1(self, doc: MyDocument, **kwargs) -> OutputDocument: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task1') @requests(on='/task2') async def task2( self, doc: MyDocument, **kwargs ) -> Generator[OutputDocument, None, None]: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task2') @requests(on='/task3') async def task3( self, doc: MyDocument, **kwargs ) -> AsyncGenerator[OutputDocument, None]: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task3') @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) @pytest.mark.parametrize('include_gateway', [False, True]) async def test_streaming_deployment(protocol, include_gateway): from jina import Deployment port = random_port() with Deployment( uses=MyExecutor, timeout_ready=-1, protocol=protocol, cors=True, port=port, include_gateway=include_gateway, ): client = Client(port=port, protocol=protocol, cors=True, asyncio=True) i = 10 async for doc in client.stream_doc( on='/hello', inputs=MyDocument(text='hello world', number=i), return_type=MyDocument, ): assert doc.text == f'hello world {i}' i += 1 @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) @pytest.mark.parametrize('endpoint', ['task1', 'task2', 'task3']) @pytest.mark.parametrize('include_gateway', [False, True]) async def test_streaming_custom_response(protocol, endpoint, include_gateway): from jina import Deployment port = random_port() with Deployment( uses=CustomResponseExecutor, timeout_ready=-1, protocol=protocol, cors=True, port=port, include_gateway=include_gateway, ): client = Client(port=port, protocol=protocol, cors=True, asyncio=True) i = 0 async for doc in client.stream_doc( on=f'/{endpoint}', inputs=MyDocument(text='hello world', number=5), return_type=OutputDocument, ): assert doc.text == f'hello world 5-{i}-{endpoint}' i += 1 class Executor1(Executor): @requests def generator(self, doc: MyDocument, **kwargs) -> MyDocument: yield MyDocument(text='new document') @requests(on='/non_generator') def non_generator(self, docs: DocumentArray, **kwargs): return docs class Executor2(Executor): @requests def non_generator(self, docs: DocumentArray, **kwargs): return docs @requests(on='/generator') def generator(self, doc: MyDocument, **kwargs): yield MyDocument(text='new document') class Executor3(Executor): @requests(on='/non_generator') def non_generator(self, docs: DocumentArray, **kwargs): return docs @requests(on='/generator') def generator(self, doc: MyDocument, **kwargs): yield MyDocument(text='new document') @pytest.mark.asyncio @pytest.mark.parametrize( 'executor,expected', [ ('Executor1', {'/default': True, '/non_generator': False}), ('Executor2', {'/default': False, '/generator': True}), ('Executor3', {'/generator': True, '/non_generator': False}), ], ) async def test_endpoint_discovery(executor, expected): from google.protobuf import json_format from jina.logging.logger import JinaLogger from jina.parsers import set_pod_parser from jina.serve.runtimes.worker.request_handling import WorkerRequestHandler args = set_pod_parser().parse_args(['--uses', executor]) handler = WorkerRequestHandler(args, JinaLogger('data request handler')) res = await handler.endpoint_discovery(None, None) for endpoint, is_generator in expected.items(): assert ( json_format.MessageToDict(res.schemas)[endpoint]['is_generator'] == is_generator )
from typing import AsyncGenerator, Generator, Optional import pytest from jina import Client, Executor, requests from jina._docarray import Document, DocumentArray from jina.helper import random_port class MyDocument(Document): text: str number: Optional[int] class OutputDocument(Document): text: str class MyExecutor(Executor): @requests(on='/hello') async def task(self, doc: MyDocument, **kwargs) -> MyDocument: for i in range(100): yield MyDocument(text=f'{doc.text} {doc.number + i}') class CustomResponseExecutor(Executor): @requests(on='/task1') async def task1(self, doc: MyDocument, **kwargs) -> OutputDocument: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task1') @requests(on='/task2') async def task2( self, doc: MyDocument, **kwargs ) -> Generator[OutputDocument, None, None]: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task2') @requests(on='/task3') async def task3( self, doc: MyDocument, **kwargs ) -> AsyncGenerator[OutputDocument, None]: for i in range(100): yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task3') @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) async def test_streaming_deployment(protocol): from jina import Deployment port = random_port() with Deployment( uses=MyExecutor, timeout_ready=-1, protocol=protocol, cors=True, port=port, include_gateway=False, ): client = Client(port=port, protocol=protocol, cors=True, asyncio=True) i = 10 async for doc in client.stream_doc( on='/hello', inputs=MyDocument(text='hello world', number=i), return_type=MyDocument, ): assert doc.text == f'hello world {i}' i += 1 @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) @pytest.mark.parametrize('endpoint', ['task1', 'task2', 'task3']) async def test_streaming_custom_response(protocol, endpoint): from jina import Deployment port = random_port() with Deployment( uses=CustomResponseExecutor, timeout_ready=-1, protocol=protocol, cors=True, port=port, include_gateway=False, ): client = Client(port=port, protocol=protocol, cors=True, asyncio=True) i = 0 async for doc in client.stream_doc( on=f'/{endpoint}', inputs=MyDocument(text='hello world', number=5), return_type=OutputDocument, ): assert doc.text == f'hello world 5-{i}-{endpoint}' i += 1 class Executor1(Executor): @requests def generator(self, doc: MyDocument, **kwargs) -> MyDocument: yield MyDocument(text='new document') @requests(on='/non_generator') def non_generator(self, docs: DocumentArray, **kwargs): return docs class Executor2(Executor): @requests def non_generator(self, docs: DocumentArray, **kwargs): return docs @requests(on='/generator') def generator(self, doc: MyDocument, **kwargs): yield MyDocument(text='new document') class Executor3(Executor): @requests(on='/non_generator') def non_generator(self, docs: DocumentArray, **kwargs): return docs @requests(on='/generator') def generator(self, doc: MyDocument, **kwargs): yield MyDocument(text='new document') @pytest.mark.asyncio @pytest.mark.parametrize( 'executor,expected', [ ('Executor1', {'/default': True, '/non_generator': False}), ('Executor2', {'/default': False, '/generator': True}), ('Executor3', {'/generator': True, '/non_generator': False}), ], ) async def test_endpoint_discovery(executor, expected): from google.protobuf import json_format from jina.logging.logger import JinaLogger from jina.parsers import set_pod_parser from jina.serve.runtimes.worker.request_handling import WorkerRequestHandler args = set_pod_parser().parse_args(['--uses', executor]) handler = WorkerRequestHandler(args, JinaLogger('data request handler')) res = await handler.endpoint_discovery(None, None) for endpoint, is_generator in expected.items(): assert ( json_format.MessageToDict(res.schemas)[endpoint]['is_generator'] == is_generator )
from pathlib import Path from typing import List import pytest from dpr_text import DPRTextEncoder from jina import Document, DocumentArray, Executor _EMBEDDING_DIM = 768 @pytest.fixture(scope='session') def basic_encoder() -> DPRTextEncoder: return DPRTextEncoder() @pytest.fixture(scope='session') def basic_encoder_ctx() -> DPRTextEncoder: return DPRTextEncoder( 'facebook/dpr-ctx_encoder-single-nq-base', encoder_type='context', title_tag_key='title', ) def test_config(): encoder = Executor.load_config(str(Path(__file__).parents[2] / 'config.yml')) assert encoder.encoder_type == 'question' def test_no_document(basic_encoder: DPRTextEncoder): basic_encoder.encode(None, {}) def test_empty_documents(basic_encoder: DPRTextEncoder): docs = DocumentArray([]) basic_encoder.encode(docs, {}) assert len(docs) == 0 def test_no_text_documents(basic_encoder: DPRTextEncoder): docs = DocumentArray([Document()]) basic_encoder.encode(docs, {}) assert len(docs) == 1 assert docs[0].embedding is None def test_context_encoder_doc_no_title(basic_encoder_ctx: DPRTextEncoder): docs = DocumentArray([Document(text='hello there')]) with pytest.raises(ValueError, match='If you set `title_tag_key` property'): basic_encoder_ctx.encode(docs, {}) def test_wrong_encoder_type(): with pytest.raises(ValueError, match='The ``encoder_type`` parameter'): DPRTextEncoder(encoder_type='worng_type') def test_encoding_cpu(): docs = DocumentArray([Document(text='hello there')]) encoder = DPRTextEncoder(device='cpu') encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) def test_encoding_question_type(basic_encoder: DPRTextEncoder): docs = DocumentArray([Document(text='hello there')]) basic_encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) def test_encoding_context_type(basic_encoder_ctx: DPRTextEncoder): docs = DocumentArray([Document(text='hello there', tags={'title': 'greeting'})]) basic_encoder_ctx.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) @pytest.mark.gpu def test_encoding_gpu(): docs = DocumentArray([Document(text='hello there')]) encoder = DPRTextEncoder(device='cuda') encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) @pytest.mark.parametrize( 'traversal_paths, counts', [ (['r'], [['r', 1], ['c', 0], ['cc', 0]]), (['c'], [['r', 0], ['c', 3], ['cc', 0]]), (['cc'], [['r', 0], ['c', 0], ['cc', 2]]), (['cc', 'r'], [['r', 1], ['c', 0], ['cc', 2]]), ], ) def test_traversal_path( traversal_paths: List[str], counts: List, basic_encoder: DPRTextEncoder ): text = 'blah' docs = DocumentArray([Document(id='root1', text=text)]) docs[0].chunks = [ Document(id='chunk11', text=text), Document(id='chunk12', text=text), Document(id='chunk13', text=text), ] docs[0].chunks[0].chunks = [ Document(id='chunk111', text=text), Document(id='chunk112', text=text), ] basic_encoder.encode(docs=docs, parameters={'traversal_paths': traversal_paths}) for path, count in counts: embeddings = docs.traverse_flat([path]).get_attributes('embedding') assert len(list(filter(lambda x: x is not None, embeddings))) == count @pytest.mark.parametrize('batch_size', [1, 2, 4, 8]) def test_batch_size(basic_encoder: DPRTextEncoder, batch_size: int): docs = DocumentArray([Document(text='hello there') for _ in range(32)]) basic_encoder.encode(docs, parameters={'batch_size': batch_size}) for doc in docs: assert doc.embedding.shape == (_EMBEDDING_DIM,) def test_quality_embeddings(basic_encoder: DPRTextEncoder): docs = DocumentArray( [ Document(id='A', text='a furry animal that with a long tail'), Document(id='B', text='a domesticated mammal with four legs'), Document(id='C', text='a type of aircraft that uses rotating wings'), Document(id='D', text='flying vehicle that has fixed wings and engines'), ] ) basic_encoder.encode(DocumentArray(docs), {}) # assert semantic meaning is captured in the encoding docs.match(docs) matches = ['B', 'A', 'D', 'C'] for i, doc in enumerate(docs): assert doc.matches[1].id == matches[i]
from pathlib import Path from typing import List import pytest from jina import Document, DocumentArray, Executor from ...dpr_text import DPRTextEncoder _EMBEDDING_DIM = 768 @pytest.fixture(scope='session') def basic_encoder() -> DPRTextEncoder: return DPRTextEncoder() @pytest.fixture(scope='session') def basic_encoder_ctx() -> DPRTextEncoder: return DPRTextEncoder( 'facebook/dpr-ctx_encoder-single-nq-base', encoder_type='context', title_tag_key='title', ) def test_config(): encoder = Executor.load_config(str(Path(__file__).parents[2] / 'config.yml')) assert encoder.encoder_type == 'question' def test_no_document(basic_encoder: DPRTextEncoder): basic_encoder.encode(None, {}) def test_empty_documents(basic_encoder: DPRTextEncoder): docs = DocumentArray([]) basic_encoder.encode(docs, {}) assert len(docs) == 0 def test_no_text_documents(basic_encoder: DPRTextEncoder): docs = DocumentArray([Document()]) basic_encoder.encode(docs, {}) assert len(docs) == 1 assert docs[0].embedding is None def test_context_encoder_doc_no_title(basic_encoder_ctx: DPRTextEncoder): docs = DocumentArray([Document(text='hello there')]) with pytest.raises(ValueError, match='If you set `title_tag_key` property'): basic_encoder_ctx.encode(docs, {}) def test_wrong_encoder_type(): with pytest.raises(ValueError, match='The ``encoder_type`` parameter'): DPRTextEncoder(encoder_type='worng_type') def test_encoding_cpu(): docs = DocumentArray([Document(text='hello there')]) encoder = DPRTextEncoder(device='cpu') encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) def test_encoding_question_type(basic_encoder: DPRTextEncoder): docs = DocumentArray([Document(text='hello there')]) basic_encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) def test_encoding_context_type(basic_encoder_ctx: DPRTextEncoder): docs = DocumentArray([Document(text='hello there', tags={'title': 'greeting'})]) basic_encoder_ctx.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) @pytest.mark.gpu def test_encoding_gpu(): docs = DocumentArray([Document(text='hello there')]) encoder = DPRTextEncoder(device='cuda') encoder.encode(docs, {}) assert docs[0].embedding.shape == (_EMBEDDING_DIM,) @pytest.mark.parametrize( 'traversal_paths, counts', [ (['r'], [['r', 1], ['c', 0], ['cc', 0]]), (['c'], [['r', 0], ['c', 3], ['cc', 0]]), (['cc'], [['r', 0], ['c', 0], ['cc', 2]]), (['cc', 'r'], [['r', 1], ['c', 0], ['cc', 2]]), ], ) def test_traversal_path( traversal_paths: List[str], counts: List, basic_encoder: DPRTextEncoder ): text = 'blah' docs = DocumentArray([Document(id='root1', text=text)]) docs[0].chunks = [ Document(id='chunk11', text=text), Document(id='chunk12', text=text), Document(id='chunk13', text=text), ] docs[0].chunks[0].chunks = [ Document(id='chunk111', text=text), Document(id='chunk112', text=text), ] basic_encoder.encode(docs=docs, parameters={'traversal_paths': traversal_paths}) for path, count in counts: embeddings = docs.traverse_flat([path]).get_attributes('embedding') assert len(list(filter(lambda x: x is not None, embeddings))) == count @pytest.mark.parametrize('batch_size', [1, 2, 4, 8]) def test_batch_size(basic_encoder: DPRTextEncoder, batch_size: int): docs = DocumentArray([Document(text='hello there') for _ in range(32)]) basic_encoder.encode(docs, parameters={'batch_size': batch_size}) for doc in docs: assert doc.embedding.shape == (_EMBEDDING_DIM,) def test_quality_embeddings(basic_encoder: DPRTextEncoder): docs = DocumentArray( [ Document(id='A', text='a furry animal that with a long tail'), Document(id='B', text='a domesticated mammal with four legs'), Document(id='C', text='a type of aircraft that uses rotating wings'), Document(id='D', text='flying vehicle that has fixed wings and engines'), ] ) basic_encoder.encode(DocumentArray(docs), {}) # assert semantic meaning is captured in the encoding docs.match(docs) matches = ['B', 'A', 'D', 'C'] for i, doc in enumerate(docs): assert doc.matches[1].id == matches[i]
from __future__ import annotations import warnings from typing import Any, Dict, List, Mapping, Optional from langchain_core.callbacks import CallbackManagerForLLMRun from langchain_core.language_models.llms import LLM from pydantic import BaseModel # Ignoring type because below is valid pydantic code # Unexpected keyword argument "extra" for "__init_subclass__" of "object" class Params(BaseModel, extra="allow"): """Parameters for the MLflow AI Gateway LLM.""" temperature: float = 0.0 candidate_count: int = 1 """The number of candidates to return.""" stop: Optional[List[str]] = None max_tokens: Optional[int] = None class MlflowAIGateway(LLM): """MLflow AI Gateway LLMs. To use, you should have the ``mlflow[gateway]`` python package installed. For more information, see https://mlflow.org/docs/latest/gateway/index.html. Example: .. code-block:: python from langchain_community.llms import MlflowAIGateway completions = MlflowAIGateway( gateway_uri="<your-mlflow-ai-gateway-uri>", route="<your-mlflow-ai-gateway-completions-route>", params={ "temperature": 0.1 } ) """ route: str gateway_uri: Optional[str] = None params: Optional[Params] = None def __init__(self, **kwargs: Any): warnings.warn( "`MlflowAIGateway` is deprecated. Use `Mlflow` or `Databricks` instead.", DeprecationWarning, ) try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e super().__init__(**kwargs) if self.gateway_uri: mlflow.gateway.set_gateway_uri(self.gateway_uri) @property def _default_params(self) -> Dict[str, Any]: params: Dict[str, Any] = { "gateway_uri": self.gateway_uri, "route": self.route, **(self.params.dict() if self.params else {}), } return params @property def _identifying_params(self) -> Mapping[str, Any]: return self._default_params def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e data: Dict[str, Any] = { "prompt": prompt, **(self.params.dict() if self.params else {}), } if s := (stop or (self.params.stop if self.params else None)): data["stop"] = s resp = mlflow.gateway.query(self.route, data=data) return resp["candidates"][0]["text"] @property def _llm_type(self) -> str: return "mlflow-ai-gateway"
from __future__ import annotations import warnings from typing import Any, Dict, List, Mapping, Optional from langchain_core.callbacks import CallbackManagerForLLMRun from langchain_core.language_models.llms import LLM from pydantic import BaseModel # Ignoring type because below is valid pydantic code # Unexpected keyword argument "extra" for "__init_subclass__" of "object" class Params(BaseModel, extra="allow"): # type: ignore[call-arg] """Parameters for the MLflow AI Gateway LLM.""" temperature: float = 0.0 candidate_count: int = 1 """The number of candidates to return.""" stop: Optional[List[str]] = None max_tokens: Optional[int] = None class MlflowAIGateway(LLM): """MLflow AI Gateway LLMs. To use, you should have the ``mlflow[gateway]`` python package installed. For more information, see https://mlflow.org/docs/latest/gateway/index.html. Example: .. code-block:: python from langchain_community.llms import MlflowAIGateway completions = MlflowAIGateway( gateway_uri="<your-mlflow-ai-gateway-uri>", route="<your-mlflow-ai-gateway-completions-route>", params={ "temperature": 0.1 } ) """ route: str gateway_uri: Optional[str] = None params: Optional[Params] = None def __init__(self, **kwargs: Any): warnings.warn( "`MlflowAIGateway` is deprecated. Use `Mlflow` or `Databricks` instead.", DeprecationWarning, ) try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e super().__init__(**kwargs) if self.gateway_uri: mlflow.gateway.set_gateway_uri(self.gateway_uri) @property def _default_params(self) -> Dict[str, Any]: params: Dict[str, Any] = { "gateway_uri": self.gateway_uri, "route": self.route, **(self.params.dict() if self.params else {}), } return params @property def _identifying_params(self) -> Mapping[str, Any]: return self._default_params def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e data: Dict[str, Any] = { "prompt": prompt, **(self.params.dict() if self.params else {}), } if s := (stop or (self.params.stop if self.params else None)): data["stop"] = s resp = mlflow.gateway.query(self.route, data=data) return resp["candidates"][0]["text"] @property def _llm_type(self) -> str: return "mlflow-ai-gateway"
"""Image prompt template for a multimodal model.""" from typing import Any from pydantic import Field from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue from langchain_core.prompts.base import BasePromptTemplate from langchain_core.prompts.string import ( DEFAULT_FORMATTER_MAPPING, PromptTemplateFormat, ) from langchain_core.runnables import run_in_executor class ImagePromptTemplate(BasePromptTemplate[ImageURL]): """Image prompt template for a multimodal model.""" template: dict = Field(default_factory=dict) """Template for the prompt.""" template_format: PromptTemplateFormat = "f-string" """The format of the prompt template. Options are: 'f-string', 'mustache', 'jinja2'.""" def __init__(self, **kwargs: Any) -> None: """Create an image prompt template.""" if "input_variables" not in kwargs: kwargs["input_variables"] = [] overlap = set(kwargs["input_variables"]) & {"url", "path", "detail"} if overlap: msg = ( "input_variables for the image template cannot contain" " any of 'url', 'path', or 'detail'." f" Found: {overlap}" ) raise ValueError(msg) super().__init__(**kwargs) @property def _prompt_type(self) -> str: """Return the prompt type key.""" return "image-prompt" @classmethod def get_lc_namespace(cls) -> list[str]: """Get the namespace of the langchain object.""" return ["langchain", "prompts", "image"] def format_prompt(self, **kwargs: Any) -> PromptValue: """Format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. """ return ImagePromptValue(image_url=self.format(**kwargs)) async def aformat_prompt(self, **kwargs: Any) -> PromptValue: """Async format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. """ return ImagePromptValue(image_url=await self.aformat(**kwargs)) def format( self, **kwargs: Any, ) -> ImageURL: """Format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Raises: ValueError: If the url is not provided. ValueError: If the url is not a string. Example: .. code-block:: python prompt.format(variable1="foo") """ formatted = {} for k, v in self.template.items(): if isinstance(v, str): formatted[k] = DEFAULT_FORMATTER_MAPPING[self.template_format]( v, **kwargs ) else: formatted[k] = v url = kwargs.get("url") or formatted.get("url") if kwargs.get("path") or formatted.get("path"): msg = ( "Loading images from 'path' has been removed as of 0.3.15 for security " "reasons. Please specify images by 'url'." ) raise ValueError(msg) detail = kwargs.get("detail") or formatted.get("detail") if not url: msg = "Must provide url." raise ValueError(msg) if not isinstance(url, str): msg = "url must be a string." raise ValueError(msg) # noqa: TRY004 output: ImageURL = {"url": url} if detail: # Don't check literal values here: let the API check them output["detail"] = detail # type: ignore[typeddict-item] return output async def aformat(self, **kwargs: Any) -> ImageURL: """Async format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Raises: ValueError: If the path or url is not a string. """ return await run_in_executor(None, self.format, **kwargs) def pretty_repr( self, html: bool = False, # noqa: FBT001,FBT002 ) -> str: """Return a pretty representation of the prompt. Args: html: Whether to return an html formatted string. Returns: A pretty representation of the prompt. """ raise NotImplementedError
"""Image prompt template for a multimodal model.""" from typing import Any from pydantic import Field from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue from langchain_core.prompts.base import BasePromptTemplate from langchain_core.prompts.string import ( DEFAULT_FORMATTER_MAPPING, PromptTemplateFormat, ) from langchain_core.runnables import run_in_executor class ImagePromptTemplate(BasePromptTemplate[ImageURL]): """Image prompt template for a multimodal model.""" template: dict = Field(default_factory=dict) """Template for the prompt.""" template_format: PromptTemplateFormat = "f-string" """The format of the prompt template. Options are: 'f-string', 'mustache', 'jinja2'.""" def __init__(self, **kwargs: Any) -> None: """Create an image prompt template.""" if "input_variables" not in kwargs: kwargs["input_variables"] = [] overlap = set(kwargs["input_variables"]) & {"url", "path", "detail"} if overlap: msg = ( "input_variables for the image template cannot contain" " any of 'url', 'path', or 'detail'." f" Found: {overlap}" ) raise ValueError(msg) super().__init__(**kwargs) @property def _prompt_type(self) -> str: """Return the prompt type key.""" return "image-prompt" @classmethod def get_lc_namespace(cls) -> list[str]: """Get the namespace of the langchain object.""" return ["langchain", "prompts", "image"] def format_prompt(self, **kwargs: Any) -> PromptValue: """Format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. """ return ImagePromptValue(image_url=self.format(**kwargs)) async def aformat_prompt(self, **kwargs: Any) -> PromptValue: """Async format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. """ return ImagePromptValue(image_url=await self.aformat(**kwargs)) def format( self, **kwargs: Any, ) -> ImageURL: """Format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Raises: ValueError: If the url is not provided. ValueError: If the url is not a string. Example: .. code-block:: python prompt.format(variable1="foo") """ formatted = {} for k, v in self.template.items(): if isinstance(v, str): formatted[k] = DEFAULT_FORMATTER_MAPPING[self.template_format]( v, **kwargs ) else: formatted[k] = v url = kwargs.get("url") or formatted.get("url") if kwargs.get("path") or formatted.get("path"): msg = ( "Loading images from 'path' has been removed as of 0.3.15 for security " "reasons. Please specify images by 'url'." ) raise ValueError(msg) detail = kwargs.get("detail") or formatted.get("detail") if not url: msg = "Must provide url." raise ValueError(msg) if not isinstance(url, str): msg = "url must be a string." raise ValueError(msg) # noqa: TRY004 output: ImageURL = {"url": url} if detail: # Don't check literal values here: let the API check them output["detail"] = detail # type: ignore[typeddict-item] return output async def aformat(self, **kwargs: Any) -> ImageURL: """Async format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Raises: ValueError: If the path or url is not a string. """ return await run_in_executor(None, self.format, **kwargs) def pretty_repr(self, html: bool = False) -> str: """Return a pretty representation of the prompt. Args: html: Whether to return an html formatted string. Returns: A pretty representation of the prompt. """ raise NotImplementedError
from torio.utils import ffmpeg_utils from . import sox_utils from .download import download_asset __all__ = [ "download_asset", "sox_utils", "ffmpeg_utils", ]
from . import ffmpeg_utils, sox_utils from .download import download_asset __all__ = [ "download_asset", "sox_utils", "ffmpeg_utils", ]
from __future__ import annotations import torch import torch.nn as nn class TopKActivation(nn.Module): """ TopK activation function for Sparse AutoEncoder. This module implements the TopK activation function. The TopK activation function keeps only the k largest values and sets the rest to zero. """ def __init__(self, k: int = 100): """ Initialize the TopK activation function. Args: k: Number of top values to keep """ super().__init__() self.k = k def forward(self, x: torch.Tensor) -> torch.Tensor: """ Forward pass of the TopK activation function. Args: x: Input tensor Returns: Tensor with only the k largest values, rest set to zero """ # Get the k largest values and their indices values, indices = torch.topk(x, k=self.k, dim=-1) # Create a mask of zeros with the same shape as x mask = torch.zeros_like(x) # Set the k largest values to 1 in the mask for i in range(self.k): mask.scatter_(-1, indices[..., i : i + 1], 1) # Apply the mask to the input tensor return x * mask
from __future__ import annotations import torch import torch.nn as nn class TopKActivation(nn.Module): """ TopK activation function for Sparse AutoEncoder. This module implements the TopK activation function as described in the paper: z_k := TopK(W_enc(f(x) - b_pre) + b_enc) The TopK activation function keeps only the k largest values and sets the rest to zero. """ def __init__(self, k: int = 100): """ Initialize the TopK activation function. Args: k: Number of top values to keep """ super().__init__() self.k = k def forward(self, x: torch.Tensor) -> torch.Tensor: """ Forward pass of the TopK activation function. Args: x: Input tensor Returns: Tensor with only the k largest values, rest set to zero """ # Get the k largest values and their indices values, indices = torch.topk(x, k=self.k, dim=-1) # Create a mask of zeros with the same shape as x mask = torch.zeros_like(x) # Set the k largest values to 1 in the mask for i in range(self.k): mask.scatter_(-1, indices[..., i : i + 1], 1) # Apply the mask to the input tensor return x * mask
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import TASK_UTILS from .base_sampler import BaseSampler @TASK_UTILS.register_module() class CombinedSampler(BaseSampler): """A sampler that combines positive sampler and negative sampler.""" def __init__(self, pos_sampler, neg_sampler, **kwargs): super(CombinedSampler, self).__init__(**kwargs) self.pos_sampler = TASK_UTILS.build(pos_sampler, default_args=kwargs) self.neg_sampler = TASK_UTILS.build(neg_sampler, default_args=kwargs) def _sample_pos(self, **kwargs): """Sample positive samples.""" raise NotImplementedError def _sample_neg(self, **kwargs): """Sample negative samples.""" raise NotImplementedError
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import BBOX_SAMPLERS, build_sampler from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class CombinedSampler(BaseSampler): """A sampler that combines positive sampler and negative sampler.""" def __init__(self, pos_sampler, neg_sampler, **kwargs): super(CombinedSampler, self).__init__(**kwargs) self.pos_sampler = build_sampler(pos_sampler, **kwargs) self.neg_sampler = build_sampler(neg_sampler, **kwargs) def _sample_pos(self, **kwargs): """Sample positive samples.""" raise NotImplementedError def _sample_neg(self, **kwargs): """Sample negative samples.""" raise NotImplementedError
"""ReAct output parser.""" import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extract_tool_use(input_text: str) -> Tuple[str, str, str]: pattern = ( r"\s*Thought: (.*?)\n+Action: ([^\n\(\) ]+).*?\n+Action Input: .*?(\{.*\})" ) match = re.search(pattern, input_text, re.DOTALL) if not match: raise ValueError(f"Could not extract tool use from input text: {input_text}") thought = match.group(1).strip() action = match.group(2).strip() action_input = match.group(3).strip() return thought, action, action_input def action_input_parser(json_str: str) -> dict: processed_string = re.sub(r"(?<!\w)\'|\'(?!\w)", '"', json_str) pattern = r'"(\w+)":\s*"([^"]*)"' matches = re.findall(pattern, processed_string) return dict(matches) def extract_final_response(input_text: str) -> Tuple[str, str]: pattern = r"\s*Thought:(.*?)Answer:(.*?)(?:$)" match = re.search(pattern, input_text, re.DOTALL) if not match: raise ValueError( f"Could not extract final answer from input text: {input_text}" ) thought = match.group(1).strip() answer = match.group(2).strip() return thought, answer def parse_action_reasoning_step(output: str) -> ActionReasoningStep: """ Parse an action reasoning step from the LLM output. """ # Weaker LLMs may generate ReActAgent steps whose Action Input are horrible JSON strings. # `dirtyjson` is more lenient than `json` in parsing JSON strings. import dirtyjson as json thought, action, action_input = extract_tool_use(output) json_str = extract_json_str(action_input) # First we try json, if this fails we use ast try: action_input_dict = json.loads(json_str) except Exception: action_input_dict = action_input_parser(json_str) return ActionReasoningStep( thought=thought, action=action, action_input=action_input_dict ) class ReActOutputParser(BaseOutputParser): """ReAct Output parser.""" def parse(self, output: str, is_streaming: bool = False) -> BaseReasoningStep: """ Parse output from ReAct agent. We expect the output to be in one of the following formats: 1. If the agent need to use a tool to answer the question: ``` Thought: <thought> Action: <action> Action Input: <action_input> ``` 2. If the agent can answer the question without any tools: ``` Thought: <thought> Answer: <answer> ``` """ if "Thought:" not in output: # NOTE: handle the case where the agent directly outputs the answer # instead of following the thought-answer format return ResponseReasoningStep( thought="(Implicit) I can answer without any more tools!", response=output, is_streaming=is_streaming, ) # An "Action" should take priority over an "Answer" if "Action:" in output: return parse_action_reasoning_step(output) if "Answer:" in output: thought, answer = extract_final_response(output) return ResponseReasoningStep( thought=thought, response=answer, is_streaming=is_streaming ) raise ValueError(f"Could not parse output: {output}") def format(self, output: str) -> str: """Format a query with structured output formatting instructions.""" raise NotImplementedError
"""ReAct output parser.""" import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extract_tool_use(input_text: str) -> Tuple[str, str, str]: pattern = ( r"\s*Thought: (.*?)\n+Action: ([^\n\(\) ]+).*?\n+Action Input: .*?(\{.*\})" ) match = re.search(pattern, input_text, re.DOTALL) if not match: raise ValueError(f"Could not extract tool use from input text: {input_text}") thought = match.group(1).strip() action = match.group(2).strip() action_input = match.group(3).strip() return thought, action, action_input def action_input_parser(json_str: str) -> dict: processed_string = re.sub(r"(?<!\w)\'|\'(?!\w)", '"', json_str) pattern = r'"(\w+)":\s*"([^"]*)"' matches = re.findall(pattern, processed_string) return dict(matches) def extract_final_response(input_text: str) -> Tuple[str, str]: pattern = r"\s*Thought:(.*?)Answer:(.*?)(?:$)" match = re.search(pattern, input_text, re.DOTALL) if not match: raise ValueError( f"Could not extract final answer from input text: {input_text}" ) thought = match.group(1).strip() answer = match.group(2).strip() return thought, answer def parse_action_reasoning_step(output: str) -> ActionReasoningStep: """ Parse an action reasoning step from the LLM output. """ # Weaker LLMs may generate ReActAgent steps whose Action Input are horrible JSON strings. # `dirtyjson` is more lenient than `json` in parsing JSON strings. import dirtyjson as json thought, action, action_input = extract_tool_use(output) json_str = extract_json_str(action_input) # First we try json, if this fails we use ast try: action_input_dict = json.loads(json_str) except Exception: action_input_dict = action_input_parser(json_str) return ActionReasoningStep( thought=thought, action=action, action_input=action_input_dict ) class ReActOutputParser(BaseOutputParser): """ReAct Output parser.""" def parse(self, output: str, is_streaming: bool = False) -> BaseReasoningStep: """Parse output from ReAct agent. We expect the output to be in one of the following formats: 1. If the agent need to use a tool to answer the question: ``` Thought: <thought> Action: <action> Action Input: <action_input> ``` 2. If the agent can answer the question without any tools: ``` Thought: <thought> Answer: <answer> ``` """ if "Thought:" not in output: # NOTE: handle the case where the agent directly outputs the answer # instead of following the thought-answer format return ResponseReasoningStep( thought="(Implicit) I can answer without any more tools!", response=output, is_streaming=is_streaming, ) # An "Action" should take priority over an "Answer" if "Action:" in output: return parse_action_reasoning_step(output) if "Answer:" in output: thought, answer = extract_final_response(output) return ResponseReasoningStep( thought=thought, response=answer, is_streaming=is_streaming ) raise ValueError(f"Could not parse output: {output}") def format(self, output: str) -> str: """Format a query with structured output formatting instructions.""" raise NotImplementedError
# Copyright (c) OpenMMLab. All rights reserved. from .batch_sampler import AspectRatioBatchSampler from .class_aware_sampler import ClassAwareSampler from .multi_source_sampler import GroupMultiSourceSampler, MultiSourceSampler from .track_img_sampler import TrackImgSampler __all__ = [ 'ClassAwareSampler', 'AspectRatioBatchSampler', 'MultiSourceSampler', 'GroupMultiSourceSampler', 'TrackImgSampler' ]
# Copyright (c) OpenMMLab. All rights reserved. from .batch_sampler import AspectRatioBatchSampler from .class_aware_sampler import ClassAwareSampler from .multi_source_sampler import GroupMultiSourceSampler, MultiSourceSampler __all__ = [ 'ClassAwareSampler', 'AspectRatioBatchSampler', 'MultiSourceSampler', 'GroupMultiSourceSampler' ]
import json import os from typing import Any, List, Literal from llama_index.vector_stores.docarray.base import DocArrayVectorStore class DocArrayHnswVectorStore(DocArrayVectorStore): """ Class representing a DocArray HNSW vector store. This class is a lightweight Document Index implementation provided by Docarray. It stores vectors on disk in hnswlib, and stores all other data in SQLite. Examples: `pip install llama-index-vector-stores-docarray` ```python from llama_index.vector_stores.docarray import DocArrayHnswVectorStore # Initialize the DocArrayHnswVectorStore vector_store = DocArrayHnswVectorStore(work_dir="hnsw_index", dim=1536) ``` """ def __init__( self, work_dir: str, dim: int = 1536, dist_metric: Literal["cosine", "ip", "l2"] = "cosine", max_elements: int = 1024, ef_construction: int = 200, ef: int = 10, M: int = 16, allow_replace_deleted: bool = True, num_threads: int = 1, ): """ Initializes the DocArrayHnswVectorStore. Args: work_dir (str): The working directory. dim (int, optional): Dimensionality of the vectors. Default is 1536. dist_metric (Literal["cosine", "ip", "l2"], optional): The distance metric to use. Default is "cosine". max_elements (int, optional): defines the maximum number of elements that can be stored in the structure(can be increased/shrunk). ef_construction (int, optional): defines a construction time/accuracy trade-off. Default is 200. ef (int, optional): The size of the dynamic candidate list. Default is 10. M (int, optional): defines the maximum number of outgoing connections in the graph. Default is 16. allow_replace_deleted (bool, optional): Whether to allow replacing deleted elements. Default is True. num_threads (int, optional): Number of threads for index construction. Default is 1. """ import_err_msg = """ `docarray` package not found. Install the package via pip: `pip install docarray[hnswlib]` """ try: import docarray # noqa except ImportError: raise ImportError(import_err_msg) self._work_dir = work_dir ref_docs_path = os.path.join(self._work_dir, "ref_docs.json") if os.path.exists(ref_docs_path): with open(ref_docs_path) as f: self._ref_docs = json.load(f) else: self._ref_docs = {} self._index, self._schema = self._init_index( dim=dim, dist_metric=dist_metric, max_elements=max_elements, ef_construction=ef_construction, ef=ef, M=M, allow_replace_deleted=allow_replace_deleted, num_threads=num_threads, ) def _init_index(self, **kwargs: Any): # type: ignore[no-untyped-def] """ Initializes the HNSW document index. Args: **kwargs: Variable length argument list for the HNSW index. Returns: tuple: The HNSW document index and its schema. """ from docarray.index import HnswDocumentIndex schema = self._get_schema(**kwargs) index = HnswDocumentIndex[schema] # type: ignore[valid-type] return index(work_dir=self._work_dir), schema def _find_docs_to_be_removed(self, doc_id: str) -> List[str]: """ Finds the documents to be removed from the vector store. Args: doc_id (str): Reference document ID that should be removed. Returns: List[str]: List of document IDs to be removed. """ docs = self._ref_docs.get(doc_id, []) del self._ref_docs[doc_id] self._save_ref_docs() return docs def _save_ref_docs(self) -> None: """Saves reference documents.""" with open(os.path.join(self._work_dir, "ref_docs.json"), "w") as f: json.dump(self._ref_docs, f) def _update_ref_docs(self, docs): # type: ignore[no-untyped-def] """ Updates reference documents. Args: docs (List): List of documents to update. """ for doc in docs: if doc.metadata["doc_id"] not in self._ref_docs: self._ref_docs[doc.metadata["doc_id"]] = [] self._ref_docs[doc.metadata["doc_id"]].append(doc.id) self._save_ref_docs()
import json import os from typing import Any, List, Literal from llama_index.vector_stores.docarray.base import DocArrayVectorStore class DocArrayHnswVectorStore(DocArrayVectorStore): """Class representing a DocArray HNSW vector store. This class is a lightweight Document Index implementation provided by Docarray. It stores vectors on disk in hnswlib, and stores all other data in SQLite. Examples: `pip install llama-index-vector-stores-docarray` ```python from llama_index.vector_stores.docarray import DocArrayHnswVectorStore # Initialize the DocArrayHnswVectorStore vector_store = DocArrayHnswVectorStore(work_dir="hnsw_index", dim=1536) ``` """ def __init__( self, work_dir: str, dim: int = 1536, dist_metric: Literal["cosine", "ip", "l2"] = "cosine", max_elements: int = 1024, ef_construction: int = 200, ef: int = 10, M: int = 16, allow_replace_deleted: bool = True, num_threads: int = 1, ): """Initializes the DocArrayHnswVectorStore. Args: work_dir (str): The working directory. dim (int, optional): Dimensionality of the vectors. Default is 1536. dist_metric (Literal["cosine", "ip", "l2"], optional): The distance metric to use. Default is "cosine". max_elements (int, optional): defines the maximum number of elements that can be stored in the structure(can be increased/shrunk). ef_construction (int, optional): defines a construction time/accuracy trade-off. Default is 200. ef (int, optional): The size of the dynamic candidate list. Default is 10. M (int, optional): defines the maximum number of outgoing connections in the graph. Default is 16. allow_replace_deleted (bool, optional): Whether to allow replacing deleted elements. Default is True. num_threads (int, optional): Number of threads for index construction. Default is 1. """ import_err_msg = """ `docarray` package not found. Install the package via pip: `pip install docarray[hnswlib]` """ try: import docarray # noqa except ImportError: raise ImportError(import_err_msg) self._work_dir = work_dir ref_docs_path = os.path.join(self._work_dir, "ref_docs.json") if os.path.exists(ref_docs_path): with open(ref_docs_path) as f: self._ref_docs = json.load(f) else: self._ref_docs = {} self._index, self._schema = self._init_index( dim=dim, dist_metric=dist_metric, max_elements=max_elements, ef_construction=ef_construction, ef=ef, M=M, allow_replace_deleted=allow_replace_deleted, num_threads=num_threads, ) def _init_index(self, **kwargs: Any): # type: ignore[no-untyped-def] """Initializes the HNSW document index. Args: **kwargs: Variable length argument list for the HNSW index. Returns: tuple: The HNSW document index and its schema. """ from docarray.index import HnswDocumentIndex schema = self._get_schema(**kwargs) index = HnswDocumentIndex[schema] # type: ignore[valid-type] return index(work_dir=self._work_dir), schema def _find_docs_to_be_removed(self, doc_id: str) -> List[str]: """Finds the documents to be removed from the vector store. Args: doc_id (str): Reference document ID that should be removed. Returns: List[str]: List of document IDs to be removed. """ docs = self._ref_docs.get(doc_id, []) del self._ref_docs[doc_id] self._save_ref_docs() return docs def _save_ref_docs(self) -> None: """Saves reference documents.""" with open(os.path.join(self._work_dir, "ref_docs.json"), "w") as f: json.dump(self._ref_docs, f) def _update_ref_docs(self, docs): # type: ignore[no-untyped-def] """Updates reference documents. Args: docs (List): List of documents to update. """ for doc in docs: if doc.metadata["doc_id"] not in self._ref_docs: self._ref_docs[doc.metadata["doc_id"]] = [] self._ref_docs[doc.metadata["doc_id"]].append(doc.id) self._save_ref_docs()
from typing import Union from langchain.agents.agent import BaseSingleActionAgent from langchain.agents.agent_types import AgentType from langchain.agents.chat.base import ChatAgent from langchain.agents.conversational.base import ConversationalAgent from langchain.agents.conversational_chat.base import ConversationalChatAgent from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent from langchain.agents.openai_functions_multi_agent.base import OpenAIMultiFunctionsAgent from langchain.agents.react.base import ReActDocstoreAgent from langchain.agents.self_ask_with_search.base import SelfAskWithSearchAgent from langchain.agents.structured_chat.base import StructuredChatAgent AGENT_TYPE = Union[type[BaseSingleActionAgent], type[OpenAIMultiFunctionsAgent]] AGENT_TO_CLASS: dict[AgentType, AGENT_TYPE] = { AgentType.ZERO_SHOT_REACT_DESCRIPTION: ZeroShotAgent, AgentType.REACT_DOCSTORE: ReActDocstoreAgent, AgentType.SELF_ASK_WITH_SEARCH: SelfAskWithSearchAgent, AgentType.CONVERSATIONAL_REACT_DESCRIPTION: ConversationalAgent, AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION: ChatAgent, AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent, AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION: StructuredChatAgent, AgentType.OPENAI_FUNCTIONS: OpenAIFunctionsAgent, AgentType.OPENAI_MULTI_FUNCTIONS: OpenAIMultiFunctionsAgent, }
from typing import Dict, Type, Union from langchain.agents.agent import BaseSingleActionAgent from langchain.agents.agent_types import AgentType from langchain.agents.chat.base import ChatAgent from langchain.agents.conversational.base import ConversationalAgent from langchain.agents.conversational_chat.base import ConversationalChatAgent from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent from langchain.agents.openai_functions_multi_agent.base import OpenAIMultiFunctionsAgent from langchain.agents.react.base import ReActDocstoreAgent from langchain.agents.self_ask_with_search.base import SelfAskWithSearchAgent from langchain.agents.structured_chat.base import StructuredChatAgent AGENT_TYPE = Union[Type[BaseSingleActionAgent], Type[OpenAIMultiFunctionsAgent]] AGENT_TO_CLASS: Dict[AgentType, AGENT_TYPE] = { AgentType.ZERO_SHOT_REACT_DESCRIPTION: ZeroShotAgent, AgentType.REACT_DOCSTORE: ReActDocstoreAgent, AgentType.SELF_ASK_WITH_SEARCH: SelfAskWithSearchAgent, AgentType.CONVERSATIONAL_REACT_DESCRIPTION: ConversationalAgent, AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION: ChatAgent, AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent, AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION: StructuredChatAgent, AgentType.OPENAI_FUNCTIONS: OpenAIFunctionsAgent, AgentType.OPENAI_MULTI_FUNCTIONS: OpenAIMultiFunctionsAgent, }
from pathlib import Path from typing import List, Tuple, Union import torch import torchaudio from torch.utils.data import Dataset SampleType = Tuple[int, torch.Tensor, List[torch.Tensor]] class LibriMix(Dataset): r"""Create the *LibriMix* [:footcite:`cosentino2020librimix`] dataset. Args: root (str or Path): The path to the directory where the directory ``Libri2Mix`` or ``Libri3Mix`` is stored. subset (str, optional): The subset to use. Options: [``train-360``, ``train-100``, ``dev``, and ``test``] (Default: ``train-360``). num_speakers (int, optional): The number of speakers, which determines the directories to traverse. The Dataset will traverse ``s1`` to ``sN`` directories to collect N source audios. (Default: 2) sample_rate (int, optional): sample rate of audio files. The ``sample_rate`` determines which subdirectory the audio are fetched. If any of the audio has a different sample rate, raises ``ValueError``. Options: [8000, 16000] (Default: 8000) task (str, optional): the task of LibriMix. Options: [``enh_single``, ``enh_both``, ``sep_clean``, ``sep_noisy``] (Default: ``sep_clean``) Note: The LibriMix dataset needs to be manually generated. Please check https://github.com/JorisCos/LibriMix """ def __init__( self, root: Union[str, Path], subset: str = "train-360", num_speakers: int = 2, sample_rate: int = 8000, task: str = "sep_clean", ): self.root = Path(root) / f"Libri{num_speakers}Mix" if sample_rate == 8000: self.root = self.root / "wav8k/min" / subset elif sample_rate == 16000: self.root = self.root / "wav16k/min" / subset else: raise ValueError(f"Unsupported sample rate. Found {sample_rate}.") self.sample_rate = sample_rate self.task = task self.mix_dir = (self.root / f"mix_{task.split('_')[1]}").resolve() self.src_dirs = [(self.root / f"s{i+1}").resolve() for i in range(num_speakers)] self.files = [p.name for p in self.mix_dir.glob("*wav")] self.files.sort() def _load_audio(self, path) -> torch.Tensor: waveform, sample_rate = torchaudio.load(path) if sample_rate != self.sample_rate: raise ValueError( f"The dataset contains audio file of sample rate {sample_rate}, " f"but the requested sample rate is {self.sample_rate}." ) return waveform def _load_sample(self, filename) -> SampleType: mixed = self._load_audio(str(self.mix_dir / filename)) srcs = [] for i, dir_ in enumerate(self.src_dirs): src = self._load_audio(str(dir_ / filename)) if mixed.shape != src.shape: raise ValueError(f"Different waveform shapes. mixed: {mixed.shape}, src[{i}]: {src.shape}") srcs.append(src) return self.sample_rate, mixed, srcs def __len__(self) -> int: return len(self.files) def __getitem__(self, key: int) -> SampleType: """Load the n-th sample from the dataset. Args: key (int): The index of the sample to be loaded Returns: (int, Tensor, List[Tensor]): ``(sample_rate, mix_waveform, list_of_source_waveforms)`` """ return self._load_sample(self.files[key])
from pathlib import Path from typing import List, Tuple, Union import torch import torchaudio from torch.utils.data import Dataset SampleType = Tuple[int, torch.Tensor, List[torch.Tensor]] class LibriMix(Dataset): r"""Create the *LibriMix* [:footcite:`cosentino2020librimix`] dataset. Args: root (str or Path): The path to the directory where the directory ``Libri2Mix`` or ``Libri3Mix`` is stored. subset (str, optional): The subset to use. Options: [``train-360``, ``train-100``, ``dev``, and ``test``] (Default: ``train-360``). num_speakers (int, optional): The number of speakers, which determines the directories to traverse. The Dataset will traverse ``s1`` to ``sN`` directories to collect N source audios. (Default: 2) sample_rate (int, optional): sample rate of audio files. The ``sample_rate`` determines which subdirectory the audio are fetched. If any of the audio has a different sample rate, raises ``ValueError``. Options: [8000, 16000] (Default: 8000) task (str, optional): the task of LibriMix. Options: [``enh_single``, ``enh_both``, ``sep_clean``, ``sep_noisy``] (Default: ``sep_clean``) Note: The LibriMix dataset needs to be manually generated. Please check https://github.com/JorisCos/LibriMix """ def __init__( self, root: Union[str, Path], subset: str = "train-360", num_speakers: int = 2, sample_rate: int = 8000, task: str = "sep_clean", ): self.root = Path(root) / f"Libri{num_speakers}Mix" if sample_rate == 8000: self.root = self.root / "wav8k/min" / subset elif sample_rate == 16000: self.root = self.root / "wav16k/min" / subset else: raise ValueError(f"Unsupported sample rate. Found {sample_rate}.") self.sample_rate = sample_rate self.task = task self.mix_dir = (self.root / f"mix_{task.split('_')[1]}").resolve() self.src_dirs = [(self.root / f"s{i+1}").resolve() for i in range(num_speakers)] self.files = [p.name for p in self.mix_dir.glob("*wav")] self.files.sort() def _load_audio(self, path) -> torch.Tensor: waveform, sample_rate = torchaudio.load(path) if sample_rate != self.sample_rate: raise ValueError( f"The dataset contains audio file of sample rate {sample_rate}, " f"but the requested sample rate is {self.sample_rate}." ) return waveform def _load_sample(self, filename) -> SampleType: mixed = self._load_audio(str(self.mix_dir / filename)) srcs = [] for i, dir_ in enumerate(self.src_dirs): src = self._load_audio(str(dir_ / filename)) if mixed.shape != src.shape: raise ValueError(f"Different waveform shapes. mixed: {mixed.shape}, src[{i}]: {src.shape}") srcs.append(src) return self.sample_rate, mixed, srcs def __len__(self) -> int: return len(self.files) def __getitem__(self, key: int) -> SampleType: """Load the n-th sample from the dataset. Args: key (int): The index of the sample to be loaded Returns: (int, Tensor, List[Tensor]): ``(sample_rate, mix_waveform, list_of_source_waveforms)`` """ return self._load_sample(self.files[key])
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.export.saved_model import ExportArchive as ExportArchive
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.export.saved_model import ExportArchive
from __future__ import annotations try: from typing import Self except ImportError: from typing_extensions import Self import torch from torch import nn from sentence_transformers.models.Module import Module class LSTM(Module): """Bidirectional LSTM running over word embeddings.""" config_keys: list[str] = ["word_embedding_dimension", "hidden_dim", "num_layers", "dropout", "bidirectional"] config_file_name: str = "lstm_config.json" def __init__( self, word_embedding_dimension: int, hidden_dim: int, num_layers: int = 1, dropout: float = 0, bidirectional: bool = True, ): super().__init__() self.word_embedding_dimension = word_embedding_dimension self.hidden_dim = hidden_dim self.num_layers = num_layers self.dropout = dropout self.bidirectional = bidirectional self.embeddings_dimension = hidden_dim if self.bidirectional: self.embeddings_dimension *= 2 self.encoder = nn.LSTM( word_embedding_dimension, hidden_dim, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True, ) def forward(self, features): token_embeddings = features["token_embeddings"] sentence_lengths = torch.clamp(features["sentence_lengths"], min=1) packed = nn.utils.rnn.pack_padded_sequence( token_embeddings, sentence_lengths.cpu(), batch_first=True, enforce_sorted=False ) packed = self.encoder(packed) unpack = nn.utils.rnn.pad_packed_sequence(packed[0], batch_first=True)[0] features.update({"token_embeddings": unpack}) return features def get_word_embedding_dimension(self) -> int: return self.embeddings_dimension def save(self, output_path: str, *args, safe_serialization: bool = True, **kwargs) -> None: self.save_config(output_path) # Saving LSTM models with Safetensors does not work unless the weights are on CPU # See https://github.com/UKPLab/sentence-transformers/pull/2722 device = next(self.parameters()).device self.cpu() self.save_torch_weights(output_path, safe_serialization=safe_serialization) self.to(device) @classmethod def load( cls, model_name_or_path: str, subfolder: str = "", token: bool | str | None = None, cache_folder: str | None = None, revision: str | None = None, local_files_only: bool = False, **kwargs, ) -> Self: hub_kwargs = { "subfolder": subfolder, "token": token, "cache_folder": cache_folder, "revision": revision, "local_files_only": local_files_only, } config = cls.load_config(model_name_or_path=model_name_or_path, **hub_kwargs) model = cls(**config) model = cls.load_torch_weights(model_name_or_path=model_name_or_path, model=model, **hub_kwargs) return model
from __future__ import annotations import json import os import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import nn class LSTM(nn.Module): """Bidirectional LSTM running over word embeddings.""" def __init__( self, word_embedding_dimension: int, hidden_dim: int, num_layers: int = 1, dropout: float = 0, bidirectional: bool = True, ): nn.Module.__init__(self) self.config_keys = ["word_embedding_dimension", "hidden_dim", "num_layers", "dropout", "bidirectional"] self.word_embedding_dimension = word_embedding_dimension self.hidden_dim = hidden_dim self.num_layers = num_layers self.dropout = dropout self.bidirectional = bidirectional self.embeddings_dimension = hidden_dim if self.bidirectional: self.embeddings_dimension *= 2 self.encoder = nn.LSTM( word_embedding_dimension, hidden_dim, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True, ) def forward(self, features): token_embeddings = features["token_embeddings"] sentence_lengths = torch.clamp(features["sentence_lengths"], min=1) packed = nn.utils.rnn.pack_padded_sequence( token_embeddings, sentence_lengths.cpu(), batch_first=True, enforce_sorted=False ) packed = self.encoder(packed) unpack = nn.utils.rnn.pad_packed_sequence(packed[0], batch_first=True)[0] features.update({"token_embeddings": unpack}) return features def get_word_embedding_dimension(self) -> int: return self.embeddings_dimension def tokenize(self, text: str, **kwargs) -> list[int]: raise NotImplementedError() def save(self, output_path: str, safe_serialization: bool = True): with open(os.path.join(output_path, "lstm_config.json"), "w") as fOut: json.dump(self.get_config_dict(), fOut, indent=2) device = next(self.parameters()).device if safe_serialization: save_safetensors_model(self.cpu(), os.path.join(output_path, "model.safetensors")) self.to(device) else: torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin")) def get_config_dict(self): return {key: self.__dict__[key] for key in self.config_keys} @staticmethod def load(input_path: str): with open(os.path.join(input_path, "lstm_config.json")) as fIn: config = json.load(fIn) model = LSTM(**config) if os.path.exists(os.path.join(input_path, "model.safetensors")): load_safetensors_model(model, os.path.join(input_path, "model.safetensors")) else: model.load_state_dict( torch.load( os.path.join(input_path, "pytorch_model.bin"), map_location=torch.device("cpu"), weights_only=True ) ) return model
from __future__ import annotations from collections.abc import Iterable from enum import Enum import torch import torch.nn as nn from sentence_transformers.sparse_encoder.losses import ( FlopsLoss, SparseDistillKLDivLoss, SparseMarginMSELoss, SparseMultipleNegativesRankingLoss, ) from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class PrincipalLoss(Enum): """The principal loss types for the model""" MMSE = SparseMarginMSELoss KL = SparseDistillKLDivLoss MRL = SparseMultipleNegativesRankingLoss class SpladeLoss(nn.Module): def __init__( self, model: SparseEncoder, main_loss: PrincipalLoss, lambda_corpus: float = 0.1, lambda_query: float = 0.1 ): super().__init__() self.model = model self.lambda_corpus = lambda_corpus self.lambda_query = lambda_query self.main_loss = main_loss self.flops_loss = FlopsLoss(model) def forward( self, sentence_features: Iterable[dict[str, torch.Tensor]], labels: torch.Tensor = None ) -> dict[str, torch.Tensor]: # Compute embeddings using the model embeddings = [self.model(sentence_feature)["sentence_embedding"] for sentence_feature in sentence_features] main_loss_value = self.main_loss.compute_loss_from_embeddings(embeddings, labels) flops_query = self.flops_loss.compute_loss_from_embeddings(embeddings, "query") flops_corpus = self.flops_loss.compute_loss_from_embeddings(embeddings, "corpus") # Compute the total loss total_loss = main_loss_value + self.lambda_query * flops_query + self.lambda_corpus * flops_corpus return total_loss def get_config_dict(self): """ Get the configuration dictionary. Returns: Dictionary containing the configuration parameters """ return {"lambda_corpus": self.lambda_corpus, "lambda_query": self.lambda_query, "main_loss": self.main_loss} @property def citation(self) -> str: return """ @inproceedings{10.1145/3477495.3531857, author = {Formal, Thibault and Lassance, Carlos and Piwowarski, Benjamin and Clinchant, St\'{e}phane}, title = {From Distillation to Hard Negative Sampling: Making Sparse Neural IR Models More Effective}, year = {2022}, isbn = {9781450387323}, publisher = {Association for Computing Machinery}, address = {New York, NY, USA}, url = {https://doi.org/10.1145/3477495.3531857}, doi = {10.1145/3477495.3531857}, abstract = {Neural retrievers based on dense representations combined with Approximate Nearest Neighbors search have recently received a lot of attention, owing their success to distillation and/or better sampling of examples for training -- while still relying on the same backbone architecture. In the meantime, sparse representation learning fueled by traditional inverted indexing techniques has seen a growing interest, inheriting from desirable IR priors such as explicit lexical matching. While some architectural variants have been proposed, a lesser effort has been put in the training of such models. In this work, we build on SPLADE -- a sparse expansion-based retriever -- and show to which extent it is able to benefit from the same training improvements as dense models, by studying the effect of distillation, hard-negative mining as well as the Pre-trained Language Model initialization. We furthermore study the link between effectiveness and efficiency, on in-domain and zero-shot settings, leading to state-of-the-art results in both scenarios for sufficiently expressive models.}, booktitle = {Proceedings of the 45th International ACM SIGIR Conference on Research and Development in Information Retrieval}, pages = {2353–2359}, numpages = {7}, keywords = {neural networks, indexing, sparse representations, regularization}, location = {Madrid, Spain}, series = {SIGIR '22} } } """
from __future__ import annotations from collections.abc import Iterable from enum import Enum import torch import torch.nn as nn from sentence_transformers.sparse_encoder.losses import ( FlopsLoss, SparseDistillKLDivLoss, SparseMarginMSELoss, SparseMultipleNegativesRankingLoss, ) from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class PrincipalLoss(Enum): """The principal loss types for the model""" MMSE = SparseMarginMSELoss KL = SparseDistillKLDivLoss MRL = SparseMultipleNegativesRankingLoss class SpladeLoss(nn.Module): def __init__( self, model: SparseEncoder, main_loss: PrincipalLoss, lambda_corpus: float = 0.1, lambda_query: float = 0.1 ): super().__init__() self.model = model self.lambda_corpus = lambda_corpus self.lambda_query = lambda_query self.main_loss = main_loss self.flops_loss = FlopsLoss(model) def forward( self, sentence_features: Iterable[dict[str, torch.Tensor]], labels: torch.Tensor = None ) -> dict[str, torch.Tensor]: # Compute embeddings using the model embeddings = [self.model(sentence_feature)["sentence_embedding"] for sentence_feature in sentence_features] main_loss_value = self.main_loss.compute_loss_from_embeddings(embeddings, labels) flops_query = self.flops_loss.compute_loss_from_embeddings(embeddings, "query") flops_corpus = self.flops_loss.compute_loss_from_embeddings(embeddings, "corpus") # Compute the total loss total_loss = main_loss_value + self.lambda_query * flops_query + self.lambda_corpus * flops_corpus return total_loss def get_config_dict(self): """ Get the configuration dictionary. Returns: Dictionary containing the configuration parameters """ return {"lambda_corpus": self.lambda_corpus, "lambda_query": self.lambda_query, "main_loss": self.main_loss} @property def citation(self) -> str: return """ @misc{wen2025matryoshkarevisitingsparsecoding, title={Beyond Matryoshka: Revisiting Sparse Coding for Adaptive Representation}, author={Tiansheng Wen and Yifei Wang and Zequn Zeng and Zhong Peng and Yudi Su and Xinyang Liu and Bo Chen and Hongwei Liu and Stefanie Jegelka and Chenyu You}, year={2025}, eprint={2503.01776}, archivePrefix={arXiv}, primaryClass={cs.LG}, url={https://arxiv.org/abs/2503.01776}, } """
import pytest import torch from torchaudio._internal.module_utils import UNSUPPORTED from torchaudio.sox_effects import apply_effects_tensor # Importing prototype modules is needed to trigger the registration of the # corresponding APIs in the UNSUPPORTED register. from torchaudio.prototype import datasets, functional, models, pipelines, transforms @pytest.mark.parametrize("func", UNSUPPORTED) def test_deprecations(func): with pytest.warns(UserWarning, match="deprecated"): try: func() except Exception as e: assert isinstance(e, (TypeError, RuntimeError, ValueError, ImportError)) # It's not great, but the deprecation decorator we're using breaks torchscript # This test just illustrates this behavior. Ideally, we wouldn't break # torchscript users. But oh well, torchscript is supposed to have been # deprecated for years. @pytest.mark.parametrize("scripted", (True, False)) def test_torchscript_fails(scripted): f = apply_effects_tensor if scripted: pytest.xfail("Deprecation decorator breaks torchscript") f = torch.jit.script(f) _, out_sample_rate = f(torch.rand(2, 1000), sample_rate=16_000, effects=[["rate", "8000"]]) assert out_sample_rate == 8000
import pytest from torchaudio._internal.module_utils import UNSUPPORTED @pytest.mark.parametrize("func", UNSUPPORTED) def test_deprecations(func): with pytest.warns(UserWarning, match="deprecated"): try: func() except Exception as e: # Type or Runtime error because we call func() without proper parameters. # The deprecation warning is still properly raised, since it is emitted before # the underlying (deprecated) function is called. assert isinstance(e, (TypeError, RuntimeError))
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 unittest.mock import patch import transformers.commands.transformers_cli as cli from transformers.commands.serving import ServeCommand from transformers.testing_utils import CaptureStd class ServeCLITest(unittest.TestCase): def test_help(self): with patch("sys.argv", ["transformers", "serve", "--help"]), CaptureStd() as cs: with self.assertRaises(SystemExit): cli.main() self.assertIn("serve", cs.out.lower()) def test_parsed_args(self): with ( patch.object(ServeCommand, "__init__", return_value=None) as init_mock, patch.object(ServeCommand, "run") as run_mock, patch("sys.argv", ["transformers", "serve", "--host", "0.0.0.0", "--port", "9000"]), ): cli.main() init_mock.assert_called_once() run_mock.assert_called_once() parsed_args = init_mock.call_args[0][0] self.assertEqual(parsed_args.host, "0.0.0.0") self.assertEqual(parsed_args.port, 9000) def test_build_chunk(self): dummy = ServeCommand.__new__(ServeCommand) dummy.args = type("Args", (), {})() chunk = ServeCommand.build_chunk(dummy, "hello", "req0", finish_reason="stop") self.assertIn("chat.completion.chunk", chunk) self.assertIn("data:", chunk)
import unittest from unittest.mock import patch import transformers.commands.transformers_cli as cli from transformers.commands.serving import ServeCommand from transformers.testing_utils import CaptureStd class ServeCLITest(unittest.TestCase): def test_help(self): with patch("sys.argv", ["transformers", "serve", "--help"]), CaptureStd() as cs: with self.assertRaises(SystemExit): cli.main() self.assertIn("serve", cs.out.lower()) def test_parsed_args(self): with ( patch.object(ServeCommand, "__init__", return_value=None) as init_mock, patch.object(ServeCommand, "run") as run_mock, patch("sys.argv", ["transformers", "serve", "--host", "0.0.0.0", "--port", "9000"]), ): cli.main() init_mock.assert_called_once() run_mock.assert_called_once() parsed_args = init_mock.call_args[0][0] self.assertEqual(parsed_args.host, "0.0.0.0") self.assertEqual(parsed_args.port, 9000) def test_build_chunk(self): dummy = ServeCommand.__new__(ServeCommand) dummy.args = type("Args", (), {})() chunk = ServeCommand.build_chunk(dummy, "hello", "req0", finish_reason="stop") self.assertIn("chat.completion.chunk", chunk) self.assertIn("data:", chunk)
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_detection.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_1x.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( num_classes=8, loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)))) # optimizer # lr is set for a batch size of 8 optim_wrapper = dict(optimizer=dict(lr=0.01)) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=8, by_epoch=True, # [7] yields higher performance than [6] milestones=[7], gamma=0.1) ] # actual epoch = 8 * 8 = 64 train_cfg = dict(max_epochs=8) # For better, more stable performance initialize from COCO load_from = 'https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' # noqa # NOTE: `auto_scale_lr` is for automatically scaling LR, # USER SHOULD NOT CHANGE ITS VALUES. # base_batch_size = (8 GPUs) x (1 samples per GPU) # TODO: support auto scaling lr # auto_scale_lr = dict(base_batch_size=8)
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/cityscapes_detection.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict(init_cfg=None), roi_head=dict( bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=8, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)))) # optimizer # lr is set for a batch size of 8 optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # learning rate 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, # [7] yields higher performance than [6] milestones=[7], gamma=0.1) ] train_cfg = dict(by_epoch=True, max_epochs=8) # actual epoch = 8 * 8 = 64 val_cfg = dict(interval=1) test_cfg = dict() # For better, more stable performance initialize from COCO load_from = 'https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' # noqa # NOTE: `auto_scale_lr` is for automatically scaling LR, # USER SHOULD NOT CHANGE ITS VALUES. # base_batch_size = (8 GPUs) x (1 samples per GPU) # TODO: support auto scaling lr # auto_scale_lr = dict(base_batch_size=8)
# Copyright (c) OpenMMLab. All rights reserved. import logging from typing import Any, List, Optional, Sequence, Tuple import torch from torch.nn.parameter import Parameter from torch.nn.utils import clip_grad from mmengine.data import BaseDataElement from mmengine.registry import HOOKS from .hook import Hook DATA_BATCH = Optional[Sequence[Tuple[Any, BaseDataElement]]] @HOOKS.register_module() class OptimizerHook(Hook): """A hook contains custom operations for the optimizer. Args: grad_clip (dict, optional): A config dict to control the clip_grad. Defaults to None. detect_anomalous_params (bool): This option is only used for debugging which will slow down the training speed. Detect anomalous parameters that are not included in the computational graph with ``loss`` as the root. There are two cases - Parameters were not used during forward pass. - Parameters were not used to produce loss. Defaults to False. """ priority = 'HIGH' def __init__(self, grad_clip: Optional[dict] = None, detect_anomalous_params: bool = False) -> None: self.grad_clip = grad_clip self.detect_anomalous_params = detect_anomalous_params def clip_grads(self, params: List[Parameter]) -> Optional[torch.Tensor]: """Clip the gradients of parameters. Args: params (list[Parameter]): Model's parameters. Returns: Optional[torch.Tensor]: Total norm of the parameters if there is at least one param requiring gradient, else None. """ params = list( filter(lambda p: p.requires_grad and p.grad is not None, params)) if len(params) > 0: return clip_grad.clip_grad_norm_(params, **self.grad_clip) return None def after_train_iter(self, runner, batch_idx: int, data_batch: DATA_BATCH = None, outputs: Optional[dict] = None) -> None: """All operations need to be finished after each training iteration. This function will finish following 3 operations: - Detect any anomalous parameters which are not included in the training graph. (optional) - Compute the gradient of model parameters. - Clip the gradients of each parameter. (optional) - Update model parameters with gradients. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the train loop. data_batch (Sequence[Tuple[Any, BaseDataElement]], optional): Data from dataloader. In order to keep this interface consistent with other hooks, we keep ``data_batch`` here. Defaults to None. outputs (dict, optional): Outputs from model. In order to keep this interface consistent with other hooks, we keep ``outputs`` here. Defaults to None. """ runner.optimizer.zero_grad() if self.detect_anomalous_params: self.detect_anomalous_parameters(runner.outputs['loss'], runner) runner.outputs['loss'].backward() if self.grad_clip is not None: grad_norm = self.clip_grads(runner.model.parameters()) if grad_norm is not None: # Add grad norm to the logger runner.log_buffer.update({'grad_norm': float(grad_norm)}, runner.outputs['num_samples']) runner.optimizer.step() def detect_anomalous_parameters(self, loss: torch.Tensor, runner) -> None: """Detect anomalous parameters that are not included in the graph. Args: loss (torch.Tensor): The loss of current iteration. runner (Runner): The runner of the training process. """ logger = runner.logger parameters_in_graph = set() visited = set() def traverse(grad_fn): if grad_fn is None: return if grad_fn not in visited: visited.add(grad_fn) if hasattr(grad_fn, 'variable'): parameters_in_graph.add(grad_fn.variable) parents = grad_fn.next_functions if parents is not None: for parent in parents: grad_fn = parent[0] traverse(grad_fn) traverse(loss.grad_fn) for n, p in runner.model.named_parameters(): if p not in parameters_in_graph and p.requires_grad: logger.log( level=logging.ERROR, msg=f'{n} with shape {p.size()} is not ' f'in the computational graph \n')
# Copyright (c) OpenMMLab. All rights reserved. import logging from typing import Any, List, Optional, Sequence, Tuple import torch from torch.nn.parameter import Parameter from torch.nn.utils import clip_grad from mmengine.data import BaseDataSample from mmengine.registry import HOOKS from .hook import Hook DATA_BATCH = Optional[Sequence[Tuple[Any, BaseDataSample]]] @HOOKS.register_module() class OptimizerHook(Hook): """A hook contains custom operations for the optimizer. Args: grad_clip (dict, optional): A config dict to control the clip_grad. Defaults to None. detect_anomalous_params (bool): This option is only used for debugging which will slow down the training speed. Detect anomalous parameters that are not included in the computational graph with ``loss`` as the root. There are two cases - Parameters were not used during forward pass. - Parameters were not used to produce loss. Defaults to False. """ priority = 'HIGH' def __init__(self, grad_clip: Optional[dict] = None, detect_anomalous_params: bool = False) -> None: self.grad_clip = grad_clip self.detect_anomalous_params = detect_anomalous_params def clip_grads(self, params: List[Parameter]) -> Optional[torch.Tensor]: """Clip the gradients of parameters. Args: params (list[Parameter]): Model's parameters. Returns: Optional[torch.Tensor]: Total norm of the parameters if there is at least one param requiring gradient, else None. """ params = list( filter(lambda p: p.requires_grad and p.grad is not None, params)) if len(params) > 0: return clip_grad.clip_grad_norm_(params, **self.grad_clip) return None def after_train_iter(self, runner, batch_idx: int, data_batch: DATA_BATCH = None, outputs: Optional[dict] = None) -> None: """All operations need to be finished after each training iteration. This function will finish following 3 operations: - Detect any anomalous parameters which are not included in the training graph. (optional) - Compute the gradient of model parameters. - Clip the gradients of each parameter. (optional) - Update model parameters with gradients. Args: runner (Runner): The runner of the training process. batch_idx (int): The index of the current batch in the train loop. data_batch (Sequence[Tuple[Any, BaseDataSample]], optional): Data from dataloader. In order to keep this interface consistent with other hooks, we keep ``data_batch`` here. Defaults to None. outputs (dict, optional): Outputs from model. In order to keep this interface consistent with other hooks, we keep ``outputs`` here. Defaults to None. """ runner.optimizer.zero_grad() if self.detect_anomalous_params: self.detect_anomalous_parameters(runner.outputs['loss'], runner) runner.outputs['loss'].backward() if self.grad_clip is not None: grad_norm = self.clip_grads(runner.model.parameters()) if grad_norm is not None: # Add grad norm to the logger runner.log_buffer.update({'grad_norm': float(grad_norm)}, runner.outputs['num_samples']) runner.optimizer.step() def detect_anomalous_parameters(self, loss: torch.Tensor, runner) -> None: """Detect anomalous parameters that are not included in the graph. Args: loss (torch.Tensor): The loss of current iteration. runner (Runner): The runner of the training process. """ logger = runner.logger parameters_in_graph = set() visited = set() def traverse(grad_fn): if grad_fn is None: return if grad_fn not in visited: visited.add(grad_fn) if hasattr(grad_fn, 'variable'): parameters_in_graph.add(grad_fn.variable) parents = grad_fn.next_functions if parents is not None: for parent in parents: grad_fn = parent[0] traverse(grad_fn) traverse(loss.grad_fn) for n, p in runner.model.named_parameters(): if p not in parameters_in_graph and p.requires_grad: logger.log( level=logging.ERROR, msg=f'{n} with shape {p.size()} is not ' f'in the computational graph \n')
from typing import List, Optional import pandas as pd import pytest from docarray import BaseDoc, DocList, DocVec from docarray.documents import ImageDoc @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDoc): count: Optional[int] text: str class MyDocNested(MyDoc): image: ImageDoc lst: List[str] return MyDocNested @pytest.mark.parametrize('doc_vec', [False, True]) def test_to_from_pandas_df(nested_doc_cls, doc_vec): da = DocList[nested_doc_cls]( [ nested_doc_cls( count=0, text='hello', image=ImageDoc(url='aux.png'), lst=["hello", "world"], ), nested_doc_cls( text='hello world', image=ImageDoc(), lst=["hello", "world"] ), ] ) if doc_vec: da = da.to_doc_vec() df = da.to_dataframe() assert isinstance(df, pd.DataFrame) assert len(df) == 2 assert ( df.columns == [ 'id', 'count', 'text', 'image__id', 'image__url', 'image__tensor', 'image__embedding', 'image__bytes_', 'lst', ] ).all() if doc_vec: da_from_df = DocVec[nested_doc_cls].from_dataframe(df) assert isinstance(da_from_df, DocVec) else: da_from_df = DocList[nested_doc_cls].from_dataframe(df) assert isinstance(da_from_df, DocList) for doc1, doc2 in zip(da, da_from_df): assert doc1 == doc2 @pytest.fixture() def nested_doc(): class Inner(BaseDoc): img: Optional[ImageDoc] class Middle(BaseDoc): img: Optional[ImageDoc] inner: Optional[Inner] class Outer(BaseDoc): img: Optional[ImageDoc] middle: Optional[Middle] doc = Outer( img=ImageDoc(), middle=Middle(img=ImageDoc(), inner=Inner(img=ImageDoc())) ) return doc @pytest.mark.parametrize('array_cls', [DocList, DocVec]) def test_from_pandas_without_schema_raise_exception(array_cls): with pytest.raises(TypeError, match='no document schema defined'): df = pd.DataFrame( columns=['title', 'count'], data=[['title 0', 0], ['title 1', 1]] ) array_cls.from_dataframe(df=df) @pytest.mark.parametrize('array_cls', [DocList, DocVec]) def test_from_pandas_with_wrong_schema_raise_exception(nested_doc, array_cls): with pytest.raises(ValueError, match='Column names do not match the schema'): df = pd.DataFrame( columns=['title', 'count'], data=[['title 0', 0], ['title 1', 1]] ) array_cls[nested_doc.__class__].from_dataframe(df=df) def test_doc_list_error(): class Book(BaseDoc): title: str # not testing DocVec bc it already fails here (as it should!) docs = DocList([Book(title='hello'), Book(title='world')]) with pytest.raises(TypeError): docs.to_dataframe() @pytest.mark.proto def test_union_type_error(): from typing import Union from docarray.documents import TextDoc class CustomDoc(BaseDoc): ud: Union[TextDoc, ImageDoc] = TextDoc(text='union type') docs = DocList[CustomDoc]([CustomDoc(ud=TextDoc(text='union type'))]) with pytest.raises(ValueError): DocList[CustomDoc].from_dataframe(docs.to_dataframe()) class BasisUnion(BaseDoc): ud: Union[int, str] docs_basic = DocList[BasisUnion]([BasisUnion(ud="hello")]) docs_copy = DocList[BasisUnion].from_dataframe(docs_basic.to_dataframe()) assert docs_copy == docs_basic
from typing import List, Optional import pandas as pd import pytest from docarray import BaseDoc, DocList from docarray.documents import ImageDoc @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDoc): count: Optional[int] text: str class MyDocNested(MyDoc): image: ImageDoc lst: List[str] return MyDocNested def test_to_from_pandas_df(nested_doc_cls): da = DocList[nested_doc_cls]( [ nested_doc_cls( count=0, text='hello', image=ImageDoc(url='aux.png'), lst=["hello", "world"], ), nested_doc_cls( text='hello world', image=ImageDoc(), lst=["hello", "world"] ), ] ) df = da.to_dataframe() assert isinstance(df, pd.DataFrame) assert len(df) == 2 assert ( df.columns == [ 'id', 'count', 'text', 'image__id', 'image__url', 'image__tensor', 'image__embedding', 'image__bytes_', 'lst', ] ).all() da_from_df = DocList[nested_doc_cls].from_dataframe(df) for doc1, doc2 in zip(da, da_from_df): assert doc1 == doc2 @pytest.fixture() def nested_doc(): class Inner(BaseDoc): img: Optional[ImageDoc] class Middle(BaseDoc): img: Optional[ImageDoc] inner: Optional[Inner] class Outer(BaseDoc): img: Optional[ImageDoc] middle: Optional[Middle] doc = Outer( img=ImageDoc(), middle=Middle(img=ImageDoc(), inner=Inner(img=ImageDoc())) ) return doc def test_from_pandas_without_schema_raise_exception(): with pytest.raises(TypeError, match='no document schema defined'): df = pd.DataFrame( columns=['title', 'count'], data=[['title 0', 0], ['title 1', 1]] ) DocList.from_dataframe(df=df) def test_from_pandas_with_wrong_schema_raise_exception(nested_doc): with pytest.raises(ValueError, match='Column names do not match the schema'): df = pd.DataFrame( columns=['title', 'count'], data=[['title 0', 0], ['title 1', 1]] ) DocList[nested_doc.__class__].from_dataframe(df=df) def test_doc_list_error(): class Book(BaseDoc): title: str docs = DocList([Book(title='hello'), Book(title='world')]) with pytest.raises(TypeError): docs.to_dataframe() @pytest.mark.proto def test_union_type_error(): from typing import Union from docarray.documents import TextDoc class CustomDoc(BaseDoc): ud: Union[TextDoc, ImageDoc] = TextDoc(text='union type') docs = DocList[CustomDoc]([CustomDoc(ud=TextDoc(text='union type'))]) with pytest.raises(ValueError): DocList[CustomDoc].from_dataframe(docs.to_dataframe()) class BasisUnion(BaseDoc): ud: Union[int, str] docs_basic = DocList[BasisUnion]([BasisUnion(ud="hello")]) docs_copy = DocList[BasisUnion].from_dataframe(docs_basic.to_dataframe()) assert docs_copy == docs_basic
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable from sentence_transformers.evaluation import RerankingEvaluator from sentence_transformers.util import cos_sim if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = logging.getLogger(__name__) class SparseRerankingEvaluator(RerankingEvaluator): def __init__( self, samples: list[dict[str, str | list[str]]], at_k: int = 10, name: str = "", write_csv: bool = True, similarity_fct: Callable[[Tensor, Tensor], Tensor] = cos_sim, batch_size: int = 64, show_progress_bar: bool = False, use_batched_encoding: bool = True, truncate_dim: int | None = None, mrr_at_k: int | None = None, ): super().__init__( samples=samples, at_k=at_k, name=name, write_csv=write_csv, similarity_fct=similarity_fct, batch_size=batch_size, show_progress_bar=show_progress_bar, use_batched_encoding=use_batched_encoding, truncate_dim=truncate_dim, mrr_at_k=mrr_at_k, ) def __call__( self, model: SparseEncoder, output_path: str = None, epoch: int = -1, steps: int = -1 ) -> dict[str, float]: return super().__call__(model, output_path, epoch, steps) def compute_metrices( self, model: SparseEncoder, ): return super().compute_metrices(model) def compute_metrices_batched( self, model: SparseEncoder, ): return super().compute_metrices_batched(model) def compute_metrices_individual( self, model: SparseEncoder, ): return super().compute_metrices_individual(model) def embed_inputs( self, model: SparseEncoder, sentences: str | list[str] | np.ndarray, show_progress_bar: bool | None = None, **kwargs, ) -> Tensor: return model.encode( sentences, batch_size=self.batch_size, show_progress_bar=show_progress_bar, convert_to_tensor=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, step)
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import RerankingEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = logging.getLogger(__name__) class SparseRerankingEvaluator(RerankingEvaluator): def __call__( self, model: SparseEncoder, output_path: str = None, epoch: int = -1, steps: int = -1 ) -> dict[str, float]: return super.__call__(model, output_path, epoch, steps) def compute_metrices( self, model: SparseEncoder, ): return super.compute_metrices(model) def compute_metrices_batched( self, model: SparseEncoder, ): return super.compute_metrices_batched(model) def compute_metrices_individual( self, model: SparseEncoder, ): return super.compute_metrices_individual(model) def embed_inputs( self, model: SparseEncoder, sentences: str | list[str] | np.ndarray, show_progress_bar: bool | None = None, **kwargs, ) -> Tensor: return model.encode( sentences, batch_size=self.batch_size, show_progress_bar=show_progress_bar, convert_to_tensor=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, step)
_base_ = './retinanet_r50-caffe_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomChoiceResize', scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] train_dataloader = dict(dataset=dict(pipeline=train_pipeline))
_base_ = './retinanet_r50-caffe_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), dict(type='PackDetInputs') ] train_dataloader = dict(dataset=dict(pipeline=train_pipeline))
from typing import Optional from fastapi import Depends, FastAPI, Query, status from fastapi.testclient import TestClient app = FastAPI() def _get_client_key(client_id: str = Query(...)) -> str: return f"{client_id}_key" def _get_client_tag(client_id: Optional[str] = Query(None)) -> Optional[str]: if client_id is None: return None return f"{client_id}_tag" @app.get("/foo") def foo_handler( client_key: str = Depends(_get_client_key), client_tag: Optional[str] = Depends(_get_client_tag), ): return {"client_id": client_key, "client_tag": client_tag} client = TestClient(app) expected_schema = { "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "title": "Detail", "type": "array", } }, "title": "HTTPValidationError", "type": "object", }, "ValidationError": { "properties": { "loc": { "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, "title": "Location", "type": "array", }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", "type": "object", }, } }, "info": {"title": "FastAPI", "version": "0.1.0"}, "openapi": "3.1.0", "paths": { "/foo": { "get": { "operationId": "foo_handler_foo_get", "parameters": [ { "in": "query", "name": "client_id", "required": True, "schema": {"title": "Client Id", "type": "string"}, }, ], "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, "description": "Validation Error", }, }, "summary": "Foo Handler", } } }, } def test_schema(): response = client.get("/openapi.json") assert response.status_code == status.HTTP_200_OK actual_schema = response.json() assert actual_schema == expected_schema def test_get_invalid(): response = client.get("/foo") assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY def test_get_valid(): response = client.get("/foo", params={"client_id": "bar"}) assert response.status_code == 200 assert response.json() == {"client_id": "bar_key", "client_tag": "bar_tag"}
from typing import Optional from fastapi import Depends, FastAPI, Query, status from fastapi.testclient import TestClient app = FastAPI() def _get_client_key(client_id: str = Query(...)) -> str: return f"{client_id}_key" def _get_client_tag(client_id: Optional[str] = Query(None)) -> Optional[str]: if client_id is None: return None return f"{client_id}_tag" @app.get("/foo") def foo_handler( client_key: str = Depends(_get_client_key), client_tag: Optional[str] = Depends(_get_client_tag), ): return {"client_id": client_key, "client_tag": client_tag} client = TestClient(app) expected_schema = { "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "title": "Detail", "type": "array", } }, "title": "HTTPValidationError", "type": "object", }, "ValidationError": { "properties": { "loc": { "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, "title": "Location", "type": "array", }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error " "Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", "type": "object", }, } }, "info": {"title": "FastAPI", "version": "0.1.0"}, "openapi": "3.1.0", "paths": { "/foo": { "get": { "operationId": "foo_handler_foo_get", "parameters": [ { "in": "query", "name": "client_id", "required": True, "schema": {"title": "Client Id", "type": "string"}, }, ], "responses": { "200": { "content": {"application/json": {"schema": {}}}, "description": "Successful " "Response", }, "422": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, "description": "Validation " "Error", }, }, "summary": "Foo Handler", } } }, } def test_schema(): response = client.get("/openapi.json") assert response.status_code == status.HTTP_200_OK actual_schema = response.json() assert actual_schema == expected_schema def test_get_invalid(): response = client.get("/foo") assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY def test_get_valid(): response = client.get("/foo", params={"client_id": "bar"}) assert response.status_code == 200 assert response.json() == {"client_id": "bar_key", "client_tag": "bar_tag"}
from typing import Any, Dict, List, Optional, Tuple from llama_index.core.schema import BaseNode, TextNode from llama_index.core.vector_stores.utils import ( metadata_dict_to_node, legacy_metadata_dict_to_node, ) import json import logging logger = logging.getLogger(__name__) def create_node_from_result( result: Dict[str, Any], field_mapping: Dict[str, str] ) -> BaseNode: """ Create a node from a search result. Args: result (Dict[str, Any]): Search result dictionary field_mapping (Dict[str, str]): Field mapping dictionary Returns: BaseNode: Created node """ metadata_str = result[field_mapping["metadata"]] metadata = json.loads(metadata_str) if metadata_str else {} try: node = metadata_dict_to_node(metadata) node.set_content(result[field_mapping["chunk"]]) node.embedding = result.get(field_mapping["embedding"]) except Exception: # NOTE: deprecated legacy logic for backward compatibility metadata, node_info, relationships = legacy_metadata_dict_to_node(metadata) node = TextNode( text=result[field_mapping["chunk"]], id_=result[field_mapping["id"]], metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) if field_mapping.get("embedding"): node.embedding = result.get(field_mapping["embedding"]) return node def process_batch_results( batch_nodes: List[BaseNode], nodes: List[BaseNode], batch_size: int, limit: Optional[int] = None, ) -> Tuple[List[BaseNode], bool]: """ Process batch results and determine if we should continue fetching. Args: batch_nodes (List[BaseNode]): Current batch of nodes nodes (List[BaseNode]): Accumulated nodes batch_size (int): Size of each batch limit (Optional[int]): Maximum number of nodes to retrieve Returns: Tuple[List[BaseNode], bool]: Updated nodes list and whether to continue fetching """ if not batch_nodes: return nodes, False nodes.extend(batch_nodes) # If we've hit the requested limit, stop if limit and len(nodes) >= limit: return nodes[:limit], False # If we got less than batch_size results, we've hit the end if len(batch_nodes) < batch_size: return nodes, False return nodes, True def create_search_request( field_mapping: Dict[str, str], filter_str: Optional[str], batch_size: int, offset: int, ) -> Dict[str, Any]: """ Create a search request dictionary. Args: field_mapping (Dict[str, str]): Field mapping dictionary filter_str (Optional[str]): OData filter string batch_size (int): Size of batch to retrieve offset (int): Number of results to skip Returns: Dict[str, Any]: Search request parameters """ return { "search_text": "*", "filter": filter_str, "top": batch_size, "skip": offset, "select": list(field_mapping.values()), } def handle_search_error(e: Exception) -> None: """ Handle search errors by logging them appropriately. Args: e (Exception): The exception that occurred """ if isinstance(e, ValueError): logger.error(f"Invalid search parameters: {e}") else: logger.error(f"Error during search operation: {e}")
from typing import Any, Dict, List, Optional, Tuple from llama_index.core.schema import BaseNode, TextNode from llama_index.core.vector_stores.utils import ( metadata_dict_to_node, legacy_metadata_dict_to_node, ) import json import logging logger = logging.getLogger(__name__) def create_node_from_result( result: Dict[str, Any], field_mapping: Dict[str, str] ) -> BaseNode: """Create a node from a search result. Args: result (Dict[str, Any]): Search result dictionary field_mapping (Dict[str, str]): Field mapping dictionary Returns: BaseNode: Created node """ metadata_str = result[field_mapping["metadata"]] metadata = json.loads(metadata_str) if metadata_str else {} try: node = metadata_dict_to_node(metadata) node.set_content(result[field_mapping["chunk"]]) node.embedding = result.get(field_mapping["embedding"]) except Exception: # NOTE: deprecated legacy logic for backward compatibility metadata, node_info, relationships = legacy_metadata_dict_to_node(metadata) node = TextNode( text=result[field_mapping["chunk"]], id_=result[field_mapping["id"]], metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) if field_mapping.get("embedding"): node.embedding = result.get(field_mapping["embedding"]) return node def process_batch_results( batch_nodes: List[BaseNode], nodes: List[BaseNode], batch_size: int, limit: Optional[int] = None, ) -> Tuple[List[BaseNode], bool]: """Process batch results and determine if we should continue fetching. Args: batch_nodes (List[BaseNode]): Current batch of nodes nodes (List[BaseNode]): Accumulated nodes batch_size (int): Size of each batch limit (Optional[int]): Maximum number of nodes to retrieve Returns: Tuple[List[BaseNode], bool]: Updated nodes list and whether to continue fetching """ if not batch_nodes: return nodes, False nodes.extend(batch_nodes) # If we've hit the requested limit, stop if limit and len(nodes) >= limit: return nodes[:limit], False # If we got less than batch_size results, we've hit the end if len(batch_nodes) < batch_size: return nodes, False return nodes, True def create_search_request( field_mapping: Dict[str, str], filter_str: Optional[str], batch_size: int, offset: int, ) -> Dict[str, Any]: """Create a search request dictionary. Args: field_mapping (Dict[str, str]): Field mapping dictionary filter_str (Optional[str]): OData filter string batch_size (int): Size of batch to retrieve offset (int): Number of results to skip Returns: Dict[str, Any]: Search request parameters """ return { "search_text": "*", "filter": filter_str, "top": batch_size, "skip": offset, "select": list(field_mapping.values()), } def handle_search_error(e: Exception) -> None: """Handle search errors by logging them appropriately. Args: e (Exception): The exception that occurred """ if isinstance(e, ValueError): logger.error(f"Invalid search parameters: {e}") else: logger.error(f"Error during search operation: {e}")
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder class CrossEntropyLoss(nn.Module): def __init__(self, model: CrossEncoder, activation_fct: nn.Module = nn.Identity(), **kwargs) -> None: """ Computes the Cross Entropy Loss for a CrossEncoder model. This loss is used to train a model to predict the correct class label for a given pair of sentences. The number of classes should be equal to the number of model output labels. Args: model (:class:`~sentence_transformers.cross_encoder.CrossEncoder`): A CrossEncoder model to be trained. activation_fct (:class:`~torch.nn.Module`): Activation function applied to the logits before computing the loss. Defaults to :class:`~torch.nn.Identity`. **kwargs: Additional keyword arguments passed to the underlying :class:`torch.nn.CrossEntropyLoss`. References: - :class:`torch.nn.CrossEntropyLoss` Requirements: 1. Your model can be initialized with `num_labels > 1` to predict multiple classes. 2. The number of dataset classes should be equal to the number of model output labels (`model.num_labels`). Inputs: +-------------------------------------------------+--------+-------------------------------+ | Texts | Labels | Number of Model Output Labels | +=================================================+========+===============================+ | (sentence_A, sentence_B) pairs | class | `num_classes` | +-------------------------------------------------+--------+-------------------------------+ Example: :: from sentence_transformers.cross_encoder import CrossEncoder, CrossEncoderTrainer, losses from datasets import Dataset model = CrossEncoder("microsoft/mpnet-base", num_labels=2) train_dataset = Dataset.from_dict({ "sentence1": ["How can I be a good geologist?", "What is the capital of France?"], "sentence2": ["What should I do to be a great geologist?", "What is the capital of Germany?"], "label": [1, 0], # 1: duplicate, 0: not duplicate }) loss = losses.CrossEntropyLoss(model) trainer = CrossEncoderTrainer( model=model, train_dataset=train_dataset, loss=loss, ) trainer.train() """ super().__init__() self.model = model self.activation_fct = activation_fct self.ce_loss = nn.CrossEntropyLoss(**kwargs) if not isinstance(self.model, CrossEncoder): raise ValueError( f"{self.__class__.__name__} expects a model of type CrossEncoder, " f"but got a model of type {type(self.model)}." ) def forward(self, inputs: list[list[str]], labels: Tensor) -> Tensor: if len(inputs) != 2: raise ValueError( f"CrossEntropyLoss expects a dataset with two non-label columns, but got a dataset with {len(inputs)} columns." ) pairs = list(zip(inputs[0], inputs[1])) tokens = self.model.tokenizer( pairs, padding=True, truncation=True, return_tensors="pt", ) tokens.to(self.model.device) logits = self.model(**tokens)[0] logits = self.activation_fct(logits) loss = self.ce_loss(logits, labels) return loss
from __future__ import annotations from torch import Tensor, nn from sentence_transformers.cross_encoder import CrossEncoder # TODO: Consider the naming of this class class CrossEntropyLoss(nn.Module): def __init__(self, model: CrossEncoder, activation_fct: nn.Module = nn.Identity(), **kwargs) -> None: super().__init__() self.model = model self.activation_fct = activation_fct self.ce_loss = nn.CrossEntropyLoss(**kwargs) def forward(self, inputs: list[list[str]], labels: Tensor) -> Tensor: if len(inputs) != 2: raise ValueError( f"CrossEntropyLoss expects a dataset with two non-label columns, but got a dataset with {len(inputs)} columns." ) pairs = list(zip(inputs[0], inputs[1])) tokens = self.model.tokenizer( pairs, padding=True, truncation=True, return_tensors="pt", ) tokens.to(self.model.device) logits = self.model(**tokens)[0] logits = self.activation_fct(logits) loss = self.ce_loss(logits, labels) return loss
from typing import Any import torch import enum from torch._C import _to_dlpack as to_dlpack __all__ = [ "DLDeviceType", "from_dlpack", ] class DLDeviceType(enum.IntEnum): # Enums as in DLPack specification (aten/src/ATen/dlpack.h) kDLCPU = 1, kDLCUDA = 2, kDLCUDAHost = 3, kDLOpenCL = 4, kDLVulkan = 7, kDLMetal = 8, kDLVPI = 9, kDLROCM = 10, kDLROCMHost = 11, kDLExtDev = 12, kDLCUDAManaged = 13, kDLOneAPI = 14, kDLWebGPU = 15, kDLHexagon = 16, kDLMAIA = 17, torch._C._add_docstr(to_dlpack, r"""to_dlpack(tensor) -> PyCapsule Returns an opaque object (a "DLPack capsule") representing the tensor. .. note:: ``to_dlpack`` is a legacy DLPack interface. The capsule it returns cannot be used for anything in Python other than use it as input to ``from_dlpack``. The more idiomatic use of DLPack is to call ``from_dlpack`` directly on the tensor object - this works when that object has a ``__dlpack__`` method, which PyTorch and most other libraries indeed have now. .. warning:: Only call ``from_dlpack`` once per capsule produced with ``to_dlpack``. Behavior when a capsule is consumed multiple times is undefined. Args: tensor: a tensor to be exported The DLPack capsule shares the tensor's memory. """) # TODO: add a typing.Protocol to be able to tell Mypy that only objects with # __dlpack__ and __dlpack_device__ methods are accepted. def from_dlpack(ext_tensor: Any) -> 'torch.Tensor': """from_dlpack(ext_tensor) -> Tensor Converts a tensor from an external library into a ``torch.Tensor``. The returned PyTorch tensor will share the memory with the input tensor (which may have come from another library). Note that in-place operations will therefore also affect the data of the input tensor. This may lead to unexpected issues (e.g., other libraries may have read-only flags or immutable data structures), so the user should only do this if they know for sure that this is fine. Args: ext_tensor (object with ``__dlpack__`` attribute, or a DLPack capsule): The tensor or DLPack capsule to convert. If ``ext_tensor`` is a tensor (or ndarray) object, it must support the ``__dlpack__`` protocol (i.e., have a ``ext_tensor.__dlpack__`` method). Otherwise ``ext_tensor`` may be a DLPack capsule, which is an opaque ``PyCapsule`` instance, typically produced by a ``to_dlpack`` function or method. Examples:: >>> import torch.utils.dlpack >>> t = torch.arange(4) # Convert a tensor directly (supported in PyTorch >= 1.10) >>> t2 = torch.from_dlpack(t) >>> t2[:2] = -1 # show that memory is shared >>> t2 tensor([-1, -1, 2, 3]) >>> t tensor([-1, -1, 2, 3]) # The old-style DLPack usage, with an intermediate capsule object >>> capsule = torch.utils.dlpack.to_dlpack(t) >>> capsule <capsule object "dltensor" at ...> >>> t3 = torch.from_dlpack(capsule) >>> t3 tensor([-1, -1, 2, 3]) >>> t3[0] = -9 # now we're sharing memory between 3 tensors >>> t3 tensor([-9, -1, 2, 3]) >>> t2 tensor([-9, -1, 2, 3]) >>> t tensor([-9, -1, 2, 3]) """ if hasattr(ext_tensor, '__dlpack__'): kwargs: dict[str, Any] = {} kwargs["max_version"] = (1, 0) device = ext_tensor.__dlpack_device__() # device is either CUDA or ROCm, we need to pass the current # stream if device[0] in (DLDeviceType.kDLCUDA, DLDeviceType.kDLROCM): stream = torch.cuda.current_stream(f'cuda:{device[1]}') # cuda_stream is the pointer to the stream and it is a public # attribute, but it is not documented # The array API specify that the default legacy stream must be passed # with a value of 1 for CUDA # https://data-apis.org/array-api/latest/API_specification/array_object.html?dlpack-self-stream-none#dlpack-self-stream-none is_cuda = device[0] == DLDeviceType.kDLCUDA # Since pytorch is not using PTDS by default, lets directly pass # the legacy stream stream_ptr = 1 if is_cuda and stream.cuda_stream == 0 else stream.cuda_stream kwargs["stream"] = stream_ptr try: # Try running __dlpack__ while specifying `max_version` argument. dlpack = ext_tensor.__dlpack__(**kwargs) except TypeError: # If that doesn't work, try removing the `max_version` argument. kwargs.pop("max_version") dlpack = ext_tensor.__dlpack__(**kwargs) else: # Old versions just call the converter dlpack = ext_tensor return torch._C._from_dlpack(dlpack)
from typing import Any import torch import enum from torch._C import _from_dlpack from torch._C import _to_dlpack as to_dlpack __all__ = [ "DLDeviceType", "from_dlpack", "to_dlpack", ] class DLDeviceType(enum.IntEnum): # Enums as in DLPack specification (aten/src/ATen/dlpack.h) kDLCPU = 1, kDLGPU = 2, kDLCPUPinned = 3, kDLOpenCL = 4, kDLVulkan = 7, kDLMetal = 8, kDLVPI = 9, kDLROCM = 10, kDLExtDev = 12, kDLOneAPI = 14, torch._C._add_docstr(to_dlpack, r"""to_dlpack(tensor) -> PyCapsule Returns an opaque object (a "DLPack capsule") representing the tensor. .. note:: ``to_dlpack`` is a legacy DLPack interface. The capsule it returns cannot be used for anything in Python other than use it as input to ``from_dlpack``. The more idiomatic use of DLPack is to call ``from_dlpack`` directly on the tensor object - this works when that object has a ``__dlpack__`` method, which PyTorch and most other libraries indeed have now. .. warning:: Only call ``from_dlpack`` once per capsule produced with ``to_dlpack``. Behavior when a capsule is consumed multiple times is undefined. Args: tensor: a tensor to be exported The DLPack capsule shares the tensor's memory. """) # TODO: add a typing.Protocol to be able to tell Mypy that only objects with # __dlpack__ and __dlpack_device__ methods are accepted. def from_dlpack(ext_tensor: Any) -> 'torch.Tensor': """from_dlpack(ext_tensor) -> Tensor Converts a tensor from an external library into a ``torch.Tensor``. The returned PyTorch tensor will share the memory with the input tensor (which may have come from another library). Note that in-place operations will therefore also affect the data of the input tensor. This may lead to unexpected issues (e.g., other libraries may have read-only flags or immutable data structures), so the user should only do this if they know for sure that this is fine. Args: ext_tensor (object with ``__dlpack__`` attribute, or a DLPack capsule): The tensor or DLPack capsule to convert. If ``ext_tensor`` is a tensor (or ndarray) object, it must support the ``__dlpack__`` protocol (i.e., have a ``ext_tensor.__dlpack__`` method). Otherwise ``ext_tensor`` may be a DLPack capsule, which is an opaque ``PyCapsule`` instance, typically produced by a ``to_dlpack`` function or method. Examples:: >>> import torch.utils.dlpack >>> t = torch.arange(4) # Convert a tensor directly (supported in PyTorch >= 1.10) >>> t2 = torch.from_dlpack(t) >>> t2[:2] = -1 # show that memory is shared >>> t2 tensor([-1, -1, 2, 3]) >>> t tensor([-1, -1, 2, 3]) # The old-style DLPack usage, with an intermediate capsule object >>> capsule = torch.utils.dlpack.to_dlpack(t) >>> capsule <capsule object "dltensor" at ...> >>> t3 = torch.from_dlpack(capsule) >>> t3 tensor([-1, -1, 2, 3]) >>> t3[0] = -9 # now we're sharing memory between 3 tensors >>> t3 tensor([-9, -1, 2, 3]) >>> t2 tensor([-9, -1, 2, 3]) >>> t tensor([-9, -1, 2, 3]) """ if hasattr(ext_tensor, '__dlpack__'): device = ext_tensor.__dlpack_device__() # device is either CUDA or ROCm, we need to pass the current # stream if device[0] in (DLDeviceType.kDLGPU, DLDeviceType.kDLROCM): stream = torch.cuda.current_stream(f'cuda:{device[1]}') # cuda_stream is the pointer to the stream and it is a public # attribute, but it is not documented # The array API specify that the default legacy stream must be passed # with a value of 1 for CUDA # https://data-apis.org/array-api/latest/API_specification/array_object.html?dlpack-self-stream-none#dlpack-self-stream-none is_cuda = device[0] == DLDeviceType.kDLGPU # Since pytorch is not using PTDS by default, lets directly pass # the legacy stream stream_ptr = 1 if is_cuda and stream.cuda_stream == 0 else stream.cuda_stream dlpack = ext_tensor.__dlpack__(stream=stream_ptr) else: dlpack = ext_tensor.__dlpack__() else: # Old versions just call the converter dlpack = ext_tensor return _from_dlpack(dlpack)
from __future__ import annotations from sentence_transformers.sparse_encoder.data_collator import SparseEncoderDataCollator from sentence_transformers.sparse_encoder.evaluation import ( SparseBinaryClassificationEvaluator, SparseEmbeddingSimilarityEvaluator, SparseInformationRetrievalEvaluator, SparseMSEEvaluator, SparseNanoBEIREvaluator, SparseRerankingEvaluator, SparseTranslationEvaluator, SparseTripletEvaluator, ) from sentence_transformers.sparse_encoder.losses import ( CSRLoss, CSRReconstructionLoss, FlopsLoss, SparseAnglELoss, SparseCachedGISTEmbedLoss, SparseCachedMultipleNegativesRankingLoss, SparseCoSENTLoss, SparseCosineSimilarityLoss, SparseDistillKLDivLoss, SparseGISTEmbedLoss, SparseMarginMSELoss, SparseMSELoss, SparseMultipleNegativesRankingLoss, SparseTripletLoss, SpladeLoss, ) from sentence_transformers.sparse_encoder.model_card import SparseEncoderModelCardData from sentence_transformers.sparse_encoder.models import CSRSparsity, MLMTransformer, SpladePooling from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder from sentence_transformers.sparse_encoder.trainer import SparseEncoderTrainer from sentence_transformers.sparse_encoder.training_args import ( SparseEncoderTrainingArguments, ) __all__ = [ # Core components "SparseEncoder", "SparseEncoderDataCollator", "SparseEncoderTrainer", "SparseEncoderTrainingArguments", # Models "CSRSparsity", "MLMTransformer", "SpladePooling", # Losses "CSRLoss", "CSRReconstructionLoss", "SparseMultipleNegativesRankingLoss", "SparseCoSENTLoss", "SparseTripletLoss", "SparseCachedMultipleNegativesRankingLoss", "SparseMarginMSELoss", "SparseGISTEmbedLoss", "SparseCachedGISTEmbedLoss", "SparseCosineSimilarityLoss", "SparseMSELoss", "SparseAnglELoss", "SparseDistillKLDivLoss", "FlopsLoss", "SpladeLoss", # Evaluators "SparseBinaryClassificationEvaluator", "SparseEmbeddingSimilarityEvaluator", "SparseInformationRetrievalEvaluator", "SparseMSEEvaluator", "SparseNanoBEIREvaluator", "SparseTranslationEvaluator", "SparseRerankingEvaluator", "SparseTripletEvaluator", # Model card "SparseEncoderModelCardData", ] # TODO : Complete the SparseEncoder class # TODO : Add tests for all the components # TODO : Add the equivalent of the quantization file for the sparse encoder
from __future__ import annotations from sentence_transformers.sparse_encoder.data_collator import SparseEncoderDataCollator from sentence_transformers.sparse_encoder.evaluation import ( SparseBinaryClassificationEvaluator, SparseEmbeddingSimilarityEvaluator, SparseInformationRetrievalEvaluator, SparseMSEEvaluator, SparseNanoBEIREvaluator, SparseRerankingEvaluator, SparseTranslationEvaluator, SparseTripletEvaluator, ) from sentence_transformers.sparse_encoder.losses import ( CSRLoss, CSRReconstructionLoss, FlopsLoss, SparseAnglELoss, SparseCachedGISTEmbedLoss, SparseCachedMultipleNegativesRankingLoss, SparseCoSENTLoss, SparseCosineSimilarityLoss, SparseDistillKLDivLoss, SparseGISTEmbedLoss, SparseMarginMSELoss, SparseMSELoss, SparseMultipleNegativesRankingLoss, SparseTripletLoss, SpladeLoss, ) from sentence_transformers.sparse_encoder.models import ( CSRSparsity, MLMTransformer, SpladePooling, ) from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder from sentence_transformers.sparse_encoder.trainer import SparseEncoderTrainer from sentence_transformers.sparse_encoder.training_args import ( SparseEncoderTrainingArguments, ) __all__ = [ # Core components "SparseEncoder", "SparseEncoderDataCollator", "SparseEncoderTrainer", "SparseEncoderTrainingArguments", # Models "CSRSparsity", "MLMTransformer", "SpladePooling", # Losses "CSRLoss", "CSRReconstructionLoss", "SparseMultipleNegativesRankingLoss", "SparseCoSENTLoss", "SparseTripletLoss", "SparseCachedMultipleNegativesRankingLoss", "SparseMarginMSELoss", "SparseGISTEmbedLoss", "SparseCachedGISTEmbedLoss", "SparseCosineSimilarityLoss", "SparseMSELoss", "SparseAnglELoss", "SparseDistillKLDivLoss", "FlopsLoss", "SpladeLoss", # Evaluators "SparseBinaryClassificationEvaluator", "SparseEmbeddingSimilarityEvaluator", "SparseInformationRetrievalEvaluator", "SparseMSEEvaluator", "SparseNanoBEIREvaluator", "SparseTranslationEvaluator", "SparseRerankingEvaluator", "SparseTripletEvaluator", ] # TODO : Complete the SparseEncoder class # TODO : Add tests for all the components # TODO : Add the equivalent of the quantization file for the sparse encoder
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.chains.graph_qa.neptune_sparql import ( INTERMEDIATE_STEPS_KEY, SPARQL_GENERATION_TEMPLATE, NeptuneSparqlQAChain, extract_sparql, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "INTERMEDIATE_STEPS_KEY": "langchain_community.chains.graph_qa.neptune_sparql", "NeptuneSparqlQAChain": "langchain_community.chains.graph_qa.neptune_sparql", "SPARQL_GENERATION_TEMPLATE": "langchain_community.chains.graph_qa.neptune_sparql", "extract_sparql": "langchain_community.chains.graph_qa.neptune_sparql", } _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "INTERMEDIATE_STEPS_KEY", "SPARQL_GENERATION_TEMPLATE", "NeptuneSparqlQAChain", "extract_sparql", ]
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.chains.graph_qa.neptune_sparql import ( INTERMEDIATE_STEPS_KEY, SPARQL_GENERATION_TEMPLATE, NeptuneSparqlQAChain, extract_sparql, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_LOOKUP = { "INTERMEDIATE_STEPS_KEY": "langchain_community.chains.graph_qa.neptune_sparql", "NeptuneSparqlQAChain": "langchain_community.chains.graph_qa.neptune_sparql", "SPARQL_GENERATION_TEMPLATE": "langchain_community.chains.graph_qa.neptune_sparql", "extract_sparql": "langchain_community.chains.graph_qa.neptune_sparql", } _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP) def __getattr__(name: str) -> Any: """Look up attributes dynamically.""" return _import_attribute(name) __all__ = [ "INTERMEDIATE_STEPS_KEY", "NeptuneSparqlQAChain", "SPARQL_GENERATION_TEMPLATE", "extract_sparql", ]
__version__ = '0.14.7' import os from docarray.document import Document from docarray.array import DocumentArray from docarray.dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
__version__ = '0.14.6' import os from docarray.document import Document from docarray.array import DocumentArray from docarray.dataclasses import dataclass, field if 'DA_RICH_HANDLER' in os.environ: from rich.traceback import install install()
# Copyright (c) OpenMMLab. All rights reserved. from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .cornernet import CornerNet from .ddod import DDOD from .deformable_detr import DeformableDETR from .detr import DETR from .fast_rcnn import FastRCNN from .faster_rcnn import FasterRCNN from .fcos import FCOS from .fovea import FOVEA from .fsaf import FSAF from .gfl import GFL from .grid_rcnn import GridRCNN from .htc import HybridTaskCascade from .kd_one_stage import KnowledgeDistillationSingleStageDetector from .lad import LAD from .mask2former import Mask2Former from .mask_rcnn import MaskRCNN from .mask_scoring_rcnn import MaskScoringRCNN from .maskformer import MaskFormer from .nasfcos import NASFCOS from .paa import PAA from .panoptic_fpn import PanopticFPN from .panoptic_two_stage_segmentor import TwoStagePanopticSegmentor from .point_rend import PointRend from .queryinst import QueryInst from .reppoints_detector import RepPointsDetector from .retinanet import RetinaNet from .rpn import RPN from .scnet import SCNet from .single_stage import SingleStageDetector from .solo import SOLO from .solov2 import SOLOv2 from .sparse_rcnn import SparseRCNN from .tood import TOOD from .trident_faster_rcnn import TridentFasterRCNN from .two_stage import TwoStageDetector from .vfnet import VFNet from .yolact import YOLACT from .yolo import YOLOV3 from .yolof import YOLOF from .yolox import YOLOX __all__ = [ 'ATSS', 'BaseDetector', 'SingleStageDetector', 'TwoStageDetector', 'RPN', 'KnowledgeDistillationSingleStageDetector', 'FastRCNN', 'FasterRCNN', 'MaskRCNN', 'CascadeRCNN', 'HybridTaskCascade', 'RetinaNet', 'FCOS', 'GridRCNN', 'MaskScoringRCNN', 'RepPointsDetector', 'FOVEA', 'FSAF', 'NASFCOS', 'PointRend', 'GFL', 'CornerNet', 'PAA', 'YOLOV3', 'YOLACT', 'VFNet', 'DETR', 'TridentFasterRCNN', 'SparseRCNN', 'SCNet', 'SOLO', 'SOLOv2', 'DeformableDETR', 'AutoAssign', 'YOLOF', 'CenterNet', 'YOLOX', 'TwoStagePanopticSegmentor', 'PanopticFPN', 'QueryInst', 'LAD', 'TOOD', 'MaskFormer', 'DDOD', 'Mask2Former' ]
# Copyright (c) OpenMMLab. All rights reserved. from .atss import ATSS from .autoassign import AutoAssign from .base import BaseDetector from .cascade_rcnn import CascadeRCNN from .centernet import CenterNet from .cornernet import CornerNet from .ddod import DDOD from .deformable_detr import DeformableDETR from .detr import DETR from .fast_rcnn import FastRCNN from .faster_rcnn import FasterRCNN from .fcos import FCOS from .fovea import FOVEA from .fsaf import FSAF from .gfl import GFL from .grid_rcnn import GridRCNN from .htc import HybridTaskCascade from .kd_one_stage import KnowledgeDistillationSingleStageDetector from .lad import LAD from .mask2former import Mask2Former from .mask_rcnn import MaskRCNN from .mask_scoring_rcnn import MaskScoringRCNN from .maskformer import MaskFormer from .nasfcos import NASFCOS from .paa import PAA from .panoptic_fpn import PanopticFPN from .panoptic_two_stage_segmentor import TwoStagePanopticSegmentor from .point_rend import PointRend from .queryinst import QueryInst from .reppoints_detector import RepPointsDetector from .retinanet import RetinaNet from .rpn import RPN from .scnet import SCNet from .single_stage import SingleStageDetector from .solo import SOLO from .sparse_rcnn import SparseRCNN from .tood import TOOD from .trident_faster_rcnn import TridentFasterRCNN from .two_stage import TwoStageDetector from .vfnet import VFNet from .yolact import YOLACT from .yolo import YOLOV3 from .yolof import YOLOF from .yolox import YOLOX __all__ = [ 'ATSS', 'BaseDetector', 'SingleStageDetector', 'TwoStageDetector', 'RPN', 'KnowledgeDistillationSingleStageDetector', 'FastRCNN', 'FasterRCNN', 'MaskRCNN', 'CascadeRCNN', 'HybridTaskCascade', 'RetinaNet', 'FCOS', 'GridRCNN', 'MaskScoringRCNN', 'RepPointsDetector', 'FOVEA', 'FSAF', 'NASFCOS', 'PointRend', 'GFL', 'CornerNet', 'PAA', 'YOLOV3', 'YOLACT', 'VFNet', 'DETR', 'TridentFasterRCNN', 'SparseRCNN', 'SCNet', 'SOLO', 'DeformableDETR', 'AutoAssign', 'YOLOF', 'CenterNet', 'YOLOX', 'TwoStagePanopticSegmentor', 'PanopticFPN', 'QueryInst', 'LAD', 'TOOD', 'MaskFormer', 'DDOD', 'Mask2Former' ]
import json import pytest from langchain.chains import OpenAIModerationChain from langchain.chains.openai_functions.openapi import get_openapi_chain api_spec = { "openapi": "3.0.0", "info": {"title": "JSONPlaceholder API", "version": "1.0.0"}, "servers": [{"url": "https://jsonplaceholder.typicode.com"}], "paths": { "/posts": { "get": { "summary": "Get posts", "parameters": [ { "name": "_limit", "in": "query", "required": False, "schema": {"type": "integer", "example": 2}, "description": "Limit the number of results", }, ], }, }, }, } @pytest.mark.requires("openapi_pydantic") @pytest.mark.requires("langchain_openai") def test_openai_openapi_chain() -> None: from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) chain = get_openapi_chain(json.dumps(api_spec), llm) output = chain.invoke({"query": "Fetch the top two posts."}) assert len(output["response"]) == 2 @pytest.mark.requires("openai") def test_openai_moderation_chain_instantiation() -> None: """Test OpenAIModerationChain.""" api_key = "foo" moderation = OpenAIModerationChain(openai_api_key=api_key) assert isinstance(moderation, OpenAIModerationChain)
import json import pytest from langchain.chains import OpenAIModerationChain from langchain.chains.openai_functions.openapi import get_openapi_chain api_spec = { "openapi": "3.0.0", "info": {"title": "JSONPlaceholder API", "version": "1.0.0"}, "servers": [{"url": "https://jsonplaceholder.typicode.com"}], "paths": { "/posts": { "get": { "summary": "Get posts", "parameters": [ { "name": "_limit", "in": "query", "required": False, "schema": {"type": "integer", "example": 2}, "description": "Limit the number of results", }, ], } } }, } @pytest.mark.requires("openapi_pydantic") @pytest.mark.requires("langchain_openai") def test_openai_openapi_chain() -> None: from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) chain = get_openapi_chain(json.dumps(api_spec), llm) output = chain.invoke({"query": "Fetch the top two posts."}) assert len(output["response"]) == 2 @pytest.mark.requires("openai") def test_openai_moderation_chain_instantiation() -> None: """Test OpenAIModerationChain.""" api_key = "foo" moderation = OpenAIModerationChain(openai_api_key=api_key) assert isinstance(moderation, OpenAIModerationChain)
_base_ = './mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py' train_cfg = dict(max_epochs=24) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=24, by_epoch=True, milestones=[16, 22], gamma=0.1) ]
_base_ = './mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py' # learning policy lr_config = dict(step=[16, 23]) runner = dict(type='EpochBasedRunner', max_epochs=24)
"""XGBoost Experimental Federated Learning related API.""" import ctypes from threading import Thread from typing import Any, Dict, Optional from .core import _LIB, _check_call, make_jcargs from .tracker import RabitTracker class FederatedTracker(RabitTracker): """Tracker for federated training. Parameters ---------- n_workers : The number of federated workers. port : The port to listen on. secure : Whether this is a secure instance. If True, then the following arguments for SSL must be provided. server_key_path : Path to the server private key file. server_cert_path : Path to the server certificate file. client_cert_path : Path to the client certificate file. """ def __init__( # pylint: disable=R0913, W0231 self, n_workers: int, port: int, secure: bool, server_key_path: str = "", server_cert_path: str = "", client_cert_path: str = "", timeout: int = 300, ) -> None: handle = ctypes.c_void_p() args = make_jcargs( n_workers=n_workers, port=port, dmlc_communicator="federated", federated_secure=secure, server_key_path=server_key_path, server_cert_path=server_cert_path, client_cert_path=client_cert_path, timeout=int(timeout), ) _check_call(_LIB.XGTrackerCreate(args, ctypes.byref(handle))) self.handle = handle def run_federated_server( # pylint: disable=too-many-arguments n_workers: int, port: int, server_key_path: Optional[str] = None, server_cert_path: Optional[str] = None, client_cert_path: Optional[str] = None, timeout: int = 300, ) -> Dict[str, Any]: """See :py:class:`~xgboost.federated.FederatedTracker` for more info.""" args: Dict[str, Any] = {"n_workers": n_workers} secure = all( path is not None for path in [server_key_path, server_cert_path, client_cert_path] ) tracker = FederatedTracker( n_workers=n_workers, port=port, secure=secure, timeout=timeout ) tracker.start() thread = Thread(target=tracker.wait_for) thread.daemon = True thread.start() args.update(tracker.worker_args()) return args
"""XGBoost Federated Learning related API.""" from .core import _LIB, XGBoostError, _check_call, build_info, c_str def run_federated_server( port: int, world_size: int, server_key_path: str = "", server_cert_path: str = "", client_cert_path: str = "", ) -> None: """Run the Federated Learning server. Parameters ---------- port : int The port to listen on. world_size: int The number of federated workers. server_key_path: str Path to the server private key file. SSL is turned off if empty. server_cert_path: str Path to the server certificate file. SSL is turned off if empty. client_cert_path: str Path to the client certificate file. SSL is turned off if empty. """ if build_info()["USE_FEDERATED"]: if not server_key_path or not server_cert_path or not client_cert_path: _check_call(_LIB.XGBRunInsecureFederatedServer(port, world_size)) else: _check_call( _LIB.XGBRunFederatedServer( port, world_size, c_str(server_key_path), c_str(server_cert_path), c_str(client_cert_path), ) ) else: raise XGBoostError( "XGBoost needs to be built with the federated learning plugin " "enabled in order to use this module" )
from typing import Any, Dict, List, Tuple, Type, cast from docarray import BaseDoc, DocList from docarray.index.abstract import BaseDocIndex from docarray.utils.filter import filter_docs from docarray.utils.find import FindResult def _collect_query_args(method_name: str): # TODO: use partialmethod instead def inner(self, *args, **kwargs): if args: raise ValueError( f'Positional arguments are not supported for ' f'`{type(self)}.{method_name}`.' f' Use keyword arguments instead.' ) updated_query = self._queries + [(method_name, kwargs)] return type(self)(updated_query) return inner def _execute_find_and_filter_query( doc_index: BaseDocIndex, query: List[Tuple[str, Dict]] ) -> FindResult: """ Executes all find calls from query first using `doc_index.find()`, and filtering queries after that using DocArray's `filter_docs()`. Text search is not supported. """ docs_found = DocList.__class_getitem__(cast(Type[BaseDoc], doc_index._schema))([]) filter_conditions = [] filter_limit = None doc_to_score: Dict[BaseDoc, Any] = {} for op, op_kwargs in query: if op == 'find': docs, scores = doc_index.find(**op_kwargs) docs_found.extend(docs) doc_to_score.update(zip(docs.__getattribute__('id'), scores)) elif op == 'filter': filter_conditions.append(op_kwargs['filter_query']) filter_limit = op_kwargs.get('limit') else: raise ValueError(f'Query operation is not supported: {op}') doc_index._logger.debug(f'Executing query {query}') docs_filtered = docs_found for cond in filter_conditions: docs_cls = DocList.__class_getitem__(cast(Type[BaseDoc], doc_index._schema)) docs_filtered = docs_cls(filter_docs(docs_filtered, cond)) if filter_limit: docs_filtered = docs_filtered[:filter_limit] doc_index._logger.debug(f'{len(docs_filtered)} results found') docs_and_scores = zip( docs_filtered, (doc_to_score[doc.id] for doc in docs_filtered) ) docs_sorted = sorted(docs_and_scores, key=lambda x: x[1]) out_docs, out_scores = zip(*docs_sorted) return FindResult(documents=out_docs, scores=out_scores)
from typing import Any, Dict, List, Tuple, Type, cast from docarray import BaseDoc, DocList from docarray.index.abstract import BaseDocIndex from docarray.utils.filter import filter_docs from docarray.utils.find import FindResult def _collect_query_args(method_name: str): # TODO: use partialmethod instead def inner(self, *args, **kwargs): if args: raise ValueError( f'Positional arguments are not supported for ' f'`{type(self)}.{method_name}`.' f' Use keyword arguments instead.' ) updated_query = self._queries + [(method_name, kwargs)] return type(self)(updated_query) return inner def _execute_find_and_filter_query( doc_index: BaseDocIndex, query: List[Tuple[str, Dict]] ) -> FindResult: """ Executes all find calls from query first using `doc_index.find()`, and filtering queries after that using DocArray's `filter_docs()`. Text search is not supported. """ docs_found = DocList.__class_getitem__(cast(Type[BaseDoc], doc_index._schema))([]) filter_conditions = [] doc_to_score: Dict[BaseDoc, Any] = {} for op, op_kwargs in query: if op == 'find': docs, scores = doc_index.find(**op_kwargs) docs_found.extend(docs) doc_to_score.update(zip(docs.__getattribute__('id'), scores)) elif op == 'filter': filter_conditions.append(op_kwargs['filter_query']) else: raise ValueError(f'Query operation is not supported: {op}') doc_index._logger.debug(f'Executing query {query}') docs_filtered = docs_found for cond in filter_conditions: docs_cls = DocList.__class_getitem__(cast(Type[BaseDoc], doc_index._schema)) docs_filtered = docs_cls(filter_docs(docs_filtered, cond)) doc_index._logger.debug(f'{len(docs_filtered)} results found') docs_and_scores = zip( docs_filtered, (doc_to_score[doc.id] for doc in docs_filtered) ) docs_sorted = sorted(docs_and_scores, key=lambda x: x[1]) out_docs, out_scores = zip(*docs_sorted) return FindResult(documents=out_docs, scores=out_scores)
"""Standard LangChain interface tests""" from typing import Type import pytest from langchain_core.language_models import BaseChatModel from langchain_core.rate_limiters import InMemoryRateLimiter from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ( ChatModelIntegrationTests, ) from langchain_groq import ChatGroq rate_limiter = InMemoryRateLimiter(requests_per_second=0.2) class BaseTestGroq(ChatModelIntegrationTests): @property def chat_model_class(self) -> Type[BaseChatModel]: return ChatGroq @pytest.mark.xfail(reason="Not yet implemented.") def test_tool_message_histories_list_content( self, model: BaseChatModel, my_adder_tool: BaseTool ) -> None: super().test_tool_message_histories_list_content(model, my_adder_tool) @property def supports_json_mode(self) -> bool: return True class TestGroqLlama(BaseTestGroq): @property def chat_model_params(self) -> dict: return { "model": "llama-3.1-8b-instant", "temperature": 0, "rate_limiter": rate_limiter, } @property def supports_json_mode(self) -> bool: return True
"""Standard LangChain interface tests""" from typing import Optional, Type import pytest from langchain_core.language_models import BaseChatModel from langchain_core.rate_limiters import InMemoryRateLimiter from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ( ChatModelIntegrationTests, ) from langchain_groq import ChatGroq rate_limiter = InMemoryRateLimiter(requests_per_second=0.2) class BaseTestGroq(ChatModelIntegrationTests): @property def chat_model_class(self) -> Type[BaseChatModel]: return ChatGroq @pytest.mark.xfail(reason="Not yet implemented.") def test_tool_message_histories_list_content( self, model: BaseChatModel, my_adder_tool: BaseTool ) -> None: super().test_tool_message_histories_list_content(model, my_adder_tool) @property def supports_json_mode(self) -> bool: return True class TestGroqLlama(BaseTestGroq): @property def chat_model_params(self) -> dict: return { "model": "llama-3.1-8b-instant", "temperature": 0, "rate_limiter": rate_limiter, } @property def tool_choice_value(self) -> Optional[str]: """Value to use for tool choice when used in tests.""" return "any" @property def supports_json_mode(self) -> bool: return True
"""Logic for converting internal query language to a valid Chroma query.""" from typing import Tuple, Union from langchain_core.structured_query import ( Comparator, Comparison, Operation, Operator, StructuredQuery, Visitor, ) COMPARATOR_TO_TQL = { Comparator.EQ: "==", Comparator.GT: ">", Comparator.GTE: ">=", Comparator.LT: "<", Comparator.LTE: "<=", } OPERATOR_TO_TQL = { Operator.AND: "and", Operator.OR: "or", Operator.NOT: "NOT", } def can_cast_to_float(string: str) -> bool: """Check if a string can be cast to a float.""" try: float(string) return True except ValueError: return False class DeepLakeTranslator(Visitor): """Translate `DeepLake` internal query language elements to valid filters.""" allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] """Subset of allowed logical operators.""" allowed_comparators = [ Comparator.EQ, Comparator.GT, Comparator.GTE, Comparator.LT, Comparator.LTE, ] """Subset of allowed logical comparators.""" def _format_func(self, func: Union[Operator, Comparator]) -> str: self._validate_func(func) if isinstance(func, Operator): value = OPERATOR_TO_TQL[func.value] # type: ignore[index] elif isinstance(func, Comparator): value = COMPARATOR_TO_TQL[func.value] # type: ignore[index] return f"{value}" def visit_operation(self, operation: Operation) -> str: args = [arg.accept(self) for arg in operation.arguments] operator = self._format_func(operation.operator) return "(" + (" " + operator + " ").join(args) + ")" def visit_comparison(self, comparison: Comparison) -> str: comparator = self._format_func(comparison.comparator) values = comparison.value if isinstance(values, list): tql = [] for value in values: comparison.value = value tql.append(self.visit_comparison(comparison)) return "(" + (" or ").join(tql) + ")" if not can_cast_to_float(comparison.value): values = f"'{values}'" return f"metadata['{comparison.attribute}'] {comparator} {values}" def visit_structured_query( self, structured_query: StructuredQuery ) -> Tuple[str, dict]: if structured_query.filter is None: kwargs = {} else: tqL = f"SELECT * WHERE {structured_query.filter.accept(self)}" kwargs = {"tql": tqL} return structured_query.query, kwargs
"""Logic for converting internal query language to a valid Chroma query.""" from typing import Tuple, Union from langchain_core.structured_query import ( Comparator, Comparison, Operation, Operator, StructuredQuery, Visitor, ) COMPARATOR_TO_TQL = { Comparator.EQ: "==", Comparator.GT: ">", Comparator.GTE: ">=", Comparator.LT: "<", Comparator.LTE: "<=", } OPERATOR_TO_TQL = { Operator.AND: "and", Operator.OR: "or", Operator.NOT: "NOT", } def can_cast_to_float(string: str) -> bool: """Check if a string can be cast to a float.""" try: float(string) return True except ValueError: return False class DeepLakeTranslator(Visitor): """Translate `DeepLake` internal query language elements to valid filters.""" allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] """Subset of allowed logical operators.""" allowed_comparators = [ Comparator.EQ, Comparator.GT, Comparator.GTE, Comparator.LT, Comparator.LTE, ] """Subset of allowed logical comparators.""" def _format_func(self, func: Union[Operator, Comparator]) -> str: self._validate_func(func) if isinstance(func, Operator): value = OPERATOR_TO_TQL[func.value] # type: ignore elif isinstance(func, Comparator): value = COMPARATOR_TO_TQL[func.value] # type: ignore return f"{value}" def visit_operation(self, operation: Operation) -> str: args = [arg.accept(self) for arg in operation.arguments] operator = self._format_func(operation.operator) return "(" + (" " + operator + " ").join(args) + ")" def visit_comparison(self, comparison: Comparison) -> str: comparator = self._format_func(comparison.comparator) values = comparison.value if isinstance(values, list): tql = [] for value in values: comparison.value = value tql.append(self.visit_comparison(comparison)) return "(" + (" or ").join(tql) + ")" if not can_cast_to_float(comparison.value): values = f"'{values}'" return f"metadata['{comparison.attribute}'] {comparator} {values}" def visit_structured_query( self, structured_query: StructuredQuery ) -> Tuple[str, dict]: if structured_query.filter is None: kwargs = {} else: tqL = f"SELECT * WHERE {structured_query.filter.accept(self)}" kwargs = {"tql": tqL} return structured_query.query, kwargs
# model settings model = dict( type='MaskRCNN', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_mask=True, pad_size_divisor=32), backbone=dict( type='ResNet', depth=50, 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://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict( type='StandardRoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False), rpn_proposal=dict( nms_pre=2000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False)), test_cfg=dict( rpn=dict( nms_pre=1000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5)))
# model settings model = dict( type='MaskRCNN', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32), backbone=dict( type='ResNet', depth=50, num_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://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict( type='StandardRoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False), rpn_proposal=dict( nms_pre=2000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False)), test_cfg=dict( rpn=dict( nms_pre=1000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5)))
""" 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()
""" 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()
""" In this example we train a semantic search model to search through Wikipedia articles about programming articles & technologies. We use the text paragraphs from the following Wikipedia articles: Assembly language, C , C Sharp , C++, Go , Java , JavaScript, Keras, Laravel, MATLAB, Matplotlib, MongoDB, MySQL, Natural Language Toolkit, NumPy, pandas (software), Perl, PHP, PostgreSQL, Python , PyTorch, R , React, Rust , Scala , scikit-learn, SciPy, Swift , TensorFlow, Vue.js In: 1_programming_query_generation.py - We generate queries for all paragraphs from these articles 2_programming_train_bi-encoder.py - We train a SentenceTransformer bi-encoder with these generated queries. This results in a model we can then use for semantic search (for the given Wikipedia articles). 3_programming_semantic_search.py - Shows how the trained model can be used for semantic search """ from sentence_transformers import SentenceTransformer, InputExample, losses, models, datasets import os train_examples = [] with open("generated_queries.tsv") as fIn: for line in fIn: query, paragraph = line.strip().split("\t", maxsplit=1) train_examples.append(InputExample(texts=[query, paragraph])) # For the MultipleNegativesRankingLoss, it is important # that the batch does not contain duplicate entries, i.e. # no two equal queries and no two equal paragraphs. # To ensure this, we use a special data loader train_dataloader = datasets.NoDuplicatesDataLoader(train_examples, batch_size=64) # Now we create a SentenceTransformer model from scratch word_emb = models.Transformer("distilbert-base-uncased") pooling = models.Pooling(word_emb.get_word_embedding_dimension()) model = SentenceTransformer(modules=[word_emb, pooling]) # MultipleNegativesRankingLoss requires input pairs (query, relevant_passage) # and trains the model so that is is suitable for semantic search train_loss = losses.MultipleNegativesRankingLoss(model) # Tune the model num_epochs = 3 warmup_steps = int(len(train_dataloader) * num_epochs * 0.1) model.fit( train_objectives=[(train_dataloader, train_loss)], epochs=num_epochs, warmup_steps=warmup_steps, show_progress_bar=True, ) os.makedirs("output", exist_ok=True) model.save("output/programming-model")
""" In this example we train a semantic search model to search through Wikipedia articles about programming articles & technologies. We use the text paragraphs from the following Wikipedia articles: Assembly language, C , C Sharp , C++, Go , Java , JavaScript, Keras, Laravel, MATLAB, Matplotlib, MongoDB, MySQL, Natural Language Toolkit, NumPy, pandas (software), Perl, PHP, PostgreSQL, Python , PyTorch, R , React, Rust , Scala , scikit-learn, SciPy, Swift , TensorFlow, Vue.js In: 1_programming_query_generation.py - We generate queries for all paragraphs from these articles 2_programming_train_bi-encoder.py - We train a SentenceTransformer bi-encoder with these generated queries. This results in a model we can then use for semantic search (for the given Wikipedia articles). 3_programming_semantic_search.py - Shows how the trained model can be used for semantic search """ from sentence_transformers import SentenceTransformer, InputExample, losses, models, datasets import os train_examples = [] with open("generated_queries.tsv") as fIn: for line in fIn: query, paragraph = line.strip().split("\t", maxsplit=1) train_examples.append(InputExample(texts=[query, paragraph])) # For the MultipleNegativesRankingLoss, it is important # that the batch does not contain duplicate entries, i.e. # no two equal queries and no two equal paragraphs. # To ensure this, we use a special data loader train_dataloader = datasets.NoDuplicatesDataLoader(train_examples, batch_size=64) # Now we create a SentenceTransformer model from scratch word_emb = models.Transformer("distilbert-base-uncased") pooling = models.Pooling(word_emb.get_word_embedding_dimension()) model = SentenceTransformer(modules=[word_emb, pooling]) # MultipleNegativesRankingLoss requires input pairs (query, relevant_passage) # and trains the model so that is is suitable for semantic search train_loss = losses.MultipleNegativesRankingLoss(model) # Tune the model num_epochs = 3 warmup_steps = int(len(train_dataloader) * num_epochs * 0.1) model.fit( train_objectives=[(train_dataloader, train_loss)], epochs=num_epochs, warmup_steps=warmup_steps, show_progress_bar=True, ) os.makedirs("output", exist_ok=True) model.save("output/programming-model")
"""Example selectors. **Example selector** implements logic for selecting examples to include them in prompts. This allows us to select examples that are most relevant to the input. """ from importlib import import_module from typing import TYPE_CHECKING if TYPE_CHECKING: from langchain_core.example_selectors.base import BaseExampleSelector from langchain_core.example_selectors.length_based import ( LengthBasedExampleSelector, ) from langchain_core.example_selectors.semantic_similarity import ( MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector, sorted_values, ) __all__ = [ "BaseExampleSelector", "LengthBasedExampleSelector", "MaxMarginalRelevanceExampleSelector", "SemanticSimilarityExampleSelector", "sorted_values", ] _dynamic_imports = { "BaseExampleSelector": "base", "LengthBasedExampleSelector": "length_based", "MaxMarginalRelevanceExampleSelector": "semantic_similarity", "SemanticSimilarityExampleSelector": "semantic_similarity", "sorted_values": "semantic_similarity", } def __getattr__(attr_name: str) -> object: module_name = _dynamic_imports.get(attr_name) package = __spec__.parent if module_name == "__module__" or module_name is None: result = import_module(f".{attr_name}", package=package) else: module = import_module(f".{module_name}", package=package) result = getattr(module, attr_name) globals()[attr_name] = result return result def __dir__() -> list[str]: return list(__all__)
"""Example selectors. **Example selector** implements logic for selecting examples to include them in prompts. This allows us to select examples that are most relevant to the input. """ from importlib import import_module from typing import TYPE_CHECKING if TYPE_CHECKING: from langchain_core.example_selectors.base import BaseExampleSelector from langchain_core.example_selectors.length_based import ( LengthBasedExampleSelector, ) from langchain_core.example_selectors.semantic_similarity import ( MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector, sorted_values, ) __all__ = [ "BaseExampleSelector", "LengthBasedExampleSelector", "MaxMarginalRelevanceExampleSelector", "SemanticSimilarityExampleSelector", "sorted_values", ] _dynamic_imports = { "BaseExampleSelector": "base", "LengthBasedExampleSelector": "length_based", "MaxMarginalRelevanceExampleSelector": "semantic_similarity", "SemanticSimilarityExampleSelector": "semantic_similarity", "sorted_values": "semantic_similarity", } def __getattr__(attr_name: str) -> object: module_name = _dynamic_imports.get(attr_name) package = __spec__.parent # type: ignore[name-defined] if module_name == "__module__" or module_name is None: result = import_module(f".{attr_name}", package=package) else: module = import_module(f".{module_name}", package=package) result = getattr(module, attr_name) globals()[attr_name] = result return result def __dir__() -> list[str]: return list(__all__)
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import NdArray, PointCloud3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR / 'test.glb'), 'ply': str(TOYDATA_DIR / 'cube.ply'), } REMOTE_OBJ_FILE = 'https://people.sc.fsu.edu/~jburkardt/data/obj/al.obj' @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_format, file_path', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('remote-obj', REMOTE_OBJ_FILE), ], ) def test_load(file_format, file_path): n_samples = 100 url = parse_obj_as(PointCloud3DUrl, file_path) point_cloud = url.load(samples=n_samples) assert isinstance(point_cloud, np.ndarray) assert isinstance(point_cloud, NdArray) assert point_cloud.shape == (n_samples, 3) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_format, file_path', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('remote-obj', REMOTE_OBJ_FILE), ], ) def test_load_with_multiple_geometries_true(file_format, file_path): n_samples = 100 url = parse_obj_as(PointCloud3DUrl, file_path) point_cloud = url.load(samples=n_samples, multiple_geometries=True) assert isinstance(point_cloud, np.ndarray) assert len(point_cloud.shape) == 3 assert point_cloud.shape[1:] == (100, 3) def test_json_schema(): schema_json_of(PointCloud3DUrl) def test_dump_json(): url = parse_obj_as(PointCloud3DUrl, REMOTE_OBJ_FILE) orjson_dumps(url) @pytest.mark.parametrize( 'file_format,path_to_file', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('obj', REMOTE_OBJ_FILE), ('illegal', 'illegal'), ('illegal', 'https://www.google.com'), ('illegal', 'my/local/text/file.txt'), ('illegal', 'my/local/text/file.png'), ], ) def test_validation(file_format, path_to_file): if file_format == 'illegal': with pytest.raises(ValueError, match='PointCloud3DUrl'): parse_obj_as(PointCloud3DUrl, path_to_file) else: url = parse_obj_as(PointCloud3DUrl, path_to_file) assert isinstance(url, PointCloud3DUrl) assert isinstance(url, str) @pytest.mark.proto def test_proto_point_cloud_url(): uri = parse_obj_as(PointCloud3DUrl, REMOTE_OBJ_FILE) uri._to_node_protobuf()
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import NdArray, PointCloud3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR / 'test.glb'), 'ply': str(TOYDATA_DIR / 'cube.ply'), } REMOTE_OBJ_FILE = 'https://people.sc.fsu.edu/~jburkardt/data/obj/al.obj' @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_format, file_path', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('remote-obj', REMOTE_OBJ_FILE), ], ) def test_load(file_format, file_path): n_samples = 100 url = parse_obj_as(PointCloud3DUrl, file_path) point_cloud = url.load(samples=n_samples) assert isinstance(point_cloud, np.ndarray) assert isinstance(point_cloud, NdArray) assert point_cloud.shape == (n_samples, 3) @pytest.mark.slow @pytest.mark.internet @pytest.mark.parametrize( 'file_format, file_path', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('remote-obj', REMOTE_OBJ_FILE), ], ) def test_load_with_multiple_geometries_true(file_format, file_path): n_samples = 100 url = parse_obj_as(PointCloud3DUrl, file_path) point_cloud = url.load(samples=n_samples, multiple_geometries=True) assert isinstance(point_cloud, np.ndarray) assert len(point_cloud.shape) == 3 assert point_cloud.shape[1:] == (100, 3) def test_json_schema(): schema_json_of(PointCloud3DUrl) def test_dump_json(): url = parse_obj_as(PointCloud3DUrl, REMOTE_OBJ_FILE) orjson_dumps(url) @pytest.mark.parametrize( 'file_format,path_to_file', [ ('obj', MESH_FILES['obj']), ('glb', MESH_FILES['glb']), ('ply', MESH_FILES['ply']), ('obj', REMOTE_OBJ_FILE), ('illegal', 'illegal'), ('illegal', 'https://www.google.com'), ('illegal', 'my/local/text/file.txt'), ('illegal', 'my/local/text/file.png'), ], ) def test_validation(file_format, path_to_file): if file_format == 'illegal': with pytest.raises(ValueError, match='PointCloud3DUrl'): parse_obj_as(PointCloud3DUrl, path_to_file) else: url = parse_obj_as(PointCloud3DUrl, path_to_file) assert isinstance(url, PointCloud3DUrl) assert isinstance(url, str) def test_proto_point_cloud_url(): uri = parse_obj_as(PointCloud3DUrl, REMOTE_OBJ_FILE) uri._to_node_protobuf()
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str] arg3: Optional[str] class ProcessedResponseModel(BaseModel): text: str tags: Optional[dict] class DummyGateway(Gateway): def __init__( self, arg1: str = None, arg2: str = None, arg3: str = 'default-arg3', **kwargs ): super().__init__(**kwargs) self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 async def setup_server(self): from fastapi import FastAPI app = FastAPI( title='Dummy Server', ) @app.get(path='/', response_model=DummyResponseModel) def _get_response(): return { 'arg1': self.arg1, 'arg2': self.arg2, 'arg3': self.arg3, } @app.get( path='/stream', response_model=ProcessedResponseModel, ) async def _process(text: str): doc = None async for req in self.streamer.stream( request_generator( exec_endpoint='/', data=DocumentArray([Document(text=text)]), ) ): doc = req.to_dict()['data'][0] return {'text': doc['text'], 'tags': doc['tags']} self.server = Server(Config(app, host=self.host, port=self.port)) async def run_server(self): await self.server.serve() async def shutdown(self): self.server.should_exit = True await self.server.shutdown()
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str] arg3: Optional[str] class ProcessedResponseModel(BaseModel): text: str tags: Optional[dict] class DummyGateway(Gateway): def __init__( self, arg1: str = None, arg2: str = None, arg3: str = 'default-arg3', **kwargs ): super().__init__(**kwargs) self.port = self.runtime_args.port[0] self.host = self.runtime_args.host self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 async def setup_server(self): from fastapi import FastAPI app = FastAPI( title='Dummy Server', ) @app.get(path='/', response_model=DummyResponseModel) def _get_response(): return { 'arg1': self.arg1, 'arg2': self.arg2, 'arg3': self.arg3, } @app.get( path='/stream', response_model=ProcessedResponseModel, ) async def _process(text: str): doc = None async for req in self.streamer.stream( request_generator( exec_endpoint='/', data=DocumentArray([Document(text=text)]), ) ): doc = req.to_dict()['data'][0] return {'text': doc['text'], 'tags': doc['tags']} self.server = Server(Config(app, host=self.host, port=self.port)) async def run_server(self): await self.server.serve() async def shutdown(self): self.server.should_exit = True await self.server.shutdown()
import os as _os import sys as _sys from pathlib import Path as _Path import datetime as _datetime __windows__ = _sys.platform == 'win32' __uptime__ = _datetime.datetime.now().isoformat() # update on MacOS 1. clean this tuple, 2. grep -rohEI --exclude-dir=jina/hub --exclude-dir=tests --include \*.py # "\'JINA_.*?\'" jina | sort -u | sed "s/$/,/g" 3. copy all lines EXCEPT the first (which is the grep command in the # last line) __jina_env__ = ( 'JINA_DEFAULT_HOST', 'JINA_DEFAULT_TIMEOUT_CTRL', 'JINA_DEPLOYMENT_NAME', 'JINA_DISABLE_UVLOOP', 'JINA_EARLY_STOP', 'JINA_FULL_CLI', 'JINA_GATEWAY_IMAGE', 'JINA_GRPC_RECV_BYTES', 'JINA_GRPC_SEND_BYTES', 'JINA_HUB_NO_IMAGE_REBUILD', 'JINA_LOG_CONFIG', 'JINA_LOG_LEVEL', 'JINA_LOG_NO_COLOR', 'JINA_MP_START_METHOD', 'JINA_OPTOUT_TELEMETRY', 'JINA_RANDOM_PORT_MAX', 'JINA_RANDOM_PORT_MIN', 'JINA_LOCKS_ROOT', 'JINA_OPTOUT_TELEMETRY', 'JINA_K8S_ACCESS_MODES', 'JINA_K8S_STORAGE_CLASS_NAME', 'JINA_K8S_STORAGE_CAPACITY', 'JINA_STREAMER_ARGS', ) __default_host__ = _os.environ.get( 'JINA_DEFAULT_HOST', '127.0.0.1' if __windows__ else '0.0.0.0' ) __docker_host__ = 'host.docker.internal' __default_executor__ = 'BaseExecutor' __default_gateway__ = 'BaseGateway' __default_http_gateway__ = 'HTTPGateway' __default_composite_gateway__ = 'CompositeGateway' __default_websocket_gateway__ = 'WebSocketGateway' __default_grpc_gateway__ = 'GRPCGateway' __default_endpoint__ = '/default' __ready_msg__ = 'ready and listening' __stop_msg__ = 'terminated' __unset_msg__ = '(unset)' __args_executor_func__ = { 'docs', 'parameters', 'docs_matrix', } __args_executor_init__ = {'metas', 'requests', 'runtime_args'} __resources_path__ = _os.path.join( _os.path.dirname(_sys.modules['jina'].__file__), 'resources' ) __cache_path__ = f'{_os.path.expanduser("~")}/.cache/{__package__}' if not _Path(__cache_path__).exists(): _Path(__cache_path__).mkdir(parents=True, exist_ok=True) _names_with_underscore = [ '__version__', '__proto_version__', '__default_host__', '__ready_msg__', '__stop_msg__', '__jina_env__', '__uptime__', '__default_endpoint__', '__default_executor__', '__unset_msg__', '__windows__', ] __all__ = [_s for _s in dir() if not _s.startswith('_')] __all__.extend(_names_with_underscore) RAFT_TO_EXECUTOR_PORT = 100
import os as _os import sys as _sys from pathlib import Path as _Path import datetime as _datetime __windows__ = _sys.platform == 'win32' __uptime__ = _datetime.datetime.now().isoformat() # update on MacOS 1. clean this tuple, 2. grep -rohEI --exclude-dir=jina/hub --exclude-dir=tests --include \*.py # "\'JINA_.*?\'" jina | sort -u | sed "s/$/,/g" 3. copy all lines EXCEPT the first (which is the grep command in the # last line) __jina_env__ = ( 'JINA_DEFAULT_HOST', 'JINA_DEFAULT_TIMEOUT_CTRL', 'JINA_DEPLOYMENT_NAME', 'JINA_DISABLE_UVLOOP', 'JINA_EARLY_STOP', 'JINA_FULL_CLI', 'JINA_GATEWAY_IMAGE', 'JINA_GRPC_RECV_BYTES', 'JINA_GRPC_SEND_BYTES', 'JINA_HUB_NO_IMAGE_REBUILD', 'JINA_LOG_CONFIG', 'JINA_LOG_LEVEL', 'JINA_LOG_NO_COLOR', 'JINA_MP_START_METHOD', 'JINA_OPTOUT_TELEMETRY', 'JINA_RANDOM_PORT_MAX', 'JINA_RANDOM_PORT_MIN', 'JINA_LOCKS_ROOT', 'JINA_OPTOUT_TELEMETRY', 'JINA_K8S_ACCESS_MODES', 'JINA_K8S_STORAGE_CLASS_NAME', 'JINA_K8S_STORAGE_CAPACITY', 'JINA_STREAMER_ARGS', ) __default_host__ = _os.environ.get( 'JINA_DEFAULT_HOST', '127.0.0.1' if __windows__ else '0.0.0.0' ) __docker_host__ = 'host.docker.internal' __default_executor__ = 'BaseExecutor' __default_gateway__ = 'BaseGateway' __default_http_gateway__ = 'HTTPGateway' __default_composite_gateway__ = 'CompositeGateway' __default_websocket_gateway__ = 'WebSocketGateway' __default_grpc_gateway__ = 'GRPCGateway' __default_endpoint__ = '/default' __ready_msg__ = 'ready and listening' __stop_msg__ = 'terminated' __unset_msg__ = '(unset)' __args_executor_func__ = { 'docs', 'parameters', 'docs_matrix', } __args_executor_init__ = {'metas', 'requests', 'runtime_args'} __resources_path__ = _os.path.join( _os.path.dirname(_sys.modules['jina'].__file__), 'resources' ) __cache_path__ = f'{_os.path.expanduser("~")}/.cache/{__package__}' if not _Path(__cache_path__).exists(): _Path(__cache_path__).mkdir(parents=True, exist_ok=True) _names_with_underscore = [ '__version__', '__proto_version__', '__default_host__', '__ready_msg__', '__stop_msg__', '__jina_env__', '__uptime__', '__default_endpoint__', '__default_executor__', '__unset_msg__', '__windows__', ] __all__ = [_s for _s in dir() if not _s.startswith('_')] __all__.extend(_names_with_underscore)
""" Computes embeddings """ from typing import Optional import numpy as np import pytest from sentence_transformers import SentenceTransformer @pytest.mark.parametrize("normalize_embeddings", (False, True)) @pytest.mark.parametrize("prompt_name", (None, "retrieval")) def test_encode_multi_process( stsb_bert_tiny_model: SentenceTransformer, normalize_embeddings: bool, prompt_name: Optional[str] ) -> None: model = stsb_bert_tiny_model model.prompts = {"retrieval": "Represent this sentence for searching relevant passages: "} sentences = ["This is sentence {}".format(i) for i in range(40)] # Start the multi-process pool on e.g. two CPU devices & compute the embeddings using the pool pool = model.start_multi_process_pool(["cpu", "cpu"]) emb = model.encode_multi_process( sentences, pool, chunk_size=10, normalize_embeddings=normalize_embeddings, prompt_name=prompt_name ) model.stop_multi_process_pool(pool) assert emb.shape == (len(sentences), 128) # Make sure the embeddings aren't just all 0 assert emb.sum() != 0.0 # Compare against normal embeddings emb_normal = model.encode(sentences, normalize_embeddings=normalize_embeddings, prompt_name=prompt_name) diff = np.max(np.abs(emb - emb_normal)) assert diff < 0.001 # Ensure that after normalizing, the means are all almost 0, and otherwise not assert np.all(np.abs(emb.mean(1)) < 0.01) == normalize_embeddings
""" Computes embeddings """ import unittest from sentence_transformers import SentenceTransformer import numpy as np class ComputeMultiProcessTest(unittest.TestCase): def setUp(self): self.model = SentenceTransformer('paraphrase-distilroberta-base-v1') def test_multi_gpu_encode(self): # Start the multi-process pool on all available CUDA devices pool = self.model.start_multi_process_pool(['cpu', 'cpu']) sentences = ["This is sentence {}".format(i) for i in range(1000)] # Compute the embeddings using the multi-process pool emb = self.model.encode_multi_process(sentences, pool, chunk_size=50) assert emb.shape == (len(sentences), 768) emb_normal = self.model.encode(sentences) diff = np.max(np.abs(emb - emb_normal)) print("Max multi proc diff", diff) assert diff < 0.001
from __future__ import annotations import logging import torch from torch import Tensor, nn from sentence_transformers.models.Module import Module logger = logging.getLogger(__name__) class WordWeights(Module): """This model can weight word embeddings, for example, with idf-values.""" config_keys: list[str] = ["vocab", "word_weights", "unknown_word_weight"] def __init__(self, vocab: list[str], word_weights: dict[str, float], unknown_word_weight: float = 1): """ Initializes the WordWeights class. Args: vocab (List[str]): Vocabulary of the tokenizer. word_weights (Dict[str, float]): Mapping of tokens to a float weight value. Word embeddings are multiplied by this float value. Tokens in word_weights must not be equal to the vocab (can contain more or less values). unknown_word_weight (float, optional): Weight for words in vocab that do not appear in the word_weights lookup. These can be, for example, rare words in the vocab where no weight exists. Defaults to 1. """ super().__init__() self.vocab = vocab self.word_weights = word_weights self.unknown_word_weight = unknown_word_weight weights = [] num_unknown_words = 0 for word in vocab: weight = unknown_word_weight if word in word_weights: weight = word_weights[word] elif word.lower() in word_weights: weight = word_weights[word.lower()] else: num_unknown_words += 1 weights.append(weight) logger.info( f"{num_unknown_words} of {len(vocab)} words without a weighting value. Set weight to {unknown_word_weight}" ) self.emb_layer = nn.Embedding(len(vocab), 1) self.emb_layer.load_state_dict({"weight": torch.FloatTensor(weights).unsqueeze(1)}) def forward(self, features: dict[str, Tensor]): attention_mask = features["attention_mask"] token_embeddings = features["token_embeddings"] # Compute a weight value for each token token_weights_raw = self.emb_layer(features["input_ids"]).squeeze(-1) token_weights = token_weights_raw * attention_mask.float() token_weights_sum = torch.sum(token_weights, 1) # Multiply embedding by token weight value token_weights_expanded = token_weights.unsqueeze(-1).expand(token_embeddings.size()) token_embeddings = token_embeddings * token_weights_expanded features.update({"token_embeddings": token_embeddings, "token_weights_sum": token_weights_sum}) return features def save(self, output_path: str, *args, safe_serialization: bool = True, **kwargs) -> None: self.save_config(output_path)
from __future__ import annotations import json import logging import os import torch from torch import Tensor, nn logger = logging.getLogger(__name__) class WordWeights(nn.Module): """This model can weight word embeddings, for example, with idf-values.""" def __init__(self, vocab: list[str], word_weights: dict[str, float], unknown_word_weight: float = 1): """ Initializes the WordWeights class. Args: vocab (List[str]): Vocabulary of the tokenizer. word_weights (Dict[str, float]): Mapping of tokens to a float weight value. Word embeddings are multiplied by this float value. Tokens in word_weights must not be equal to the vocab (can contain more or less values). unknown_word_weight (float, optional): Weight for words in vocab that do not appear in the word_weights lookup. These can be, for example, rare words in the vocab where no weight exists. Defaults to 1. """ super().__init__() self.config_keys = ["vocab", "word_weights", "unknown_word_weight"] self.vocab = vocab self.word_weights = word_weights self.unknown_word_weight = unknown_word_weight weights = [] num_unknown_words = 0 for word in vocab: weight = unknown_word_weight if word in word_weights: weight = word_weights[word] elif word.lower() in word_weights: weight = word_weights[word.lower()] else: num_unknown_words += 1 weights.append(weight) logger.info( f"{num_unknown_words} of {len(vocab)} words without a weighting value. Set weight to {unknown_word_weight}" ) self.emb_layer = nn.Embedding(len(vocab), 1) self.emb_layer.load_state_dict({"weight": torch.FloatTensor(weights).unsqueeze(1)}) def forward(self, features: dict[str, Tensor]): attention_mask = features["attention_mask"] token_embeddings = features["token_embeddings"] # Compute a weight value for each token token_weights_raw = self.emb_layer(features["input_ids"]).squeeze(-1) token_weights = token_weights_raw * attention_mask.float() token_weights_sum = torch.sum(token_weights, 1) # Multiply embedding by token weight value token_weights_expanded = token_weights.unsqueeze(-1).expand(token_embeddings.size()) token_embeddings = token_embeddings * token_weights_expanded features.update({"token_embeddings": token_embeddings, "token_weights_sum": token_weights_sum}) return features 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) @staticmethod def load(input_path): with open(os.path.join(input_path, "config.json")) as fIn: config = json.load(fIn) return WordWeights(**config)
_base_ = '../common/lsj-200e_coco-detection.py' image_size = (1024, 1024) batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] model = dict( type='ATSS', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32, batch_augments=batch_augments), backbone=dict( type='ResNet', depth=50, 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://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='ATSSHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=2.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), # training and testing settings train_cfg=dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) train_dataloader = dict(batch_size=8, num_workers=4) # Enable automatic-mixed-precision training with AmpOptimWrapper. optim_wrapper = dict( type='AmpOptimWrapper', optimizer=dict( type='SGD', lr=0.01 * 4, momentum=0.9, weight_decay=0.00004)) # NOTE: `auto_scale_lr` is for automatically scaling LR, # USER SHOULD NOT CHANGE ITS VALUES. # base_batch_size = (8 GPUs) x (8 samples per GPU) auto_scale_lr = dict(base_batch_size=64)
_base_ = '../common/lsj_200e_coco_detection.py' image_size = (1024, 1024) batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] model = dict( type='ATSS', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32, batch_augments=batch_augments), backbone=dict( type='ResNet', depth=50, 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://resnet50')), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='ATSSHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=2.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), # training and testing settings train_cfg=dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) train_dataloader = dict(batch_size=8, num_workers=4) # Enable automatic-mixed-precision training with AmpOptimWrapper. optim_wrapper = dict( type='AmpOptimWrapper', optimizer=dict( type='SGD', lr=0.01 * 4, momentum=0.9, weight_decay=0.00004)) # NOTE: `auto_scale_lr` is for automatically scaling LR, # USER SHOULD NOT CHANGE ITS VALUES. # base_batch_size = (8 GPUs) x (8 samples per GPU) auto_scale_lr = dict(base_batch_size=64)
from jina.serve.runtimes.servers import BaseServer from aiohttp import web class LoadBalancingServer(BaseServer): """Base FastAPI server. Implement this abstract class in-case you want to build a fastapi-based server by implementing the `app` property. This property should return a fastapi app. The base Gateway will handle starting a server and serving the application using that server.""" def __init__( self, **kwargs ): """Initialize the LoadBalancingServer :param kwargs: keyword args """ super().__init__(**kwargs) # get server list from args self._server_exit = False async def handle_request(self, request): """Method called to handle requests coming to the LoadBalancer :param request: request to handle :return: the response to the request """ return await self._request_handler._load_balance(request) async def setup_server(self): """ Initialize and return server """ self.logger.debug(f'Setting up LoadBalancer server') self.app = web.Application() self.app.router.add_route('*', '/{path:.*}', self.handle_request) self.logger.debug(f'LoadBalancer server setup successful') async def run_server(self): """Run HTTP server forever""" await web._run_app( app=self.app, host=self.host, port=self.port, ) async def shutdown(self): """Shutdown the server and free other allocated resources, e.g, streamer object, health check service, ...""" self.logger.debug(f'Shutting down server') self._server_exit = True await super().shutdown() await self._request_handler.close() self.logger.debug(f'Server shutdown finished') @property def _should_exit(self): """Property describing if server is ready to exit :return: boolean indicating if Server ready to exit """ return self._server_exit @property def should_exit(self): """Property describing if server is ready to exit :return: boolean indicating if Server ready to exit """ return self._should_exit
from jina.serve.runtimes.servers import BaseServer from aiohttp import web class LoadBalancingServer(BaseServer): """Base FastAPI server. Implement this abstract class in-case you want to build a fastapi-based server by implementing the `app` property. This property should return a fastapi app. The base Gateway will handle starting a server and serving the application using that server.""" def __init__( self, **kwargs ): """Initialize the LoadBalancingServer :param kwargs: keyword args """ super().__init__(**kwargs) # get server list from args self._server_exit = False async def handle_request(self, request): """Method called to handle requests coming to the LoadBalancer :param request: request to handle :return: the response to the request """ return await self._request_handler._load_balance(request) async def setup_server(self): """ Initialize and return server """ self.app = web.Application() self.app.router.add_route('*', '/{path:.*}', self.handle_request) async def run_server(self): """Run HTTP server forever""" await web._run_app( app=self.app, host=self.host, port=self.port, ) async def shutdown(self): """Shutdown the server and free other allocated resources, e.g, streamer object, health check service, ...""" self._server_exit = True await super().shutdown() await self._request_handler.close() @property def _should_exit(self): """Property describing if server is ready to exit :return: boolean indicating if Server ready to exit """ return self._server_exit @property def should_exit(self): """Property describing if server is ready to exit :return: boolean indicating if Server ready to exit """ return self._should_exit
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseBinaryClassificationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Initialize the SPLADE model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") # Load a dataset with two text columns and a class label column (https://huggingface.co/datasets/sentence-transformers/quora-duplicates) eval_dataset = load_dataset("sentence-transformers/quora-duplicates", "pair-class", split="train[-1000:]") # Initialize the evaluator binary_acc_evaluator = SparseBinaryClassificationEvaluator( sentences1=eval_dataset["sentence1"], sentences2=eval_dataset["sentence2"], labels=eval_dataset["label"], name="quora_duplicates_dev", show_progress_bar=True, similarity_fn_names=["cosine", "dot", "euclidean", "manhattan"], ) results = binary_acc_evaluator(model) """ Accuracy with Cosine-Similarity: 75.00 (Threshold: 0.8668) F1 with Cosine-Similarity: 67.22 (Threshold: 0.5974) Precision with Cosine-Similarity: 54.18 Recall with Cosine-Similarity: 88.51 Average Precision with Cosine-Similarity: 67.81 Matthews Correlation with Cosine-Similarity: 49.56 Accuracy with Dot-Product: 76.50 (Threshold: 23.4236) F1 with Dot-Product: 67.00 (Threshold: 19.0095) Precision with Dot-Product: 55.93 Recall with Dot-Product: 83.54 Average Precision with Dot-Product: 65.89 Matthews Correlation with Dot-Product: 48.88 Accuracy with Euclidean-Distance: 67.70 (Threshold: -10.0041) F1 with Euclidean-Distance: 48.60 (Threshold: -0.1876) Precision with Euclidean-Distance: 32.13 Recall with Euclidean-Distance: 99.69 Average Precision with Euclidean-Distance: 20.52 Matthews Correlation with Euclidean-Distance: -4.59 Accuracy with Manhattan-Distance: 67.70 (Threshold: -103.0263) F1 with Manhattan-Distance: 48.60 (Threshold: -0.8532) Precision with Manhattan-Distance: 32.13 Recall with Manhattan-Distance: 99.69 Average Precision with Manhattan-Distance: 21.05 Matthews Correlation with Manhattan-Distance: -4.59 Model Sparsity: Active Dimensions: 61.2, Sparsity Ratio: 0.9980 """ # Print the results print(f"Primary metric: {binary_acc_evaluator.primary_metric}") # => Primary metric: quora_duplicates_dev_max_ap print(f"Primary metric value: {results[binary_acc_evaluator.primary_metric]:.4f}") # => Primary metric value: 0.6781
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseBinaryClassificationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Initialize the SPLADE model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") # Load a dataset with two text columns and a class label column (https://huggingface.co/datasets/sentence-transformers/quora-duplicates) eval_dataset = load_dataset("sentence-transformers/quora-duplicates", "pair-class", split="train[-1000:]") # Initialize the evaluator binary_acc_evaluator = SparseBinaryClassificationEvaluator( sentences1=eval_dataset["sentence1"], sentences2=eval_dataset["sentence2"], labels=eval_dataset["label"], name="quora_duplicates_dev", show_progress_bar=True, similarity_fn_names=["cosine", "dot", "euclidean", "manhattan"], ) results = binary_acc_evaluator(model) """ Accuracy with Cosine-Similarity: 74.90 (Threshold: 0.8668) F1 with Cosine-Similarity: 67.37 (Threshold: 0.5959) Precision with Cosine-Similarity: 54.15 Recall with Cosine-Similarity: 89.13 Average Precision with Cosine-Similarity: 67.81 Matthews Correlation with Cosine-Similarity: 49.89 Accuracy with Dot-Product: 76.50 (Threshold: 24.3460) F1 with Dot-Product: 66.93 (Threshold: 20.0762) Precision with Dot-Product: 57.62 Recall with Dot-Product: 79.81 Average Precision with Dot-Product: 65.94 Matthews Correlation with Dot-Product: 48.82 Accuracy with Euclidean-Distance: 67.70 (Threshold: -10.0062) F1 with Euclidean-Distance: 48.60 (Threshold: -0.2346) Precision with Euclidean-Distance: 32.13 Recall with Euclidean-Distance: 99.69 Average Precision with Euclidean-Distance: 20.52 Matthews Correlation with Euclidean-Distance: -4.59 Accuracy with Manhattan-Distance: 67.70 (Threshold: -103.1993) F1 with Manhattan-Distance: 48.60 (Threshold: -1.1565) Precision with Manhattan-Distance: 32.13 Recall with Manhattan-Distance: 99.69 Average Precision with Manhattan-Distance: 21.05 Matthews Correlation with Manhattan-Distance: -4.59 Model Sparsity: Active Dimensions: 63.1, Sparsity Ratio: 0.9979 """ # Print the results print(f"Primary metric: {binary_acc_evaluator.primary_metric}") # => Primary metric: quora_duplicates_dev_max_ap print(f"Primary metric value: {results[binary_acc_evaluator.primary_metric]:.4f}") # => Primary metric value: 0.6781
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/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. # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __version__ = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _arrow_dataset.concatenate_datasets = concatenate_datasets _utils.DownloadConfig = DownloadConfig _utils.DownloadManager = DownloadManager _utils.DownloadMode = DownloadMode _deprecated_download_manager.DownloadConfig = DownloadConfig _deprecated_download_manager.DownloadMode = DownloadMode _deprecated_download_manager.DownloadManager = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/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. # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __version__ = "2.13.1.dev0" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _arrow_dataset.concatenate_datasets = concatenate_datasets _utils.DownloadConfig = DownloadConfig _utils.DownloadManager = DownloadManager _utils.DownloadMode = DownloadMode _deprecated_download_manager.DownloadConfig = DownloadConfig _deprecated_download_manager.DownloadMode = DownloadMode _deprecated_download_manager.DownloadManager = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import shutil import time from unittest import TestCase from unittest.mock import Mock import torch from mmengine.structures import InstanceData from mmdet.engine.hooks import DetVisualizationHook, TrackVisualizationHook from mmdet.structures import DetDataSample, TrackDataSample from mmdet.visualization import DetLocalVisualizer, TrackLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, cy, bw, bh = torch.rand(num_boxes, 4).T tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T return bboxes class TestVisualizationHook(TestCase): def setUp(self) -> None: DetLocalVisualizer.get_instance('current_visualizer') pred_instances = InstanceData() pred_instances.bboxes = _rand_bboxes(5, 10, 12) pred_instances.labels = torch.randint(0, 2, (5, )) pred_instances.scores = torch.rand((5, )) pred_det_data_sample = DetDataSample() pred_det_data_sample.set_metainfo({ 'img_path': osp.join(osp.dirname(__file__), '../../data/color.jpg') }) pred_det_data_sample.pred_instances = pred_instances self.outputs = [pred_det_data_sample] * 2 def test_after_val_iter(self): runner = Mock() runner.iter = 1 hook = DetVisualizationHook() hook.after_val_iter(runner, 1, {}, self.outputs) def test_after_test_iter(self): runner = Mock() runner.iter = 1 hook = DetVisualizationHook(draw=True) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertEqual(hook._test_index, 2) # test timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) test_out_dir = timestamp + '1' runner.work_dir = timestamp runner.timestamp = '1' hook = DetVisualizationHook(draw=False, test_out_dir=test_out_dir) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertTrue(not osp.exists(f'{timestamp}/1/{test_out_dir}')) hook = DetVisualizationHook(draw=True, test_out_dir=test_out_dir) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) shutil.rmtree(f'{timestamp}') class TestTrackVisualizationHook(TestCase): def setUp(self) -> None: TrackLocalVisualizer.get_instance('visualizer') # pseudo data_batch self.data_batch = dict(data_samples=None, inputs=None) pred_instances_data = dict( bboxes=torch.tensor([[100, 100, 200, 200], [150, 150, 400, 200]]), instances_id=torch.tensor([1, 2]), labels=torch.tensor([0, 1]), scores=torch.tensor([0.955, 0.876])) pred_instances = InstanceData(**pred_instances_data) img_data_sample = DetDataSample() img_data_sample.pred_track_instances = pred_instances img_data_sample.gt_instances = pred_instances img_data_sample.set_metainfo( dict( img_path=osp.join( osp.dirname(__file__), '../../data/color.jpg'), scale_factor=(1.0, 1.0))) track_data_sample = TrackDataSample() track_data_sample.video_data_samples = [img_data_sample] track_data_sample.set_metainfo(dict(ori_length=1)) self.outputs = [track_data_sample] def test_after_val_iter_image(self): runner = Mock() runner.iter = 1 hook = TrackVisualizationHook(frame_interval=10, draw=True) hook.after_val_iter(runner, 9, self.data_batch, self.outputs) def test_after_test_iter(self): runner = Mock() runner.iter = 1 hook = TrackVisualizationHook(frame_interval=10, draw=True) hook.after_val_iter(runner, 9, self.data_batch, self.outputs) # test test_out_dir timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) test_out_dir = timestamp + '1' runner.work_dir = timestamp runner.timestamp = '1' hook = TrackVisualizationHook( frame_interval=10, draw=True, test_out_dir=test_out_dir) hook.after_test_iter(runner, 9, self.data_batch, self.outputs) self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) shutil.rmtree(f'{timestamp}')
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import shutil import time from unittest import TestCase from unittest.mock import Mock import torch from mmengine.structures import InstanceData from mmdet.engine.hooks import DetVisualizationHook from mmdet.structures import DetDataSample from mmdet.visualization import DetLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, cy, bw, bh = torch.rand(num_boxes, 4).T tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T return bboxes class TestVisualizationHook(TestCase): def setUp(self) -> None: DetLocalVisualizer.get_instance('current_visualizer') pred_instances = InstanceData() pred_instances.bboxes = _rand_bboxes(5, 10, 12) pred_instances.labels = torch.randint(0, 2, (5, )) pred_instances.scores = torch.rand((5, )) pred_det_data_sample = DetDataSample() pred_det_data_sample.set_metainfo({ 'img_path': osp.join(osp.dirname(__file__), '../../data/color.jpg') }) pred_det_data_sample.pred_instances = pred_instances self.outputs = [pred_det_data_sample] * 2 def test_after_val_iter(self): runner = Mock() runner.iter = 1 hook = DetVisualizationHook() hook.after_val_iter(runner, 1, {}, self.outputs) def test_after_test_iter(self): runner = Mock() runner.iter = 1 hook = DetVisualizationHook(draw=True) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertEqual(hook._test_index, 2) # test timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) test_out_dir = timestamp + '1' runner.work_dir = timestamp runner.timestamp = '1' hook = DetVisualizationHook(draw=False, test_out_dir=test_out_dir) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertTrue(not osp.exists(f'{timestamp}/1/{test_out_dir}')) hook = DetVisualizationHook(draw=True, test_out_dir=test_out_dir) hook.after_test_iter(runner, 1, {}, self.outputs) self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) shutil.rmtree(f'{timestamp}')
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmdet.models.backbones import ResNeSt from mmdet.models.backbones.resnest import Bottleneck as BottleneckS def test_resnest_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow') # Test ResNeSt Bottleneck structure block = BottleneckS( 64, 256, radix=2, reduction_factor=4, stride=2, style='pytorch') assert block.avd_layer.stride == 2 assert block.conv2.channels == 256 # Test ResNeSt Bottleneck forward block = BottleneckS(64, 16, radix=2, reduction_factor=4) x = torch.randn(2, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([2, 64, 56, 56]) def test_resnest_backbone(): with pytest.raises(KeyError): # ResNeSt depth should be in [50, 101, 152, 200] ResNeSt(depth=18) # Test ResNeSt with radix 2, reduction_factor 4 model = ResNeSt( depth=50, radix=2, reduction_factor=4, out_indices=(0, 1, 2, 3)) model.init_weights() model.train() imgs = torch.randn(2, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([2, 256, 56, 56]) assert feat[1].shape == torch.Size([2, 512, 28, 28]) assert feat[2].shape == torch.Size([2, 1024, 14, 14]) assert feat[3].shape == torch.Size([2, 2048, 7, 7])
import pytest import torch from mmdet.models.backbones import ResNeSt from mmdet.models.backbones.resnest import Bottleneck as BottleneckS def test_resnest_bottleneck(): with pytest.raises(AssertionError): # Style must be in ['pytorch', 'caffe'] BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow') # Test ResNeSt Bottleneck structure block = BottleneckS( 64, 256, radix=2, reduction_factor=4, stride=2, style='pytorch') assert block.avd_layer.stride == 2 assert block.conv2.channels == 256 # Test ResNeSt Bottleneck forward block = BottleneckS(64, 16, radix=2, reduction_factor=4) x = torch.randn(2, 64, 56, 56) x_out = block(x) assert x_out.shape == torch.Size([2, 64, 56, 56]) def test_resnest_backbone(): with pytest.raises(KeyError): # ResNeSt depth should be in [50, 101, 152, 200] ResNeSt(depth=18) # Test ResNeSt with radix 2, reduction_factor 4 model = ResNeSt( depth=50, radix=2, reduction_factor=4, out_indices=(0, 1, 2, 3)) model.init_weights() model.train() imgs = torch.randn(2, 3, 224, 224) feat = model(imgs) assert len(feat) == 4 assert feat[0].shape == torch.Size([2, 256, 56, 56]) assert feat[1].shape == torch.Size([2, 512, 28, 28]) assert feat[2].shape == torch.Size([2, 1024, 14, 14]) assert feat[3].shape == torch.Size([2, 2048, 7, 7])
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( backbone=dict( frozen_stages=-1, zero_init_residual=False, norm_cfg=norm_cfg, init_cfg=None), neck=dict(norm_cfg=norm_cfg), roi_head=dict( bbox_head=dict( type='Shared4Conv1FCBBoxHead', conv_out_channels=256, norm_cfg=norm_cfg), mask_head=dict(norm_cfg=norm_cfg))) optim_wrapper = dict(paramwise_cfg=dict(norm_decay_mult=0.)) max_epochs = 73 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=[65, 71], gamma=0.1) ] train_cfg = dict(max_epochs=max_epochs) # only keep latest 3 checkpoints default_hooks = dict(checkpoint=dict(max_keep_ckpts=3))
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( backbone=dict( frozen_stages=-1, zero_init_residual=False, norm_cfg=norm_cfg, init_cfg=None), neck=dict(norm_cfg=norm_cfg), roi_head=dict( bbox_head=dict( type='Shared4Conv1FCBBoxHead', conv_out_channels=256, norm_cfg=norm_cfg), mask_head=dict(norm_cfg=norm_cfg))) # optimizer optimizer = dict(paramwise_cfg=dict(norm_decay_mult=0)) optimizer_config = dict(_delete_=True, grad_clip=None) # learning policy lr_config = dict(warmup_ratio=0.1, step=[65, 71]) runner = dict(type='EpochBasedRunner', max_epochs=73)
import copy import json try: import difflib except ImportError: difflib = None from keras.src.api_export import keras_export @keras_export("keras.utils.Config") class Config: """A Config is a dict-like container for named values. It offers a few advantages over a plain dict: - Setting and retrieving values via attribute setting / getting. - Ability to freeze the config to ensure no accidental config modifications occur past a certain point in your program. - Easy serialization of the whole config as JSON. Examples: ```python # Create a config via constructor arguments config = Config("learning_rate"=0.1, "momentum"=0.9) # Then keep adding to it via attribute-style setting config.use_ema = True config.ema_overwrite_frequency = 100 # You can also add attributes via dict-like access config["seed"] = 123 # You can retrieve entries both via attribute-style # access and dict-style access assert config.seed == 100 assert config["learning_rate"] == 0.1 ``` A config behaves like a dict: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) for k, v in config.items(): print(f"{k}={v}") print(f"keys: {list(config.keys())}") print(f"values: {list(config.values())}") ``` In fact, it can be turned into one: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) dict_config = config.as_dict() ``` You can easily serialize a config to JSON: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) json_str = config.to_json() ``` You can also freeze a config to prevent further changes: ```python config = Config() config.optimizer = "adam" config.seed = 123 # Freeze the config to prevent changes. config.freeze() assert config.frozen config.foo = "bar" # This will raise an error. ``` """ __attrs__ = None def __init__(self, **kwargs): self._config = kwargs self._frozen = False self.__attrs__ = set(dir(self)) @property def frozen(self): """Returns True if the config is frozen.""" return self._frozen def freeze(self): """Marks the config as frozen, preventing any ulterior modification.""" self._frozen = True def unfreeze(self): self._frozen = False def _raise_if_frozen(self): if self._frozen: raise ValueError( "Cannot mutate attribute(s) because the config is frozen." ) def as_dict(self): return copy.copy(self._config) def to_json(self): return json.dumps(self._config) def keys(self): return self._config.keys() def values(self): return self._config.values() def items(self): return self._config.items() def pop(self, *args): self._raise_if_frozen() return self._config.pop(*args) def update(self, *args, **kwargs): self._raise_if_frozen() return self._config.update(*args, **kwargs) def get(self, keyname, value=None): return self._config.get(keyname, value) def __setattr__(self, name, value): attrs = object.__getattribute__(self, "__attrs__") if attrs is None or name in attrs: return object.__setattr__(self, name, value) self._raise_if_frozen() self._config[name] = value def __getattr__(self, name): attrs = object.__getattribute__(self, "__attrs__") if attrs is None or name in attrs: return object.__getattribute__(self, name) if name in self._config: return self._config[name] msg = f"Unknown attribute: '{name}'." if difflib is not None: closest_matches = difflib.get_close_matches( name, self._config.keys(), n=1, cutoff=0.7 ) if closest_matches: msg += f" Did you mean '{closest_matches[0]}'?" raise AttributeError(msg) def __setitem__(self, key, item): self._raise_if_frozen() self._config[key] = item def __getitem__(self, key): return self._config[key] def __repr__(self): return f"<Config {self._config}>" def __iter__(self): keys = sorted(self._config.keys()) for k in keys: yield k def __len__(self): return len(self._config) def __delitem__(self, key): self._raise_if_frozen() del self._config[key] def __contains__(self, item): return item in self._config
import copy import json try: import difflib except ImportError: difflib = None from keras.src.api_export import keras_export @keras_export("keras.utils.Config") class Config: """A Config is a dict-like container for named values. It offers a few advantages over a plain dict: - Setting and retrieving values via attribute setting / getting. - Ability to freeze the config to ensure no accidental config modifications occur past a certain point in your program. - Easy serialization of the whole config as JSON. Examples: ```python # Create a config via constructor arguments config = Config("learning_rate"=0.1, "momentum"=0.9) # Then keep adding to it via attribute-style setting config.use_ema = True config.ema_overwrite_frequency = 100 # You can also add attributes via dict-like access config["seed"] = 123 # You can retrieve entries both via attribute-style # access and dict-style access assert config.seed == 100 assert config["learning_rate"] == 0.1 ``` A config behaves like a dict: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) for k, v in config.items(): print(f"{k}={v}") print(f"keys: {list(config.keys())}") print(f"values: {list(config.values())}") ``` In fact, it can be turned into one: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) dict_config = config.as_dict() ``` You can easily serialize a config to JSON: ```python config = Config("learning_rate"=0.1, "momentum"=0.9) json_str = config.to_json() ``` You can also freeze a config to prevent further changes: ```python config = Config() config.optimizer = "adam" config.seed = 123 # Freeze the config to prevent changes. config.freeze() assert config.frozen config.foo = "bar" # This will raise an error. ``` """ __attrs__ = None def __init__(self, **kwargs): self._config = kwargs self._frozen = False self.__attrs__ = set(dir(self)) @property def frozen(self): """Returns True if the config is frozen.""" return self._frozen def freeze(self): """Marks the config as frozen, preventing any ulterior modification.""" self._frozen = True def unfreeze(self): self._frozen = False def _raise_if_frozen(self): if self._frozen: raise ValueError( "Cannot mutate attribute(s) because the config is frozen." ) def as_dict(self): return copy.copy(self._config) def to_json(self): return json.dumps(self._config) def keys(self): return self._config.keys() def values(self): return self._config.values() def items(self): return self._config.items() def pop(self, *args): self._raise_if_frozen() return self._config.pop(*args) def update(self, *args, **kwargs): self._raise_if_frozen() return self._config.update(*args, **kwargs) def __setattr__(self, name, value): attrs = object.__getattribute__(self, "__attrs__") if attrs is None or name in attrs: return object.__setattr__(self, name, value) self._raise_if_frozen() self._config[name] = value def __getattr__(self, name): attrs = object.__getattribute__(self, "__attrs__") if attrs is None or name in attrs: return object.__getattribute__(self, name) if name in self._config: return self._config[name] msg = f"Unknown attribute: '{name}'." if difflib is not None: closest_matches = difflib.get_close_matches( name, self._config.keys(), n=1, cutoff=0.7 ) if closest_matches: msg += f" Did you mean '{closest_matches[0]}'?" raise AttributeError(msg) def __setitem__(self, key, item): self._raise_if_frozen() self._config[key] = item def __getitem__(self, key): return self._config[key] def __repr__(self): return f"<Config {self._config}>" def __iter__(self): keys = sorted(self._config.keys()) for k in keys: yield k def __len__(self): return len(self._config) def __delitem__(self, key): self._raise_if_frozen() del self._config[key] def __contains__(self, item): return item in self._config
# Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 import torch from diffusers import WanTransformer3DModel from diffusers.utils.testing_utils import ( enable_full_determinism, is_torch_compile, require_torch_2, require_torch_gpu, slow, torch_device, ) from ..test_modeling_common import ModelTesterMixin enable_full_determinism() class WanTransformer3DTests(ModelTesterMixin, unittest.TestCase): model_class = WanTransformer3DModel main_input_name = "hidden_states" uses_custom_attn_processor = True @property def dummy_input(self): batch_size = 1 num_channels = 4 num_frames = 2 height = 16 width = 16 text_encoder_embedding_dim = 16 sequence_length = 12 hidden_states = torch.randn((batch_size, num_channels, num_frames, height, width)).to(torch_device) timestep = torch.randint(0, 1000, size=(batch_size,)).to(torch_device) encoder_hidden_states = torch.randn((batch_size, sequence_length, text_encoder_embedding_dim)).to(torch_device) return { "hidden_states": hidden_states, "encoder_hidden_states": encoder_hidden_states, "timestep": timestep, } @property def input_shape(self): return (4, 1, 16, 16) @property def output_shape(self): return (4, 1, 16, 16) def prepare_init_args_and_inputs_for_common(self): init_dict = { "patch_size": (1, 2, 2), "num_attention_heads": 2, "attention_head_dim": 12, "in_channels": 4, "out_channels": 4, "text_dim": 16, "freq_dim": 256, "ffn_dim": 32, "num_layers": 2, "cross_attn_norm": True, "qk_norm": "rms_norm_across_heads", "rope_max_seq_len": 32, } inputs_dict = self.dummy_input return init_dict, inputs_dict def test_gradient_checkpointing_is_applied(self): expected_set = {"WanTransformer3DModel"} super().test_gradient_checkpointing_is_applied(expected_set=expected_set) @require_torch_gpu @require_torch_2 @is_torch_compile @slow def test_torch_compile_recompilation_and_graph_break(self): torch._dynamo.reset() init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() model = self.model_class(**init_dict).to(torch_device) model = torch.compile(model, fullgraph=True) with torch._dynamo.config.patch(error_on_recompile=True), torch.no_grad(): _ = model(**inputs_dict) _ = model(**inputs_dict)
# Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 import torch from diffusers import WanTransformer3DModel from diffusers.utils.testing_utils import enable_full_determinism, torch_device from ..test_modeling_common import ModelTesterMixin enable_full_determinism() class WanTransformer3DTests(ModelTesterMixin, unittest.TestCase): model_class = WanTransformer3DModel main_input_name = "hidden_states" uses_custom_attn_processor = True @property def dummy_input(self): batch_size = 1 num_channels = 4 num_frames = 2 height = 16 width = 16 text_encoder_embedding_dim = 16 sequence_length = 12 hidden_states = torch.randn((batch_size, num_channels, num_frames, height, width)).to(torch_device) timestep = torch.randint(0, 1000, size=(batch_size,)).to(torch_device) encoder_hidden_states = torch.randn((batch_size, sequence_length, text_encoder_embedding_dim)).to(torch_device) return { "hidden_states": hidden_states, "encoder_hidden_states": encoder_hidden_states, "timestep": timestep, } @property def input_shape(self): return (4, 1, 16, 16) @property def output_shape(self): return (4, 1, 16, 16) def prepare_init_args_and_inputs_for_common(self): init_dict = { "patch_size": (1, 2, 2), "num_attention_heads": 2, "attention_head_dim": 12, "in_channels": 4, "out_channels": 4, "text_dim": 16, "freq_dim": 256, "ffn_dim": 32, "num_layers": 2, "cross_attn_norm": True, "qk_norm": "rms_norm_across_heads", "rope_max_seq_len": 32, } inputs_dict = self.dummy_input return init_dict, inputs_dict def test_gradient_checkpointing_is_applied(self): expected_set = {"WanTransformer3DModel"} super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
import torch 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 | +=========================================+=============================+ | sentence | model sentence embeddings | +-----------------------------------------+-----------------------------+ | sentence_1, sentence_2, ..., sentence_N | 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): # 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", } """
import torch 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 | +=========================================+=============================+ | sentence | model sentence embeddings | +-----------------------------------------+-----------------------------+ | sentence_1, sentence_2, ..., sentence_N | 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): # Concatenate multiple inputs on the batch dimension embeddings = torch.cat([self.model(inputs)["sentence_embedding"] for inputs in sentence_features], dim=0) if len(sentence_features) > 1: # Repeat the labels for each input labels = labels.repeat(len(sentence_features), 1) 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", } """
import asyncio from typing import AsyncIterator, Iterator, Optional, Union from jina.helper import get_or_reuse_loop class RequestsCounter: """Class used to wrap a count integer so that it can be updated inside methods. .. code-block:: python def count_increment(i: int, rc: RequestCounter): i += 1 rc.count += 1 c_int = 0 c_rc = RequestsCounter() count_increment(c_int, c_rc) assert c_int == 0 assert c_rc.count == 1 """ count = 0 class AsyncRequestsIterator: """Iterator to allow async iteration of blocking/non-blocking iterator from the Client""" def __init__( self, iterator: Union[Iterator, AsyncIterator], request_counter: Optional[RequestsCounter] = None, prefetch: int = 0, ) -> None: """Async request iterator :param iterator: request iterator :param request_counter: counter of the numbers of request being handled at a given moment :param prefetch: The max amount of requests to be handled at a given moment (0 disables feature) """ self.iterator = iterator self._request_counter = request_counter self._prefetch = prefetch def iterator__next__(self): """ Executed inside a `ThreadPoolExecutor` via `loop.run_in_executor` to avoid following exception. "StopIteration interacts badly with generators and cannot be raised into a Future" :return: next request or None """ try: return self.iterator.__next__() except StopIteration: return None def __aiter__(self): return self async def __anext__(self): if self._prefetch > 0: while self._request_counter.count >= self._prefetch: await asyncio.sleep(0) if isinstance(self.iterator, Iterator): """ An `Iterator` indicates "blocking" code, which might block all tasks in the event loop. Hence we iterate in the default executor provided by asyncio. """ request = await get_or_reuse_loop().run_in_executor( None, self.iterator__next__ ) """ `iterator.__next__` can be executed directly and that'd raise `StopIteration` in the executor, which raises the following exception while chaining states in futures. "StopIteration interacts badly with generators and cannot be raised into a Future" To avoid that, we handle the raise by a `return None` """ if request is None: raise StopAsyncIteration elif isinstance(self.iterator, AsyncIterator): # we assume that `AsyncIterator` doesn't block the event loop request = await self.iterator.__anext__() return request
from typing import Iterator, AsyncIterator, Union from jina.helper import get_or_reuse_loop class AsyncRequestsIterator: """Iterator to allow async iteration of blocking/non-blocking iterator from the Client""" def __init__(self, iterator: Union[Iterator, AsyncIterator]) -> None: """Async request iterator TODO (Deepankar): accept `num_req` :param iterator: request iterator """ self.iterator = iterator def iterator__next__(self): """ Executed inside a `ThreadPoolExecutor` via `loop.run_in_executor` to avoid following exception. "StopIteration interacts badly with generators and cannot be raised into a Future" :return: next request or None """ try: return self.iterator.__next__() except StopIteration: return None def __aiter__(self): return self async def __anext__(self): if isinstance(self.iterator, Iterator): """ An `Iterator` indicates "blocking" code, which might block all tasks in the event loop. Hence we iterate in the default executor provided by asyncio. """ request = await get_or_reuse_loop().run_in_executor( None, self.iterator__next__ ) """ `iterator.__next__` can be executed directly and that'd raise `StopIteration` in the executor, which raises the following exception while chaining states in futures. "StopIteration interacts badly with generators and cannot be raised into a Future" To avoid that, we handle the raise by a `return None` """ if request is None: raise StopAsyncIteration elif isinstance(self.iterator, AsyncIterator): # we assume that `AsyncIterator` doesn't block the event loop request = await self.iterator.__anext__() return request