code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" def __UpperCAmelCase ( __a : float ,__a : float ) -> float: """simple docstring""" if mass < 0: raise ValueError('''The mass of a body cannot be negative''' ) return 0.5 * mass * abs(__a ) * abs(__a ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
354
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset a__ = random.Random() def __UpperCAmelCase ( __a : Tuple ,__a : str=1.0 ,__a : Optional[int]=None ,__a : List[Any]=None ) -> Any: """simple docstring""" if rng is None: _a : Dict = global_rng _a : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _a , _a=7 , _a=4_0_0 , _a=2_0_0_0 , _a=2_0_4_8 , _a=1_2_8 , _a=1 , _a=5_1_2 , _a=3_0 , _a=4_4_1_0_0 , ) -> List[Any]: _a : Optional[Any] = parent _a : str = batch_size _a : List[str] = min_seq_length _a : str = max_seq_length _a : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : List[Any] = spectrogram_length _a : List[str] = feature_size _a : List[Any] = num_audio_channels _a : Tuple = hop_length _a : Optional[int] = chunk_length _a : int = sampling_rate def __lowercase ( self ) -> Union[str, Any]: return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __lowercase ( self , _a=False , _a=False ) -> List[Any]: def _flatten(_a ): return list(itertools.chain(*_a ) ) if equal_length: _a : List[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _a : List[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : str = [np.asarray(_a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = TvltFeatureExtractor def __lowercase ( self ) -> Dict: _a : List[str] = TvltFeatureExtractionTester(self ) def __lowercase ( self ) -> Any: _a : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a , '''spectrogram_length''' ) ) self.assertTrue(hasattr(_a , '''feature_size''' ) ) self.assertTrue(hasattr(_a , '''num_audio_channels''' ) ) self.assertTrue(hasattr(_a , '''hop_length''' ) ) self.assertTrue(hasattr(_a , '''chunk_length''' ) ) self.assertTrue(hasattr(_a , '''sampling_rate''' ) ) def __lowercase ( self ) -> Optional[int]: _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : int = feat_extract_first.save_pretrained(_a )[0] check_json_file_has_correct_format(_a ) _a : Dict = self.feature_extraction_class.from_pretrained(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Union[str, Any] = feat_extract_second.to_dict() _a : Any = dict_first.pop('''mel_filters''' ) _a : int = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Optional[int]: _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Optional[int] = os.path.join(_a , '''feat_extract.json''' ) feat_extract_first.to_json_file(_a ) _a : List[str] = self.feature_extraction_class.from_json_file(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Dict = feat_extract_second.to_dict() _a : str = dict_first.pop('''mel_filters''' ) _a : str = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Union[str, Any]: # Initialize feature_extractor _a : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 _a : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _a : List[str] = [np.asarray(_a ) for speech_input in speech_inputs] # Test not batched input _a : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched _a : Dict = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking _a : Union[str, Any] = feature_extractor( _a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 , mask_audio=_a ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. _a : Optional[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _a : int = np.asarray(_a ) _a : Tuple = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __lowercase ( self , _a ) -> Optional[Any]: _a : List[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech _a : Optional[int] = ds.sort('''id''' ).select(range(_a ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __lowercase ( self ) -> int: _a : Union[str, Any] = self._load_datasamples(1 ) _a : int = TvltFeatureExtractor() _a : Union[str, Any] = feature_extractor(_a , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_9_2, 1_2_8) ) _a : Union[str, Any] = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , _a , atol=1e-4 ) )
15
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor a__ = logging.get_logger(__name__) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __init__( self , *_a , **_a ) -> None: warnings.warn( '''The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use DeformableDetrImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
355
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch a__ = logging.get_logger(__name__) @add_end_docstrings( __lowercase , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self , _a ) -> np.ndarray: if self.framework == "tf": _a : List[str] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": _a : Tuple = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a ) else: raise ValueError('''Unsupported framework''' ) return masked_index def __lowercase ( self , _a ) -> np.ndarray: _a : int = self.get_masked_index(_a ) _a : Tuple = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( '''fill-mask''' , self.model.base_model_prefix , F"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , ) def __lowercase ( self , _a ) -> Optional[int]: if isinstance(_a , _a ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_a ) def __lowercase ( self , _a , _a=None , **_a ) -> Dict[str, GenericTensor]: if return_tensors is None: _a : Union[str, Any] = self.framework _a : str = self.tokenizer(_a , return_tensors=_a ) self.ensure_exactly_one_mask_token(_a ) return model_inputs def __lowercase ( self , _a ) -> Optional[Any]: _a : List[str] = self.model(**_a ) _a : Any = model_inputs['''input_ids'''] return model_outputs def __lowercase ( self , _a , _a=5 , _a=None ) -> str: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: _a : List[Any] = target_ids.shape[0] _a : Any = model_outputs['''input_ids'''][0] _a : List[str] = model_outputs['''logits'''] if self.framework == "tf": _a : Tuple = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] _a : List[str] = outputs.numpy() _a : Dict = outputs[0, masked_index, :] _a : str = stable_softmax(_a , axis=-1 ) if target_ids is not None: _a : Any = tf.gather_nd(tf.squeeze(_a , 0 ) , target_ids.reshape(-1 , 1 ) ) _a : Union[str, Any] = tf.expand_dims(_a , 0 ) _a : Optional[int] = tf.math.top_k(_a , k=_a ) _a , _a : Optional[Any] = topk.values.numpy(), topk.indices.numpy() else: _a : Optional[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample _a : List[str] = outputs[0, masked_index, :] _a : List[Any] = logits.softmax(dim=-1 ) if target_ids is not None: _a : List[Any] = probs[..., target_ids] _a , _a : Optional[Any] = probs.topk(_a ) _a : Dict = [] _a : List[Any] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): _a : Optional[Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place _a : Optional[int] = input_ids.numpy().copy() if target_ids is not None: _a : Tuple = target_ids[p].tolist() _a : List[str] = p # Filter padding out: _a : List[Any] = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back _a : List[str] = self.tokenizer.decode(_a , skip_special_tokens=_a ) _a : List[Any] = {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p] ), '''sequence''': sequence} row.append(_a ) result.append(_a ) if single_mask: return result[0] return result def __lowercase ( self , _a , _a=None ) -> Dict: if isinstance(_a , _a ): _a : Tuple = [targets] try: _a : int = self.tokenizer.get_vocab() except Exception: _a : Any = {} _a : List[Any] = [] for target in targets: _a : List[Any] = vocab.get(_a , _a ) if id_ is None: _a : Tuple = self.tokenizer( _a , add_special_tokens=_a , return_attention_mask=_a , return_token_type_ids=_a , max_length=1 , truncation=_a , )['''input_ids'''] if len(_a ) == 0: logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ '''We cannot replace it with anything meaningful, ignoring it''' ) continue _a : Tuple = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" ) target_ids.append(id_ ) _a : List[str] = list(set(_a ) ) if len(_a ) == 0: raise ValueError('''At least one target must be provided when passed.''' ) _a : int = np.array(_a ) return target_ids def __lowercase ( self , _a=None , _a=None ) -> Tuple: _a : str = {} if targets is not None: _a : List[Any] = self.get_target_ids(_a , _a ) _a : Optional[Any] = target_ids if top_k is not None: _a : Union[str, Any] = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( '''fill-mask''' , self.model.base_model_prefix , '''The tokenizer does not define a `mask_token`.''' ) return {}, {}, postprocess_params def __call__( self , _a , *_a , **_a ) -> int: _a : Optional[Any] = super().__call__(_a , **_a ) if isinstance(_a , _a ) and len(_a ) == 1: return outputs[0] return outputs
15
0
def __UpperCAmelCase ( __a : int = 1_000 ) -> int: """simple docstring""" _a : Union[str, Any] = 2**power _a : Union[str, Any] = 0 while n: _a : Dict = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
356
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow a__ = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ '''text-classification''', '''language-modeling''', '''summarization''', '''token-classification''', '''question-answering''', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) a__ = logging.getLogger() def __UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" _a : Any = argparse.ArgumentParser() parser.add_argument('''-f''' ) _a : Dict = parser.parse_args() return args.f def __UpperCAmelCase ( __a : Optional[int] ,__a : List[str]="eval" ) -> Any: """simple docstring""" _a : Any = os.path.join(__a ,F"""{split}_results.json""" ) if os.path.exists(__a ): with open(__a ,'''r''' ) as f: return json.load(__a ) raise ValueError(F"""can't find {path}""" ) a__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> str: _a : Any = self.get_auto_remove_tmp_dir() _a : Optional[Any] = F""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(_a , '''argv''' , _a ): run_flax_glue.main() _a : Any = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __lowercase ( self ) -> Dict: _a : Tuple = self.get_auto_remove_tmp_dir() _a : Tuple = F""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(_a , '''argv''' , _a ): run_clm_flax.main() _a : List[str] = get_results(_a ) self.assertLess(result['''eval_perplexity'''] , 1_0_0 ) @slow def __lowercase ( self ) -> Optional[int]: _a : str = self.get_auto_remove_tmp_dir() _a : Optional[int] = F""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(_a , '''argv''' , _a ): run_summarization_flax.main() _a : Optional[int] = get_results(_a , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 1_0 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __lowercase ( self ) -> Tuple: _a : List[str] = self.get_auto_remove_tmp_dir() _a : List[Any] = F""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(_a , '''argv''' , _a ): run_mlm_flax.main() _a : List[Any] = get_results(_a ) self.assertLess(result['''eval_perplexity'''] , 4_2 ) @slow def __lowercase ( self ) -> Dict: _a : Optional[Any] = self.get_auto_remove_tmp_dir() _a : int = F""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(_a , '''argv''' , _a ): run_ta_mlm_flax.main() _a : List[Any] = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __lowercase ( self ) -> Optional[Any]: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu _a : Any = 7 if get_gpu_count() > 1 else 2 _a : List[Any] = self.get_auto_remove_tmp_dir() _a : List[Any] = F""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(_a , '''argv''' , _a ): run_flax_ner.main() _a : Dict = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __lowercase ( self ) -> Any: _a : Optional[int] = self.get_auto_remove_tmp_dir() _a : Union[str, Any] = F""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(_a , '''argv''' , _a ): run_qa.main() _a : Any = get_results(_a ) self.assertGreaterEqual(result['''eval_f1'''] , 3_0 ) self.assertGreaterEqual(result['''eval_exact'''] , 3_0 )
15
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 a__ = get_tests_dir('''fixtures''') class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> List[Any]: # A mock response for an HTTP head request to emulate server down _a : Dict = mock.Mock() _a : List[Any] = 5_0_0 _a : Optional[Any] = {} _a : Any = HTTPError _a : Union[str, Any] = {} # Download this model to make sure it's in the cache. _a : Union[str, Any] = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=_a ) as mock_head: _a : Union[str, Any] = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # This check we did call the fake head request mock_head.assert_called() def __lowercase ( self ) -> Any: # This test is for deprecated behavior and can be removed in v5 _a : List[str] = WavaVecaFeatureExtractor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json''' ) @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def __lowercase ( cls ) -> Tuple: _a : Optional[int] = TOKEN HfFolder.save_token(_a ) @classmethod def __lowercase ( cls ) -> int: try: delete_repo(token=cls._token , repo_id='''test-feature-extractor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-feature-extractor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-feature-extractor''' ) except HTTPError: pass def __lowercase ( self ) -> str: _a : int = WavaVecaFeatureExtractor.from_pretrained(_a ) feature_extractor.push_to_hub('''test-feature-extractor''' , use_auth_token=self._token ) _a : List[Any] = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _a , repo_id='''test-feature-extractor''' , push_to_hub=_a , use_auth_token=self._token ) _a : Dict = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) def __lowercase ( self ) -> List[Any]: _a : int = WavaVecaFeatureExtractor.from_pretrained(_a ) feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' , use_auth_token=self._token ) _a : List[str] = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _a , repo_id='''valid_org/test-feature-extractor-org''' , push_to_hub=_a , use_auth_token=self._token ) _a : str = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) def __lowercase ( self ) -> Union[str, Any]: CustomFeatureExtractor.register_for_auto_class() _a : Union[str, Any] = CustomFeatureExtractor.from_pretrained(_a ) feature_extractor.push_to_hub('''test-dynamic-feature-extractor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''} , ) _a : str = AutoFeatureExtractor.from_pretrained( F"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=_a ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , '''CustomFeatureExtractor''' )
357
import argparse import os import re import packaging.version a__ = '''examples/''' a__ = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } a__ = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } a__ = '''README.md''' def __UpperCAmelCase ( __a : List[str] ,__a : int ,__a : Optional[Any] ) -> int: """simple docstring""" with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Tuple = f.read() _a , _a : str = REPLACE_PATTERNS[pattern] _a : List[str] = replace.replace('''VERSION''' ,__a ) _a : List[Any] = re_pattern.sub(__a ,__a ) with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.write(__a ) def __UpperCAmelCase ( __a : Any ) -> List[Any]: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a ,__a ) ,__a ,pattern='''examples''' ) def __UpperCAmelCase ( __a : List[Any] ,__a : List[str]=False ) -> int: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a ,__a ,__a ) if not patch: update_version_in_examples(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" _a : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' _a : str = '''1. Want to contribute a new model?''' with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Optional[int] = f.readlines() # Find the start of the list. _a : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _a : List[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): _a : Tuple = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' ,'''https://huggingface.co/docs/transformers/model_doc''' ,) index += 1 with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.writelines(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] ,'''r''' ) as f: _a : Optional[Any] = f.read() _a : Optional[Any] = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def __UpperCAmelCase ( __a : Dict=False ) -> str: """simple docstring""" _a : Optional[Any] = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: _a : List[Any] = default_version.base_version elif patch: _a : str = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _a : List[str] = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _a : Dict = input(F"""Which version are you releasing? [{default_version}]""" ) if len(__a ) == 0: _a : int = default_version print(F"""Updating version to {version}.""" ) global_version_update(__a ,patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def __UpperCAmelCase ( ) -> Tuple: """simple docstring""" _a : str = get_version() _a : int = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _a : List[Any] = current_version.base_version # Check with the user we got that right. _a : Union[str, Any] = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(__a ) == 0: _a : List[str] = dev_version print(F"""Updating version to {version}.""" ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') a__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
15
0
# Copyright 2023 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. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
358
def __UpperCAmelCase ( __a : int ) -> int: """simple docstring""" if n == 1 or not isinstance(__a ,__a ): return 0 elif n == 2: return 1 else: _a : Any = [0, 1] for i in range(2 ,n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def __UpperCAmelCase ( __a : int ) -> int: """simple docstring""" _a : Any = 0 _a : Dict = 2 while digits < n: index += 1 _a : Dict = len(str(fibonacci(__a ) ) ) return index def __UpperCAmelCase ( __a : int = 1_000 ) -> int: """simple docstring""" return fibonacci_digits_index(__a ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
15
0
import datasets from .evaluate import evaluate a__ = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowercase ( self , _a , _a ) -> Optional[int]: _a : Optional[int] = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} _a : Dict = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] _a : Union[str, Any] = evaluate(dataset=_a , predictions=_a ) return score
359
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record a__ = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' a__ = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' a__ = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def __UpperCAmelCase ( __a : int ,__a : List[str] ) -> Optional[Any]: """simple docstring""" return float((preds == labels).mean() ) def __UpperCAmelCase ( __a : List[Any] ,__a : Union[str, Any] ,__a : List[str]="binary" ) -> Optional[int]: """simple docstring""" _a : List[str] = simple_accuracy(__a ,__a ) _a : Any = float(fa_score(y_true=__a ,y_pred=__a ,average=__a ) ) return { "accuracy": acc, "f1": fa, } def __UpperCAmelCase ( __a : Optional[Any] ,__a : str ) -> List[Any]: """simple docstring""" _a : Union[str, Any] = {} for id_pred, label in zip(__a ,__a ): _a : Optional[int] = F"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" _a : Optional[Any] = id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: _a : str = [(pred, label)] _a , _a : Any = [], [] for question, preds_labels in question_map.items(): _a , _a : Any = zip(*__a ) _a : List[Any] = fa_score(y_true=__a ,y_pred=__a ,average='''macro''' ) fas.append(__a ) _a : List[str] = int(sum(pred == label for pred, label in preds_labels ) == len(__a ) ) ems.append(__a ) _a : List[str] = float(sum(__a ) / len(__a ) ) _a : str = sum(__a ) / len(__a ) _a : Optional[int] = float(fa_score(y_true=__a ,y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> List[Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def __lowercase ( self ) -> Any: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def __lowercase ( self , _a , _a ) -> Optional[Any]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_a , _a )} elif self.config_name == "cb": return acc_and_fa(_a , _a , fa_avg='''macro''' ) elif self.config_name == "record": _a : Any = [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] _a : Any = {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(_a , _a )[0] elif self.config_name == "multirc": return evaluate_multirc(_a , _a ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
15
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer a__ = logging.get_logger(__name__) a__ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart a__ = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } a__ = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : int = VOCAB_FILES_NAMES UpperCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] UpperCAmelCase__ : Union[str, Any] = BartTokenizer def __init__( self , _a=None , _a=None , _a=None , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , _a=True , **_a , ) -> List[str]: """simple docstring""" super().__init__( _a , _a , tokenizer_file=_a , errors=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , trim_offsets=_a , **_a , ) _a : int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _a ) != add_prefix_space: _a : Tuple = getattr(_a , pre_tok_state.pop('''type''' ) ) _a : int = add_prefix_space _a : Optional[Any] = pre_tok_class(**_a ) _a : Dict = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _a : Optional[int] = '''post_processor''' _a : Optional[int] = getattr(self.backend_tokenizer , _a , _a ) if tokenizer_component_instance: _a : List[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _a : List[str] = tuple(state['''sep'''] ) if "cls" in state: _a : Tuple = tuple(state['''cls'''] ) _a : int = False if state.get('''add_prefix_space''' , _a ) != add_prefix_space: _a : Any = add_prefix_space _a : Optional[Any] = True if state.get('''trim_offsets''' , _a ) != trim_offsets: _a : Tuple = trim_offsets _a : str = True if changes_to_apply: _a : Dict = getattr(_a , state.pop('''type''' ) ) _a : Tuple = component_class(**_a ) setattr(self.backend_tokenizer , _a , _a ) @property def __lowercase ( self ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __lowercase ( self , _a ) -> str: """simple docstring""" _a : List[str] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else value _a : List[Any] = value def __lowercase ( self , *_a , **_a ) -> BatchEncoding: """simple docstring""" _a : Optional[Any] = kwargs.get('''is_split_into_words''' , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*_a , **_a ) def __lowercase ( self , *_a , **_a ) -> BatchEncoding: """simple docstring""" _a : List[Any] = kwargs.get('''is_split_into_words''' , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*_a , **_a ) def __lowercase ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" _a : Optional[int] = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def __lowercase ( self , _a , _a=None ) -> Any: """simple docstring""" _a : Optional[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __lowercase ( self , _a , _a = None ) -> List[int]: """simple docstring""" _a : Tuple = [self.sep_token_id] _a : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
360
import numpy as np def __UpperCAmelCase ( __a : np.ndarray ,__a : np.ndarray ,__a : float = 1E-12 ,__a : int = 100 ,) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(__a )[0] == np.shape(__a )[1] # Ensure proper dimensionality. assert np.shape(__a )[0] == np.shape(__a )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(__a ) == np.iscomplexobj(__a ) _a : List[str] = np.iscomplexobj(__a ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(__a ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _a : List[str] = False _a : List[str] = 0 _a : Tuple = 0 _a : str = 1E12 while not convergence: # Multiple matrix by the vector. _a : str = np.dot(__a ,__a ) # Normalize the resulting output vector. _a : List[Any] = w / np.linalg.norm(__a ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _a : Dict = vector.conj().T if is_complex else vector.T _a : Tuple = np.dot(__a ,np.dot(__a ,__a ) ) # Check convergence. _a : List[str] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _a : Dict = True _a : str = lambda_ if is_complex: _a : Tuple = np.real(lambda_ ) return lambda_, vector def __UpperCAmelCase ( ) -> None: """simple docstring""" _a : List[str] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) _a : int = np.array([41, 4, 20] ) _a : Optional[Any] = real_input_matrix.astype(np.complexaaa ) _a : int = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _a : Union[str, Any] = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _a : Optional[int] = real_input_matrix _a : Union[str, Any] = real_vector elif problem_type == "complex": _a : str = complex_input_matrix _a : str = complex_vector # Our implementation. _a , _a : Optional[Any] = power_iteration(__a ,__a ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _a , _a : List[str] = np.linalg.eigh(__a ) # Last eigenvalue is the maximum one. _a : Tuple = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _a : List[Any] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(__a ) - np.abs(__a ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a__ = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
361
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase_ ( datasets.BuilderConfig ): """simple docstring""" UpperCAmelCase__ : Optional[datasets.Features] = None class UpperCAmelCase_ ( datasets.ArrowBasedBuilder ): """simple docstring""" UpperCAmelCase__ : Any = PandasConfig def __lowercase ( self ) -> Any: return datasets.DatasetInfo(features=self.config.features ) def __lowercase ( self , _a ) -> List[Any]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _a : str = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): _a : Dict = data_files if isinstance(_a , _a ): _a : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : int = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _a : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): _a : List[str] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : Any = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={'''files''': files} ) ) return splits def __lowercase ( self , _a ) -> pa.Table: if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _a : Optional[Any] = table_cast(_a , self.config.features.arrow_schema ) return pa_table def __lowercase ( self , _a ) -> List[str]: for i, file in enumerate(itertools.chain.from_iterable(_a ) ): with open(_a , '''rb''' ) as f: _a : str = pa.Table.from_pandas(pd.read_pickle(_a ) ) yield i, self._cast_table(_a )
15
0
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ = '''platform''' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def __UpperCAmelCase ( __a : str ,__a : Dict ,__a : Optional[Any]=None ,__a : Optional[Any]=None ,__a : str=None ,__a : int=None ,__a : Optional[Any]=None ,__a : Union[str, Any]=None ,) -> Optional[Any]: """simple docstring""" if attention_mask is None: _a : Union[str, Any] = np.where(input_ids != config.pad_token_id ,1 ,0 ) if decoder_attention_mask is None: _a : str = np.where(decoder_input_ids != config.pad_token_id ,1 ,0 ) if head_mask is None: _a : Optional[Any] = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _a : List[Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _a : List[str] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a , _a=1_3 , _a=7 , _a=True , _a=False , _a=9_9 , _a=1_6 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=3_2 , _a=2 , _a=1 , _a=0 , _a=0.02 , ) -> List[str]: _a : List[Any] = parent _a : List[Any] = batch_size _a : List[str] = seq_length _a : Any = is_training _a : Tuple = use_labels _a : List[Any] = vocab_size _a : Union[str, Any] = hidden_size _a : Optional[Any] = num_hidden_layers _a : Tuple = num_attention_heads _a : Union[str, Any] = intermediate_size _a : Dict = hidden_act _a : Any = hidden_dropout_prob _a : Optional[Any] = attention_probs_dropout_prob _a : List[Any] = max_position_embeddings _a : List[Any] = eos_token_id _a : Optional[Any] = pad_token_id _a : Any = bos_token_id _a : Any = initializer_range def __lowercase ( self ) -> Dict: _a : int = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) _a : Optional[Any] = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) _a : Tuple = shift_tokens_right(_a , 1 , 2 ) _a : Optional[int] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_a , ) _a : Tuple = prepare_blenderbot_inputs_dict(_a , _a , _a ) return config, inputs_dict def __lowercase ( self ) -> List[str]: _a : Dict = self.prepare_config_and_inputs() return config, inputs_dict def __lowercase ( self , _a , _a , _a ) -> str: _a : Optional[int] = 2_0 _a : Union[str, Any] = model_class_name(_a ) _a : Optional[Any] = model.encode(inputs_dict['''input_ids'''] ) _a : str = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) _a : Any = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) _a : Optional[Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) _a : str = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a : Union[str, Any] = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) _a : str = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) _a : Any = model.decode( decoder_input_ids[:, -1:] , _a , decoder_attention_mask=_a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_a , ) _a : Union[str, Any] = model.decode(_a , _a ) _a : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def __lowercase ( self , _a , _a , _a ) -> str: _a : Union[str, Any] = 2_0 _a : str = model_class_name(_a ) _a : Optional[int] = model.encode(inputs_dict['''input_ids'''] ) _a : str = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) _a : str = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _a : Tuple = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) _a : List[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _a : List[str] = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) _a : List[str] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) _a : List[str] = model.decode( decoder_input_ids[:, -1:] , _a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_a , decoder_position_ids=_a , ) _a : Dict = model.decode(_a , _a , decoder_attention_mask=_a ) _a : List[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) @require_flax class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = 99 def __lowercase ( self ) -> List[str]: _a : List[Any] = np.array( [ [7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2], [5, 9_7, 1_7, 3_9, 9_4, 4_0, 2], [7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2], [8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2], [5_5, 1_3, 1_6, 5_8, 5, 2, 1], # note padding [6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2], [5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2], [4_8, 6_1, 9, 2_4, 7_1, 8_2, 2], [2_6, 1, 6_0, 4_8, 2_2, 1_3, 2], [2_1, 5, 6_2, 2_8, 1_4, 7_6, 2], [4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2], [7_0, 7_0, 5_0, 9, 2_8, 0, 2], ] , dtype=np.intaa , ) _a : List[str] = input_ids.shape[0] _a : Dict = BlenderbotConfig( vocab_size=self.vocab_size , d_model=2_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=3_2 , decoder_ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __lowercase ( self ) -> int: _a : List[Any] = self._get_config_and_data() _a : Optional[Any] = FlaxBlenderbotForConditionalGeneration(_a ) _a : Dict = lm_model(input_ids=_a ) _a : Optional[int] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _a ) def __lowercase ( self ) -> Dict: _a : str = BlenderbotConfig( vocab_size=self.vocab_size , d_model=1_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=4_8 , ) _a : Optional[Any] = FlaxBlenderbotForConditionalGeneration(_a ) _a : List[str] = np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]] , dtype=np.intaa ) _a : Optional[Any] = np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]] , dtype=np.intaa ) _a : Tuple = lm_model(input_ids=_a , decoder_input_ids=_a ) _a : Optional[Any] = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _a ) def __lowercase ( self ) -> Union[str, Any]: _a : Optional[Any] = np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]] , dtype=np.intaa ) _a : List[str] = shift_tokens_right(_a , 1 , 2 ) _a : Union[str, Any] = np.equal(_a , 1 ).astype(np.floataa ).sum() _a : int = np.equal(_a , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_a , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class UpperCAmelCase_ ( __lowercase , unittest.TestCase , __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = True UpperCAmelCase__ : List[Any] = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) UpperCAmelCase__ : Tuple = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def __lowercase ( self ) -> Union[str, Any]: _a : Optional[int] = FlaxBlenderbotModelTester(self ) def __lowercase ( self ) -> int: _a : List[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_a , _a , _a ) def __lowercase ( self ) -> Tuple: _a : int = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_a , _a , _a ) def __lowercase ( self ) -> str: _a : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _a : List[Any] = self._prepare_for_class(_a , _a ) _a : Optional[Any] = model_class(_a ) @jax.jit def encode_jitted(_a , _a=None , **_a ): return model.encode(input_ids=_a , attention_mask=_a ) with self.subTest('''JIT Enabled''' ): _a : Optional[Any] = encode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _a : Tuple = encode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) def __lowercase ( self ) -> Dict: _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _a : List[str] = model_class(_a ) _a : List[Any] = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) _a : Union[str, Any] = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_a , _a , _a ): return model.decode( decoder_input_ids=_a , decoder_attention_mask=_a , encoder_outputs=_a , ) with self.subTest('''JIT Enabled''' ): _a : Optional[int] = decode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _a : Dict = decode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowercase ( self ) -> Tuple: for model_class_name in self.all_model_classes: _a : str = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids _a : Union[str, Any] = np.ones((1, 1) ) * model.config.eos_token_id _a : str = model(_a ) self.assertIsNotNone(_a ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def __lowercase ( self ) -> Any: _a : Tuple = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 1_5, '''max_length''': 2_5} _a : Union[str, Any] = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} _a : Tuple = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=_a ) _a : str = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) _a : List[Any] = ['''Sam'''] _a : str = tokenizer(_a , return_tensors='''jax''' ) _a : List[Any] = model.generate(**_a , **_a ) _a : Optional[Any] = '''Sam is a great name. It means "sun" in Gaelic.''' _a : Dict = tokenizer.batch_decode(_a , **_a ) assert generated_txt[0].strip() == tgt_text
362
def __UpperCAmelCase ( __a : int ,__a : int ,__a : int ) -> int: """simple docstring""" if exponent == 1: return base if exponent % 2 == 0: _a : List[Any] = _modexpt(__a ,exponent // 2 ,__a ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(__a ,exponent - 1 ,__a )) % modulo_value def __UpperCAmelCase ( __a : int = 1_777 ,__a : int = 1_855 ,__a : int = 8 ) -> int: """simple docstring""" _a : List[Any] = base for _ in range(1 ,__a ): _a : Any = _modexpt(__a ,__a ,10**digits ) return result if __name__ == "__main__": print(f'''{solution() = }''')
15
0
from maths.prime_check import is_prime def __UpperCAmelCase ( __a : int ) -> int: """simple docstring""" if not isinstance(__a ,__a ): _a : str = F"""Input value of [number={number}] must be an integer""" raise TypeError(__a ) if is_prime(__a ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
363
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging a__ = '''\ ''' a__ = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' a__ = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''input_texts''': datasets.Value('''string''' ), } ) , reference_urls=['''https://huggingface.co/docs/transformers/perplexity'''] , ) def __lowercase ( self , _a , _a , _a = 1_6 , _a = True , _a=None ) -> List[Any]: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": _a : List[str] = '''cuda''' else: _a : Optional[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' _a : Dict = AutoModelForCausalLM.from_pretrained(_a ) _a : List[Any] = model.to(_a ) _a : List[str] = AutoTokenizer.from_pretrained(_a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: _a : str = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" _a : List[Any] = model.config.max_length - 1 else: _a : List[str] = model.config.max_length _a : Union[str, Any] = tokenizer( _a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , return_tensors='''pt''' , return_attention_mask=_a , ).to(_a ) _a : List[Any] = encodings['''input_ids'''] _a : int = encodings['''attention_mask'''] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." _a : Optional[int] = [] _a : Dict = CrossEntropyLoss(reduction='''none''' ) for start_index in logging.tqdm(range(0 , len(_a ) , _a ) ): _a : Dict = min(start_index + batch_size , len(_a ) ) _a : Union[str, Any] = encoded_texts[start_index:end_index] _a : int = attn_masks[start_index:end_index] if add_start_token: _a : Dict = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_a ) _a : List[str] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) _a : Dict = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_a ), attn_mask] , dim=1 ) _a : Dict = encoded_batch with torch.no_grad(): _a : Any = model(_a , attention_mask=_a ).logits _a : List[str] = out_logits[..., :-1, :].contiguous() _a : Union[str, Any] = labels[..., 1:].contiguous() _a : Optional[int] = attn_mask[..., 1:].contiguous() _a : Union[str, Any] = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_a )}
15
0
"""simple docstring""" # Copyright 2021 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. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter a__ = '''Create a default config file for Accelerate with only a few flags set.''' def __UpperCAmelCase ( __a : Optional[int]="no" ,__a : str = default_json_config_file ,__a : bool = False ) -> Any: """simple docstring""" _a : List[Any] = Path(__a ) path.parent.mkdir(parents=__a ,exist_ok=__a ) if path.exists(): print( F"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.""" ) return False _a : List[Any] = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}""" ) _a : Optional[int] = { '''compute_environment''': '''LOCAL_MACHINE''', '''mixed_precision''': mixed_precision, } if torch.cuda.is_available(): _a : Any = torch.cuda.device_count() _a : List[Any] = num_gpus _a : Dict = False if num_gpus > 1: _a : str = '''MULTI_GPU''' else: _a : Union[str, Any] = '''NO''' elif is_xpu_available() and use_xpu: _a : str = torch.xpu.device_count() _a : List[str] = num_xpus _a : Union[str, Any] = False if num_xpus > 1: _a : Tuple = '''MULTI_XPU''' else: _a : Tuple = '''NO''' elif is_npu_available(): _a : Dict = torch.npu.device_count() _a : Dict = num_npus _a : Optional[int] = False if num_npus > 1: _a : List[str] = '''MULTI_NPU''' else: _a : int = '''NO''' else: _a : str = 0 _a : Optional[Any] = True _a : int = 1 _a : int = '''NO''' _a : Tuple = ClusterConfig(**__a ) config.to_json_file(__a ) return path def __UpperCAmelCase ( __a : Tuple ,__a : Any ) -> List[Any]: """simple docstring""" _a : List[str] = parser.add_parser('''default''' ,parents=__a ,help=__a ,formatter_class=__a ) parser.add_argument( '''--config_file''' ,default=__a ,help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) ,dest='''save_location''' ,) parser.add_argument( '''--mixed_precision''' ,choices=['''no''', '''fp16''', '''bf16'''] ,type=__a ,help='''Whether or not to use mixed precision training. ''' '''Choose between FP16 and BF16 (bfloat16) training. ''' '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' ,default='''no''' ,) parser.set_defaults(func=__a ) return parser def __UpperCAmelCase ( __a : Dict ) -> List[Any]: """simple docstring""" _a : List[Any] = write_basic_config(args.mixed_precision ,args.save_location ) if config_file: print(F"""accelerate configuration saved at {config_file}""" )
364
# Copyright 2023 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. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
15
0
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a , _a=3 , _a=3_2 , _a=3 , _a=1_0 , _a=[8, 1_6, 3_2, 6_4] , _a=[1, 1, 2, 1] , _a=True , _a=True , _a="relu" , _a=3 , _a=None , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=1 , ) -> List[Any]: _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Any = num_channels _a : Any = embeddings_size _a : Optional[Any] = hidden_sizes _a : Dict = depths _a : List[Any] = is_training _a : List[Any] = use_labels _a : Dict = hidden_act _a : str = num_labels _a : Optional[Any] = scope _a : List[Any] = len(_a ) _a : Optional[Any] = out_features _a : Dict = out_indices _a : Optional[Any] = num_groups def __lowercase ( self ) -> Union[str, Any]: _a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : int = None if self.use_labels: _a : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) _a : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase ( self ) -> Tuple: return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def __lowercase ( self , _a , _a , _a ) -> Dict: _a : Optional[int] = BitModel(config=_a ) model.to(_a ) model.eval() _a : int = model(_a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __lowercase ( self , _a , _a , _a ) -> List[Any]: _a : List[str] = self.num_labels _a : str = BitForImageClassification(_a ) model.to(_a ) model.eval() _a : List[str] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase ( self , _a , _a , _a ) -> str: _a : str = BitBackbone(config=_a ) model.to(_a ) model.eval() _a : Optional[Any] = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : List[Any] = None _a : Tuple = BitBackbone(config=_a ) model.to(_a ) model.eval() _a : Dict = model(_a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def __lowercase ( self ) -> Dict: _a : Optional[Any] = self.prepare_config_and_inputs() _a : Dict = config_and_inputs _a : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () UpperCAmelCase__ : Optional[Any] = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) UpperCAmelCase__ : Any = False UpperCAmelCase__ : Any = False UpperCAmelCase__ : Any = False UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : str = False def __lowercase ( self ) -> str: _a : Optional[int] = BitModelTester(self ) _a : List[Any] = ConfigTester(self , config_class=_a , has_text_modality=_a ) def __lowercase ( self ) -> Optional[int]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self ) -> str: return @unittest.skip(reason='''Bit does not output attentions''' ) def __lowercase ( self ) -> Union[str, Any]: pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def __lowercase ( self ) -> List[str]: pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def __lowercase ( self ) -> Tuple: pass def __lowercase ( self ) -> Tuple: _a : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : List[Any] = model_class(_a ) _a : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Any = [*signature.parameters.keys()] _a : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __lowercase ( self ) -> Optional[int]: _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self ) -> Union[str, Any]: _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_a ) def __lowercase ( self ) -> List[Any]: _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Tuple = model_class(config=_a ) for name, module in model.named_modules(): if isinstance(_a , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) def __lowercase ( self ) -> List[Any]: def check_hidden_states_output(_a , _a , _a ): _a : Optional[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _a : Union[str, Any] = model(**self._prepare_for_class(_a , _a ) ) _a : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : Dict = self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _a : str = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: _a : Tuple = layer_type _a : Union[str, Any] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : int = True check_hidden_states_output(_a , _a , _a ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def __lowercase ( self ) -> List[Any]: pass def __lowercase ( self ) -> str: _a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def __lowercase ( self ) -> List[str]: for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : List[str] = BitModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __UpperCAmelCase ( ) -> Dict: """simple docstring""" _a : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self ) -> str: return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase ( self ) -> str: _a : Optional[Any] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_a ) _a : Union[str, Any] = self.default_image_processor _a : str = prepare_img() _a : List[str] = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): _a : Tuple = model(**_a ) # verify the logits _a : int = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _a ) _a : Optional[int] = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @require_torch class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : str = (BitBackbone,) if is_torch_available() else () UpperCAmelCase__ : Union[str, Any] = BitConfig UpperCAmelCase__ : List[Any] = False def __lowercase ( self ) -> Any: _a : Optional[Any] = BitModelTester(self )
365
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a__ = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) a__ = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Extra Ignored Subsection''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], } ], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } a__ = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) a__ = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) a__ = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' a__ = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.''' a__ = '''''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.''' @pytest.mark.parametrize( '''readme_md, expected_dict''' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : List[str] ) -> Optional[int]: """simple docstring""" assert ReadMe.from_string(__a ,__a ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def __UpperCAmelCase ( __a : List[str] ,__a : Optional[Any] ) -> Union[str, Any]: """simple docstring""" with pytest.raises(__a ,match=re.escape(expected_error.format(path='''root''' ) ) ): _a : List[Any] = ReadMe.from_string(__a ,__a ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Dict ,__a : Dict ) -> Tuple: """simple docstring""" with pytest.raises(__a ,match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__a ,__a ) @pytest.mark.parametrize( '''readme_md,''' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Optional[Any] ) -> Tuple: """simple docstring""" ReadMe.from_string(__a ,__a ,suppress_parsing_errors=__a ) @pytest.mark.parametrize( '''readme_md, expected_dict''' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : Any ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : Tuple = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : Optional[Any] = ReadMe.from_readme(__a ,__a ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def __UpperCAmelCase ( __a : List[Any] ,__a : List[Any] ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : int = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : Optional[int] = expected_error.format(path=__a ) with pytest.raises(__a ,match=re.escape(__a ) ): _a : Any = ReadMe.from_readme(__a ,__a ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : str ,__a : Union[str, Any] ) -> Dict: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : Optional[Any] = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : str = expected_error.format(path=__a ) with pytest.raises(__a ,match=re.escape(__a ) ): ReadMe.from_readme(__a ,__a ) @pytest.mark.parametrize( '''readme_md,''' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Optional[Any] ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : int = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) ReadMe.from_readme(__a ,__a ,suppress_parsing_errors=__a )
15
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib a__ = get_logger() a__ = None class UpperCAmelCase_ ( TensorFormatter[Mapping, "jax.Array", Mapping] ): """simple docstring""" def __init__( self , _a=None , _a=None , **_a ) -> str: super().__init__(features=_a ) import jax from jaxlib.xla_client import Device if isinstance(_a , _a ): raise ValueError( F"""Expected {device} to be a `str` not {type(_a )}, as `jaxlib.xla_extension.Device` """ '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) _a : List[str] = device if isinstance(_a , _a ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a : Dict = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) _a : Any = str(jax.devices()[0] ) _a : Optional[Any] = jnp_array_kwargs @staticmethod def __lowercase ( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(_a ): device for device in jax.devices()} def __lowercase ( self , _a ) -> str: import jax import jax.numpy as jnp if isinstance(_a , _a ) and column: if all( isinstance(_a , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(_a , axis=0 ) return column def __lowercase ( self , _a ) -> Optional[Any]: import jax import jax.numpy as jnp if isinstance(_a , (str, bytes, type(_a )) ): return value elif isinstance(_a , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _a : str = {} if isinstance(_a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: _a : Dict = {'''dtype''': jnp.intaa} else: _a : Optional[int] = {'''dtype''': jnp.intaa} elif isinstance(_a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _a : Optional[Any] = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_a , PIL.Image.Image ): _a : int = np.asarray(_a ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a : str = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(_a , **{**default_dtype, **self.jnp_array_kwargs} ) def __lowercase ( self , _a ) -> int: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(_a , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(_a , '''__array__''' ) and not isinstance(_a , jax.Array ): _a : List[Any] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_a , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) elif isinstance(_a , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) return self._tensorize(_a ) def __lowercase ( self , _a ) -> List[Any]: return map_nested(self._recursive_tensorize , _a , map_list=_a ) def __lowercase ( self , _a ) -> Mapping: _a : Any = self.numpy_arrow_extractor().extract_row(_a ) _a : int = self.python_features_decoder.decode_row(_a ) return self.recursive_tensorize(_a ) def __lowercase ( self , _a ) -> "jax.Array": _a : int = self.numpy_arrow_extractor().extract_column(_a ) _a : Dict = self.python_features_decoder.decode_column(_a , pa_table.column_names[0] ) _a : Optional[Any] = self.recursive_tensorize(_a ) _a : Dict = self._consolidate(_a ) return column def __lowercase ( self , _a ) -> Mapping: _a : Union[str, Any] = self.numpy_arrow_extractor().extract_batch(_a ) _a : Optional[Any] = self.python_features_decoder.decode_batch(_a ) _a : Any = self.recursive_tensorize(_a ) for column_name in batch: _a : int = self._consolidate(batch[column_name] ) return batch
366
from __future__ import annotations def __UpperCAmelCase ( __a : list ) -> float: """simple docstring""" if not nums: raise ValueError('''List is empty''' ) return sum(__a ) / len(__a ) if __name__ == "__main__": import doctest doctest.testmod()
15
0
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a__ = logging.get_logger(__name__) def __UpperCAmelCase ( __a : str ) -> Optional[int]: """simple docstring""" _a : str = SwinConfig.from_pretrained( '''microsoft/swin-tiny-patch4-window7-224''' ,out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) _a : int = MaskFormerConfig(backbone_config=__a ) _a : Union[str, Any] = '''huggingface/label-files''' if "ade20k-full" in model_name: # this should be ok _a : Union[str, Any] = 847 _a : str = '''maskformer-ade20k-full-id2label.json''' elif "ade" in model_name: # this should be ok _a : int = 150 _a : Optional[int] = '''ade20k-id2label.json''' elif "coco-stuff" in model_name: # this should be ok _a : Optional[int] = 171 _a : Optional[Any] = '''maskformer-coco-stuff-id2label.json''' elif "coco" in model_name: # TODO _a : Dict = 133 _a : str = '''coco-panoptic-id2label.json''' elif "cityscapes" in model_name: # this should be ok _a : Optional[Any] = 19 _a : Optional[int] = '''cityscapes-id2label.json''' elif "vistas" in model_name: # this should be ok _a : List[str] = 65 _a : List[str] = '''mapillary-vistas-id2label.json''' _a : List[Any] = json.load(open(hf_hub_download(__a ,__a ,repo_type='''dataset''' ) ,'''r''' ) ) _a : List[str] = {int(__a ): v for k, v in idalabel.items()} return config def __UpperCAmelCase ( __a : Optional[int] ) -> Union[str, Any]: """simple docstring""" _a : Tuple = [] # stem # fmt: off rename_keys.append(('''backbone.patch_embed.proj.weight''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.patch_embed.proj.bias''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.patch_embed.norm.weight''', '''model.pixel_level_module.encoder.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.patch_embed.norm.bias''', '''model.pixel_level_module.encoder.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.norm1.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.norm1.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.attn.relative_position_index""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.attn.proj.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.attn.proj.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.norm2.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.norm2.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.mlp.fc1.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.mlp.fc1.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.mlp.fc2.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((F"""backbone.layers.{i}.blocks.{j}.mlp.fc2.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((F"""backbone.layers.{i}.downsample.reduction.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((F"""backbone.layers.{i}.downsample.norm.weight""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((F"""backbone.layers.{i}.downsample.norm.bias""", F"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append((F"""backbone.norm{i}.weight""", F"""model.pixel_level_module.encoder.hidden_states_norms.{i}.weight""") ) rename_keys.append((F"""backbone.norm{i}.bias""", F"""model.pixel_level_module.encoder.hidden_states_norms.{i}.bias""") ) # FPN rename_keys.append(('''sem_seg_head.layer_4.weight''', '''model.pixel_level_module.decoder.fpn.stem.0.weight''') ) rename_keys.append(('''sem_seg_head.layer_4.norm.weight''', '''model.pixel_level_module.decoder.fpn.stem.1.weight''') ) rename_keys.append(('''sem_seg_head.layer_4.norm.bias''', '''model.pixel_level_module.decoder.fpn.stem.1.bias''') ) for source_index, target_index in zip(range(3 ,0 ,-1 ) ,range(0 ,3 ) ): rename_keys.append((F"""sem_seg_head.adapter_{source_index}.weight""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight""") ) rename_keys.append((F"""sem_seg_head.adapter_{source_index}.norm.weight""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight""") ) rename_keys.append((F"""sem_seg_head.adapter_{source_index}.norm.bias""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias""") ) rename_keys.append((F"""sem_seg_head.layer_{source_index}.weight""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight""") ) rename_keys.append((F"""sem_seg_head.layer_{source_index}.norm.weight""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight""") ) rename_keys.append((F"""sem_seg_head.layer_{source_index}.norm.bias""", F"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias""") ) rename_keys.append(('''sem_seg_head.mask_features.weight''', '''model.pixel_level_module.decoder.mask_projection.weight''') ) rename_keys.append(('''sem_seg_head.mask_features.bias''', '''model.pixel_level_module.decoder.mask_projection.bias''') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight""", F"""model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias""", F"""model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias""") ) # cross-attention out projection rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight""", F"""model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias""", F"""model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias""") ) # MLP 1 rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight""", F"""model.transformer_module.decoder.layers.{idx}.fc1.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias""", F"""model.transformer_module.decoder.layers.{idx}.fc1.bias""") ) # MLP 2 rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight""", F"""model.transformer_module.decoder.layers.{idx}.fc2.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias""", F"""model.transformer_module.decoder.layers.{idx}.fc2.bias""") ) # layernorm 1 (self-attention layernorm) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight""", F"""model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias""", F"""model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias""") ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight""", F"""model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias""", F"""model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias""") ) # layernorm 3 (final layernorm) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight""", F"""model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias""", F"""model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias""") ) rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.weight''', '''model.transformer_module.decoder.layernorm.weight''') ) rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.bias''', '''model.transformer_module.decoder.layernorm.bias''') ) # heads on top rename_keys.append(('''sem_seg_head.predictor.query_embed.weight''', '''model.transformer_module.queries_embedder.weight''') ) rename_keys.append(('''sem_seg_head.predictor.input_proj.weight''', '''model.transformer_module.input_projection.weight''') ) rename_keys.append(('''sem_seg_head.predictor.input_proj.bias''', '''model.transformer_module.input_projection.bias''') ) rename_keys.append(('''sem_seg_head.predictor.class_embed.weight''', '''class_predictor.weight''') ) rename_keys.append(('''sem_seg_head.predictor.class_embed.bias''', '''class_predictor.bias''') ) for i in range(3 ): rename_keys.append((F"""sem_seg_head.predictor.mask_embed.layers.{i}.weight""", F"""mask_embedder.{i}.0.weight""") ) rename_keys.append((F"""sem_seg_head.predictor.mask_embed.layers.{i}.bias""", F"""mask_embedder.{i}.0.bias""") ) # fmt: on return rename_keys def __UpperCAmelCase ( __a : Any ,__a : Tuple ,__a : str ) -> List[Any]: """simple docstring""" _a : Any = dct.pop(__a ) _a : int = val def __UpperCAmelCase ( __a : Optional[int] ,__a : Union[str, Any] ) -> Optional[int]: """simple docstring""" _a : Union[str, Any] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): _a : Union[str, Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) _a : Any = state_dict.pop(F"""backbone.layers.{i}.blocks.{j}.attn.qkv.weight""" ) _a : List[str] = state_dict.pop(F"""backbone.layers.{i}.blocks.{j}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _a : int = in_proj_weight[:dim, :] _a : int = in_proj_bias[: dim] _a : Tuple = in_proj_weight[ dim : dim * 2, : ] _a : Optional[Any] = in_proj_bias[ dim : dim * 2 ] _a : List[str] = in_proj_weight[ -dim :, : ] _a : Dict = in_proj_bias[-dim :] # fmt: on def __UpperCAmelCase ( __a : Tuple ,__a : Tuple ) -> Dict: """simple docstring""" _a : Union[str, Any] = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) _a : Optional[Any] = state_dict.pop(F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight""" ) _a : List[str] = state_dict.pop(F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict _a : str = in_proj_weight[: hidden_size, :] _a : Dict = in_proj_bias[:config.hidden_size] _a : Optional[int] = in_proj_weight[hidden_size : hidden_size * 2, :] _a : List[str] = in_proj_bias[hidden_size : hidden_size * 2] _a : Dict = in_proj_weight[-hidden_size :, :] _a : List[str] = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) _a : List[Any] = state_dict.pop(F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight""" ) _a : str = state_dict.pop(F"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict _a : List[Any] = in_proj_weight[: hidden_size, :] _a : Any = in_proj_bias[:config.hidden_size] _a : Any = in_proj_weight[hidden_size : hidden_size * 2, :] _a : List[str] = in_proj_bias[hidden_size : hidden_size * 2] _a : int = in_proj_weight[-hidden_size :, :] _a : List[Any] = in_proj_bias[-hidden_size :] # fmt: on def __UpperCAmelCase ( ) -> torch.Tensor: """simple docstring""" _a : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _a : Optional[int] = Image.open(requests.get(__a ,stream=__a ).raw ) return im @torch.no_grad() def __UpperCAmelCase ( __a : str ,__a : str ,__a : str ,__a : bool = False ) -> Optional[Any]: """simple docstring""" _a : Union[str, Any] = get_maskformer_config(__a ) # load original state_dict with open(__a ,'''rb''' ) as f: _a : int = pickle.load(__a ) _a : Union[str, Any] = data['''model'''] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys _a : Tuple = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a ,__a ,__a ) read_in_swin_q_k_v(__a ,config.backbone_config ) read_in_decoder_q_k_v(__a ,__a ) # update to torch tensors for key, value in state_dict.items(): _a : Optional[Any] = torch.from_numpy(__a ) # load 🤗 model _a : Union[str, Any] = MaskFormerForInstanceSegmentation(__a ) model.eval() for name, param in model.named_parameters(): print(__a ,param.shape ) _a : List[Any] = model.load_state_dict(__a ,strict=__a ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(__a ) == 0, F"""Unexpected keys: {unexpected_keys}""" # verify results _a : int = prepare_img() if "vistas" in model_name: _a : Optional[Any] = 65 elif "cityscapes" in model_name: _a : List[str] = 65_535 else: _a : Tuple = 255 _a : int = True if '''ade''' in model_name else False _a : Optional[int] = MaskFormerImageProcessor(ignore_index=__a ,reduce_labels=__a ) _a : List[str] = image_processor(__a ,return_tensors='''pt''' ) _a : Dict = model(**__a ) print('''Logits:''' ,outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": _a : Dict = torch.tensor( [[3.63_53, -4.47_70, -2.60_65], [0.50_81, -4.23_94, -3.53_43], [2.19_09, -5.03_53, -1.93_23]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] ,__a ,atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F"""Saving model and image processor to {pytorch_dump_folder_path}""" ) Path(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) image_processor.save_pretrained(__a ) if push_to_hub: print('''Pushing model and image processor to the hub...''' ) model.push_to_hub(F"""nielsr/{model_name}""" ) image_processor.push_to_hub(F"""nielsr/{model_name}""" ) if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''maskformer-swin-tiny-ade''', type=str, help=('''Name of the MaskFormer model you\'d like to convert''',), ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl''', type=str, help='''Path to the original state dict (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) a__ = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
367
import argparse import os import torch from transformers.utils import WEIGHTS_NAME a__ = ['''small''', '''medium''', '''large'''] a__ = '''lm_head.decoder.weight''' a__ = '''lm_head.weight''' def __UpperCAmelCase ( __a : str ,__a : str ) -> List[str]: """simple docstring""" _a : Any = torch.load(__a ) _a : List[str] = d.pop(__a ) os.makedirs(__a ,exist_ok=__a ) torch.save(__a ,os.path.join(__a ,__a ) ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--dialogpt_path''', default='''.''', type=str) a__ = parser.parse_args() for MODEL in DIALOGPT_MODELS: a__ = os.path.join(args.dialogpt_path, f'''{MODEL}_ft.pkl''') a__ = f'''./DialoGPT-{MODEL}''' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
15
0
from math import ceil def __UpperCAmelCase ( __a : int = 1_001 ) -> int: """simple docstring""" _a : Dict = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): _a : int = 2 * i + 1 _a : str = 2 * i _a : Any = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: a__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
368
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class UpperCAmelCase_ ( enum.Enum ): """simple docstring""" UpperCAmelCase__ : int = 0 UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Optional[Any] = 2 @add_end_docstrings(__lowercase ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self , *_a , **_a ) -> List[str]: super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _a : Dict = None if self.model.config.prefix is not None: _a : List[Any] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _a : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _a , _a , _a : str = self._sanitize_parameters(prefix=_a , **self._forward_params ) _a : Optional[Any] = {**self._preprocess_params, **preprocess_params} _a : List[Any] = {**self._forward_params, **forward_params} def __lowercase ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> Optional[int]: _a : List[Any] = {} if prefix is not None: _a : Optional[Any] = prefix if prefix: _a : Dict = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) _a : Tuple = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _a : Dict = handle_long_generation preprocess_params.update(_a ) _a : Tuple = generate_kwargs _a : Any = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _a : List[str] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _a : Any = ReturnType.TENSORS if return_type is not None: _a : Any = return_type if clean_up_tokenization_spaces is not None: _a : List[Any] = clean_up_tokenization_spaces if stop_sequence is not None: _a : Tuple = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _a : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowercase ( self , *_a , **_a ) -> Union[str, Any]: # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> List[str]: return super().__call__(_a , **_a ) def __lowercase ( self , _a , _a="" , _a=None , **_a ) -> List[Any]: _a : Optional[int] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) _a : Union[str, Any] = prompt_text if handle_long_generation == "hole": _a : List[str] = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _a : int = generate_kwargs['''max_new_tokens'''] else: _a : List[Any] = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _a : List[str] = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _a : List[Any] = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _a : List[str] = inputs['''attention_mask'''][:, -keep_length:] return inputs def __lowercase ( self , _a , **_a ) -> Optional[int]: _a : Any = model_inputs['''input_ids'''] _a : Optional[Any] = model_inputs.get('''attention_mask''' , _a ) # Allow empty prompts if input_ids.shape[1] == 0: _a : int = None _a : int = None _a : List[str] = 1 else: _a : List[Any] = input_ids.shape[0] _a : Union[str, Any] = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _a : int = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _a : Tuple = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _a : int = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _a : Dict = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _a : Optional[Any] = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) _a : int = generated_sequence.shape[0] if self.framework == "pt": _a : Tuple = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _a : List[Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowercase ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> int: _a : Tuple = model_outputs['''generated_sequence'''][0] _a : int = model_outputs['''input_ids'''] _a : Any = model_outputs['''prompt_text'''] _a : Any = generated_sequence.numpy().tolist() _a : Any = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _a : Optional[int] = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _a : str = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _a : Union[str, Any] = 0 else: _a : str = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: _a : str = prompt_text + text[prompt_length:] else: _a : List[str] = text[prompt_length:] _a : Union[str, Any] = {'''generated_text''': all_text} records.append(_a ) return records
15
0
def __UpperCAmelCase ( __a : int ,__a : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __UpperCAmelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 ,0 ) == 1 assert xnor_gate(0 ,1 ) == 0 assert xnor_gate(1 ,0 ) == 0 assert xnor_gate(1 ,1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
369
# Copyright 2021 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 argparse import os from accelerate.test_utils import execute_subprocess_async def __UpperCAmelCase ( __a : Dict=None ) -> str: """simple docstring""" if subparsers is not None: _a : Union[str, Any] = subparsers.add_parser('''test''' ) else: _a : List[str] = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' ,default=__a ,help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) ,) if subparsers is not None: parser.set_defaults(func=__a ) return parser def __UpperCAmelCase ( __a : List[Any] ) -> Union[str, Any]: """simple docstring""" _a : Dict = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: _a : List[Any] = script_name else: _a : Union[str, Any] = F"""--config_file={args.config_file} {script_name}""" _a : str = ['''accelerate-launch'''] + test_args.split() _a : str = execute_subprocess_async(__a ,env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def __UpperCAmelCase ( ) -> List[Any]: """simple docstring""" _a : Optional[int] = test_command_parser() _a : List[Any] = parser.parse_args() test_command(__a ) if __name__ == "__main__": main()
15
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def __UpperCAmelCase ( __a : list ,__a : list ,__a : list ,__a : list ,__a : list ) -> float: """simple docstring""" _a : Optional[Any] = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__a )] ) _a : List[str] = np.array(__a ) _a : List[Any] = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() ,__a ) ) ,x.transpose() ) ,__a ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def __UpperCAmelCase ( __a : list ,__a : list ,__a : list ) -> float: """simple docstring""" _a : int = (1, 2, 1) _a : List[str] = (1, 1, 0, 7) _a : Tuple = SARIMAX( __a ,exog=__a ,order=__a ,seasonal_order=__a ) _a : int = model.fit(disp=__a ,maxiter=600 ,method='''nm''' ) _a : Optional[int] = model_fit.predict(1 ,len(__a ) ,exog=[test_match] ) return result[0] def __UpperCAmelCase ( __a : list ,__a : list ,__a : list ) -> float: """simple docstring""" _a : int = SVR(kernel='''rbf''' ,C=1 ,gamma=0.1 ,epsilon=0.1 ) regressor.fit(__a ,__a ) _a : Union[str, Any] = regressor.predict(__a ) return y_pred[0] def __UpperCAmelCase ( __a : list ) -> float: """simple docstring""" train_user.sort() _a : Tuple = np.percentile(__a ,25 ) _a : List[Any] = np.percentile(__a ,75 ) _a : Optional[Any] = qa - qa _a : str = qa - (iqr * 0.1) return low_lim def __UpperCAmelCase ( __a : list ,__a : float ) -> bool: """simple docstring""" _a : Any = 0 _a : str = 0 for i in list_vote: if i > actual_result: _a : Optional[Any] = not_safe + 1 else: if abs(abs(__a ) - abs(__a ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) a__ = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] a__ = pd.DataFrame( data_input, columns=['''total_user''', '''total_even''', '''days'''] ) a__ = Normalizer().fit_transform(data_input_df.values) # split data a__ = normalize_df[:, 2].tolist() a__ = normalize_df[:, 0].tolist() a__ = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) a__ = normalize_df[:, [1, 2]].tolist() a__ = x[: len(x) - 1] a__ = x[len(x) - 1 :] # for linear regression & sarimax a__ = total_date[: len(total_date) - 1] a__ = total_user[: len(total_user) - 1] a__ = total_match[: len(total_match) - 1] a__ = total_date[len(total_date) - 1 :] a__ = total_user[len(total_user) - 1 :] a__ = total_match[len(total_match) - 1 :] # voting system with forecasting a__ = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data a__ = '''''' if data_safety_checker(res_vote, tst_user) else '''not ''' print('''Today\'s data is {not_str}safe.''')
370
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> Union[str, Any]: _a : Optional[Any] = tempfile.mkdtemp() # fmt: off _a : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _a : Any = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _a : str = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_a , _a ) def __lowercase ( self , **_a ) -> Any: return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self , **_a ) -> str: return ViTImageProcessor.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __lowercase ( self ) -> Any: _a : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] _a : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase ( self ) -> str: _a : List[str] = self.get_tokenizer() _a : Tuple = self.get_image_processor() _a : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) processor.save_pretrained(self.tmpdirname ) _a : Dict = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def __lowercase ( self ) -> Dict: _a : List[str] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _a : Any = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _a : List[Any] = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) _a : Dict = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def __lowercase ( self ) -> Any: _a : Dict = self.get_image_processor() _a : str = self.get_tokenizer() _a : int = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : List[str] = self.prepare_image_inputs() _a : List[Any] = image_processor(_a , return_tensors='''np''' ) _a : Dict = processor(images=_a , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase ( self ) -> List[str]: _a : Union[str, Any] = self.get_image_processor() _a : Dict = self.get_tokenizer() _a : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Tuple = '''lower newer''' _a : int = processor(text=_a ) _a : str = tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase ( self ) -> List[Any]: _a : Any = self.get_image_processor() _a : str = self.get_tokenizer() _a : Tuple = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : List[Any] = '''lower newer''' _a : Union[str, Any] = self.prepare_image_inputs() _a : Any = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_a ): processor() def __lowercase ( self ) -> Optional[int]: _a : Union[str, Any] = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : Any = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _a : int = processor.batch_decode(_a ) _a : int = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def __lowercase ( self ) -> List[Any]: _a : Tuple = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : str = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Optional[int] = '''lower newer''' _a : Dict = self.prepare_image_inputs() _a : Any = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
15
0
def __UpperCAmelCase ( __a : list ) -> float: """simple docstring""" _a : List[Any] = 0 while len(__a ) > 1: _a : Optional[int] = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): _a : Dict = files.index(min(__a ) ) temp += files[min_index] files.pop(__a ) files.append(__a ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
371
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a__ = logging.get_logger(__name__) a__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def __UpperCAmelCase ( __a : List[Any] ,__a : Optional[int] ,__a : Optional[int] ,__a : List[str] ,__a : List[Any] ) -> Union[str, Any]: """simple docstring""" for attribute in key.split('''.''' ): _a : Optional[Any] = getattr(__a ,__a ) if weight_type is not None: _a : Dict = getattr(__a ,__a ).shape else: _a : Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": _a : List[Any] = value elif weight_type == "weight_g": _a : Any = value elif weight_type == "weight_v": _a : Union[str, Any] = value elif weight_type == "bias": _a : Optional[int] = value else: _a : List[Any] = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def __UpperCAmelCase ( __a : Any ,__a : Union[str, Any] ,__a : Union[str, Any] ) -> int: """simple docstring""" _a : Union[str, Any] = [] _a : Union[str, Any] = fairseq_model.state_dict() _a : Union[str, Any] = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _a : int = False if "conv_layers" in name: load_conv_layer( __a ,__a ,__a ,__a ,hf_model.config.feat_extract_norm == '''group''' ,) _a : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): _a : Union[str, Any] = '''hubert.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or (key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0] and not is_finetuned): _a : Any = True if "*" in mapped_key: _a : Optional[int] = name.split(__a )[0].split('''.''' )[-2] _a : Any = mapped_key.replace('''*''' ,__a ) if "weight_g" in name: _a : List[Any] = '''weight_g''' elif "weight_v" in name: _a : List[str] = '''weight_v''' elif "weight" in name: _a : Any = '''weight''' elif "bias" in name: _a : str = '''bias''' else: _a : Any = None set_recursively(__a ,__a ,__a ,__a ,__a ) continue if not is_used: unused_weights.append(__a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def __UpperCAmelCase ( __a : int ,__a : Optional[Any] ,__a : Dict ,__a : List[str] ,__a : Any ) -> Tuple: """simple docstring""" _a : int = full_name.split('''conv_layers.''' )[-1] _a : Any = name.split('''.''' ) _a : List[Any] = int(items[0] ) _a : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _a : Optional[int] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _a : Optional[Any] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _a : int = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _a : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__a ) @torch.no_grad() def __UpperCAmelCase ( __a : Dict ,__a : List[Any] ,__a : List[str]=None ,__a : Optional[int]=None ,__a : int=True ) -> List[Any]: """simple docstring""" if config_path is not None: _a : Tuple = HubertConfig.from_pretrained(__a ) else: _a : Any = HubertConfig() if is_finetuned: if dict_path: _a : Tuple = Dictionary.load(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a : Any = target_dict.pad_index _a : Tuple = target_dict.bos_index _a : Optional[int] = target_dict.eos_index _a : Optional[Any] = len(target_dict.symbols ) _a : Tuple = os.path.join(__a ,'''vocab.json''' ) if not os.path.isdir(__a ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__a ) ) return os.makedirs(__a ,exist_ok=__a ) with open(__a ,'''w''' ,encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices ,__a ) _a : Tuple = WavaVecaCTCTokenizer( __a ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token='''|''' ,do_lower_case=__a ,) _a : Tuple = True if config.feat_extract_norm == '''layer''' else False _a : List[Any] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__a ,return_attention_mask=__a ,) _a : List[Any] = WavaVecaProcessor(feature_extractor=__a ,tokenizer=__a ) processor.save_pretrained(__a ) _a : Tuple = HubertForCTC(__a ) else: _a : Tuple = HubertModel(__a ) if is_finetuned: _a , _a , _a : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: _a , _a , _a : str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _a : Any = model[0].eval() recursively_load_weights(__a ,__a ,__a ) hf_wavavec.save_pretrained(__a ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) a__ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
15
0
def __UpperCAmelCase ( __a : int = 1_000_000 ) -> int: """simple docstring""" _a : List[str] = [i - 1 for i in range(limit + 1 )] for i in range(2 ,limit + 1 ): if phi[i] == i - 1: for j in range(2 * i ,limit + 1 ,__a ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
350
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : List[str] = ["image_processor", "tokenizer"] UpperCAmelCase__ : str = "ViltImageProcessor" UpperCAmelCase__ : Union[str, Any] = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a=None , _a=None , **_a ) -> Any: _a : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) _a : Dict = kwargs.pop('''feature_extractor''' ) _a : Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) _a : int = self.image_processor def __call__( self , _a , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: _a : Tuple = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel_values + pixel_mask _a : str = self.image_processor(_a , return_tensors=_a ) encoding.update(_a ) return encoding def __lowercase ( self , *_a , **_a ) -> Optional[Any]: return self.tokenizer.batch_decode(*_a , **_a ) def __lowercase ( self , *_a , **_a ) -> str: return self.tokenizer.decode(*_a , **_a ) @property def __lowercase ( self ) -> Optional[int]: _a : str = self.tokenizer.model_input_names _a : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowercase ( self ) -> Optional[Any]: warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __lowercase ( self ) -> Any: warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
15
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = LDMTextToImagePipeline UpperCAmelCase__ : List[Any] = TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } UpperCAmelCase__ : int = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } UpperCAmelCase__ : Dict = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase__ : str = False def __lowercase ( self ) -> Optional[Any]: torch.manual_seed(0 ) _a : List[str] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) _a : Tuple = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=_a , set_alpha_to_one=_a , ) torch.manual_seed(0 ) _a : Tuple = AutoencoderKL( block_out_channels=(3_2, 6_4) , in_channels=3 , out_channels=3 , down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''') , up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''') , latent_channels=4 , ) torch.manual_seed(0 ) _a : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) _a : int = CLIPTextModel(_a ) _a : int = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _a : List[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vqvae''': vae, '''bert''': text_encoder, '''tokenizer''': tokenizer, } return components def __lowercase ( self , _a , _a=0 ) -> List[Any]: if str(_a ).startswith('''mps''' ): _a : Any = torch.manual_seed(_a ) else: _a : Tuple = torch.Generator(device=_a ).manual_seed(_a ) _a : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowercase ( self ) -> int: _a : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator _a : Tuple = self.get_dummy_components() _a : str = LDMTextToImagePipeline(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : Optional[Any] = self.get_dummy_inputs(_a ) _a : Optional[Any] = pipe(**_a ).images _a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_6, 1_6, 3) _a : List[Any] = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self , _a , _a=torch.floataa , _a=0 ) -> List[Any]: _a : List[str] = torch.manual_seed(_a ) _a : Dict = np.random.RandomState(_a ).standard_normal((1, 4, 3_2, 3_2) ) _a : List[Any] = torch.from_numpy(_a ).to(device=_a , dtype=_a ) _a : Optional[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowercase ( self ) -> Optional[Any]: _a : Any = LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : List[str] = self.get_inputs(_a ) _a : Optional[Any] = pipe(**_a ).images _a : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 2_5_6, 2_5_6, 3) _a : Union[str, Any] = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) _a : int = np.abs(expected_slice - image_slice ).max() assert max_diff < 1e-3 @nightly @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self , _a , _a=torch.floataa , _a=0 ) -> Dict: _a : Optional[int] = torch.manual_seed(_a ) _a : List[str] = np.random.RandomState(_a ).standard_normal((1, 4, 3_2, 3_2) ) _a : List[Any] = torch.from_numpy(_a ).to(device=_a , dtype=_a ) _a : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 5_0, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowercase ( self ) -> List[str]: _a : str = LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : int = self.get_inputs(_a ) _a : Tuple = pipe(**_a ).images[0] _a : List[str] = load_numpy( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy''' ) _a : Optional[int] = np.abs(expected_image - image ).max() assert max_diff < 1e-3
351
from math import ceil def __UpperCAmelCase ( __a : int = 1_001 ) -> int: """simple docstring""" _a : Dict = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): _a : int = 2 * i + 1 _a : str = 2 * i _a : Any = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: a__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
15
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a__ = logging.get_logger(__name__) a__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} a__ = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', } } a__ = { '''camembert-base''': 512, } a__ = '''▁''' class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : str = VOCAB_FILES_NAMES UpperCAmelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=["<s>NOTUSED", "</s>NOTUSED"] , _a = None , **_a , ) -> None: # Mask token behave like a normal word, i.e. include the space before it _a : str = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token _a : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) _a : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) _a : str = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> _a : Tuple = {'''<s>NOTUSED''': 0, '''<pad>''': 1, '''</s>NOTUSED''': 2, '''<unk>''': 3} _a : Union[str, Any] = len(self.fairseq_tokens_to_ids ) _a : str = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _a : List[str] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __lowercase ( self , _a , _a = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _a : Dict = [self.cls_token_id] _a : Optional[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __lowercase ( self , _a , _a = None , _a = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __lowercase ( self , _a , _a = None ) -> List[int]: _a : Any = [self.sep_token_id] _a : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def __lowercase ( self ) -> Dict: return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def __lowercase ( self ) -> List[Any]: _a : List[Any] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowercase ( self , _a ) -> List[str]: return self.sp_model.encode(_a , out_type=_a ) def __lowercase ( self , _a ) -> List[Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_a ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_a ) def __lowercase ( self , _a ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowercase ( self , _a ) -> Tuple: _a : Dict = [] _a : int = '''''' _a : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token _a : Optional[int] = True _a : Any = [] else: current_sub_tokens.append(_a ) _a : str = False out_string += self.sp_model.decode(_a ) return out_string.strip() def __getstate__( self ) -> Union[str, Any]: _a : Optional[Any] = self.__dict__.copy() _a : int = None return state def __setstate__( self , _a ) -> Optional[int]: _a : List[str] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _a : List[str] = {} _a : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowercase ( self , _a , _a = None ) -> Tuple[str]: if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : int = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , '''wb''' ) as fi: _a : Tuple = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
352
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract a__ = logging.get_logger(__name__) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : str ,__a : Union[str, Any] ) -> List[str]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def __UpperCAmelCase ( __a : np.ndarray ,__a : Optional[str] ,__a : Optional[str] ) -> List[Any]: """simple docstring""" _a : str = to_pil_image(__a ) _a , _a : Optional[Any] = pil_image.size _a : Tuple = pytesseract.image_to_data(__a ,lang=__a ,output_type='''dict''' ,config=__a ) _a , _a , _a , _a , _a : List[str] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates _a : Dict = [idx for idx, word in enumerate(__a ) if not word.strip()] _a : str = [word for idx, word in enumerate(__a ) if idx not in irrelevant_indices] _a : List[str] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : Union[str, Any] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : str = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : Union[str, Any] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : int = [] for x, y, w, h in zip(__a ,__a ,__a ,__a ): _a : List[str] = [x, y, x + w, y + h] actual_boxes.append(__a ) # finally, normalize the bounding boxes _a : Dict = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__a ,__a ,__a ) ) assert len(__a ) == len(__a ), "Not as many words as there are bounding boxes" return words, normalized_boxes class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = ["pixel_values"] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = 1 / 2_5_5 , _a = True , _a = None , _a = None , _a = True , _a = None , _a = "" , **_a , ) -> None: super().__init__(**_a ) _a : List[str] = size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} _a : Union[str, Any] = get_size_dict(_a ) _a : int = do_resize _a : Optional[int] = size _a : str = resample _a : str = do_rescale _a : Any = rescale_value _a : Optional[Any] = do_normalize _a : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _a : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD _a : List[Any] = apply_ocr _a : Optional[int] = ocr_lang _a : Tuple = tesseract_config def __lowercase ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ) -> np.ndarray: _a : Any = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) _a : Optional[int] = (size['''height'''], size['''width''']) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def __lowercase ( self , _a , _a , _a = None , **_a , ) -> np.ndarray: return rescale(_a , scale=_a , data_format=_a , **_a ) def __lowercase ( self , _a , _a , _a , _a = None , **_a , ) -> np.ndarray: return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def __lowercase ( self , _a , _a = None , _a = None , _a=None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> PIL.Image.Image: _a : Optional[int] = do_resize if do_resize is not None else self.do_resize _a : Union[str, Any] = size if size is not None else self.size _a : Any = get_size_dict(_a ) _a : List[str] = resample if resample is not None else self.resample _a : int = do_rescale if do_rescale is not None else self.do_rescale _a : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _a : int = do_normalize if do_normalize is not None else self.do_normalize _a : str = image_mean if image_mean is not None else self.image_mean _a : Tuple = image_std if image_std is not None else self.image_std _a : Any = apply_ocr if apply_ocr is not None else self.apply_ocr _a : int = ocr_lang if ocr_lang is not None else self.ocr_lang _a : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[Any] = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.''' ) # All transformations expect numpy arrays. _a : Any = [to_numpy_array(_a ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , '''pytesseract''' ) _a : str = [] _a : str = [] for image in images: _a , _a : Union[str, Any] = apply_tesseract(_a , _a , _a ) words_batch.append(_a ) boxes_batch.append(_a ) if do_resize: _a : List[str] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_rescale: _a : Optional[Any] = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: _a : List[Any] = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] _a : List[str] = [to_channel_dimension_format(_a , _a ) for image in images] _a : List[str] = BatchFeature(data={'''pixel_values''': images} , tensor_type=_a ) if apply_ocr: _a : Optional[int] = words_batch _a : List[Any] = boxes_batch return data
15
0
"""simple docstring""" # Copyright 2021 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. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def __UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" _a : int = ArgumentParser('''Accelerate CLI tool''' ,usage='''accelerate <command> [<args>]''' ,allow_abbrev=__a ) _a : Optional[int] = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=__a ) env_command_parser(subparsers=__a ) launch_command_parser(subparsers=__a ) tpu_command_parser(subparsers=__a ) test_command_parser(subparsers=__a ) # Let's go _a : Dict = parser.parse_args() if not hasattr(__a ,'''func''' ): parser.print_help() exit(1 ) # Run args.func(__a ) if __name__ == "__main__": main()
353
# Copyright 2021 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. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def __UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" _a : int = ArgumentParser('''Accelerate CLI tool''' ,usage='''accelerate <command> [<args>]''' ,allow_abbrev=__a ) _a : Optional[int] = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=__a ) env_command_parser(subparsers=__a ) launch_command_parser(subparsers=__a ) tpu_command_parser(subparsers=__a ) test_command_parser(subparsers=__a ) # Let's go _a : Dict = parser.parse_args() if not hasattr(__a ,'''func''' ): parser.print_help() exit(1 ) # Run args.func(__a ) if __name__ == "__main__": main()
15
0
"""simple docstring""" import math def __UpperCAmelCase ( __a : float ,__a : float ) -> float: """simple docstring""" if ( not isinstance(__a ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * power_factor def __UpperCAmelCase ( __a : float ,__a : float ) -> float: """simple docstring""" if ( not isinstance(__a ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
354
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset a__ = random.Random() def __UpperCAmelCase ( __a : Tuple ,__a : str=1.0 ,__a : Optional[int]=None ,__a : List[Any]=None ) -> Any: """simple docstring""" if rng is None: _a : Dict = global_rng _a : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _a , _a=7 , _a=4_0_0 , _a=2_0_0_0 , _a=2_0_4_8 , _a=1_2_8 , _a=1 , _a=5_1_2 , _a=3_0 , _a=4_4_1_0_0 , ) -> List[Any]: _a : Optional[Any] = parent _a : str = batch_size _a : List[str] = min_seq_length _a : str = max_seq_length _a : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : List[Any] = spectrogram_length _a : List[str] = feature_size _a : List[Any] = num_audio_channels _a : Tuple = hop_length _a : Optional[int] = chunk_length _a : int = sampling_rate def __lowercase ( self ) -> Union[str, Any]: return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __lowercase ( self , _a=False , _a=False ) -> List[Any]: def _flatten(_a ): return list(itertools.chain(*_a ) ) if equal_length: _a : List[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _a : List[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : str = [np.asarray(_a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = TvltFeatureExtractor def __lowercase ( self ) -> Dict: _a : List[str] = TvltFeatureExtractionTester(self ) def __lowercase ( self ) -> Any: _a : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a , '''spectrogram_length''' ) ) self.assertTrue(hasattr(_a , '''feature_size''' ) ) self.assertTrue(hasattr(_a , '''num_audio_channels''' ) ) self.assertTrue(hasattr(_a , '''hop_length''' ) ) self.assertTrue(hasattr(_a , '''chunk_length''' ) ) self.assertTrue(hasattr(_a , '''sampling_rate''' ) ) def __lowercase ( self ) -> Optional[int]: _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : int = feat_extract_first.save_pretrained(_a )[0] check_json_file_has_correct_format(_a ) _a : Dict = self.feature_extraction_class.from_pretrained(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Union[str, Any] = feat_extract_second.to_dict() _a : Any = dict_first.pop('''mel_filters''' ) _a : int = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Optional[int]: _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Optional[int] = os.path.join(_a , '''feat_extract.json''' ) feat_extract_first.to_json_file(_a ) _a : List[str] = self.feature_extraction_class.from_json_file(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Dict = feat_extract_second.to_dict() _a : str = dict_first.pop('''mel_filters''' ) _a : str = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Union[str, Any]: # Initialize feature_extractor _a : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 _a : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _a : List[str] = [np.asarray(_a ) for speech_input in speech_inputs] # Test not batched input _a : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched _a : Dict = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking _a : Union[str, Any] = feature_extractor( _a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 , mask_audio=_a ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. _a : Optional[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _a : int = np.asarray(_a ) _a : Tuple = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __lowercase ( self , _a ) -> Optional[Any]: _a : List[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech _a : Optional[int] = ds.sort('''id''' ).select(range(_a ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __lowercase ( self ) -> int: _a : Union[str, Any] = self._load_datasamples(1 ) _a : int = TvltFeatureExtractor() _a : Union[str, Any] = feature_extractor(_a , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_9_2, 1_2_8) ) _a : Union[str, Any] = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , _a , atol=1e-4 ) )
15
0
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a__ = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def __UpperCAmelCase ( __a : Optional[int] ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def __UpperCAmelCase ( __a : Optional[int] ) -> str: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main _a : Union[str, Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a ,id=__a )
355
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch a__ = logging.get_logger(__name__) @add_end_docstrings( __lowercase , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self , _a ) -> np.ndarray: if self.framework == "tf": _a : List[str] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": _a : Tuple = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a ) else: raise ValueError('''Unsupported framework''' ) return masked_index def __lowercase ( self , _a ) -> np.ndarray: _a : int = self.get_masked_index(_a ) _a : Tuple = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( '''fill-mask''' , self.model.base_model_prefix , F"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , ) def __lowercase ( self , _a ) -> Optional[int]: if isinstance(_a , _a ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_a ) def __lowercase ( self , _a , _a=None , **_a ) -> Dict[str, GenericTensor]: if return_tensors is None: _a : Union[str, Any] = self.framework _a : str = self.tokenizer(_a , return_tensors=_a ) self.ensure_exactly_one_mask_token(_a ) return model_inputs def __lowercase ( self , _a ) -> Optional[Any]: _a : List[str] = self.model(**_a ) _a : Any = model_inputs['''input_ids'''] return model_outputs def __lowercase ( self , _a , _a=5 , _a=None ) -> str: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: _a : List[Any] = target_ids.shape[0] _a : Any = model_outputs['''input_ids'''][0] _a : List[str] = model_outputs['''logits'''] if self.framework == "tf": _a : Tuple = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] _a : List[str] = outputs.numpy() _a : Dict = outputs[0, masked_index, :] _a : str = stable_softmax(_a , axis=-1 ) if target_ids is not None: _a : Any = tf.gather_nd(tf.squeeze(_a , 0 ) , target_ids.reshape(-1 , 1 ) ) _a : Union[str, Any] = tf.expand_dims(_a , 0 ) _a : Optional[int] = tf.math.top_k(_a , k=_a ) _a , _a : Optional[Any] = topk.values.numpy(), topk.indices.numpy() else: _a : Optional[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample _a : List[str] = outputs[0, masked_index, :] _a : List[Any] = logits.softmax(dim=-1 ) if target_ids is not None: _a : List[Any] = probs[..., target_ids] _a , _a : Optional[Any] = probs.topk(_a ) _a : Dict = [] _a : List[Any] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): _a : Optional[Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place _a : Optional[int] = input_ids.numpy().copy() if target_ids is not None: _a : Tuple = target_ids[p].tolist() _a : List[str] = p # Filter padding out: _a : List[Any] = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back _a : List[str] = self.tokenizer.decode(_a , skip_special_tokens=_a ) _a : List[Any] = {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p] ), '''sequence''': sequence} row.append(_a ) result.append(_a ) if single_mask: return result[0] return result def __lowercase ( self , _a , _a=None ) -> Dict: if isinstance(_a , _a ): _a : Tuple = [targets] try: _a : int = self.tokenizer.get_vocab() except Exception: _a : Any = {} _a : List[Any] = [] for target in targets: _a : List[Any] = vocab.get(_a , _a ) if id_ is None: _a : Tuple = self.tokenizer( _a , add_special_tokens=_a , return_attention_mask=_a , return_token_type_ids=_a , max_length=1 , truncation=_a , )['''input_ids'''] if len(_a ) == 0: logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ '''We cannot replace it with anything meaningful, ignoring it''' ) continue _a : Tuple = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" ) target_ids.append(id_ ) _a : List[str] = list(set(_a ) ) if len(_a ) == 0: raise ValueError('''At least one target must be provided when passed.''' ) _a : int = np.array(_a ) return target_ids def __lowercase ( self , _a=None , _a=None ) -> Tuple: _a : str = {} if targets is not None: _a : List[Any] = self.get_target_ids(_a , _a ) _a : Optional[Any] = target_ids if top_k is not None: _a : Union[str, Any] = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( '''fill-mask''' , self.model.base_model_prefix , '''The tokenizer does not define a `mask_token`.''' ) return {}, {}, postprocess_params def __call__( self , _a , *_a , **_a ) -> int: _a : Optional[Any] = super().__call__(_a , **_a ) if isinstance(_a , _a ) and len(_a ) == 1: return outputs[0] return outputs
15
0
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset a__ = random.Random() def __UpperCAmelCase ( __a : Tuple ,__a : str=1.0 ,__a : Optional[int]=None ,__a : List[Any]=None ) -> Any: """simple docstring""" if rng is None: _a : Dict = global_rng _a : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _a , _a=7 , _a=4_0_0 , _a=2_0_0_0 , _a=2_0_4_8 , _a=1_2_8 , _a=1 , _a=5_1_2 , _a=3_0 , _a=4_4_1_0_0 , ) -> List[Any]: _a : Optional[Any] = parent _a : str = batch_size _a : List[str] = min_seq_length _a : str = max_seq_length _a : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : List[Any] = spectrogram_length _a : List[str] = feature_size _a : List[Any] = num_audio_channels _a : Tuple = hop_length _a : Optional[int] = chunk_length _a : int = sampling_rate def __lowercase ( self ) -> Union[str, Any]: return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __lowercase ( self , _a=False , _a=False ) -> List[Any]: def _flatten(_a ): return list(itertools.chain(*_a ) ) if equal_length: _a : List[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _a : List[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : str = [np.asarray(_a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = TvltFeatureExtractor def __lowercase ( self ) -> Dict: _a : List[str] = TvltFeatureExtractionTester(self ) def __lowercase ( self ) -> Any: _a : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_a , '''spectrogram_length''' ) ) self.assertTrue(hasattr(_a , '''feature_size''' ) ) self.assertTrue(hasattr(_a , '''num_audio_channels''' ) ) self.assertTrue(hasattr(_a , '''hop_length''' ) ) self.assertTrue(hasattr(_a , '''chunk_length''' ) ) self.assertTrue(hasattr(_a , '''sampling_rate''' ) ) def __lowercase ( self ) -> Optional[int]: _a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : int = feat_extract_first.save_pretrained(_a )[0] check_json_file_has_correct_format(_a ) _a : Dict = self.feature_extraction_class.from_pretrained(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Union[str, Any] = feat_extract_second.to_dict() _a : Any = dict_first.pop('''mel_filters''' ) _a : int = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Optional[int]: _a : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Optional[int] = os.path.join(_a , '''feat_extract.json''' ) feat_extract_first.to_json_file(_a ) _a : List[str] = self.feature_extraction_class.from_json_file(_a ) _a : List[Any] = feat_extract_first.to_dict() _a : Dict = feat_extract_second.to_dict() _a : str = dict_first.pop('''mel_filters''' ) _a : str = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(_a , _a ) ) self.assertEqual(_a , _a ) def __lowercase ( self ) -> Union[str, Any]: # Initialize feature_extractor _a : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 _a : Any = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _a : List[str] = [np.asarray(_a ) for speech_input in speech_inputs] # Test not batched input _a : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched _a : Dict = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking _a : Union[str, Any] = feature_extractor( _a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 , mask_audio=_a ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. _a : Optional[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _a : int = np.asarray(_a ) _a : Tuple = feature_extractor(_a , return_tensors='''np''' , sampling_rate=4_4_1_0_0 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __lowercase ( self , _a ) -> Optional[Any]: _a : List[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech _a : Optional[int] = ds.sort('''id''' ).select(range(_a ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __lowercase ( self ) -> int: _a : Union[str, Any] = self._load_datasamples(1 ) _a : int = TvltFeatureExtractor() _a : Union[str, Any] = feature_extractor(_a , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_9_2, 1_2_8) ) _a : Union[str, Any] = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , _a , atol=1e-4 ) )
356
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow a__ = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ '''text-classification''', '''language-modeling''', '''summarization''', '''token-classification''', '''question-answering''', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) a__ = logging.getLogger() def __UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" _a : Any = argparse.ArgumentParser() parser.add_argument('''-f''' ) _a : Dict = parser.parse_args() return args.f def __UpperCAmelCase ( __a : Optional[int] ,__a : List[str]="eval" ) -> Any: """simple docstring""" _a : Any = os.path.join(__a ,F"""{split}_results.json""" ) if os.path.exists(__a ): with open(__a ,'''r''' ) as f: return json.load(__a ) raise ValueError(F"""can't find {path}""" ) a__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> str: _a : Any = self.get_auto_remove_tmp_dir() _a : Optional[Any] = F""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(_a , '''argv''' , _a ): run_flax_glue.main() _a : Any = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __lowercase ( self ) -> Dict: _a : Tuple = self.get_auto_remove_tmp_dir() _a : Tuple = F""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(_a , '''argv''' , _a ): run_clm_flax.main() _a : List[str] = get_results(_a ) self.assertLess(result['''eval_perplexity'''] , 1_0_0 ) @slow def __lowercase ( self ) -> Optional[int]: _a : str = self.get_auto_remove_tmp_dir() _a : Optional[int] = F""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(_a , '''argv''' , _a ): run_summarization_flax.main() _a : Optional[int] = get_results(_a , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 1_0 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __lowercase ( self ) -> Tuple: _a : List[str] = self.get_auto_remove_tmp_dir() _a : List[Any] = F""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(_a , '''argv''' , _a ): run_mlm_flax.main() _a : List[Any] = get_results(_a ) self.assertLess(result['''eval_perplexity'''] , 4_2 ) @slow def __lowercase ( self ) -> Dict: _a : Optional[Any] = self.get_auto_remove_tmp_dir() _a : int = F""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(_a , '''argv''' , _a ): run_ta_mlm_flax.main() _a : List[Any] = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __lowercase ( self ) -> Optional[Any]: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu _a : Any = 7 if get_gpu_count() > 1 else 2 _a : List[Any] = self.get_auto_remove_tmp_dir() _a : List[Any] = F""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(_a , '''argv''' , _a ): run_flax_ner.main() _a : Dict = get_results(_a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __lowercase ( self ) -> Any: _a : Optional[int] = self.get_auto_remove_tmp_dir() _a : Union[str, Any] = F""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(_a , '''argv''' , _a ): run_qa.main() _a : Any = get_results(_a ) self.assertGreaterEqual(result['''eval_f1'''] , 3_0 ) self.assertGreaterEqual(result['''eval_exact'''] , 3_0 )
15
0
import argparse import math import traceback import dateutil.parser as date_parser import requests def __UpperCAmelCase ( __a : str ) -> Any: """simple docstring""" _a : Tuple = {} _a : Tuple = job['''started_at'''] _a : List[str] = job['''completed_at'''] _a : int = date_parser.parse(__a ) _a : Tuple = date_parser.parse(__a ) _a : int = round((end_datetime - start_datetime).total_seconds() / 60.0 ) _a : List[str] = start _a : Optional[int] = end _a : Any = duration_in_min return job_info def __UpperCAmelCase ( __a : Tuple ,__a : List[Any]=None ) -> Any: """simple docstring""" _a : List[str] = None if token is not None: _a : List[str] = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': F"""Bearer {token}"""} _a : Tuple = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" _a : List[Any] = requests.get(__a ,headers=__a ).json() _a : Tuple = {} try: job_time.update({job['''name''']: extract_time_from_single_job(__a ) for job in result['''jobs''']} ) _a : List[str] = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(__a ): _a : Union[str, Any] = requests.get(url + F"""&page={i + 2}""" ,headers=__a ).json() job_time.update({job['''name''']: extract_time_from_single_job(__a ) for job in result['''jobs''']} ) return job_time except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} if __name__ == "__main__": a__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') a__ = parser.parse_args() a__ = get_job_time(args.workflow_run_id) a__ = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
357
import argparse import os import re import packaging.version a__ = '''examples/''' a__ = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } a__ = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } a__ = '''README.md''' def __UpperCAmelCase ( __a : List[str] ,__a : int ,__a : Optional[Any] ) -> int: """simple docstring""" with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Tuple = f.read() _a , _a : str = REPLACE_PATTERNS[pattern] _a : List[str] = replace.replace('''VERSION''' ,__a ) _a : List[Any] = re_pattern.sub(__a ,__a ) with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.write(__a ) def __UpperCAmelCase ( __a : Any ) -> List[Any]: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a ,__a ) ,__a ,pattern='''examples''' ) def __UpperCAmelCase ( __a : List[Any] ,__a : List[str]=False ) -> int: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a ,__a ,__a ) if not patch: update_version_in_examples(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" _a : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' _a : str = '''1. Want to contribute a new model?''' with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Optional[int] = f.readlines() # Find the start of the list. _a : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _a : List[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): _a : Tuple = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' ,'''https://huggingface.co/docs/transformers/model_doc''' ,) index += 1 with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.writelines(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] ,'''r''' ) as f: _a : Optional[Any] = f.read() _a : Optional[Any] = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def __UpperCAmelCase ( __a : Dict=False ) -> str: """simple docstring""" _a : Optional[Any] = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: _a : List[Any] = default_version.base_version elif patch: _a : str = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _a : List[str] = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _a : Dict = input(F"""Which version are you releasing? [{default_version}]""" ) if len(__a ) == 0: _a : int = default_version print(F"""Updating version to {version}.""" ) global_version_update(__a ,patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def __UpperCAmelCase ( ) -> Tuple: """simple docstring""" _a : str = get_version() _a : int = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _a : List[Any] = current_version.base_version # Check with the user we got that right. _a : Union[str, Any] = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(__a ) == 0: _a : List[str] = dev_version print(F"""Updating version to {version}.""" ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') a__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
15
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ = { '''configuration_vision_text_dual_encoder''': ['''VisionTextDualEncoderConfig'''], '''processing_vision_text_dual_encoder''': ['''VisionTextDualEncoderProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''VisionTextDualEncoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''FlaxVisionTextDualEncoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''TFVisionTextDualEncoderModel'''] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
358
def __UpperCAmelCase ( __a : int ) -> int: """simple docstring""" if n == 1 or not isinstance(__a ,__a ): return 0 elif n == 2: return 1 else: _a : Any = [0, 1] for i in range(2 ,n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def __UpperCAmelCase ( __a : int ) -> int: """simple docstring""" _a : Any = 0 _a : Dict = 2 while digits < n: index += 1 _a : Dict = len(str(fibonacci(__a ) ) ) return index def __UpperCAmelCase ( __a : int = 1_000 ) -> int: """simple docstring""" return fibonacci_digits_index(__a ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
15
0
def __UpperCAmelCase ( __a : int ,__a : float ,__a : float ) -> float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def __UpperCAmelCase ( __a : float ,__a : float ,__a : float ) -> float: """simple docstring""" return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __UpperCAmelCase ( __a : float ,__a : float ,__a : float ) -> float: """simple docstring""" return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __UpperCAmelCase ( __a : float ,__a : float ,__a : float ) -> float: """simple docstring""" return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
359
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record a__ = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' a__ = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' a__ = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def __UpperCAmelCase ( __a : int ,__a : List[str] ) -> Optional[Any]: """simple docstring""" return float((preds == labels).mean() ) def __UpperCAmelCase ( __a : List[Any] ,__a : Union[str, Any] ,__a : List[str]="binary" ) -> Optional[int]: """simple docstring""" _a : List[str] = simple_accuracy(__a ,__a ) _a : Any = float(fa_score(y_true=__a ,y_pred=__a ,average=__a ) ) return { "accuracy": acc, "f1": fa, } def __UpperCAmelCase ( __a : Optional[Any] ,__a : str ) -> List[Any]: """simple docstring""" _a : Union[str, Any] = {} for id_pred, label in zip(__a ,__a ): _a : Optional[int] = F"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" _a : Optional[Any] = id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: _a : str = [(pred, label)] _a , _a : Any = [], [] for question, preds_labels in question_map.items(): _a , _a : Any = zip(*__a ) _a : List[Any] = fa_score(y_true=__a ,y_pred=__a ,average='''macro''' ) fas.append(__a ) _a : List[str] = int(sum(pred == label for pred, label in preds_labels ) == len(__a ) ) ems.append(__a ) _a : List[str] = float(sum(__a ) / len(__a ) ) _a : str = sum(__a ) / len(__a ) _a : Optional[int] = float(fa_score(y_true=__a ,y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> List[Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def __lowercase ( self ) -> Any: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def __lowercase ( self , _a , _a ) -> Optional[Any]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_a , _a )} elif self.config_name == "cb": return acc_and_fa(_a , _a , fa_avg='''macro''' ) elif self.config_name == "record": _a : Any = [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] _a : Any = {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(_a , _a )[0] elif self.config_name == "multirc": return evaluate_multirc(_a , _a ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
15
0
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = MobileBertTokenizer UpperCAmelCase__ : List[Any] = MobileBertTokenizerFast UpperCAmelCase__ : Optional[int] = True UpperCAmelCase__ : List[Any] = True UpperCAmelCase__ : Dict = filter_non_english UpperCAmelCase__ : List[Any] = "google/mobilebert-uncased" def __lowercase ( self ) -> Any: """simple docstring""" super().setUp() _a : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] _a : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _a : Optional[Any] = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def __lowercase ( self , _a ) -> Any: """simple docstring""" _a : Any = '''UNwant\u00E9d,running''' _a : str = '''unwanted, running''' return input_text, output_text def __lowercase ( self ) -> Tuple: """simple docstring""" _a : Union[str, Any] = self.tokenizer_class(self.vocab_file ) _a : str = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_a , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def __lowercase ( self ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return _a : int = self.get_tokenizer() _a : Optional[int] = self.get_rust_tokenizer() _a : Any = '''UNwant\u00E9d,running''' _a : List[str] = tokenizer.tokenize(_a ) _a : str = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _a : Tuple = tokenizer.encode(_a , add_special_tokens=_a ) _a : Optional[int] = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _a : List[str] = self.get_rust_tokenizer() _a : Optional[int] = tokenizer.encode(_a ) _a : Any = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) # With lower casing _a : Dict = self.get_tokenizer(do_lower_case=_a ) _a : Tuple = self.get_rust_tokenizer(do_lower_case=_a ) _a : str = '''UNwant\u00E9d,running''' _a : Any = tokenizer.tokenize(_a ) _a : str = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _a : Optional[int] = tokenizer.encode(_a , add_special_tokens=_a ) _a : Tuple = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _a : Optional[Any] = self.get_rust_tokenizer() _a : Optional[Any] = tokenizer.encode(_a ) _a : List[str] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def __lowercase ( self ) -> int: """simple docstring""" _a : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowercase ( self ) -> Dict: """simple docstring""" _a : str = BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowercase ( self ) -> Optional[Any]: """simple docstring""" _a : Any = BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowercase ( self ) -> Optional[int]: """simple docstring""" _a : List[Any] = BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowercase ( self ) -> str: """simple docstring""" _a : str = BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowercase ( self ) -> Optional[int]: """simple docstring""" _a : Dict = BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowercase ( self ) -> Optional[Any]: """simple docstring""" _a : Optional[int] = BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowercase ( self ) -> Union[str, Any]: """simple docstring""" _a : int = BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowercase ( self ) -> Any: """simple docstring""" _a : Optional[Any] = BasicTokenizer(do_lower_case=_a , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowercase ( self ) -> int: """simple docstring""" _a : Dict = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] _a : List[str] = {} for i, token in enumerate(_a ): _a : str = i _a : Tuple = WordpieceTokenizer(vocab=_a , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def __lowercase ( self ) -> Optional[Any]: """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def __lowercase ( self ) -> Optional[Any]: """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def __lowercase ( self ) -> int: """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def __lowercase ( self ) -> List[Any]: """simple docstring""" _a : int = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_a ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(_a ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def __lowercase ( self ) -> Dict: """simple docstring""" _a : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) _a : Dict = tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) _a : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) _a : Any = tokenizer.build_inputs_with_special_tokens(_a ) _a : int = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def __lowercase ( self ) -> int: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _a : int = self.rust_tokenizer_class.from_pretrained(_a , **_a ) _a : Any = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" _a : Tuple = tokenizer_r.encode_plus( _a , return_attention_mask=_a , return_token_type_ids=_a , return_offsets_mapping=_a , add_special_tokens=_a , ) _a : Union[str, Any] = tokenizer_r.do_lower_case if hasattr(_a , '''do_lower_case''' ) else False _a : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''Allen'''), ((2_1, 2_3), '''##NL'''), ((2_3, 2_4), '''##P'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), '''allen'''), ((2_1, 2_3), '''##nl'''), ((2_3, 2_4), '''##p'''), ((2_5, 3_3), '''sentence'''), ((3_3, 3_4), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def __lowercase ( self ) -> Optional[Any]: """simple docstring""" _a : Union[str, Any] = ['''的''', '''人''', '''有'''] _a : Optional[int] = ''''''.join(_a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _a : int = True _a : Union[str, Any] = self.tokenizer_class.from_pretrained(_a , **_a ) _a : Dict = self.rust_tokenizer_class.from_pretrained(_a , **_a ) _a : Any = tokenizer_p.encode(_a , add_special_tokens=_a ) _a : List[str] = tokenizer_r.encode(_a , add_special_tokens=_a ) _a : Optional[Any] = tokenizer_r.convert_ids_to_tokens(_a ) _a : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(_a ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_a , _a ) self.assertListEqual(_a , _a ) _a : int = False _a : int = self.rust_tokenizer_class.from_pretrained(_a , **_a ) _a : Dict = self.tokenizer_class.from_pretrained(_a , **_a ) _a : Optional[int] = tokenizer_r.encode(_a , add_special_tokens=_a ) _a : Union[str, Any] = tokenizer_p.encode(_a , add_special_tokens=_a ) _a : Optional[Any] = tokenizer_r.convert_ids_to_tokens(_a ) _a : Any = tokenizer_p.convert_ids_to_tokens(_a ) # it is expected that only the first Chinese character is not preceded by "##". _a : Optional[int] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(_a ) ] self.assertListEqual(_a , _a ) self.assertListEqual(_a , _a )
360
import numpy as np def __UpperCAmelCase ( __a : np.ndarray ,__a : np.ndarray ,__a : float = 1E-12 ,__a : int = 100 ,) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(__a )[0] == np.shape(__a )[1] # Ensure proper dimensionality. assert np.shape(__a )[0] == np.shape(__a )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(__a ) == np.iscomplexobj(__a ) _a : List[str] = np.iscomplexobj(__a ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(__a ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _a : List[str] = False _a : List[str] = 0 _a : Tuple = 0 _a : str = 1E12 while not convergence: # Multiple matrix by the vector. _a : str = np.dot(__a ,__a ) # Normalize the resulting output vector. _a : List[Any] = w / np.linalg.norm(__a ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _a : Dict = vector.conj().T if is_complex else vector.T _a : Tuple = np.dot(__a ,np.dot(__a ,__a ) ) # Check convergence. _a : List[str] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _a : Dict = True _a : str = lambda_ if is_complex: _a : Tuple = np.real(lambda_ ) return lambda_, vector def __UpperCAmelCase ( ) -> None: """simple docstring""" _a : List[str] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) _a : int = np.array([41, 4, 20] ) _a : Optional[Any] = real_input_matrix.astype(np.complexaaa ) _a : int = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _a : Union[str, Any] = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _a : Optional[int] = real_input_matrix _a : Union[str, Any] = real_vector elif problem_type == "complex": _a : str = complex_input_matrix _a : str = complex_vector # Our implementation. _a , _a : Optional[Any] = power_iteration(__a ,__a ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _a , _a : List[str] = np.linalg.eigh(__a ) # Last eigenvalue is the maximum one. _a : Tuple = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _a : List[Any] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(__a ) - np.abs(__a ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase_ ( datasets.BuilderConfig ): """simple docstring""" UpperCAmelCase__ : Optional[datasets.Features] = None class UpperCAmelCase_ ( datasets.ArrowBasedBuilder ): """simple docstring""" UpperCAmelCase__ : Any = PandasConfig def __lowercase ( self ) -> Any: return datasets.DatasetInfo(features=self.config.features ) def __lowercase ( self , _a ) -> List[Any]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _a : str = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): _a : Dict = data_files if isinstance(_a , _a ): _a : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : int = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _a : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): _a : List[str] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : Any = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={'''files''': files} ) ) return splits def __lowercase ( self , _a ) -> pa.Table: if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _a : Optional[Any] = table_cast(_a , self.config.features.arrow_schema ) return pa_table def __lowercase ( self , _a ) -> List[str]: for i, file in enumerate(itertools.chain.from_iterable(_a ) ): with open(_a , '''rb''' ) as f: _a : str = pa.Table.from_pandas(pd.read_pickle(_a ) ) yield i, self._cast_table(_a )
361
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase_ ( datasets.BuilderConfig ): """simple docstring""" UpperCAmelCase__ : Optional[datasets.Features] = None class UpperCAmelCase_ ( datasets.ArrowBasedBuilder ): """simple docstring""" UpperCAmelCase__ : Any = PandasConfig def __lowercase ( self ) -> Any: return datasets.DatasetInfo(features=self.config.features ) def __lowercase ( self , _a ) -> List[Any]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _a : str = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): _a : Dict = data_files if isinstance(_a , _a ): _a : Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : int = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _a : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): _a : List[str] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _a : Any = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={'''files''': files} ) ) return splits def __lowercase ( self , _a ) -> pa.Table: if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _a : Optional[Any] = table_cast(_a , self.config.features.arrow_schema ) return pa_table def __lowercase ( self , _a ) -> List[str]: for i, file in enumerate(itertools.chain.from_iterable(_a ) ): with open(_a , '''rb''' ) as f: _a : str = pa.Table.from_pandas(pd.read_pickle(_a ) ) yield i, self._cast_table(_a )
15
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ = logging.get_logger(__name__) a__ = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } a__ = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } a__ = { '''ctrl''': 256, } a__ = { '''Pregnancy''': 168629, '''Christianity''': 7675, '''Explain''': 106423, '''Fitness''': 63440, '''Saving''': 63163, '''Ask''': 27171, '''Ass''': 95985, '''Joke''': 163509, '''Questions''': 45622, '''Thoughts''': 49605, '''Retail''': 52342, '''Feminism''': 164338, '''Writing''': 11992, '''Atheism''': 192263, '''Netflix''': 48616, '''Computing''': 39639, '''Opinion''': 43213, '''Alone''': 44967, '''Funny''': 58917, '''Gaming''': 40358, '''Human''': 4088, '''India''': 1331, '''Joker''': 77138, '''Diet''': 36206, '''Legal''': 11859, '''Norman''': 4939, '''Tip''': 72689, '''Weight''': 52343, '''Movies''': 46273, '''Running''': 23425, '''Science''': 2090, '''Horror''': 37793, '''Confession''': 60572, '''Finance''': 12250, '''Politics''': 16360, '''Scary''': 191985, '''Support''': 12654, '''Technologies''': 32516, '''Teenage''': 66160, '''Event''': 32769, '''Learned''': 67460, '''Notion''': 182770, '''Wikipedia''': 37583, '''Books''': 6665, '''Extract''': 76050, '''Confessions''': 102701, '''Conspiracy''': 75932, '''Links''': 63674, '''Narcissus''': 150425, '''Relationship''': 54766, '''Relationships''': 134796, '''Reviews''': 41671, '''News''': 4256, '''Translation''': 26820, '''multilingual''': 128406, } def __UpperCAmelCase ( __a : Tuple ) -> str: """simple docstring""" _a : Union[str, Any] = set() _a : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _a : Union[str, Any] = char _a : int = set(__a ) return pairs class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Tuple = VOCAB_FILES_NAMES UpperCAmelCase__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : List[Any] = CONTROL_CODES def __init__( self , _a , _a , _a="<unk>" , **_a ) -> Optional[Any]: super().__init__(unk_token=_a , **_a ) with open(_a , encoding='''utf-8''' ) as vocab_handle: _a : str = json.load(_a ) _a : List[Any] = {v: k for k, v in self.encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: _a : List[Any] = merges_handle.read().split('''\n''' )[1:-1] _a : List[Any] = [tuple(merge.split() ) for merge in merges] _a : Tuple = dict(zip(_a , range(len(_a ) ) ) ) _a : str = {} @property def __lowercase ( self ) -> List[str]: return len(self.encoder ) def __lowercase ( self ) -> Any: return dict(self.encoder , **self.added_tokens_encoder ) def __lowercase ( self , _a ) -> Optional[Any]: if token in self.cache: return self.cache[token] _a : Tuple = tuple(_a ) _a : Any = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _a : Dict = get_pairs(_a ) if not pairs: return token while True: _a : str = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _a : Union[str, Any] = bigram _a : List[str] = [] _a : Dict = 0 while i < len(_a ): try: _a : Optional[Any] = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _a : str = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _a : List[str] = tuple(_a ) _a : Optional[Any] = new_word if len(_a ) == 1: break else: _a : Union[str, Any] = get_pairs(_a ) _a : int = '''@@ '''.join(_a ) _a : Optional[Any] = word[:-4] _a : Any = word return word def __lowercase ( self , _a ) -> Dict: _a : Tuple = [] _a : Any = re.findall(R'''\S+\n?''' , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(''' ''' ) ) ) return split_tokens def __lowercase ( self , _a ) -> List[Any]: return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __lowercase ( self , _a ) -> List[Any]: return self.decoder.get(_a , self.unk_token ) def __lowercase ( self , _a ) -> List[Any]: _a : Dict = ''' '''.join(_a ).replace('''@@ ''' , '''''' ).strip() return out_string def __lowercase ( self , _a , _a = None ) -> Tuple[str]: if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : Any = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _a : Union[str, Any] = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) _a : str = 0 with open(_a , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _a : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _a : Tuple = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
362
def __UpperCAmelCase ( __a : int ,__a : int ,__a : int ) -> int: """simple docstring""" if exponent == 1: return base if exponent % 2 == 0: _a : List[Any] = _modexpt(__a ,exponent // 2 ,__a ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(__a ,exponent - 1 ,__a )) % modulo_value def __UpperCAmelCase ( __a : int = 1_777 ,__a : int = 1_855 ,__a : int = 8 ) -> int: """simple docstring""" _a : List[Any] = base for _ in range(1 ,__a ): _a : Any = _modexpt(__a ,__a ,10**digits ) return result if __name__ == "__main__": print(f'''{solution() = }''')
15
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
363
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging a__ = '''\ ''' a__ = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' a__ = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def __lowercase ( self ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''input_texts''': datasets.Value('''string''' ), } ) , reference_urls=['''https://huggingface.co/docs/transformers/perplexity'''] , ) def __lowercase ( self , _a , _a , _a = 1_6 , _a = True , _a=None ) -> List[Any]: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": _a : List[str] = '''cuda''' else: _a : Optional[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' _a : Dict = AutoModelForCausalLM.from_pretrained(_a ) _a : List[Any] = model.to(_a ) _a : List[str] = AutoTokenizer.from_pretrained(_a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: _a : str = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" _a : List[Any] = model.config.max_length - 1 else: _a : List[str] = model.config.max_length _a : Union[str, Any] = tokenizer( _a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , return_tensors='''pt''' , return_attention_mask=_a , ).to(_a ) _a : List[Any] = encodings['''input_ids'''] _a : int = encodings['''attention_mask'''] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." _a : Optional[int] = [] _a : Dict = CrossEntropyLoss(reduction='''none''' ) for start_index in logging.tqdm(range(0 , len(_a ) , _a ) ): _a : Dict = min(start_index + batch_size , len(_a ) ) _a : Union[str, Any] = encoded_texts[start_index:end_index] _a : int = attn_masks[start_index:end_index] if add_start_token: _a : Dict = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_a ) _a : List[str] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) _a : Dict = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_a ), attn_mask] , dim=1 ) _a : Dict = encoded_batch with torch.no_grad(): _a : Any = model(_a , attention_mask=_a ).logits _a : List[str] = out_logits[..., :-1, :].contiguous() _a : Union[str, Any] = labels[..., 1:].contiguous() _a : Optional[int] = attn_mask[..., 1:].contiguous() _a : Union[str, Any] = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_a )}
15
0
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin a__ = get_tests_dir('''fixtures/test_sentencepiece.model''') a__ = {'''target_lang''': '''fi''', '''source_lang''': '''en'''} a__ = '''>>zh<<''' a__ = '''Helsinki-NLP/''' if is_torch_available(): a__ = '''pt''' elif is_tf_available(): a__ = '''tf''' else: a__ = '''jax''' @require_sentencepiece class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = MarianTokenizer UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Dict = True def __lowercase ( self ) -> List[Any]: super().setUp() _a : List[str] = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] _a : Optional[Any] = dict(zip(_a , range(len(_a ) ) ) ) _a : Dict = Path(self.tmpdirname ) save_json(_a , save_dir / VOCAB_FILES_NAMES['''vocab'''] ) save_json(_a , save_dir / VOCAB_FILES_NAMES['''tokenizer_config_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(_a , save_dir / VOCAB_FILES_NAMES['''source_spm'''] ) copyfile(_a , save_dir / VOCAB_FILES_NAMES['''target_spm'''] ) _a : List[str] = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase ( self , **_a ) -> MarianTokenizer: return MarianTokenizer.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self , _a ) -> Optional[int]: return ( "This is a test", "This is a test", ) def __lowercase ( self ) -> Dict: _a : Tuple = '''</s>''' _a : Union[str, Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __lowercase ( self ) -> Tuple: _a : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(_a ) , 9 ) def __lowercase ( self ) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __lowercase ( self ) -> List[Any]: _a : Union[str, Any] = MarianTokenizer.from_pretrained(F"""{ORG_NAME}opus-mt-en-de""" ) _a : List[str] = en_de_tokenizer(['''I am a small frog'''] , return_tensors=_a ) self.assertIsInstance(_a , _a ) _a : str = [3_8, 1_2_1, 1_4, 6_9_7, 3_8_8_4_8, 0] self.assertListEqual(_a , batch.input_ids[0] ) _a : Tuple = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(_a ) _a : Optional[Any] = [x.name for x in Path(_a ).glob('''*''' )] self.assertIn('''source.spm''' , _a ) MarianTokenizer.from_pretrained(_a ) def __lowercase ( self ) -> Optional[Any]: _a : Union[str, Any] = self.get_tokenizer() _a : List[str] = tok( ['''I am a small frog''' * 1_0_0_0, '''I am a small frog'''] , padding=_a , truncation=_a , return_tensors=_a ) self.assertIsInstance(_a , _a ) self.assertEqual(batch.input_ids.shape , (2, 5_1_2) ) def __lowercase ( self ) -> Any: _a : Dict = self.get_tokenizer() _a : List[Any] = tok(['''I am a tiny frog''', '''I am a small frog'''] , padding=_a , return_tensors=_a ) self.assertIsInstance(_a , _a ) self.assertEqual(batch_smaller.input_ids.shape , (2, 1_0) ) @slow def __lowercase ( self ) -> Dict: # fmt: off _a : List[str] = {'''input_ids''': [[4_3_4_9_5, 4_6_2, 2_0, 4_2_1_6_4, 1_3_6_9, 5_2, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 7_4_9_1, 3_8_9_9_9, 6, 8, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 4_6_6_9, 3_7_8_6_7, 1_3, 7_5_2_5, 2_7, 1_5_9_3, 9_8_8, 1_3, 3_3_9_7_2, 7_0_2_9, 6, 2_0, 8_2_5_1, 3_8_3, 2, 2_7_0, 5_8_6_6, 3_7_8_8, 2, 2_3_5_3, 8_2_5_1, 1_2_3_3_8, 2, 1_3_9_5_8, 3_8_7, 2, 3_6_2_9, 6_9_5_3, 1_8_8, 2_9_0_0, 2, 1_3_9_5_8, 8_0_1_1, 1_1_5_0_1, 2_3, 8_4_6_0, 4_0_7_3, 3_4_0_0_9, 2_0, 4_3_5, 1_1_4_3_9, 2_7, 8, 8_4_6_0, 4_0_7_3, 6_0_0_4, 2_0, 9_9_8_8, 3_7_5, 2_7, 3_3, 2_6_6, 1_9_4_5, 1_0_7_6, 1_3_5_0, 3_7_8_6_7, 3_2_8_8, 5, 5_7_7, 1_0_7_6, 4_3_7_4, 8, 5_0_8_2, 5, 2_6_4_5_3, 2_5_7, 5_5_6, 4_0_3, 2, 2_4_2, 1_3_2, 3_8_3, 3_1_6, 4_9_2, 8, 1_0_7_6_7, 6, 3_1_6, 3_0_4, 4_2_3_9, 3, 0], [1_4_8, 1_5_7_2_2, 1_9, 1_8_3_9, 1_2, 1_3_5_0, 1_3, 2_2_3_2_7, 5_0_8_2, 5_4_1_8, 4_7_5_6_7, 3_5_9_3_8, 5_9, 3_1_8, 1_9_5_5_2, 1_0_8, 2_1_8_3, 5_4, 1_4_9_7_6, 4_8_3_5, 3_2, 5_4_7, 1_1_1_4, 8, 3_1_5, 2_4_1_7, 5, 9_2, 1_9_0_8_8, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0], [3_6, 6_3_9_5, 1_2_5_7_0, 3_9_1_4_7, 1_1_5_9_7, 6, 2_6_6, 4, 4_5_4_0_5, 7_2_9_6, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''Helsinki-NLP/opus-mt-en-de''' , revision='''1a8c2263da11e68e50938f97e10cd57820bd504c''' , decode_kwargs={'''use_source_tokenizer''': True} , ) def __lowercase ( self ) -> Optional[Any]: _a : Optional[int] = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) _a : Any = '''Tämä on testi''' _a : List[Any] = '''This is a test''' _a : Tuple = [7_6, 7, 2_0_4_7, 2] _a : Union[str, Any] = [6_9, 1_2, 1_1, 9_4_0, 2] _a : str = tokenizer(_a ).input_ids self.assertListEqual(_a , _a ) _a : str = tokenizer(text_target=_a ).input_ids self.assertListEqual(_a , _a ) _a : List[str] = tokenizer.decode(_a , skip_special_tokens=_a ) self.assertEqual(_a , _a )
364
# Copyright 2023 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. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
15
0
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available a__ = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : str UpperCAmelCase__ : List[str] UpperCAmelCase__ : Optional[List[str]] @dataclass class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : List[int] UpperCAmelCase__ : List[int] UpperCAmelCase__ : Optional[List[int]] = None UpperCAmelCase__ : Optional[List[int]] = None class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Any = "train" UpperCAmelCase__ : Dict = "dev" UpperCAmelCase__ : Optional[int] = "test" class UpperCAmelCase_ : """simple docstring""" @staticmethod def __lowercase ( _a , _a ) -> List[InputExample]: raise NotImplementedError @staticmethod def __lowercase ( _a ) -> List[str]: raise NotImplementedError @staticmethod def __lowercase ( _a , _a , _a , _a , _a=False , _a="[CLS]" , _a=1 , _a="[SEP]" , _a=False , _a=False , _a=0 , _a=0 , _a=-1_0_0 , _a=0 , _a=True , ) -> List[InputFeatures]: _a : str = {label: i for i, label in enumerate(_a )} _a : Any = [] for ex_index, example in enumerate(_a ): if ex_index % 1_0_0_0_0 == 0: logger.info('''Writing example %d of %d''' , _a , len(_a ) ) _a : Optional[int] = [] _a : List[str] = [] for word, label in zip(example.words , example.labels ): _a : str = tokenizer.tokenize(_a ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(_a ) > 0: tokens.extend(_a ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_a ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Any = tokenizer.num_special_tokens_to_add() if len(_a ) > max_seq_length - special_tokens_count: _a : Tuple = tokens[: (max_seq_length - special_tokens_count)] _a : Optional[int] = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : List[str] = [sequence_a_segment_id] * len(_a ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Tuple = [cls_token] + tokens _a : Optional[Any] = [pad_token_label_id] + label_ids _a : Dict = [cls_token_segment_id] + segment_ids _a : Union[str, Any] = tokenizer.convert_tokens_to_ids(_a ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Tuple = [1 if mask_padding_with_zero else 0] * len(_a ) # Zero-pad up to the sequence length. _a : Dict = max_seq_length - len(_a ) if pad_on_left: _a : Dict = ([pad_token] * padding_length) + input_ids _a : str = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : str = ([pad_token_segment_id] * padding_length) + segment_ids _a : Tuple = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(_a ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(_a ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(_a ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(_a ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(_a ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Dict = None features.append( InputFeatures( input_ids=_a , attention_mask=_a , token_type_ids=_a , label_ids=_a ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : List[InputFeatures] UpperCAmelCase__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self , _a , _a , _a , _a , _a , _a = None , _a=False , _a = Split.train , ) -> List[Any]: # Load data features from cache or dataset file _a : int = os.path.join( _a , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(_a ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : Optional[int] = cached_features_file + '''.lock''' with FileLock(_a ): if os.path.exists(_a ) and not overwrite_cache: logger.info(F"""Loading features from cached file {cached_features_file}""" ) _a : Tuple = torch.load(_a ) else: logger.info(F"""Creating features from dataset file at {data_dir}""" ) _a : Optional[int] = token_classification_task.read_examples_from_file(_a , _a ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] = token_classification_task.convert_examples_to_features( _a , _a , _a , _a , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_a , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F"""Saving features into cached file {cached_features_file}""" ) torch.save(self.features , _a ) def __len__( self ) -> Union[str, Any]: return len(self.features ) def __getitem__( self , _a ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : List[InputFeatures] UpperCAmelCase__ : int = -100 def __init__( self , _a , _a , _a , _a , _a , _a = None , _a=False , _a = Split.train , ) -> List[Any]: _a : Dict = token_classification_task.read_examples_from_file(_a , _a ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] = token_classification_task.convert_examples_to_features( _a , _a , _a , _a , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_a , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Optional[Any] = tf.data.Dataset.from_generator( _a , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Dict = tf.data.Dataset.from_generator( _a , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __lowercase ( self ) -> Optional[int]: _a : Tuple = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self ) -> int: return len(self.features ) def __getitem__( self , _a ) -> InputFeatures: return self.features[i]
365
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a__ = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) a__ = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Extra Ignored Subsection''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], } ], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } a__ = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) a__ = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) a__ = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' a__ = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.''' a__ = '''''' a__ = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' a__ = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' a__ = '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.''' @pytest.mark.parametrize( '''readme_md, expected_dict''' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : List[str] ) -> Optional[int]: """simple docstring""" assert ReadMe.from_string(__a ,__a ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def __UpperCAmelCase ( __a : List[str] ,__a : Optional[Any] ) -> Union[str, Any]: """simple docstring""" with pytest.raises(__a ,match=re.escape(expected_error.format(path='''root''' ) ) ): _a : List[Any] = ReadMe.from_string(__a ,__a ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Dict ,__a : Dict ) -> Tuple: """simple docstring""" with pytest.raises(__a ,match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__a ,__a ) @pytest.mark.parametrize( '''readme_md,''' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Optional[Any] ) -> Tuple: """simple docstring""" ReadMe.from_string(__a ,__a ,suppress_parsing_errors=__a ) @pytest.mark.parametrize( '''readme_md, expected_dict''' ,[ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] ,) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : Any ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : Tuple = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : Optional[Any] = ReadMe.from_readme(__a ,__a ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] ,) def __UpperCAmelCase ( __a : List[Any] ,__a : List[Any] ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : int = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : Optional[int] = expected_error.format(path=__a ) with pytest.raises(__a ,match=re.escape(__a ) ): _a : Any = ReadMe.from_readme(__a ,__a ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' ,[ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : str ,__a : Union[str, Any] ) -> Dict: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : Optional[Any] = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) _a : str = expected_error.format(path=__a ) with pytest.raises(__a ,match=re.escape(__a ) ): ReadMe.from_readme(__a ,__a ) @pytest.mark.parametrize( '''readme_md,''' ,[ (README_MULTIPLE_SAME_HEADING_1), ] ,) def __UpperCAmelCase ( __a : Optional[Any] ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _a : int = Path(__a ) / '''README.md''' with open(__a ,'''w+''' ) as readme_file: readme_file.write(__a ) ReadMe.from_readme(__a ,__a ,suppress_parsing_errors=__a )
15
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def __UpperCAmelCase ( __a : str ,__a : str ,__a : List[str]=None ,__a : List[Any]=None ) -> Optional[int]: """simple docstring""" if attention_mask is None: _a : Optional[int] = tf.cast(tf.math.not_equal(__a ,config.pad_token_id ) ,tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : List[Any] = OPTConfig UpperCAmelCase__ : Dict = {} UpperCAmelCase__ : Tuple = "gelu" def __init__( self , _a , _a=1_3 , _a=7 , _a=True , _a=False , _a=9_9 , _a=1_6 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=2_0 , _a=2 , _a=1 , _a=0 , _a=1_6 , _a=1_6 , ) -> Union[str, Any]: _a : List[str] = parent _a : Tuple = batch_size _a : List[str] = seq_length _a : Optional[Any] = is_training _a : List[str] = use_labels _a : Optional[int] = vocab_size _a : Optional[Any] = hidden_size _a : List[Any] = num_hidden_layers _a : Any = num_attention_heads _a : int = intermediate_size _a : List[str] = hidden_act _a : Optional[Any] = hidden_dropout_prob _a : Optional[Any] = attention_probs_dropout_prob _a : Optional[Any] = max_position_embeddings _a : Tuple = eos_token_id _a : Dict = pad_token_id _a : int = bos_token_id _a : Optional[int] = embed_dim _a : Dict = word_embed_proj_dim _a : Tuple = False def __lowercase ( self ) -> int: _a : Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _a : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _a : Optional[int] = tf.concat([input_ids, eos_tensor] , axis=1 ) _a : Dict = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=_a , **self.config_updates , ) _a : Optional[Any] = prepare_opt_inputs_dict(_a , _a ) return config, inputs_dict def __lowercase ( self , _a , _a ) -> Union[str, Any]: _a : int = TFOPTModel(config=_a ) _a : int = inputs_dict['''input_ids'''] _a : Optional[int] = input_ids[:1, :] _a : Optional[Any] = inputs_dict['''attention_mask'''][:1, :] _a : Union[str, Any] = 1 # first forward pass _a : Any = model(_a , attention_mask=_a , use_cache=_a ) _a : Optional[Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _a : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _a : str = tf.concat([input_ids, next_tokens] , axis=-1 ) _a : Dict = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _a : str = model(_a , attention_mask=_a )[0] _a : List[str] = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _a : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _a : str = output_from_no_past[:, -3:, random_slice_idx] _a : int = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) @require_tf class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () UpperCAmelCase__ : Union[str, Any] = (TFOPTForCausalLM,) if is_tf_available() else () UpperCAmelCase__ : Tuple = ( {"feature-extraction": TFOPTModel, "text-generation": TFOPTForCausalLM} if is_tf_available() else {} ) UpperCAmelCase__ : Any = False UpperCAmelCase__ : Dict = False UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : Any = 10 def __lowercase ( self ) -> int: _a : str = TFOPTModelTester(self ) _a : int = ConfigTester(self , config_class=_a ) def __lowercase ( self ) -> Optional[int]: self.config_tester.run_common_tests() def __lowercase ( self ) -> Optional[int]: _a : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) def __lowercase ( self ) -> Tuple: _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(_a , _a ): if hasattr(_a , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(_a , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]: # build the embeddings _a : List[str] = model_class(config=_a ) _a : List[str] = _get_word_embedding_weight(_a , model.get_input_embeddings() ) _a : Union[str, Any] = _get_word_embedding_weight(_a , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(_a ) _a : List[Any] = _get_word_embedding_weight(_a , model.get_input_embeddings() ) _a : List[str] = _get_word_embedding_weight(_a , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. _a : Union[str, Any] = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , _a ) # check that weights remain the same after resizing _a : Any = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _a : Union[str, Any] = False self.assertTrue(_a ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , _a ) _a : List[Any] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _a : Optional[Any] = False self.assertTrue(_a ) def __UpperCAmelCase ( __a : List[str] ) -> Dict: """simple docstring""" return tf.constant(__a ,dtype=tf.intaa ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = 99 def __lowercase ( self ) -> List[str]: _a : Dict = tf.ones((4, 1) , dtype=tf.intaa ) * 2 _a : Optional[Any] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) _a : str = input_ids.shape[0] _a : Tuple = OPTConfig( vocab_size=self.vocab_size , hidden_size=2_4 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self ) -> List[Any]: _a : int = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) _a : Tuple = _long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _a : List[Any] = tf.not_equal(_a , model.config.pad_token_id ) with tf.GradientTape(): _a : Dict = model(input_ids=_a , attention_mask=_a ).last_hidden_state _a : Union[str, Any] = (1, 1_1, 5_1_2) self.assertEqual(output.shape , _a ) _a : Tuple = tf.constant( [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=4e-3 ) ) _a : Optional[int] = tf.function(_a , jit_compile=_a ) _a : Dict = xla_generate(_a , _a )[0] self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=4e-2 ) ) @require_tf @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> Optional[Any]: super().setUp() _a : Dict = '''facebook/opt-350m''' def __lowercase ( self ) -> List[str]: _a : str = TFOPTForCausalLM.from_pretrained(self.path_model ) _a : Tuple = GPTaTokenizer.from_pretrained(self.path_model ) _a : str = [ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False _a : Any = tokenizer(_a , return_tensors='''tf''' , padding=_a , add_special_tokens=_a ) _a : Union[str, Any] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) _a : Dict = tf.constant( [ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670], [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822], [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703], [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477], ] ) self.assertTrue(np.allclose(_a , _a , atol=1e-4 ) ) _a : str = tf.function(_a , jit_compile=_a ) _a : Optional[int] = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(_a , _a , atol=1e-4 ) ) @require_tf @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @property def __lowercase ( self ) -> Any: return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def __lowercase ( self ) -> str: _a : List[Any] = '''facebook/opt-125m''' _a : Optional[Any] = [ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] _a : str = [] _a : List[Any] = GPTaTokenizer.from_pretrained(_a ) _a : Tuple = TFOPTForCausalLM.from_pretrained(_a ) for prompt in self.prompts: _a : Union[str, Any] = tokenizer(_a , return_tensors='''tf''' ).input_ids _a : Union[str, Any] = model.generate(_a , max_length=1_0 ) _a : str = tokenizer.batch_decode(_a , skip_special_tokens=_a ) predicted_outputs += generated_string self.assertListEqual(_a , _a ) def __lowercase ( self ) -> Tuple: _a : Any = '''facebook/opt-350m''' _a : Any = GPTaTokenizer.from_pretrained(_a ) _a : Any = TFOPTForCausalLM.from_pretrained(_a ) _a : Dict = '''left''' # use different length sentences to test batching _a : Dict = [ '''Hello, my dog is a little''', '''Today, I''', ] _a : int = tokenizer(_a , return_tensors='''tf''' , padding=_a ) _a : List[str] = inputs['''input_ids'''] _a : Optional[Any] = model.generate(input_ids=_a , attention_mask=inputs['''attention_mask'''] ) _a : Any = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids _a : Tuple = model.generate(input_ids=_a ) _a : str = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) _a : Optional[int] = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids _a : Tuple = model.generate(input_ids=_a , max_length=model.config.max_length - num_paddings ) _a : str = tokenizer.batch_decode(_a , skip_special_tokens=_a ) _a : List[str] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=_a ) _a : Dict = tokenizer.decode(output_padded[0] , skip_special_tokens=_a ) _a : List[str] = [ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(_a , _a ) self.assertListEqual(_a , [non_padded_sentence, padded_sentence] ) def __lowercase ( self ) -> str: _a : Union[str, Any] = '''facebook/opt-350m''' _a : Optional[Any] = [ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] _a : List[Any] = [] _a : Any = GPTaTokenizer.from_pretrained(_a ) _a : Any = TFOPTForCausalLM.from_pretrained(_a ) for prompt in self.prompts: _a : str = tokenizer(_a , return_tensors='''tf''' ).input_ids _a : List[Any] = model.generate(_a , max_length=1_0 ) _a : List[str] = tokenizer.batch_decode(_a , skip_special_tokens=_a ) predicted_outputs += generated_string self.assertListEqual(_a , _a )
366
from __future__ import annotations def __UpperCAmelCase ( __a : list ) -> float: """simple docstring""" if not nums: raise ValueError('''List is empty''' ) return sum(__a ) / len(__a ) if __name__ == "__main__": import doctest doctest.testmod()
15
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler a__ = 16 a__ = 32 def __UpperCAmelCase ( __a : Accelerator ,__a : int = 16 ,__a : str = "bert-base-cased" ) -> int: """simple docstring""" _a : int = AutoTokenizer.from_pretrained(__a ) _a : Optional[Any] = load_dataset('''glue''' ,'''mrpc''' ) def tokenize_function(__a : List[str] ): # max_length=None => use the model max length (it's actually the default) _a : int = tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=__a ,max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _a : Optional[Any] = datasets.map( __a ,batched=__a ,remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,load_from_cache_file=__a ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : Union[str, Any] = tokenized_datasets.rename_column('''label''' ,'''labels''' ) def collate_fn(__a : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__a ,padding='''max_length''' ,max_length=128 ,return_tensors='''pt''' ) return tokenizer.pad(__a ,padding='''longest''' ,return_tensors='''pt''' ) # Instantiate dataloaders. _a : Dict = DataLoader( tokenized_datasets['''train'''] ,shuffle=__a ,collate_fn=__a ,batch_size=__a ) _a : List[str] = DataLoader( tokenized_datasets['''validation'''] ,shuffle=__a ,collate_fn=__a ,batch_size=__a ) return train_dataloader, eval_dataloader def __UpperCAmelCase ( __a : str ,__a : Tuple ) -> List[str]: """simple docstring""" _a : Tuple = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[int] = config['''lr'''] _a : Optional[int] = int(config['''num_epochs'''] ) _a : Optional[Any] = int(config['''seed'''] ) _a : Union[str, Any] = int(config['''batch_size'''] ) _a : List[str] = args.model_name_or_path set_seed(__a ) _a : List[Any] = get_dataloaders(__a ,__a ,__a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : str = AutoModelForSequenceClassification.from_pretrained(__a ,return_dict=__a ) # Instantiate optimizer _a : Dict = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _a : Union[str, Any] = optimizer_cls(params=model.parameters() ,lr=__a ) if accelerator.state.deepspeed_plugin is not None: _a : Dict = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: _a : str = 1 _a : Optional[Any] = (len(__a ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _a : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=__a ,num_warmup_steps=0 ,num_training_steps=__a ,) else: _a : Optional[int] = DummyScheduler(__a ,total_num_steps=__a ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _a : str = accelerator.prepare( __a ,__a ,__a ,__a ,__a ) # We need to keep track of how many total steps we have iterated over _a : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly _a : Dict = 0 # Now we train the model _a : Dict = evaluate.load('''glue''' ,'''mrpc''' ) _a : Union[str, Any] = 0 _a : int = {} for epoch in range(__a ,__a ): model.train() for step, batch in enumerate(__a ): _a : List[Any] = model(**__a ) _a : Any = outputs.loss _a : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _a : Dict = 0 for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _a : Union[str, Any] = model(**__a ) _a : Dict = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _a : Tuple = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__a ) - 1: _a : Any = predictions[: len(eval_dataloader.dataset ) - samples_seen] _a : List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__a ,references=__a ,) _a : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" ,__a ) _a : List[Any] = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: _a : Union[str, Any] = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,'''all_results.json''' ) ,'''w''' ) as f: json.dump(__a ,__a ) def __UpperCAmelCase ( ) -> Tuple: """simple docstring""" _a : int = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' ,type=__a ,default='''bert-base-cased''' ,help='''Path to pretrained model or model identifier from huggingface.co/models.''' ,required=__a ,) parser.add_argument( '''--output_dir''' ,type=__a ,default='''.''' ,help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' ,) parser.add_argument( '''--performance_lower_bound''' ,type=__a ,default=__a ,help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''' ,) parser.add_argument( '''--num_epochs''' ,type=__a ,default=3 ,help='''Number of train epochs.''' ,) _a : Union[str, Any] = parser.parse_args() _a : Optional[int] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(__a ,__a ) if __name__ == "__main__": main()
367
import argparse import os import torch from transformers.utils import WEIGHTS_NAME a__ = ['''small''', '''medium''', '''large'''] a__ = '''lm_head.decoder.weight''' a__ = '''lm_head.weight''' def __UpperCAmelCase ( __a : str ,__a : str ) -> List[str]: """simple docstring""" _a : Any = torch.load(__a ) _a : List[str] = d.pop(__a ) os.makedirs(__a ,exist_ok=__a ) torch.save(__a ,os.path.join(__a ,__a ) ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--dialogpt_path''', default='''.''', type=str) a__ = parser.parse_args() for MODEL in DIALOGPT_MODELS: a__ = os.path.join(args.dialogpt_path, f'''{MODEL}_ft.pkl''') a__ = f'''./DialoGPT-{MODEL}''' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
15
0
def __UpperCAmelCase ( __a : list ) -> list: """simple docstring""" if len(__a ) <= 1: return lst _a : Optional[Any] = 1 while i < len(__a ): if lst[i - 1] <= lst[i]: i += 1 else: _a : Optional[Any] = lst[i], lst[i - 1] i -= 1 if i == 0: _a : Dict = 1 return lst if __name__ == "__main__": a__ = input('''Enter numbers separated by a comma:\n''').strip() a__ = [int(item) for item in user_input.split(''',''')] print(gnome_sort(unsorted))
368
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class UpperCAmelCase_ ( enum.Enum ): """simple docstring""" UpperCAmelCase__ : int = 0 UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Optional[Any] = 2 @add_end_docstrings(__lowercase ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self , *_a , **_a ) -> List[str]: super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _a : Dict = None if self.model.config.prefix is not None: _a : List[Any] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _a : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _a , _a , _a : str = self._sanitize_parameters(prefix=_a , **self._forward_params ) _a : Optional[Any] = {**self._preprocess_params, **preprocess_params} _a : List[Any] = {**self._forward_params, **forward_params} def __lowercase ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> Optional[int]: _a : List[Any] = {} if prefix is not None: _a : Optional[Any] = prefix if prefix: _a : Dict = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) _a : Tuple = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _a : Dict = handle_long_generation preprocess_params.update(_a ) _a : Tuple = generate_kwargs _a : Any = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _a : List[str] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _a : Any = ReturnType.TENSORS if return_type is not None: _a : Any = return_type if clean_up_tokenization_spaces is not None: _a : List[Any] = clean_up_tokenization_spaces if stop_sequence is not None: _a : Tuple = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _a : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowercase ( self , *_a , **_a ) -> Union[str, Any]: # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> List[str]: return super().__call__(_a , **_a ) def __lowercase ( self , _a , _a="" , _a=None , **_a ) -> List[Any]: _a : Optional[int] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) _a : Union[str, Any] = prompt_text if handle_long_generation == "hole": _a : List[str] = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _a : int = generate_kwargs['''max_new_tokens'''] else: _a : List[Any] = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _a : List[str] = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _a : List[Any] = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _a : List[str] = inputs['''attention_mask'''][:, -keep_length:] return inputs def __lowercase ( self , _a , **_a ) -> Optional[int]: _a : Any = model_inputs['''input_ids'''] _a : Optional[Any] = model_inputs.get('''attention_mask''' , _a ) # Allow empty prompts if input_ids.shape[1] == 0: _a : int = None _a : int = None _a : List[str] = 1 else: _a : List[Any] = input_ids.shape[0] _a : Union[str, Any] = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _a : int = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _a : Tuple = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _a : int = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _a : Dict = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _a : Optional[Any] = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) _a : int = generated_sequence.shape[0] if self.framework == "pt": _a : Tuple = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _a : List[Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowercase ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> int: _a : Tuple = model_outputs['''generated_sequence'''][0] _a : int = model_outputs['''input_ids'''] _a : Any = model_outputs['''prompt_text'''] _a : Any = generated_sequence.numpy().tolist() _a : Any = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _a : Optional[int] = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _a : str = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _a : Union[str, Any] = 0 else: _a : str = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: _a : str = prompt_text + text[prompt_length:] else: _a : List[str] = text[prompt_length:] _a : Union[str, Any] = {'''generated_text''': all_text} records.append(_a ) return records
15
0
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''width_multiplier''' ) ) class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a , _a=1_3 , _a=6_4 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=3_2 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=1_0 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ) -> Optional[int]: _a : int = parent _a : str = batch_size _a : Dict = image_size _a : str = patch_size _a : Optional[Any] = num_channels _a : str = make_divisible(5_1_2 * width_multiplier , divisor=8 ) _a : Any = hidden_act _a : Dict = conv_kernel_size _a : List[Any] = output_stride _a : Any = classifier_dropout_prob _a : Optional[int] = use_labels _a : List[str] = is_training _a : List[Any] = num_labels _a : Any = initializer_range _a : Union[str, Any] = scope _a : Dict = width_multiplier _a : int = ffn_dropout _a : int = attn_dropout def __lowercase ( self ) -> int: _a : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None _a : List[str] = None if self.use_labels: _a : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels ) _a : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _a : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __lowercase ( self ) -> List[Any]: return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __lowercase ( self , _a , _a , _a , _a ) -> Any: _a : str = MobileViTVaModel(config=_a ) model.to(_a ) model.eval() _a : List[str] = model(_a ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __lowercase ( self , _a , _a , _a , _a ) -> str: _a : Union[str, Any] = self.num_labels _a : int = MobileViTVaForImageClassification(_a ) model.to(_a ) model.eval() _a : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase ( self , _a , _a , _a , _a ) -> Union[str, Any]: _a : Optional[Any] = self.num_labels _a : List[str] = MobileViTVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() _a : Optional[int] = model(_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _a : Union[str, Any] = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __lowercase ( self ) -> int: _a : str = self.prepare_config_and_inputs() _a : Dict = config_and_inputs _a : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) UpperCAmelCase__ : List[str] = ( { "feature-extraction": MobileViTVaModel, "image-classification": MobileViTVaForImageClassification, "image-segmentation": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCAmelCase__ : int = False UpperCAmelCase__ : str = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : str = False def __lowercase ( self ) -> List[str]: _a : Any = MobileViTVaModelTester(self ) _a : List[Any] = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a ) def __lowercase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __lowercase ( self ) -> Tuple: pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __lowercase ( self ) -> Optional[int]: pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __lowercase ( self ) -> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __lowercase ( self ) -> Union[str, Any]: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowercase ( self ) -> Any: pass def __lowercase ( self ) -> List[Any]: _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Dict = model_class(_a ) _a : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Optional[int] = [*signature.parameters.keys()] _a : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __lowercase ( self ) -> Union[str, Any]: _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self ) -> Any: def check_hidden_states_output(_a , _a , _a ): _a : List[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _a : Tuple = model(**self._prepare_for_class(_a , _a ) ) _a : Optional[int] = outputs.hidden_states _a : List[str] = 5 self.assertEqual(len(_a ) , _a ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. _a : List[str] = 2 for i in range(len(_a ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : List[str] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : List[str] = True check_hidden_states_output(_a , _a , _a ) def __lowercase ( self ) -> Dict: _a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def __lowercase ( self ) -> Any: _a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def __lowercase ( self ) -> Union[str, Any]: for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = MobileViTVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __UpperCAmelCase ( ) -> Union[str, Any]: """simple docstring""" _a : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self ) -> int: return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __lowercase ( self ) -> Union[str, Any]: _a : Tuple = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _a ) _a : str = self.default_image_processor _a : List[Any] = prepare_img() _a : str = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): _a : Any = model(**_a ) # verify the logits _a : List[str] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _a ) _a : Dict = torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @slow def __lowercase ( self ) -> Tuple: _a : int = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) _a : List[str] = model.to(_a ) _a : Any = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) _a : Any = prepare_img() _a : Any = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): _a : List[Any] = model(**_a ) _a : Dict = outputs.logits # verify the logits _a : Tuple = torch.Size((1, 2_1, 3_2, 3_2) ) self.assertEqual(logits.shape , _a ) _a : Any = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1e-4 ) ) @slow def __lowercase ( self ) -> Tuple: _a : Optional[int] = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) _a : Optional[Any] = model.to(_a ) _a : str = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) _a : List[str] = prepare_img() _a : Dict = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): _a : int = model(**_a ) _a : List[Any] = outputs.logits.detach().cpu() _a : List[Any] = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(5_0, 6_0)] ) _a : Tuple = torch.Size((5_0, 6_0) ) self.assertEqual(segmentation[0].shape , _a ) _a : Union[str, Any] = image_processor.post_process_semantic_segmentation(outputs=_a ) _a : Optional[int] = torch.Size((3_2, 3_2) ) self.assertEqual(segmentation[0].shape , _a )
369
# Copyright 2021 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 argparse import os from accelerate.test_utils import execute_subprocess_async def __UpperCAmelCase ( __a : Dict=None ) -> str: """simple docstring""" if subparsers is not None: _a : Union[str, Any] = subparsers.add_parser('''test''' ) else: _a : List[str] = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' ,default=__a ,help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) ,) if subparsers is not None: parser.set_defaults(func=__a ) return parser def __UpperCAmelCase ( __a : List[Any] ) -> Union[str, Any]: """simple docstring""" _a : Dict = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: _a : List[Any] = script_name else: _a : Union[str, Any] = F"""--config_file={args.config_file} {script_name}""" _a : str = ['''accelerate-launch'''] + test_args.split() _a : str = execute_subprocess_async(__a ,env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def __UpperCAmelCase ( ) -> List[Any]: """simple docstring""" _a : Optional[int] = test_command_parser() _a : List[Any] = parser.parse_args() test_command(__a ) if __name__ == "__main__": main()
15
0
a__ = 256 # Modulus to hash a string a__ = 1000003 def __UpperCAmelCase ( __a : str ,__a : str ) -> bool: """simple docstring""" _a : str = len(__a ) _a : List[str] = len(__a ) if p_len > t_len: return False _a : Optional[Any] = 0 _a : List[Any] = 0 _a : Optional[int] = 1 # Calculating the hash of pattern and substring of text for i in range(__a ): _a : int = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus _a : List[Any] = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue _a : int = (modulus_power * alphabet_size) % modulus for i in range(0 ,t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash _a : List[str] = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def __UpperCAmelCase ( ) -> None: """simple docstring""" _a : List[str] = '''abc1abc12''' _a : Union[str, Any] = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' _a : Optional[Any] = '''alskfjaldsk23adsfabcabc''' assert rabin_karp(__a ,__a ) and not rabin_karp(__a ,__a ) # Test 2) _a : str = '''ABABX''' _a : List[str] = '''ABABZABABYABABX''' assert rabin_karp(__a ,__a ) # Test 3) _a : Dict = '''AAAB''' _a : List[Any] = '''ABAAAAAB''' assert rabin_karp(__a ,__a ) # Test 4) _a : Optional[Any] = '''abcdabcy''' _a : str = '''abcxabcdabxabcdabcdabcy''' assert rabin_karp(__a ,__a ) # Test 5) _a : Union[str, Any] = '''Lü''' _a : Any = '''Lüsai''' assert rabin_karp(__a ,__a ) _a : Tuple = '''Lue''' assert not rabin_karp(__a ,__a ) print('''Success.''' ) if __name__ == "__main__": test_rabin_karp()
370
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> Union[str, Any]: _a : Optional[Any] = tempfile.mkdtemp() # fmt: off _a : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _a : Any = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _a : str = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_a , _a ) def __lowercase ( self , **_a ) -> Any: return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self , **_a ) -> str: return ViTImageProcessor.from_pretrained(self.tmpdirname , **_a ) def __lowercase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __lowercase ( self ) -> Any: _a : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] _a : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase ( self ) -> str: _a : List[str] = self.get_tokenizer() _a : Tuple = self.get_image_processor() _a : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) processor.save_pretrained(self.tmpdirname ) _a : Dict = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def __lowercase ( self ) -> Dict: _a : List[str] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _a : Any = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _a : List[Any] = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) _a : Dict = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def __lowercase ( self ) -> Any: _a : Dict = self.get_image_processor() _a : str = self.get_tokenizer() _a : int = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : List[str] = self.prepare_image_inputs() _a : List[Any] = image_processor(_a , return_tensors='''np''' ) _a : Dict = processor(images=_a , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase ( self ) -> List[str]: _a : Union[str, Any] = self.get_image_processor() _a : Dict = self.get_tokenizer() _a : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Tuple = '''lower newer''' _a : int = processor(text=_a ) _a : str = tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase ( self ) -> List[Any]: _a : Any = self.get_image_processor() _a : str = self.get_tokenizer() _a : Tuple = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : List[Any] = '''lower newer''' _a : Union[str, Any] = self.prepare_image_inputs() _a : Any = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_a ): processor() def __lowercase ( self ) -> Optional[int]: _a : Union[str, Any] = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : Any = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _a : int = processor.batch_decode(_a ) _a : int = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def __lowercase ( self ) -> List[Any]: _a : Tuple = self.get_image_processor() _a : List[str] = self.get_tokenizer() _a : str = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) _a : Optional[int] = '''lower newer''' _a : Dict = self.prepare_image_inputs() _a : Any = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
15
0
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a__ = logging.get_logger(__name__) a__ = {'''vocab_file''': '''vocab.txt''', '''emoji_file''': '''emoji.json'''} a__ = { '''vocab_file''': { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt''', }, '''emoji_file''': { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json''', }, } a__ = { '''abeja/gpt-neox-japanese-2.7b''': 2048, } def __UpperCAmelCase ( __a : List[Any] ,__a : Optional[Any] ) -> Optional[int]: """simple docstring""" with open(__a ,'''r''' ,encoding='''utf-8''' ) as f: _a : Dict = json.loads(f.read() ) _a : Tuple = collections.OrderedDict() _a : List[str] = collections.OrderedDict() _a : Any = collections.OrderedDict() with open(__a ,'''r''' ,encoding='''utf-8''' ) as f: _a : List[str] = f.readlines() _a : Dict = [[t.rstrip('''\n''' )] if (t == ''',''' or ''',''' not in t) else t.rstrip('''\n''' ).split(''',''' ) for t in token] for idx, b in enumerate(__a ): _a : List[str] = b _a : Optional[Any] = idx for wd in b: _a : List[Any] = idx return vocab, raw_vocab, ids_to_tokens, emoji class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Dict = VOCAB_FILES_NAMES UpperCAmelCase__ : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : List[str] = ["input_ids", "attention_mask"] def __init__( self , _a , _a , _a="<|endoftext|>" , _a="<|endoftext|>" , _a="<|startoftext|>" , _a="<|endoftext|>" , _a=False , **_a , ) -> Optional[Any]: super().__init__( unk_token=_a , pad_token=_a , bos_token=_a , eos_token=_a , do_clean_text=_a , **_a , ) if not os.path.isfile(_a ): raise ValueError( F"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained""" ''' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' ) if not os.path.isfile(_a ): raise ValueError( F"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google""" ''' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' ) _a : Dict = do_clean_text _a : Any = load_vocab_and_emoji(_a , _a ) _a : List[Any] = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def __lowercase ( self ) -> Any: # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab return len(self.raw_vocab ) def __lowercase ( self ) -> List[Any]: return dict(self.raw_vocab , **self.added_tokens_encoder ) def __lowercase ( self , _a ) -> Tuple: return self.subword_tokenizer.tokenize(_a , clean=self.do_clean_text ) def __lowercase ( self , _a ) -> Any: return self.vocab.get(_a , self.vocab.get(self.unk_token ) ) def __lowercase ( self , _a ) -> Dict: return self.subword_tokenizer.convert_id_to_token(_a ) def __lowercase ( self , _a ) -> Dict: _a : Optional[int] = ''''''.join(_a ).strip() return out_string def __lowercase ( self , _a ) -> List[int]: _a : Any = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_a , add_special_tokens=_a ) + [self.eos_token_id] ) if len(_a ) > self.model_max_length: _a : Dict = input_ids[-self.model_max_length :] return input_ids def __lowercase ( self , _a , _a = None ) -> Tuple[str]: _a : int = 0 if os.path.isdir(_a ): _a : Any = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _a : Dict = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''emoji_file'''] ) else: _a : str = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''vocab_file'''] ) _a : Optional[int] = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''emoji_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) _a : Tuple = token_index writer.write(''','''.join(_a ) + '''\n''' ) index += 1 with open(_a , '''w''' , encoding='''utf-8''' ) as writer: json.dump(self.emoji , _a ) return vocab_file, emoji_file class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __init__( self , _a , _a , _a ) -> Optional[Any]: _a : Tuple = vocab # same as swe _a : str = ids_to_tokens # same as bpe _a : str = emoji _a : List[str] = np.max([len(_a ) for w in self.vocab.keys()] ) _a : int = re.compile(R'''(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)''' ) _a : Any = re.compile(R'''[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*''' ) _a : Union[str, Any] = re.compile(R'''[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}''' ) _a : Any = re.compile( R'''([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' ) _a : Union[str, Any] = re.compile( R'''(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' ) _a : int = re.compile( R'''((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*''' ) _a : Union[str, Any] = '''─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿''' _a : Any = '''▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟''' _a : str = str.maketrans({k: '''<BLOCK>''' for k in keisen + blocks} ) def __len__( self ) -> Optional[Any]: return len(self.ids_to_tokens ) def __lowercase ( self , _a ) -> int: _a : Union[str, Any] = self.content_repattera.sub('''<URL>''' , _a ) _a : List[Any] = self.content_repattera.sub('''<EMAIL>''' , _a ) _a : Optional[Any] = self.content_repattera.sub('''<TEL>''' , _a ) _a : str = self.content_repattera.sub('''<DATE>''' , _a ) _a : Union[str, Any] = self.content_repattera.sub('''<DATE>''' , _a ) _a : Dict = self.content_repattera.sub('''<PRICE>''' , _a ) _a : Union[str, Any] = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: _a : Union[str, Any] = content.replace('''<BLOCK><BLOCK>''' , '''<BLOCK>''' ) return content def __lowercase ( self , _a , _a=False ) -> Dict: _a : List[str] = text.replace(''' ''' , '''<SP>''' ) _a : Any = text.replace(''' ''' , '''<SP>''' ) _a : Any = text.replace('''\r\n''' , '''<BR>''' ) _a : int = text.replace('''\n''' , '''<BR>''' ) _a : Optional[int] = text.replace('''\r''' , '''<BR>''' ) _a : Union[str, Any] = text.replace('''\t''' , '''<TAB>''' ) _a : Optional[Any] = text.replace('''—''' , '''ー''' ) _a : Tuple = text.replace('''−''' , '''ー''' ) for k, v in self.emoji["emoji"].items(): if k in text: _a : Union[str, Any] = text.replace(_a , _a ) if clean: _a : int = self.clean_text(_a ) def check_simbol(_a ): _a : str = x.encode() if len(_a ) == 1 and len(_a ) == 2: _a : int = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0xc_2_a_1 and c <= 0xc_2_b_f) or (c >= 0xc_7_8_0 and c <= 0xc_7_8_3) or (c >= 0xc_a_b_9 and c <= 0xc_b_b_f) or (c >= 0xc_c_8_0 and c <= 0xc_d_a_2) ): return True return False def checkuae(_a ): _a : Any = x.encode() if len(_a ) == 1 and len(_a ) == 3: _a : List[Any] = (int(e[0] ) << 1_6) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0xe_2_8_0_8_0 and c <= 0xe_2_b_0_7_f: return True return False _a : str = 0 _a : Optional[Any] = [] while pos < len(_a ): _a : int = min(len(_a ) , pos + self.maxlen + 1 ) if text[pos] == '''<''' else pos + 3 _a : List[Any] = [] # (token_id, token, pos) for e in range(_a , _a , -1 ): _a : Tuple = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(_a ) > 2: _a : List[Any] = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(_a ) > 0: # the smallest token_id is adopted _a : List[Any] = sorted(_a , key=lambda _a : x[0] )[0] result.append(_a ) _a : Tuple = e else: _a : Optional[int] = pos + 1 _a : str = text[pos:end] if check_simbol(_a ): result.append('''<KIGOU>''' ) elif checkuae(_a ): result.append('''<U2000U2BFF>''' ) else: for i in wd.encode('''utf-8''' ): result.append('''<|byte%d|>''' % i ) _a : str = end return result def __lowercase ( self , _a , _a="\n" ) -> List[str]: _a : Optional[int] = [] _a : str = [] _a : int = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(_a ) > 0: words.append(bytearray(_a ).decode('''utf-8''' , errors='''replace''' ) ) _a : List[Any] = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji['''emoji_inv'''][word] ) elif word == "<SP>": words.append(''' ''' ) elif word == "<BR>": words.append(_a ) elif word == "<TAB>": words.append('''\t''' ) elif word == "<BLOCK>": words.append('''▀''' ) elif word == "<KIGOU>": words.append('''ǀ''' ) elif word == "<U2000U2BFF>": words.append('''‖''' ) else: words.append(_a ) if len(_a ) > 0: words.append(bytearray(_a ).decode('''utf-8''' , errors='''replace''' ) ) _a : str = ''''''.join(_a ) return text
371
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a__ = logging.get_logger(__name__) a__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def __UpperCAmelCase ( __a : List[Any] ,__a : Optional[int] ,__a : Optional[int] ,__a : List[str] ,__a : List[Any] ) -> Union[str, Any]: """simple docstring""" for attribute in key.split('''.''' ): _a : Optional[Any] = getattr(__a ,__a ) if weight_type is not None: _a : Dict = getattr(__a ,__a ).shape else: _a : Optional[int] = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": _a : List[Any] = value elif weight_type == "weight_g": _a : Any = value elif weight_type == "weight_v": _a : Union[str, Any] = value elif weight_type == "bias": _a : Optional[int] = value else: _a : List[Any] = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def __UpperCAmelCase ( __a : Any ,__a : Union[str, Any] ,__a : Union[str, Any] ) -> int: """simple docstring""" _a : Union[str, Any] = [] _a : Union[str, Any] = fairseq_model.state_dict() _a : Union[str, Any] = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _a : int = False if "conv_layers" in name: load_conv_layer( __a ,__a ,__a ,__a ,hf_model.config.feat_extract_norm == '''group''' ,) _a : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): _a : Union[str, Any] = '''hubert.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or (key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0] and not is_finetuned): _a : Any = True if "*" in mapped_key: _a : Optional[int] = name.split(__a )[0].split('''.''' )[-2] _a : Any = mapped_key.replace('''*''' ,__a ) if "weight_g" in name: _a : List[Any] = '''weight_g''' elif "weight_v" in name: _a : List[str] = '''weight_v''' elif "weight" in name: _a : Any = '''weight''' elif "bias" in name: _a : str = '''bias''' else: _a : Any = None set_recursively(__a ,__a ,__a ,__a ,__a ) continue if not is_used: unused_weights.append(__a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def __UpperCAmelCase ( __a : int ,__a : Optional[Any] ,__a : Dict ,__a : List[str] ,__a : Any ) -> Tuple: """simple docstring""" _a : int = full_name.split('''conv_layers.''' )[-1] _a : Any = name.split('''.''' ) _a : List[Any] = int(items[0] ) _a : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _a : Optional[int] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _a : Optional[Any] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _a : int = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _a : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__a ) @torch.no_grad() def __UpperCAmelCase ( __a : Dict ,__a : List[Any] ,__a : List[str]=None ,__a : Optional[int]=None ,__a : int=True ) -> List[Any]: """simple docstring""" if config_path is not None: _a : Tuple = HubertConfig.from_pretrained(__a ) else: _a : Any = HubertConfig() if is_finetuned: if dict_path: _a : Tuple = Dictionary.load(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a : Any = target_dict.pad_index _a : Tuple = target_dict.bos_index _a : Optional[int] = target_dict.eos_index _a : Optional[Any] = len(target_dict.symbols ) _a : Tuple = os.path.join(__a ,'''vocab.json''' ) if not os.path.isdir(__a ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__a ) ) return os.makedirs(__a ,exist_ok=__a ) with open(__a ,'''w''' ,encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices ,__a ) _a : Tuple = WavaVecaCTCTokenizer( __a ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token='''|''' ,do_lower_case=__a ,) _a : Tuple = True if config.feat_extract_norm == '''layer''' else False _a : List[Any] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__a ,return_attention_mask=__a ,) _a : List[Any] = WavaVecaProcessor(feature_extractor=__a ,tokenizer=__a ) processor.save_pretrained(__a ) _a : Tuple = HubertForCTC(__a ) else: _a : Tuple = HubertModel(__a ) if is_finetuned: _a , _a , _a : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: _a , _a , _a : str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _a : Any = model[0].eval() recursively_load_weights(__a ,__a ,__a ) hf_wavavec.save_pretrained(__a ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) a__ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
15
0
'''simple docstring''' from __future__ import annotations import pandas as pd def lowercase_ ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : List[str] = [0] * no_of_processes __UpperCAmelCase : Optional[Any] = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase__ ): __UpperCAmelCase : Union[str, Any] = burst_time[i] __UpperCAmelCase : Optional[int] = 0 __UpperCAmelCase : int = 0 __UpperCAmelCase : Tuple = 999999999 __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : Optional[int] = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase__ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __UpperCAmelCase : int = remaining_time[j] __UpperCAmelCase : Tuple = j __UpperCAmelCase : Union[str, Any] = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __UpperCAmelCase : Optional[int] = remaining_time[short] if minm == 0: __UpperCAmelCase : List[str] = 999999999 if remaining_time[short] == 0: complete += 1 __UpperCAmelCase : Tuple = False # Find finish time of current process __UpperCAmelCase : List[Any] = increment_time + 1 # Calculate waiting time __UpperCAmelCase : str = finish_time - arrival_time[short] __UpperCAmelCase : Any = finar - burst_time[short] if waiting_time[short] < 0: __UpperCAmelCase : List[str] = 0 # Increment time increment_time += 1 return waiting_time def lowercase_ ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] ): """simple docstring""" __UpperCAmelCase : int = [0] * no_of_processes for i in range(lowerCAmelCase__ ): __UpperCAmelCase : List[str] = burst_time[i] + waiting_time[i] return turn_around_time def lowercase_ ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Any = 0 __UpperCAmelCase : Tuple = 0 for i in range(lowerCAmelCase__ ): __UpperCAmelCase : Optional[int] = total_waiting_time + waiting_time[i] __UpperCAmelCase : Dict = total_turn_around_time + turn_around_time[i] print(f'Average waiting time = {total_waiting_time / no_of_processes:.5f}' ) print("""Average turn around time =""" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') _UpperCamelCase = int(input()) _UpperCamelCase = [0] * no_of_processes _UpperCamelCase = [0] * no_of_processes _UpperCamelCase = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) _UpperCamelCase , _UpperCamelCase = map(int, input().split()) _UpperCamelCase = calculate_waitingtime(arrival_time, burst_time, no_of_processes) _UpperCamelCase = burst_time _UpperCamelCase = no_of_processes _UpperCamelCase = waiting_time _UpperCamelCase = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) _UpperCamelCase = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
16
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _UpperCamelCase = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _SCREAMING_SNAKE_CASE : int = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _SCREAMING_SNAKE_CASE : int = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __UpperCAmelCase : List[Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : int = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __UpperCAmelCase : Optional[int] = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : Dict = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __UpperCAmelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' import torch __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = pipeline("""text-classification""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : Any = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = pipeline("""text-classification""" , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : int = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = TextClassificationPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) return text_classifier, ["HuggingFace is in", "This is another test"] def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : int = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __UpperCAmelCase : Union[str, Any] = """HuggingFace is in""" __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __UpperCAmelCase : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}, {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase , top_k=__UpperCAmelCase ) __UpperCAmelCase : Any = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N, [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N] , ) __UpperCAmelCase : str = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __UpperCAmelCase : Optional[int] = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __UpperCAmelCase : Union[str, Any] = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(__UpperCAmelCase ): text_classifier(__UpperCAmelCase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __UpperCAmelCase : Tuple = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
16
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowercase_ ( lowerCAmelCase__ : Optional[int] ): """simple docstring""" __UpperCAmelCase : Tuple = SwinvaConfig() __UpperCAmelCase : Dict = swinva_name.split("""_""" ) __UpperCAmelCase : List[str] = name_split[1] if "to" in name_split[3]: __UpperCAmelCase : Optional[int] = int(name_split[3][-3:] ) else: __UpperCAmelCase : Optional[int] = int(name_split[3] ) if "to" in name_split[2]: __UpperCAmelCase : Optional[int] = int(name_split[2][-2:] ) else: __UpperCAmelCase : Any = int(name_split[2][6:] ) if model_size == "tiny": __UpperCAmelCase : List[Any] = 96 __UpperCAmelCase : str = (2, 2, 6, 2) __UpperCAmelCase : Any = (3, 6, 12, 24) elif model_size == "small": __UpperCAmelCase : int = 96 __UpperCAmelCase : Any = (2, 2, 18, 2) __UpperCAmelCase : Optional[int] = (3, 6, 12, 24) elif model_size == "base": __UpperCAmelCase : Union[str, Any] = 128 __UpperCAmelCase : Any = (2, 2, 18, 2) __UpperCAmelCase : int = (4, 8, 16, 32) else: __UpperCAmelCase : int = 192 __UpperCAmelCase : Tuple = (2, 2, 18, 2) __UpperCAmelCase : Union[str, Any] = (6, 12, 24, 48) if "to" in swinva_name: __UpperCAmelCase : Dict = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): __UpperCAmelCase : Tuple = 21841 __UpperCAmelCase : Any = """huggingface/label-files""" __UpperCAmelCase : List[Any] = """imagenet-22k-id2label.json""" __UpperCAmelCase : Dict = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) __UpperCAmelCase : Union[str, Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __UpperCAmelCase : List[Any] = idalabel __UpperCAmelCase : Tuple = {v: k for k, v in idalabel.items()} else: __UpperCAmelCase : Optional[int] = 1000 __UpperCAmelCase : Optional[int] = """huggingface/label-files""" __UpperCAmelCase : str = """imagenet-1k-id2label.json""" __UpperCAmelCase : str = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) __UpperCAmelCase : int = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __UpperCAmelCase : Dict = idalabel __UpperCAmelCase : Optional[Any] = {v: k for k, v in idalabel.items()} __UpperCAmelCase : Union[str, Any] = img_size __UpperCAmelCase : Optional[Any] = num_classes __UpperCAmelCase : Dict = embed_dim __UpperCAmelCase : Union[str, Any] = depths __UpperCAmelCase : Dict = num_heads __UpperCAmelCase : Optional[int] = window_size return config def lowercase_ ( lowerCAmelCase__ : List[Any] ): """simple docstring""" if "patch_embed.proj" in name: __UpperCAmelCase : Union[str, Any] = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __UpperCAmelCase : str = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: __UpperCAmelCase : Optional[Any] = """encoder.""" + name if "attn.proj" in name: __UpperCAmelCase : int = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __UpperCAmelCase : Union[str, Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __UpperCAmelCase : List[Any] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __UpperCAmelCase : str = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __UpperCAmelCase : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __UpperCAmelCase : Union[str, Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "q_bias" in name: __UpperCAmelCase : Optional[Any] = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: __UpperCAmelCase : Optional[int] = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: __UpperCAmelCase : Any = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: __UpperCAmelCase : Optional[int] = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if name == "norm.weight": __UpperCAmelCase : Any = """layernorm.weight""" if name == "norm.bias": __UpperCAmelCase : List[Any] = """layernorm.bias""" if "head" in name: __UpperCAmelCase : Optional[int] = name.replace("""head""" , """classifier""" ) else: __UpperCAmelCase : Dict = """swinv2.""" + name return name def lowercase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int ): """simple docstring""" for key in orig_state_dict.copy().keys(): __UpperCAmelCase : str = orig_state_dict.pop(lowerCAmelCase__ ) if "mask" in key: continue elif "qkv" in key: __UpperCAmelCase : Any = key.split(""".""" ) __UpperCAmelCase : str = int(key_split[1] ) __UpperCAmelCase : Optional[int] = int(key_split[3] ) __UpperCAmelCase : Any = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __UpperCAmelCase : str = val[:dim, :] __UpperCAmelCase : Any = val[dim : dim * 2, :] __UpperCAmelCase : Union[str, Any] = val[-dim:, :] else: __UpperCAmelCase : int = val[:dim] __UpperCAmelCase : int = val[ dim : dim * 2 ] __UpperCAmelCase : Optional[int] = val[-dim:] else: __UpperCAmelCase : Optional[int] = val return orig_state_dict def lowercase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : str = timm.create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() __UpperCAmelCase : List[Any] = get_swinva_config(lowerCAmelCase__ ) __UpperCAmelCase : str = SwinvaForImageClassification(lowerCAmelCase__ ) model.eval() __UpperCAmelCase : Union[str, Any] = convert_state_dict(timm_model.state_dict() , lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) __UpperCAmelCase : Tuple = """http://images.cocodataset.org/val2017/000000039769.jpg""" __UpperCAmelCase : Optional[int] = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" , """-""" ) ) ) __UpperCAmelCase : int = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) __UpperCAmelCase : Tuple = image_processor(images=lowerCAmelCase__ , return_tensors="""pt""" ) __UpperCAmelCase : Dict = timm_model(inputs["""pixel_values"""] ) __UpperCAmelCase : str = model(**lowerCAmelCase__ ).logits assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) print(f'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase__ ) model.push_to_hub( repo_path_or_name=Path(lowerCAmelCase__ , lowerCAmelCase__ ) , organization="""nandwalritik""" , commit_message="""Add model""" , ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _UpperCamelCase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
16
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] )
16
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _UpperCamelCase = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''ChineseCLIPFeatureExtractor'''] _UpperCamelCase = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class _A : def __init__( self , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=64 , __UpperCAmelCase=None ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = np.random.default_rng(__UpperCAmelCase ) __UpperCAmelCase : List[str] = length __UpperCAmelCase : List[Any] = rng.normal(size=(length,) ).astype(np.floataa ) __UpperCAmelCase : Union[str, Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Dict: '''simple docstring''' return self.length def __getitem__( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> int: '''simple docstring''' super().__init__() __UpperCAmelCase : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Optional[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Any = True def __A ( self , __UpperCAmelCase=None ) -> str: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : Optional[int] = False return x * self.a[0] + self.b[0] class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> Optional[Any]: '''simple docstring''' super().__init__() __UpperCAmelCase : Tuple = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : List[str] = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : str = True def __A ( self , __UpperCAmelCase=None ) -> Tuple: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : int = False return x * self.a + self.b def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int = 16 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __UpperCAmelCase : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __UpperCAmelCase : List[str] = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} __UpperCAmelCase : Tuple = load_dataset("""csv""" , data_files=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = datasets["""train"""].unique("""label""" ) __UpperCAmelCase : str = {v: i for i, v in enumerate(lowerCAmelCase__ )} def tokenize_function(lowerCAmelCase__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __UpperCAmelCase : List[Any] = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding="""max_length""" ) if "label" in examples: __UpperCAmelCase : Optional[Any] = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __UpperCAmelCase : Tuple = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. __UpperCAmelCase : Optional[Any] = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=2 ) __UpperCAmelCase : List[Any] = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=1 ) return train_dataloader, eval_dataloader
16
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } _UpperCamelCase = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def lowercase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] ): """simple docstring""" for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __UpperCAmelCase : Any = """lm_head""" __UpperCAmelCase : int = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) if weight_type is not None: __UpperCAmelCase : str = getattr(lowerCAmelCase__ , lowerCAmelCase__ ).shape else: __UpperCAmelCase : str = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": __UpperCAmelCase : Union[str, Any] = value elif weight_type == "weight_g": __UpperCAmelCase : List[Any] = value elif weight_type == "weight_v": __UpperCAmelCase : Optional[Any] = value elif weight_type == "bias": __UpperCAmelCase : List[str] = value else: __UpperCAmelCase : Dict = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowercase_ ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Dict ): """simple docstring""" __UpperCAmelCase : List[Any] = [] __UpperCAmelCase : List[str] = fairseq_model.state_dict() __UpperCAmelCase : Tuple = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __UpperCAmelCase : Optional[int] = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , hf_model.config.feat_extract_norm == """group""" , ) __UpperCAmelCase : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): __UpperCAmelCase : Optional[Any] = """unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __UpperCAmelCase : Optional[int] = True if "*" in mapped_key: __UpperCAmelCase : List[str] = name.split(lowerCAmelCase__ )[0].split(""".""" )[-2] __UpperCAmelCase : List[Any] = mapped_key.replace("""*""" , lowerCAmelCase__ ) if "weight_g" in name: __UpperCAmelCase : int = """weight_g""" elif "weight_v" in name: __UpperCAmelCase : Union[str, Any] = """weight_v""" elif "bias" in name: __UpperCAmelCase : Optional[int] = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj __UpperCAmelCase : List[str] = """weight""" else: __UpperCAmelCase : int = None set_recursively(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(f'Unused weights: {unused_weights}' ) def lowercase_ ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict , lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : List[Any] = full_name.split("""conv_layers.""" )[-1] __UpperCAmelCase : str = name.split(""".""" ) __UpperCAmelCase : Dict = int(items[0] ) __UpperCAmelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) __UpperCAmelCase : Optional[int] = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) __UpperCAmelCase : int = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) __UpperCAmelCase : Union[str, Any] = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) __UpperCAmelCase : Dict = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowerCAmelCase__ ) @torch.no_grad() def lowercase_ ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : Any=True ): """simple docstring""" if config_path is not None: __UpperCAmelCase : str = UniSpeechConfig.from_pretrained(lowerCAmelCase__ ) else: __UpperCAmelCase : Any = UniSpeechConfig() if is_finetuned: if dict_path: __UpperCAmelCase : str = Dictionary.load_from_json(lowerCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCAmelCase : Union[str, Any] = target_dict.pad_index __UpperCAmelCase : Tuple = target_dict.bos_index __UpperCAmelCase : Tuple = target_dict.eos_index __UpperCAmelCase : Union[str, Any] = len(target_dict.symbols ) __UpperCAmelCase : Any = os.path.join(lowerCAmelCase__ , """vocab.json""" ) if not os.path.isdir(lowerCAmelCase__ ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowerCAmelCase__ ) ) return os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) __UpperCAmelCase : Any = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCAmelCase : Tuple = 42 __UpperCAmelCase : Optional[Any] = 43 with open(lowerCAmelCase__ , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : List[Any] = WavaVecaPhonemeCTCTokenizer( lowerCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowerCAmelCase__ , ) __UpperCAmelCase : str = True if config.feat_extract_norm == """layer""" else False __UpperCAmelCase : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) __UpperCAmelCase : List[Any] = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = UniSpeechForCTC(lowerCAmelCase__ ) else: __UpperCAmelCase : Dict = UniSpeechForPreTraining(lowerCAmelCase__ ) if is_finetuned: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __UpperCAmelCase : int = model[0].eval() recursively_load_weights(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) hf_unispeech.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) _UpperCamelCase = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ViTImageProcessor if is_vision_available() else None @property def __A ( self ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = (3, 32, 128) __UpperCAmelCase : Tuple = tempfile.mkdtemp() # fmt: off __UpperCAmelCase : Any = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __UpperCAmelCase : Optional[int] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) __UpperCAmelCase : List[Any] = { """do_normalize""": False, """do_resize""": True, """image_processor_type""": """ViTImageProcessor""", """resample""": 3, """size""": {"""height""": 32, """width""": 128}, } __UpperCAmelCase : Tuple = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __UpperCAmelCase : Dict = Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) return image_input def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.get_tokenizer() __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Tuple = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Dict = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __UpperCAmelCase : Union[str, Any] = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) __UpperCAmelCase : List[Any] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Tuple = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.prepare_image_inputs() __UpperCAmelCase : str = image_processor(__UpperCAmelCase , return_tensors="""np""" ) __UpperCAmelCase : int = processor(images=__UpperCAmelCase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : int = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Dict = """test""" __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Optional[int] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = """test""" __UpperCAmelCase : int = self.prepare_image_inputs() __UpperCAmelCase : Tuple = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """labels"""] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : List[str] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __UpperCAmelCase : Optional[Any] = processor.char_decode(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = tokenizer.batch_decode(__UpperCAmelCase ) __UpperCAmelCase : int = [seq.replace(""" """ , """""" ) for seq in decoded_tok] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : Any = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : str = None __UpperCAmelCase : Dict = self.prepare_image_inputs() __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Any = self.get_image_processor() __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : str = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = torch.randn(1 , 27 , 38 ) __UpperCAmelCase : Union[str, Any] = torch.randn(1 , 27 , 50_257 ) __UpperCAmelCase : Any = torch.randn(1 , 27 , 30_522 ) __UpperCAmelCase : Tuple = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["""generated_text""", """scores""", """char_preds""", """bpe_preds""", """wp_preds"""] )
16
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _UpperCamelCase = { '''vocab_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-german-cased''': ( '''https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json''' ), '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json''' ), }, } _UpperCamelCase = { '''distilbert-base-uncased''': 512, '''distilbert-base-uncased-distilled-squad''': 512, '''distilbert-base-cased''': 512, '''distilbert-base-cased-distilled-squad''': 512, '''distilbert-base-german-cased''': 512, '''distilbert-base-multilingual-cased''': 512, } _UpperCamelCase = { '''distilbert-base-uncased''': {'''do_lower_case''': True}, '''distilbert-base-uncased-distilled-squad''': {'''do_lower_case''': True}, '''distilbert-base-cased''': {'''do_lower_case''': False}, '''distilbert-base-cased-distilled-squad''': {'''do_lower_case''': False}, '''distilbert-base-german-cased''': {'''do_lower_case''': False}, '''distilbert-base-multilingual-cased''': {'''do_lower_case''': False}, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE : str = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : Any = DistilBertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Union[str, Any]: '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCAmelCase ) != tokenize_chinese_chars ): __UpperCAmelCase : Tuple = getattr(__UpperCAmelCase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : Optional[Any] = do_lower_case __UpperCAmelCase : Dict = strip_accents __UpperCAmelCase : int = tokenize_chinese_chars __UpperCAmelCase : Union[str, Any] = normalizer_class(**__UpperCAmelCase ) __UpperCAmelCase : Tuple = do_lower_case def __A ( self , __UpperCAmelCase , __UpperCAmelCase=None ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : str = [self.sep_token_id] __UpperCAmelCase : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' __UpperCAmelCase : str = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
16
'''simple docstring''' from collections.abc import Sequence def lowercase_ ( lowerCAmelCase__ : Sequence[int] | None = None ): """simple docstring""" if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) __UpperCAmelCase : Any = nums[0] for i in range(1 , len(lowerCAmelCase__ ) ): __UpperCAmelCase : Union[str, Any] = nums[i] __UpperCAmelCase : List[Any] = max(lowerCAmelCase__ , ans + num , lowerCAmelCase__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _UpperCamelCase = int(input('''Enter number of elements : ''').strip()) _UpperCamelCase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n] print(max_subsequence_sum(array))
16
1
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging _UpperCamelCase = logging.get_logger(__name__) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : int = ["input_features", "attention_mask"] def __init__( self , __UpperCAmelCase=80 , __UpperCAmelCase=16_000 , __UpperCAmelCase=80 , __UpperCAmelCase=0.0 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , **__UpperCAmelCase , ) -> Optional[Any]: '''simple docstring''' super().__init__(feature_size=__UpperCAmelCase , sampling_rate=__UpperCAmelCase , padding_value=__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : List[Any] = num_mel_bins __UpperCAmelCase : List[str] = do_ceptral_normalize __UpperCAmelCase : int = normalize_means __UpperCAmelCase : str = normalize_vars __UpperCAmelCase : Optional[Any] = True def __A ( self , __UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Tuple = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __UpperCAmelCase : Dict = torch.from_numpy(__UpperCAmelCase ).unsqueeze(0 ) __UpperCAmelCase : Optional[Any] = ta_kaldi.fbank(__UpperCAmelCase , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def __A ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = 0.0 , ) -> np.ndarray: '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __UpperCAmelCase : Optional[Any] = x[:input_length].mean(axis=0 ) __UpperCAmelCase : Optional[int] = np.subtract(__UpperCAmelCase , __UpperCAmelCase ) if normalize_vars: __UpperCAmelCase : str = x[:input_length].std(axis=0 ) __UpperCAmelCase : Tuple = np.divide(__UpperCAmelCase , __UpperCAmelCase ) if input_length < x.shape[0]: __UpperCAmelCase : Any = padding_value # make sure array is in float32 __UpperCAmelCase : Dict = x.astype(np.floataa ) return x def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[np.ndarray]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(__UpperCAmelCase , __UpperCAmelCase , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(__UpperCAmelCase , __UpperCAmelCase ) ] def __call__( self , __UpperCAmelCase , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) __UpperCAmelCase : Optional[Any] = isinstance(__UpperCAmelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __UpperCAmelCase : Optional[Any] = is_batched_numpy or ( isinstance(__UpperCAmelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __UpperCAmelCase : Union[str, Any] = [np.asarray(__UpperCAmelCase , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__UpperCAmelCase , np.ndarray ): __UpperCAmelCase : Optional[Any] = np.asarray(__UpperCAmelCase , dtype=np.floataa ) elif isinstance(__UpperCAmelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __UpperCAmelCase : Optional[Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __UpperCAmelCase : List[Any] = [raw_speech] # extract fbank features __UpperCAmelCase : Dict = [self._extract_fbank_features(__UpperCAmelCase ) for waveform in raw_speech] # convert into correct format for padding __UpperCAmelCase : str = BatchFeature({"""input_features""": features} ) __UpperCAmelCase : List[str] = self.pad( __UpperCAmelCase , padding=__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , **__UpperCAmelCase , ) # make sure list is in array format __UpperCAmelCase : Union[str, Any] = padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , __UpperCAmelCase ): __UpperCAmelCase : Any = [np.asarray(__UpperCAmelCase , dtype=np.floataa ) for feature in input_features] __UpperCAmelCase : Tuple = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: __UpperCAmelCase : Any = [np.asarray(__UpperCAmelCase , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __UpperCAmelCase : Optional[int] = ( np.array(__UpperCAmelCase , dtype=np.intaa ) if self._get_padding_strategies(__UpperCAmelCase , max_length=__UpperCAmelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __UpperCAmelCase : Union[str, Any] = self.normalize( padded_inputs["""input_features"""] , attention_mask=__UpperCAmelCase ) if return_tensors is not None: __UpperCAmelCase : Dict = padded_inputs.convert_to_tensors(__UpperCAmelCase ) return padded_inputs
16
'''simple docstring''' class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : int = data __UpperCAmelCase : int = previous __UpperCAmelCase : Union[str, Any] = next_node def __str__( self ) -> str: '''simple docstring''' return f'{self.data}' def __A ( self ) -> int: '''simple docstring''' return self.data def __A ( self ) -> List[str]: '''simple docstring''' return self.next def __A ( self ) -> str: '''simple docstring''' return self.previous class _A : def __init__( self , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = head def __iter__( self ) -> str: '''simple docstring''' return self def __A ( self ) -> str: '''simple docstring''' if not self.current: raise StopIteration else: __UpperCAmelCase : List[str] = self.current.get_data() __UpperCAmelCase : int = self.current.get_next() return value class _A : def __init__( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = None # First node in list __UpperCAmelCase : List[str] = None # Last node in list def __str__( self ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = self.head __UpperCAmelCase : Optional[int] = [] while current is not None: nodes.append(current.get_data() ) __UpperCAmelCase : Any = current.get_next() return " ".join(str(__UpperCAmelCase ) for node in nodes ) def __contains__( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.head while current: if current.get_data() == value: return True __UpperCAmelCase : Optional[Any] = current.get_next() return False def __iter__( self ) -> str: '''simple docstring''' return LinkedListIterator(self.head ) def __A ( self ) -> List[Any]: '''simple docstring''' if self.head: return self.head.get_data() return None def __A ( self ) -> Optional[Any]: '''simple docstring''' if self.tail: return self.tail.get_data() return None def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: __UpperCAmelCase : str = node __UpperCAmelCase : List[str] = node else: self.insert_before_node(self.head , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: self.set_head(__UpperCAmelCase ) else: self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[int] = Node(__UpperCAmelCase ) if self.head is None: self.set_head(__UpperCAmelCase ) else: self.set_tail(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Tuple = node __UpperCAmelCase : List[Any] = node.previous if node.get_previous() is None: __UpperCAmelCase : str = node_to_insert else: __UpperCAmelCase : Optional[Any] = node_to_insert __UpperCAmelCase : List[Any] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : List[str] = node __UpperCAmelCase : Union[str, Any] = node.next if node.get_next() is None: __UpperCAmelCase : Dict = node_to_insert else: __UpperCAmelCase : Any = node_to_insert __UpperCAmelCase : List[str] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Optional[Any] = Node(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.head while node: if current_position == position: self.insert_before_node(__UpperCAmelCase , __UpperCAmelCase ) return current_position += 1 __UpperCAmelCase : int = node.next self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Node: '''simple docstring''' __UpperCAmelCase : Dict = self.head while node: if node.get_data() == item: return node __UpperCAmelCase : List[str] = node.get_next() raise Exception("""Node not found""" ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' if (node := self.get_node(__UpperCAmelCase )) is not None: if node == self.head: __UpperCAmelCase : Optional[int] = self.head.get_next() if node == self.tail: __UpperCAmelCase : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(__UpperCAmelCase ) @staticmethod def __A ( __UpperCAmelCase ) -> None: '''simple docstring''' if node.get_next(): __UpperCAmelCase : Optional[Any] = node.previous if node.get_previous(): __UpperCAmelCase : int = node.next __UpperCAmelCase : Tuple = None __UpperCAmelCase : Union[str, Any] = None def __A ( self ) -> List[Any]: '''simple docstring''' return self.head is None def lowercase_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
16
1
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : int = MvpTokenizer _SCREAMING_SNAKE_CASE : Optional[Any] = MvpTokenizerFast _SCREAMING_SNAKE_CASE : List[Any] = True _SCREAMING_SNAKE_CASE : Any = filter_roberta_detectors def __A ( self ) -> Dict: '''simple docstring''' super().setUp() __UpperCAmelCase : Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __UpperCAmelCase : Any = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : List[str] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __UpperCAmelCase : str = {"""unk_token""": """<unk>"""} __UpperCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __UpperCAmelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__UpperCAmelCase ) ) def __A ( self , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> str: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> str: '''simple docstring''' return "lower newer", "lower newer" @cached_property def __A ( self ) -> int: '''simple docstring''' return MvpTokenizer.from_pretrained("""RUCAIBox/mvp""" ) @cached_property def __A ( self ) -> Optional[int]: '''simple docstring''' return MvpTokenizerFast.from_pretrained("""RUCAIBox/mvp""" ) @require_torch def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : List[str] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __UpperCAmelCase : int = [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __UpperCAmelCase : str = tokenizer(__UpperCAmelCase , max_length=len(__UpperCAmelCase ) , padding=__UpperCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __UpperCAmelCase : int = batch.input_ids.tolist()[0] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Test that special tokens are reset @require_torch def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Optional[Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __UpperCAmelCase : Tuple = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors="""pt""" ) # check if input_ids are returned and no labels self.assertIn("""input_ids""" , __UpperCAmelCase ) self.assertIn("""attention_mask""" , __UpperCAmelCase ) self.assertNotIn("""labels""" , __UpperCAmelCase ) self.assertNotIn("""decoder_attention_mask""" , __UpperCAmelCase ) @require_torch def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __UpperCAmelCase : Union[str, Any] = tokenizer(text_target=__UpperCAmelCase , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __UpperCAmelCase : List[str] = tokenizer( ["""I am a small frog""" * 1_024, """I am a small frog"""] , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(batch.input_ids.shape , (2, 1_024) ) @require_torch def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : str = ["""A long paragraph for summarization."""] __UpperCAmelCase : List[Any] = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __UpperCAmelCase : Optional[int] = tokenizer(__UpperCAmelCase , text_target=__UpperCAmelCase , return_tensors="""pt""" ) __UpperCAmelCase : List[str] = inputs["""input_ids"""] __UpperCAmelCase : Tuple = inputs["""labels"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def __A ( self ) -> Optional[int]: '''simple docstring''' pass def __A ( self ) -> str: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCAmelCase : List[str] = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : Dict = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : int = """A, <mask> AllenNLP sentence.""" __UpperCAmelCase : Tuple = tokenizer_r.encode_plus(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = tokenizer_p.encode_plus(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __UpperCAmelCase : str = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __UpperCAmelCase : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual( __UpperCAmelCase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __UpperCAmelCase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
16
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class _A : _SCREAMING_SNAKE_CASE : List[str] _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="Translation" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ) -> Any: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class _A : _SCREAMING_SNAKE_CASE : Optional[List] = None _SCREAMING_SNAKE_CASE : Optional[int] = None _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="TranslationVariableLanguages" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = sorted(set(self.languages ) ) if self.languages else None __UpperCAmelCase : int = len(self.languages ) if self.languages else None def __call__( self ) -> Optional[Any]: '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def __A ( self , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = set(self.languages ) if self.languages and set(__UpperCAmelCase ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(__UpperCAmelCase ) - lang_set ) )}) are not in valid set ({", ".join(__UpperCAmelCase )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __UpperCAmelCase : Dict = [] for lang, text in translation_dict.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = zip(*sorted(__UpperCAmelCase ) ) return {"language": languages, "translation": translations} def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
16
1
'''simple docstring''' import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy _UpperCamelCase = logging.getLogger(__name__) def lowercase_ ( lowerCAmelCase__ : torch.nn.Module , lowerCAmelCase__ : BnbQuantizationConfig , lowerCAmelCase__ : Union[str, os.PathLike] = None , lowerCAmelCase__ : Optional[Dict[str, Union[int, str, torch.device]]] = None , lowerCAmelCase__ : Optional[List[str]] = None , lowerCAmelCase__ : Optional[Dict[Union[int, str], Union[int, str]]] = None , lowerCAmelCase__ : Optional[Union[str, os.PathLike]] = None , lowerCAmelCase__ : bool = False , ): """simple docstring""" __UpperCAmelCase : Optional[Any] = bnb_quantization_config.load_in_abit __UpperCAmelCase : int = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) __UpperCAmelCase : Tuple = [] # custom device map if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(device_map.keys() ) > 1: __UpperCAmelCase : List[str] = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: __UpperCAmelCase : str = get_keys_to_not_convert(lowerCAmelCase__ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowerCAmelCase__ ) __UpperCAmelCase : Any = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: __UpperCAmelCase : Dict = [] __UpperCAmelCase : int = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowerCAmelCase__ ) # compatibility with peft __UpperCAmelCase : str = load_in_abit __UpperCAmelCase : Optional[Any] = load_in_abit __UpperCAmelCase : Dict = get_parameter_device(lowerCAmelCase__ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) __UpperCAmelCase : Dict = replace_with_bnb_layers(lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ ) # convert param to the right dtype __UpperCAmelCase : Any = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: __UpperCAmelCase : Union[str, Any] = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) __UpperCAmelCase : Optional[int] = getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowerCAmelCase__ ): param.to(lowerCAmelCase__ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f'The model device type is {model_device.type}. However, cuda is needed for quantization.' """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): __UpperCAmelCase : Union[str, Any] = replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ ) __UpperCAmelCase : List[Any] = get_quantized_model_device_map( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , max_memory=lowerCAmelCase__ , no_split_module_classes=lowerCAmelCase__ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): __UpperCAmelCase : Dict = True __UpperCAmelCase : List[str] = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowerCAmelCase__ , offload_state_dict=lowerCAmelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(lowerCAmelCase__ , device_map=lowerCAmelCase__ , offload_dir=lowerCAmelCase__ ) def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Tuple=None , lowerCAmelCase__ : List[Any]=None ): """simple docstring""" if device_map is None: if torch.cuda.is_available(): __UpperCAmelCase : Tuple = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) __UpperCAmelCase : Any = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) __UpperCAmelCase : Tuple = {} __UpperCAmelCase : str = special_dtypes __UpperCAmelCase : int = no_split_module_classes __UpperCAmelCase : List[str] = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": __UpperCAmelCase : List[str] = get_balanced_memory( lowerCAmelCase__ , low_zero=(device_map == """balanced_low_0""") , max_memory=lowerCAmelCase__ , **lowerCAmelCase__ , ) __UpperCAmelCase : Any = max_memory __UpperCAmelCase : Union[str, Any] = infer_auto_device_map(lowerCAmelCase__ , **lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): # check if don't have any quantized module on the cpu __UpperCAmelCase : Any = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules __UpperCAmelCase : Union[str, Any] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int]=None , lowerCAmelCase__ : str=None ): """simple docstring""" if modules_to_not_convert is None: __UpperCAmelCase : str = [] __UpperCAmelCase , __UpperCAmelCase : Dict = _replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : Dict=None , ): """simple docstring""" __UpperCAmelCase : Any = False for name, module in model.named_children(): if current_key_name is None: __UpperCAmelCase : str = [] current_key_name.append(lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` __UpperCAmelCase : List[Any] = """.""".join(lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: __UpperCAmelCase : Optional[Any] = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: __UpperCAmelCase : List[str] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowerCAmelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: __UpperCAmelCase : Any = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) __UpperCAmelCase : Optional[Any] = module.weight.data if module.bias is not None: __UpperCAmelCase : Dict = module.bias.data bnb_module.requires_grad_(lowerCAmelCase__ ) setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : str = True if len(list(module.children() ) ) > 0: __UpperCAmelCase , __UpperCAmelCase : Any = _replace_with_bnb_layers( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : List[Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" with init_empty_weights(): __UpperCAmelCase : Optional[Any] = deepcopy(lowerCAmelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` __UpperCAmelCase : str = find_tied_parameters(lowerCAmelCase__ ) # For compatibility with Accelerate < 0.18 if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __UpperCAmelCase : Union[str, Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: __UpperCAmelCase : Any = sum(lowerCAmelCase__ , [] ) __UpperCAmelCase : Dict = len(lowerCAmelCase__ ) > 0 # Check if it is a base model __UpperCAmelCase : Optional[Any] = False if hasattr(lowerCAmelCase__ , """base_model_prefix""" ): __UpperCAmelCase : Optional[Any] = not hasattr(lowerCAmelCase__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head __UpperCAmelCase : Union[str, Any] = list(model.named_children() ) __UpperCAmelCase : Tuple = [list_modules[-1][0]] # add last module together with tied weights __UpperCAmelCase : int = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) __UpperCAmelCase : Dict = list(set(lowerCAmelCase__ ) ) + list(lowerCAmelCase__ ) # remove ".weight" from the keys __UpperCAmelCase : Tuple = [""".weight""", """.bias"""] __UpperCAmelCase : List[str] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: __UpperCAmelCase : Dict = name.replace(lowerCAmelCase__ , """""" ) filtered_module_names.append(lowerCAmelCase__ ) return filtered_module_names def lowercase_ ( lowerCAmelCase__ : Tuple ): """simple docstring""" for m in model.modules(): if isinstance(lowerCAmelCase__ , bnb.nn.Linearabit ): return True return False def lowercase_ ( lowerCAmelCase__ : nn.Module ): """simple docstring""" return next(parameter.parameters() ).device def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 0 , dtype=lowerCAmelCase__ , value=lowerCAmelCase__ ) __UpperCAmelCase : Any = param_name __UpperCAmelCase : Union[str, Any] = model if "." in tensor_name: __UpperCAmelCase : Any = tensor_name.split(""".""" ) for split in splits[:-1]: __UpperCAmelCase : Optional[int] = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) if new_module is None: raise ValueError(f'{module} has no attribute {split}.' ) __UpperCAmelCase : Any = new_module __UpperCAmelCase : Tuple = splits[-1] # offload weights __UpperCAmelCase : List[str] = False offload_weight(module._parameters[tensor_name] , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , lowerCAmelCase__ , index=lowerCAmelCase__ , ) else: offload_weight(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ ) offload_weight(lowerCAmelCase__ , param_name.replace("""weight""" , """SCB""" ) , lowerCAmelCase__ , index=lowerCAmelCase__ ) set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , """meta""" , dtype=lowerCAmelCase__ , value=torch.empty(*param.size() ) )
16
'''simple docstring''' from statistics import mean import numpy as np def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Tuple = 0 # Number of processes finished __UpperCAmelCase : Optional[int] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. __UpperCAmelCase : Tuple = [0] * no_of_process # List to include calculation results __UpperCAmelCase : int = [0] * no_of_process # Sort by arrival time. __UpperCAmelCase : Dict = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] __UpperCAmelCase : Union[str, Any] = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: __UpperCAmelCase : Dict = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: __UpperCAmelCase : Any = arrival_time[i] __UpperCAmelCase : Any = 0 # Index showing the location of the process being performed __UpperCAmelCase : Any = 0 # Saves the current response ratio. __UpperCAmelCase : List[str] = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: __UpperCAmelCase : Dict = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: __UpperCAmelCase : Tuple = temp __UpperCAmelCase : List[str] = i # Calculate the turn around time __UpperCAmelCase : Tuple = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. __UpperCAmelCase : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[int] = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): __UpperCAmelCase : List[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _UpperCamelCase = 5 _UpperCamelCase = ['''A''', '''B''', '''C''', '''D''', '''E'''] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _UpperCamelCase = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
16
1
'''simple docstring''' from math import loga def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("""Input value must be a 'int' type""" ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=2 , __UpperCAmelCase=8 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=16 , __UpperCAmelCase=5 , __UpperCAmelCase=2 , __UpperCAmelCase=36 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = parent __UpperCAmelCase : Any = batch_size __UpperCAmelCase : Union[str, Any] = seq_length __UpperCAmelCase : int = is_training __UpperCAmelCase : Union[str, Any] = use_input_mask __UpperCAmelCase : List[str] = use_token_type_ids __UpperCAmelCase : List[str] = use_labels __UpperCAmelCase : Optional[Any] = vocab_size __UpperCAmelCase : Tuple = hidden_size __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : Optional[int] = num_attention_heads __UpperCAmelCase : str = intermediate_size __UpperCAmelCase : List[Any] = hidden_act __UpperCAmelCase : Optional[Any] = hidden_dropout_prob __UpperCAmelCase : List[Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[Any] = max_position_embeddings __UpperCAmelCase : List[Any] = type_vocab_size __UpperCAmelCase : Dict = type_sequence_label_size __UpperCAmelCase : Optional[Any] = initializer_range __UpperCAmelCase : Optional[Any] = num_labels __UpperCAmelCase : Optional[Any] = num_choices __UpperCAmelCase : int = scope def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : List[Any] = None if self.use_input_mask: __UpperCAmelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Any = None if self.use_token_type_ids: __UpperCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Tuple = None __UpperCAmelCase : Optional[int] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ) -> List[str]: '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_config() __UpperCAmelCase : List[Any] = 300 return config def __A ( self ) -> Dict: '''simple docstring''' ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = self.prepare_config_and_inputs() __UpperCAmelCase : Tuple = True __UpperCAmelCase : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = MraModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[str] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : Any = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : List[str] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : List[str] = True __UpperCAmelCase : List[Any] = MraModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) __UpperCAmelCase : List[Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Any = MraForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[int] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: '''simple docstring''' __UpperCAmelCase : str = MraForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[Any] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = self.num_labels __UpperCAmelCase : int = MraForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = self.num_labels __UpperCAmelCase : str = MraForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = self.num_choices __UpperCAmelCase : int = MraForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[str] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : List[Any] = config_and_inputs __UpperCAmelCase : Tuple = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : int = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Dict = () def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = MraModelTester(self ) __UpperCAmelCase : Optional[Any] = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __A ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : List[Any] = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Any: '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Tuple = MraModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip(reason="""MRA does not output attentions""" ) def __A ( self ) -> List[Any]: '''simple docstring''' return @require_torch class _A ( unittest.TestCase ): @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Tuple = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : str = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : List[Any] = model(__UpperCAmelCase )[0] __UpperCAmelCase : Optional[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : Union[str, Any] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : int = model(__UpperCAmelCase )[0] __UpperCAmelCase : Union[str, Any] = 50_265 __UpperCAmelCase : Union[str, Any] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) __UpperCAmelCase : Dict = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : Any = model(__UpperCAmelCase )[0] __UpperCAmelCase : Dict = 50_265 __UpperCAmelCase : Optional[int] = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : str = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _UpperCamelCase = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'transformer.encoder.layers.{i}.self_attn.out_proj.weight', F'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (F'transformer.encoder.layers.{i}.self_attn.out_proj.bias', F'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'encoder.layers.{i}.fc1.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'encoder.layers.{i}.fc1.bias')) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'encoder.layers.{i}.fc2.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'encoder.layers.{i}.fc2.bias')) rename_keys.append( (F'transformer.encoder.layers.{i}.norm1.weight', F'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', F'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', F'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'decoder.layers.{i}.fc1.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'decoder.layers.{i}.fc1.bias')) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'decoder.layers.{i}.fc2.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'decoder.layers.{i}.fc2.bias')) rename_keys.append( (F'transformer.decoder.layers.{i}.norm1.weight', F'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.weight', F'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.bias', F'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('''input_proj.weight''', '''input_projection.weight'''), ('''input_proj.bias''', '''input_projection.bias'''), ('''query_embed.weight''', '''query_position_embeddings.weight'''), ('''transformer.encoder.norm.weight''', '''encoder.layernorm.weight'''), ('''transformer.encoder.norm.bias''', '''encoder.layernorm.bias'''), ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''), ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''), ('''class_embed.weight''', '''class_labels_classifier.weight'''), ('''class_embed.bias''', '''class_labels_classifier.bias'''), ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''), ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''), ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''), ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''), ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''), ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''), ] ) def lowercase_ ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" __UpperCAmelCase : int = state_dict.pop(lowerCAmelCase__ ) __UpperCAmelCase : List[Any] = val def lowercase_ ( lowerCAmelCase__ : Union[str, Any] ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: __UpperCAmelCase : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) __UpperCAmelCase : str = value else: __UpperCAmelCase : List[str] = value return new_state_dict def lowercase_ ( lowerCAmelCase__ : Union[str, Any] ): """simple docstring""" __UpperCAmelCase : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) __UpperCAmelCase : Tuple = state_dict.pop(f'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight' ) __UpperCAmelCase : int = state_dict.pop(f'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict __UpperCAmelCase : Union[str, Any] = in_proj_weight[:256, :] __UpperCAmelCase : Optional[Any] = in_proj_bias[:256] __UpperCAmelCase : Optional[int] = in_proj_weight[256:512, :] __UpperCAmelCase : Optional[Any] = in_proj_bias[256:512] __UpperCAmelCase : List[Any] = in_proj_weight[-256:, :] __UpperCAmelCase : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention __UpperCAmelCase : Tuple = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight' ) __UpperCAmelCase : Optional[int] = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict __UpperCAmelCase : Tuple = in_proj_weight[:256, :] __UpperCAmelCase : Optional[int] = in_proj_bias[:256] __UpperCAmelCase : str = in_proj_weight[256:512, :] __UpperCAmelCase : str = in_proj_bias[256:512] __UpperCAmelCase : Optional[int] = in_proj_weight[-256:, :] __UpperCAmelCase : List[Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention __UpperCAmelCase : List[str] = state_dict.pop( f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight' ) __UpperCAmelCase : Optional[int] = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) of cross-attention to the state dict __UpperCAmelCase : Optional[Any] = in_proj_weight_cross_attn[:256, :] __UpperCAmelCase : List[Any] = in_proj_bias_cross_attn[:256] __UpperCAmelCase : List[Any] = in_proj_weight_cross_attn[256:512, :] __UpperCAmelCase : List[Any] = in_proj_bias_cross_attn[256:512] __UpperCAmelCase : Any = in_proj_weight_cross_attn[-256:, :] __UpperCAmelCase : Optional[Any] = in_proj_bias_cross_attn[-256:] def lowercase_ ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = image.size __UpperCAmelCase : Optional[Any] = max(lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : Dict = 800 if """detection""" in checkpoint_url else 1000 __UpperCAmelCase : Optional[int] = target_max_size / current_max_size __UpperCAmelCase : List[str] = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def lowercase_ ( lowerCAmelCase__ : Union[str, Any] ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = F.to_tensor(lowerCAmelCase__ ) __UpperCAmelCase : str = F.normalize(lowerCAmelCase__ , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" logger.info("""Converting model...""" ) # load original state dict __UpperCAmelCase : Any = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : Tuple = rename_backbone_keys(lowerCAmelCase__ ) # query, key and value matrices need special treatment read_in_q_k_v(lowerCAmelCase__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them __UpperCAmelCase : Tuple = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): __UpperCAmelCase : Union[str, Any] = state_dict.pop(lowerCAmelCase__ ) __UpperCAmelCase : Dict = val # create HuggingFace model and load state dict __UpperCAmelCase : Union[str, Any] = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: __UpperCAmelCase : List[str] = 15 __UpperCAmelCase : Union[str, Any] = 2 __UpperCAmelCase : str = {0: """table""", 1: """table rotated"""} __UpperCAmelCase : List[Any] = idalabel __UpperCAmelCase : int = {v: k for k, v in idalabel.items()} else: __UpperCAmelCase : Optional[Any] = 125 __UpperCAmelCase : Any = 6 __UpperCAmelCase : Dict = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } __UpperCAmelCase : Any = idalabel __UpperCAmelCase : int = {v: k for k, v in idalabel.items()} __UpperCAmelCase : str = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) __UpperCAmelCase : Optional[Any] = TableTransformerForObjectDetection(lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) model.eval() # verify our conversion __UpperCAmelCase : str = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" __UpperCAmelCase : List[Any] = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = Image.open(lowerCAmelCase__ ).convert("""RGB""" ) __UpperCAmelCase : int = normalize(resize(lowerCAmelCase__ , lowerCAmelCase__ ) ).unsqueeze(0 ) __UpperCAmelCase : Dict = model(lowerCAmelCase__ ) if "detection" in checkpoint_url: __UpperCAmelCase : Optional[int] = (1, 15, 3) __UpperCAmelCase : Optional[int] = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) __UpperCAmelCase : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: __UpperCAmelCase : List[str] = (1, 125, 7) __UpperCAmelCase : Dict = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) __UpperCAmelCase : Any = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , lowerCAmelCase__ , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , lowerCAmelCase__ , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) image_processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) __UpperCAmelCase : Tuple = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(lowerCAmelCase__ ) image_processor.push_to_hub(lowerCAmelCase__ ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''', type=str, choices=[ '''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''', '''https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth''', ], help='''URL of the Table Transformer checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _UpperCamelCase = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
16
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=32 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=16 , __UpperCAmelCase=[1, 2, 1] , __UpperCAmelCase=[2, 2, 4] , __UpperCAmelCase=2 , __UpperCAmelCase=2.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=10 , __UpperCAmelCase=8 , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = parent __UpperCAmelCase : Union[str, Any] = batch_size __UpperCAmelCase : Any = image_size __UpperCAmelCase : Dict = patch_size __UpperCAmelCase : Dict = num_channels __UpperCAmelCase : List[Any] = embed_dim __UpperCAmelCase : str = depths __UpperCAmelCase : Dict = num_heads __UpperCAmelCase : str = window_size __UpperCAmelCase : int = mlp_ratio __UpperCAmelCase : Union[str, Any] = qkv_bias __UpperCAmelCase : Dict = hidden_dropout_prob __UpperCAmelCase : str = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = drop_path_rate __UpperCAmelCase : List[str] = hidden_act __UpperCAmelCase : Optional[int] = use_absolute_embeddings __UpperCAmelCase : Any = patch_norm __UpperCAmelCase : Union[str, Any] = layer_norm_eps __UpperCAmelCase : Optional[int] = initializer_range __UpperCAmelCase : Tuple = is_training __UpperCAmelCase : Any = scope __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : Optional[int] = type_sequence_label_size __UpperCAmelCase : int = encoder_stride def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase : Tuple = None if self.use_labels: __UpperCAmelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __A ( self ) -> Dict: '''simple docstring''' return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase ) __UpperCAmelCase : Tuple = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Any = SwinvaForMaskedImageModeling(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model(__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Dict = SwinvaForMaskedImageModeling(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase : str = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = self.type_sequence_label_size __UpperCAmelCase : str = SwinvaForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Any = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = config_and_inputs __UpperCAmelCase : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : List[str] = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : List[str] = SwinvaModelTester(self ) __UpperCAmelCase : Any = ConfigTester(self , config_class=__UpperCAmelCase , embed_dim=37 ) def __A ( self ) -> Any: '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def __A ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def __A ( self ) -> Dict: '''simple docstring''' pass def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Tuple = model_class(__UpperCAmelCase ) __UpperCAmelCase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : str = [*signature.parameters.keys()] __UpperCAmelCase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[Any] = True for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : int = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : str = outputs.attentions __UpperCAmelCase : Any = len(self.model_tester.depths ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase : Dict = True __UpperCAmelCase : int = config.window_size**2 __UpperCAmelCase : Any = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : int = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : Dict = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase : Dict = len(__UpperCAmelCase ) # Check attention is always last and order is fine __UpperCAmelCase : Any = True __UpperCAmelCase : Any = True __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[str] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase : Any = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase : Optional[int] = 2 self.assertEqual(out_len + added_hidden_states , len(__UpperCAmelCase ) ) __UpperCAmelCase : Tuple = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : List[Any] = outputs.hidden_states __UpperCAmelCase : List[Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # Swinv2 has a different seq_length __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase : int = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : str = reshaped_hidden_states[0].shape __UpperCAmelCase : Any = ( reshaped_hidden_states[0].view(__UpperCAmelCase , __UpperCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = 3 __UpperCAmelCase : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase : Union[str, Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase : int = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Tuple = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Dict = SwinvaModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = _config_zero_init(__UpperCAmelCase ) for model_class in self.all_model_classes: __UpperCAmelCase : List[Any] = model_class(config=__UpperCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class _A ( unittest.TestCase ): @cached_property def __A ( self ) -> int: '''simple docstring''' return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __UpperCAmelCase ) __UpperCAmelCase : Tuple = self.default_image_processor __UpperCAmelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase : Any = image_processor(images=__UpperCAmelCase , return_tensors="""pt""" ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): __UpperCAmelCase : Optional[int] = model(**__UpperCAmelCase ) # verify the logits __UpperCAmelCase : int = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["torch", "torchsde"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def __A ( cls , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def __A ( cls , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(cls , ["""torch""", """torchsde"""] )
16
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase__ ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : int = size if size is not None else {"""shortest_edge""": 256} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) __UpperCAmelCase : int = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : Any = do_center_crop __UpperCAmelCase : Any = crop_size __UpperCAmelCase : Optional[Any] = resample __UpperCAmelCase : Dict = do_rescale __UpperCAmelCase : List[str] = rescale_factor __UpperCAmelCase : Dict = offset __UpperCAmelCase : List[str] = do_normalize __UpperCAmelCase : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __UpperCAmelCase : str = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : List[str] = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" in size: __UpperCAmelCase : Union[str, Any] = get_resize_output_image_size(__UpperCAmelCase , size["""shortest_edge"""] , default_to_square=__UpperCAmelCase ) elif "height" in size and "width" in size: __UpperCAmelCase : Any = (size["""height"""], size["""width"""]) else: raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}' ) return resize(__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Any = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}' ) return center_crop(__UpperCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = image.astype(np.floataa ) if offset: __UpperCAmelCase : Tuple = image - (scale / 2) return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Optional[Any] = to_numpy_array(__UpperCAmelCase ) if do_resize: __UpperCAmelCase : Optional[int] = self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase ) if do_center_crop: __UpperCAmelCase : Optional[int] = self.center_crop(__UpperCAmelCase , size=__UpperCAmelCase ) if do_rescale: __UpperCAmelCase : int = self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase , offset=__UpperCAmelCase ) if do_normalize: __UpperCAmelCase : List[str] = self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) return image def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: '''simple docstring''' __UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : List[Any] = resample if resample is not None else self.resample __UpperCAmelCase : str = do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCAmelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCAmelCase : List[Any] = offset if offset is not None else self.offset __UpperCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Optional[Any] = image_mean if image_mean is not None else self.image_mean __UpperCAmelCase : int = image_std if image_std is not None else self.image_std __UpperCAmelCase : Any = size if size is not None else self.size __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size __UpperCAmelCase : str = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) __UpperCAmelCase : int = make_batched(__UpperCAmelCase ) __UpperCAmelCase : Tuple = [ [ self._preprocess_image( image=__UpperCAmelCase , do_resize=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , do_center_crop=__UpperCAmelCase , crop_size=__UpperCAmelCase , do_rescale=__UpperCAmelCase , rescale_factor=__UpperCAmelCase , offset=__UpperCAmelCase , do_normalize=__UpperCAmelCase , image_mean=__UpperCAmelCase , image_std=__UpperCAmelCase , data_format=__UpperCAmelCase , ) for img in video ] for video in videos ] __UpperCAmelCase : Tuple = {"""pixel_values""": videos} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
16
1
'''simple docstring''' # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline _SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} _SCREAMING_SNAKE_CASE : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _SCREAMING_SNAKE_CASE : int = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"} ) _SCREAMING_SNAKE_CASE : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS def __A ( self ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : str = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) __UpperCAmelCase : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) __UpperCAmelCase : str = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) __UpperCAmelCase : List[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCAmelCase : Any = CLIPTextModel(__UpperCAmelCase ) __UpperCAmelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCAmelCase : List[Any] = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __A ( self , __UpperCAmelCase , __UpperCAmelCase=0 ) -> List[str]: '''simple docstring''' if str(__UpperCAmelCase ).startswith("""mps""" ): __UpperCAmelCase : List[str] = torch.manual_seed(__UpperCAmelCase ) else: __UpperCAmelCase : List[Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = 2 __UpperCAmelCase : Any = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCAmelCase , device=torch.device(__UpperCAmelCase ) , ) __UpperCAmelCase : Dict = floats_tensor(control_image.shape , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCAmelCase : List[Any] = Image.fromarray(np.uinta(__UpperCAmelCase ) ).convert("""RGB""" ).resize((64, 64) ) __UpperCAmelCase : str = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __A ( self ) -> Tuple: '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ) -> Optional[Any]: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __A ( self ) -> List[str]: '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionControlNetImgaImgPipeline _SCREAMING_SNAKE_CASE : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} _SCREAMING_SNAKE_CASE : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _SCREAMING_SNAKE_CASE : Tuple = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def __A ( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(__UpperCAmelCase ): if isinstance(__UpperCAmelCase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) __UpperCAmelCase : Dict = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__UpperCAmelCase ) torch.manual_seed(0 ) __UpperCAmelCase : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__UpperCAmelCase ) torch.manual_seed(0 ) __UpperCAmelCase : Any = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) __UpperCAmelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCAmelCase : Optional[int] = CLIPTextModel(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCAmelCase : Union[str, Any] = MultiControlNetModel([controlneta, controlneta] ) __UpperCAmelCase : Optional[int] = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __A ( self , __UpperCAmelCase , __UpperCAmelCase=0 ) -> str: '''simple docstring''' if str(__UpperCAmelCase ).startswith("""mps""" ): __UpperCAmelCase : List[Any] = torch.manual_seed(__UpperCAmelCase ) else: __UpperCAmelCase : Optional[int] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Dict = 2 __UpperCAmelCase : Dict = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCAmelCase , device=torch.device(__UpperCAmelCase ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__UpperCAmelCase , device=torch.device(__UpperCAmelCase ) , ), ] __UpperCAmelCase : int = floats_tensor(control_image[0].shape , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) __UpperCAmelCase : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCAmelCase : Optional[int] = Image.fromarray(np.uinta(__UpperCAmelCase ) ).convert("""RGB""" ).resize((64, 64) ) __UpperCAmelCase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.get_dummy_components() __UpperCAmelCase : str = self.pipeline_class(**__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = 10.0 __UpperCAmelCase : str = 4 __UpperCAmelCase : List[Any] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = steps __UpperCAmelCase : Optional[Any] = scale __UpperCAmelCase : List[str] = pipe(**__UpperCAmelCase )[0] __UpperCAmelCase : Dict = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : List[str] = steps __UpperCAmelCase : Optional[Any] = scale __UpperCAmelCase : int = pipe(**__UpperCAmelCase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] __UpperCAmelCase : Optional[int] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : List[str] = steps __UpperCAmelCase : int = scale __UpperCAmelCase : List[str] = pipe(**__UpperCAmelCase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] __UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : Tuple = steps __UpperCAmelCase : Union[str, Any] = scale __UpperCAmelCase : int = pipe(**__UpperCAmelCase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def __A ( self ) -> int: '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __A ( self ) -> Tuple: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __A ( self ) -> Any: '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : str = self.get_dummy_components() __UpperCAmelCase : Optional[int] = self.pipeline_class(**__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(__UpperCAmelCase ) except NotImplementedError: pass @slow @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Tuple = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) __UpperCAmelCase : str = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , safety_checker=__UpperCAmelCase , controlnet=__UpperCAmelCase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) __UpperCAmelCase : List[str] = """evil space-punk bird""" __UpperCAmelCase : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((512, 512) ) __UpperCAmelCase : Any = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((512, 512) ) __UpperCAmelCase : Tuple = pipe( __UpperCAmelCase , __UpperCAmelCase , control_image=__UpperCAmelCase , generator=__UpperCAmelCase , output_type="""np""" , num_inference_steps=50 , strength=0.6 , ) __UpperCAmelCase : Any = output.images[0] assert image.shape == (512, 512, 3) __UpperCAmelCase : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9E-2
16
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = LDMTextToImagePipeline _SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } _SCREAMING_SNAKE_CASE : List[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } _SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE : List[str] = False def __A ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __UpperCAmelCase : List[Any] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) __UpperCAmelCase : Any = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCAmelCase : Tuple = CLIPTextModel(__UpperCAmelCase ) __UpperCAmelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCAmelCase : Dict = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , __UpperCAmelCase , __UpperCAmelCase=0 ) -> Any: '''simple docstring''' if str(__UpperCAmelCase ).startswith("""mps""" ): __UpperCAmelCase : int = torch.manual_seed(__UpperCAmelCase ) else: __UpperCAmelCase : List[str] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : Dict = self.get_dummy_components() __UpperCAmelCase : Tuple = LDMTextToImagePipeline(**__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __UpperCAmelCase : Dict = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : int = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Any = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : int = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __UpperCAmelCase : Tuple = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) __UpperCAmelCase : Union[str, Any] = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = pipe(**__UpperCAmelCase ).images[0] __UpperCAmelCase : Tuple = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) __UpperCAmelCase : Dict = np.abs(expected_image - image ).max() assert max_diff < 1E-3
16
1
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer _SCREAMING_SNAKE_CASE : int = CLIPTokenizerFast _SCREAMING_SNAKE_CASE : Optional[Any] = True _SCREAMING_SNAKE_CASE : Any = {} _SCREAMING_SNAKE_CASE : Dict = False def __A ( self ) -> Any: '''simple docstring''' super().setUp() # fmt: off __UpperCAmelCase : List[Any] = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __UpperCAmelCase : Tuple = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : str = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>"""] __UpperCAmelCase : Optional[int] = {"""unk_token""": """<unk>"""} __UpperCAmelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __UpperCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__UpperCAmelCase ) ) def __A ( self , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> int: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """lower newer""" __UpperCAmelCase : Tuple = """lower newer""" return input_text, output_text def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Optional[int] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCAmelCase : Union[str, Any] = """lower newer""" __UpperCAmelCase : int = ["""lo""", """w""", """er</w>""", """n""", """e""", """w""", """er</w>"""] __UpperCAmelCase : int = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : Dict = tokens + [tokenizer.unk_token] __UpperCAmelCase : Tuple = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase ) @require_ftfy def __A ( self ) -> Tuple: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCAmelCase : Optional[Any] = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : Tuple = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = """A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d.""" __UpperCAmelCase : Optional[Any] = tokenizer_s.tokenize(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = tokenizer_r.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __UpperCAmelCase : Dict = """xa\u0303y""" + """ """ + """x\xe3y""" __UpperCAmelCase : int = tokenizer_s.tokenize(__UpperCAmelCase ) __UpperCAmelCase : Dict = tokenizer_r.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Test that the tokenization is identical on unicode of space type __UpperCAmelCase : int = [ """\u0009""", # (horizontal tab, '\t') """\u000B""", # (vertical tab) """\u000C""", # (form feed) """\u0020""", # (space, ' ') """\u200E""", # (left-to-right mark):w """\u200F""", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __UpperCAmelCase : Optional[int] = tokenizer_s.tokenize(__UpperCAmelCase ) __UpperCAmelCase : Any = tokenizer_r.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Test that the tokenization is identical on unicode of line break type __UpperCAmelCase : Union[str, Any] = [ """\u000A""", # (line feed, '\n') """\r\n""", # (carriage return and line feed, '\r\n') """\u000D""", # (carriage return, '\r') """\r""", # (carriage return, '\r') """\u000D""", # (carriage return, '\r') """\u2028""", # (line separator) """\u2029""", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __UpperCAmelCase : str = tokenizer_s.tokenize(__UpperCAmelCase ) __UpperCAmelCase : int = tokenizer_r.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> Tuple: '''simple docstring''' # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCAmelCase : Optional[Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` __UpperCAmelCase : str = f'{text_of_1_token} {text_of_1_token}' __UpperCAmelCase : Dict = self.rust_tokenizer_class.from_pretrained( __UpperCAmelCase , use_fast=__UpperCAmelCase , ) __UpperCAmelCase : Optional[Any] = tokenizer_r(__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__UpperCAmelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__UpperCAmelCase ) + 1, len(__UpperCAmelCase ) + 1 + len(__UpperCAmelCase )) , ) __UpperCAmelCase : Any = f' {text}' __UpperCAmelCase : Optional[int] = self.rust_tokenizer_class.from_pretrained( __UpperCAmelCase , use_fast=__UpperCAmelCase , ) __UpperCAmelCase : Dict = tokenizer_r(__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__UpperCAmelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__UpperCAmelCase ) + 1, 1 + len(__UpperCAmelCase ) + 1 + len(__UpperCAmelCase )) , ) def __A ( self ) -> Tuple: '''simple docstring''' # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(__UpperCAmelCase ) as context: self.rust_tokenizer_class.from_pretrained("""robot-test/old-clip-tokenizer""" ) self.assertTrue( context.exception.args[0].startswith( """The `backend_tokenizer` provided does not match the expected format.""" ) ) @require_ftfy def __A ( self ) -> Optional[int]: '''simple docstring''' super().test_tokenization_python_rust_equals() def __A ( self ) -> List[str]: '''simple docstring''' # CLIP always lower cases letters pass
16
'''simple docstring''' from __future__ import annotations from typing import Any class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 0 ) -> None: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = row, column __UpperCAmelCase : Union[str, Any] = [[default_value for c in range(__UpperCAmelCase )] for r in range(__UpperCAmelCase )] def __str__( self ) -> str: '''simple docstring''' __UpperCAmelCase : Dict = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __UpperCAmelCase : Optional[Any] = 0 for row_vector in self.array: for obj in row_vector: __UpperCAmelCase : Union[str, Any] = max(__UpperCAmelCase , len(str(__UpperCAmelCase ) ) ) __UpperCAmelCase : Optional[int] = f'%{max_element_length}s' # Make string and return def single_line(__UpperCAmelCase ) -> str: nonlocal string_format_identifier __UpperCAmelCase : Any = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__UpperCAmelCase ) for row_vector in self.array ) return s def __repr__( self ) -> str: '''simple docstring''' return str(self ) def __A ( self , __UpperCAmelCase ) -> bool: '''simple docstring''' if not (isinstance(__UpperCAmelCase , (list, tuple) ) and len(__UpperCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , __UpperCAmelCase ) -> Any: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = value def __add__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == another.row and self.column == another.column # Add __UpperCAmelCase : Dict = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] + another[r, c] return result def __neg__( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : Dict = -self[r, c] return result def __sub__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' return self + (-another) def __mul__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' if isinstance(__UpperCAmelCase , (int, float) ): # Scalar multiplication __UpperCAmelCase : Optional[int] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] * another return result elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # Matrix multiplication assert self.column == another.row __UpperCAmelCase : Dict = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __UpperCAmelCase : List[Any] = f'Unsupported type given for another ({type(__UpperCAmelCase )})' raise TypeError(__UpperCAmelCase ) def __A ( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Dict = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[str] = self[r, c] return result def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __UpperCAmelCase : Optional[Any] = v.transpose() __UpperCAmelCase : List[Any] = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Dict = Matrix(3 , 3 , 0 ) for i in range(3 ): __UpperCAmelCase : Tuple = 1 print(f'a^(-1) is {ainv}' ) # u, v __UpperCAmelCase : Dict = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = 1, 2, -3 __UpperCAmelCase : Union[str, Any] = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : int = 4, -2, 5 print(f'u is {u}' ) print(f'v is {v}' ) print(f'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCAmelCase__ , lowerCAmelCase__ )}' ) def lowercase_ ( ): """simple docstring""" import doctest doctest.testmod() testa()
16
1
'''simple docstring''' from math import pi, sqrt def lowercase_ ( lowerCAmelCase__ : float ): """simple docstring""" if num <= 0: raise ValueError("""math domain error""" ) if num > 171.5: raise OverflowError("""math range error""" ) elif num - int(lowerCAmelCase__ ) not in (0, 0.5): raise NotImplementedError("""num must be an integer or a half-integer""" ) elif num == 0.5: return sqrt(lowerCAmelCase__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def lowercase_ ( ): """simple docstring""" assert gamma(0.5 ) == sqrt(lowerCAmelCase__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _UpperCamelCase = 1.0 while num: _UpperCamelCase = float(input('''Gamma of: ''')) print(F'gamma({num}) = {gamma(num)}') print('''\nEnter 0 to exit...''')
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _UpperCamelCase = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
'''simple docstring''' from __future__ import annotations import csv import requests from bsa import BeautifulSoup def lowercase_ ( lowerCAmelCase__ : str = "" ): """simple docstring""" __UpperCAmelCase : List[Any] = url or """https://www.imdb.com/chart/top/?ref_=nv_mv_250""" __UpperCAmelCase : Dict = BeautifulSoup(requests.get(lowerCAmelCase__ ).text , """html.parser""" ) __UpperCAmelCase : int = soup.find_all("""td""" , attrs="""titleColumn""" ) __UpperCAmelCase : Tuple = soup.find_all("""td""" , class_="""ratingColumn imdbRating""" ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(lowerCAmelCase__ , lowerCAmelCase__ ) } def lowercase_ ( lowerCAmelCase__ : str = "IMDb_Top_250_Movies.csv" ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = get_imdb_top_aaa_movies() with open(lowerCAmelCase__ , """w""" , newline="""""" ) as out_file: __UpperCAmelCase : Optional[int] = csv.writer(lowerCAmelCase__ ) writer.writerow(["""Movie title""", """IMDb rating"""] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
16
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = MODEL_FOR_MASKED_LM_MAPPING _SCREAMING_SNAKE_CASE : Tuple = TF_MODEL_FOR_MASKED_LM_MAPPING def __A ( self ) -> Any: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser"""}, ] , ) __UpperCAmelCase : List[str] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser""", }, ] , ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9E-05, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : Dict = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : str = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2E-05, """token""": 2_941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask> <mask>""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" ) # convert model to fp16 pipe.model.half() __UpperCAmelCase : str = pipe("""Paris is the [MASK] of France.""" ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) @slow @require_torch def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Any = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" ) self.run_large_test(__UpperCAmelCase ) @slow @require_tf def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : int = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" ) self.run_large_test(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1_573, """token_str""": """ Chris"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.251, """token""": 2_201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.214, """token""": 12_790, """token_str""": """ Lyon""", }, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" ) __UpperCAmelCase : Tuple = None __UpperCAmelCase : int = None self.run_pipeline_test(__UpperCAmelCase , [] ) @require_tf def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : str = None self.run_pipeline_test(__UpperCAmelCase , [] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" ) __UpperCAmelCase : str = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = [ f'This is another {tokenizer.mask_token} test', ] return fill_masker, examples def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = fill_masker.tokenizer __UpperCAmelCase : Union[str, Any] = fill_masker.model __UpperCAmelCase : Tuple = fill_masker( f'This is a {tokenizer.mask_token}' , ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : int = fill_masker([f'This is a {tokenizer.mask_token}'] ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Union[str, Any] = fill_masker([f'This is a {tokenizer.mask_token}', f'Another {tokenizer.mask_token} great test.'] ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , ) with self.assertRaises(__UpperCAmelCase ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(__UpperCAmelCase ): fill_masker("""This is""" ) self.run_test_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_targets(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_top_k_targets(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_duplicate_targets_and_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_multiple_masks(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Dict = tokenizer.get_vocab() __UpperCAmelCase : Dict = sorted(vocab.keys() )[:2] # Pipeline argument __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , targets=__UpperCAmelCase ) __UpperCAmelCase : List[str] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Any = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : int = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Call argument __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Tuple = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : List[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Score equivalence __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : Dict = [top_mask["""token_str"""] for top_mask in outputs] __UpperCAmelCase : str = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ) == set(__UpperCAmelCase ): __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : int = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) # Raises with invalid with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Any = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[""""""] ) with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , targets="""""" ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , top_k=2 ) __UpperCAmelCase : Optional[int] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : int = tokenizer.get_vocab() __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) # top_k=2, ntargets=3 __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 , targets=__UpperCAmelCase ) # If we use the most probably targets, and filter differently, we should still # have the same results __UpperCAmelCase : Tuple = [el["""token_str"""] for el in sorted(__UpperCAmelCase , key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ).issubset(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=3 , targets=__UpperCAmelCase ) # They should yield exactly the same result self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = tokenizer.get_vocab() # String duplicates + id duplicates __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : Dict = [targets[0], targets[1], targets[0], targets[2], targets[1]] __UpperCAmelCase : Optional[int] = fill_masker(f'My name is {tokenizer.mask_token}' , targets=__UpperCAmelCase , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(__UpperCAmelCase ) , 3 ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Dict = fill_masker( f'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , )
16
1
'''simple docstring''' from __future__ import annotations _UpperCamelCase = list[list[int]] # assigning initial values to the grid _UpperCamelCase = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution _UpperCamelCase = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowercase_ ( lowerCAmelCase__ : Matrix , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowercase_ ( lowerCAmelCase__ : Matrix ): """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowercase_ ( lowerCAmelCase__ : Matrix ): """simple docstring""" if location := find_empty_location(lowerCAmelCase__ ): __UpperCAmelCase , __UpperCAmelCase : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): __UpperCAmelCase : int = digit if sudoku(lowerCAmelCase__ ) is not None: return grid __UpperCAmelCase : Optional[Any] = 0 return None def lowercase_ ( lowerCAmelCase__ : Matrix ): """simple docstring""" for row in grid: for cell in row: print(lowerCAmelCase__ , end=""" """ ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') _UpperCamelCase = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
16
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"image": Image()} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"labels": ClassLabel} ) _SCREAMING_SNAKE_CASE : str = "image" _SCREAMING_SNAKE_CASE : str = "labels" def __A ( self , __UpperCAmelCase ) -> str: '''simple docstring''' if self.label_column not in features: raise ValueError(f'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] , __UpperCAmelCase ): raise ValueError(f'Column {self.label_column} is not a ClassLabel.' ) __UpperCAmelCase : int = copy.deepcopy(self ) __UpperCAmelCase : str = self.label_schema.copy() __UpperCAmelCase : Optional[Any] = features[self.label_column] __UpperCAmelCase : Optional[int] = label_schema return task_template @property def __A ( self ) -> Dict[str, str]: '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
16
1
'''simple docstring''' from PIL import Image def lowercase_ ( lowerCAmelCase__ : Image , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : List[Any] = (259 * (level + 255)) / (255 * (259 - level)) def contrast(lowerCAmelCase__ : int ) -> int: return int(128 + factor * (c - 128) ) return img.point(lowerCAmelCase__ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change contrast to 170 _UpperCamelCase = change_contrast(img, 170) cont_img.save('''image_data/lena_high_contrast.png''', format='''png''')
16
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = parent __UpperCAmelCase : Union[str, Any] = batch_size __UpperCAmelCase : Tuple = seq_length __UpperCAmelCase : str = is_training __UpperCAmelCase : Union[str, Any] = use_input_mask __UpperCAmelCase : List[Any] = use_token_type_ids __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : str = vocab_size __UpperCAmelCase : Union[str, Any] = hidden_size __UpperCAmelCase : Optional[int] = num_hidden_layers __UpperCAmelCase : str = num_attention_heads __UpperCAmelCase : Optional[Any] = intermediate_size __UpperCAmelCase : Optional[int] = hidden_act __UpperCAmelCase : List[str] = hidden_dropout_prob __UpperCAmelCase : List[str] = attention_probs_dropout_prob __UpperCAmelCase : Tuple = max_position_embeddings __UpperCAmelCase : Dict = type_vocab_size __UpperCAmelCase : List[Any] = type_sequence_label_size __UpperCAmelCase : List[Any] = initializer_range __UpperCAmelCase : List[str] = num_labels __UpperCAmelCase : str = num_choices __UpperCAmelCase : List[Any] = scope def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Dict = None if self.use_input_mask: __UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : int = None if self.use_token_type_ids: __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : List[Any] = None __UpperCAmelCase : Union[str, Any] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Any = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ) -> Optional[Any]: '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = LlamaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Dict = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = True __UpperCAmelCase : List[str] = LlamaModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) __UpperCAmelCase : Tuple = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = LlamaForCausalLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : int = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Any = True __UpperCAmelCase : Tuple = LlamaForCausalLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() # first forward pass __UpperCAmelCase : Optional[int] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase , ) __UpperCAmelCase : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __UpperCAmelCase : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCAmelCase : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __UpperCAmelCase : str = torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCAmelCase : Union[str, Any] = torch.cat([input_mask, next_mask] , dim=-1 ) __UpperCAmelCase : int = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["""hidden_states"""][0] __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["""hidden_states"""][0] # select random slice __UpperCAmelCase : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCAmelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() __UpperCAmelCase : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-3 ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Any = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = config_and_inputs __UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _SCREAMING_SNAKE_CASE : Any = (LlamaForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE : List[str] = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : List[str] = False def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = LlamaModelTester(self ) __UpperCAmelCase : Tuple = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __A ( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : str = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Any = 3 __UpperCAmelCase : Optional[Any] = input_dict["""input_ids"""] __UpperCAmelCase : int = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCAmelCase : Dict = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[int] = 3 __UpperCAmelCase : Optional[Any] = """single_label_classification""" __UpperCAmelCase : int = input_dict["""input_ids"""] __UpperCAmelCase : List[Any] = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCAmelCase : Tuple = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[Any] = 3 __UpperCAmelCase : str = """multi_label_classification""" __UpperCAmelCase : Union[str, Any] = input_dict["""input_ids"""] __UpperCAmelCase : int = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __UpperCAmelCase : Dict = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def __A ( self ) -> Dict: '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def __A ( self , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : List[Any] = ids_tensor([1, 10] , config.vocab_size ) __UpperCAmelCase : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCAmelCase : Optional[Any] = LlamaModel(__UpperCAmelCase ) original_model.to(__UpperCAmelCase ) original_model.eval() __UpperCAmelCase : int = original_model(__UpperCAmelCase ).last_hidden_state __UpperCAmelCase : List[str] = original_model(__UpperCAmelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCAmelCase : Dict = {"""type""": scaling_type, """factor""": 10.0} __UpperCAmelCase : Optional[Any] = LlamaModel(__UpperCAmelCase ) scaled_model.to(__UpperCAmelCase ) scaled_model.eval() __UpperCAmelCase : Optional[Any] = scaled_model(__UpperCAmelCase ).last_hidden_state __UpperCAmelCase : List[str] = scaled_model(__UpperCAmelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) @require_torch class _A ( unittest.TestCase ): @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Optional[int] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" , device_map="""auto""" ) __UpperCAmelCase : int = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __UpperCAmelCase : str = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : List[Any] = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Any = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : int = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" , device_map="""auto""" ) __UpperCAmelCase : str = model(torch.tensor(__UpperCAmelCase ) ) # Expected mean on dim = -1 __UpperCAmelCase : str = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : List[str] = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : Union[str, Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" , device_map="""auto""" ) __UpperCAmelCase : Union[str, Any] = model(torch.tensor(__UpperCAmelCase ) ) # Expected mean on dim = -1 __UpperCAmelCase : Dict = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : Any = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Any = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : str = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" , device_map="""auto""" ) __UpperCAmelCase : List[Any] = model(torch.tensor(__UpperCAmelCase ) ) __UpperCAmelCase : Dict = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # fmt: off __UpperCAmelCase : List[str] = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Model is curently gated""" ) @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" __UpperCAmelCase : Dict = """Simply put, the theory of relativity states that """ __UpperCAmelCase : int = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) __UpperCAmelCase : int = tokenizer.encode(__UpperCAmelCase , return_tensors="""pt""" ) __UpperCAmelCase : int = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" , device_map="""sequential""" , use_safetensors=__UpperCAmelCase ) # greedy generation outputs __UpperCAmelCase : Tuple = model.generate(__UpperCAmelCase , max_new_tokens=64 , top_p=__UpperCAmelCase , temperature=1 , do_sample=__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = tokenizer.decode(generated_ids[0] , skip_special_tokens=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
16
1
'''simple docstring''' import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class _A ( unittest.TestCase ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=4 , ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = parent __UpperCAmelCase : List[Any] = batch_size __UpperCAmelCase : Union[str, Any] = seq_length __UpperCAmelCase : Optional[Any] = is_training __UpperCAmelCase : Optional[Any] = use_attention_mask __UpperCAmelCase : List[str] = use_token_type_ids __UpperCAmelCase : List[Any] = use_labels __UpperCAmelCase : Any = vocab_size __UpperCAmelCase : Dict = hidden_size __UpperCAmelCase : Optional[Any] = num_hidden_layers __UpperCAmelCase : List[str] = num_attention_heads __UpperCAmelCase : Any = intermediate_size __UpperCAmelCase : Tuple = hidden_act __UpperCAmelCase : Dict = hidden_dropout_prob __UpperCAmelCase : Optional[Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = max_position_embeddings __UpperCAmelCase : Optional[int] = type_vocab_size __UpperCAmelCase : List[str] = type_sequence_label_size __UpperCAmelCase : str = initializer_range __UpperCAmelCase : Any = num_choices def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Optional[Any] = None if self.use_attention_mask: __UpperCAmelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Tuple = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=__UpperCAmelCase , ) return config, input_ids, attention_mask def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = config_and_inputs __UpperCAmelCase : Dict = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FlaxDistilBertModelTester(self ) @slow def __A ( self ) -> List[str]: '''simple docstring''' for model_class_name in self.all_model_classes: __UpperCAmelCase : Any = model_class_name.from_pretrained("""distilbert-base-uncased""" ) __UpperCAmelCase : Any = model(np.ones((1, 1) ) ) self.assertIsNotNone(__UpperCAmelCase ) @require_flax class _A ( unittest.TestCase ): @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = FlaxDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCAmelCase : List[str] = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) __UpperCAmelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __UpperCAmelCase : str = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] __UpperCAmelCase : int = (1, 11, 768) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : List[str] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , __UpperCAmelCase , atol=1E-4 ) )
16
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip _UpperCamelCase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ): """simple docstring""" return max(metric_fn(lowerCAmelCase__ , lowerCAmelCase__ ) for gt in ground_truths ) def lowercase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = [] if args.gold_data_mode == "qa": __UpperCAmelCase : Tuple = pd.read_csv(lowerCAmelCase__ , sep="""\t""" , header=lowerCAmelCase__ ) for answer_list in data[1]: __UpperCAmelCase : Optional[int] = ast.literal_eval(lowerCAmelCase__ ) answers.append(lowerCAmelCase__ ) else: __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : str = [[reference] for reference in references] __UpperCAmelCase : Optional[int] = 0 for prediction, ground_truths in zip(lowerCAmelCase__ , lowerCAmelCase__ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) fa += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : int = 100.0 * em / total __UpperCAmelCase : Dict = 100.0 * fa / total logger.info(f'F1: {fa:.2f}' ) logger.info(f'EM: {em:.2f}' ) def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" __UpperCAmelCase : Tuple = args.k __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = 0 for hypo, reference in zip(lowerCAmelCase__ , lowerCAmelCase__ ): __UpperCAmelCase : List[str] = set(hypo.split("""\t""" )[:k] ) __UpperCAmelCase : List[Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k __UpperCAmelCase : List[str] = 100.0 * em / total logger.info(f'Precision@{k}: {em: .2f}' ) def lowercase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ): """simple docstring""" def strip_title(lowerCAmelCase__ : Optional[int] ): if title.startswith("""\"""" ): __UpperCAmelCase : List[Any] = title[1:] if title.endswith("""\"""" ): __UpperCAmelCase : int = title[:-1] return title __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , )["""input_ids"""].to(args.device ) __UpperCAmelCase : str = rag_model.rag.question_encoder(lowerCAmelCase__ ) __UpperCAmelCase : int = question_enc_outputs[0] __UpperCAmelCase : Dict = rag_model.retriever( lowerCAmelCase__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) __UpperCAmelCase : Union[str, Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) __UpperCAmelCase : Union[str, Any] = [] for docs in all_docs: __UpperCAmelCase : int = [strip_title(lowerCAmelCase__ ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(lowerCAmelCase__ ) ) return provenance_strings def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ): """simple docstring""" with torch.no_grad(): __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ ) __UpperCAmelCase : List[str] = inputs_dict.input_ids.to(args.device ) __UpperCAmelCase : List[Any] = inputs_dict.attention_mask.to(args.device ) __UpperCAmelCase : List[str] = rag_model.generate( # rag_model overwrites generate lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) __UpperCAmelCase : str = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) if args.print_predictions: for q, a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): logger.info("""Q: {} - A: {}""".format(lowerCAmelCase__ , lowerCAmelCase__ ) ) return answers def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=lowerCAmelCase__ , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=lowerCAmelCase__ , choices=["""exact""", """compressed""", """legacy"""] , type=lowerCAmelCase__ , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=lowerCAmelCase__ , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=lowerCAmelCase__ , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=lowerCAmelCase__ , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=lowerCAmelCase__ , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=lowerCAmelCase__ , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=lowerCAmelCase__ , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=lowerCAmelCase__ , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=lowerCAmelCase__ , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=lowerCAmelCase__ , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) __UpperCAmelCase : str = parser.parse_args() __UpperCAmelCase : Optional[Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowercase_ ( lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[Any] = {} if args.model_type is None: __UpperCAmelCase : str = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Tuple = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration __UpperCAmelCase : Dict = args.n_docs if args.index_name is not None: __UpperCAmelCase : Union[str, Any] = args.index_name if args.index_path is not None: __UpperCAmelCase : Dict = args.index_path else: __UpperCAmelCase : str = BartForConditionalGeneration __UpperCAmelCase : str = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = get_scores if args.eval_mode == """e2e""" else get_precision_at_k __UpperCAmelCase : Any = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(lowerCAmelCase__ ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Optional[int] = RagRetriever.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) __UpperCAmelCase : Any = model_class.from_pretrained(lowerCAmelCase__ , retriever=lowerCAmelCase__ , **lowerCAmelCase__ ) model.retriever.init_retrieval() else: __UpperCAmelCase : Tuple = model_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: __UpperCAmelCase : Union[str, Any] = [] for line in tqdm(lowerCAmelCase__ ): questions.append(line.strip() ) if len(lowerCAmelCase__ ) == args.eval_batch_size: __UpperCAmelCase : Any = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) + """\n""" ) preds_file.flush() __UpperCAmelCase : List[str] = [] if len(lowerCAmelCase__ ) > 0: __UpperCAmelCase : Optional[Any] = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) ) preds_file.flush() score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": _UpperCamelCase = get_args() main(args)
16
1
'''simple docstring''' import os def lowercase_ ( ): """simple docstring""" with open(os.path.dirname(lowerCAmelCase__ ) + """/grid.txt""" ) as f: __UpperCAmelCase : Optional[Any] = [] # noqa: E741 for _ in range(20 ): l.append([int(lowerCAmelCase__ ) for x in f.readline().split()] ) __UpperCAmelCase : Any = 0 # right for i in range(20 ): for j in range(17 ): __UpperCAmelCase : Optional[Any] = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: __UpperCAmelCase : str = temp # down for i in range(17 ): for j in range(20 ): __UpperCAmelCase : List[str] = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: __UpperCAmelCase : Union[str, Any] = temp # diagonal 1 for i in range(17 ): for j in range(17 ): __UpperCAmelCase : Optional[Any] = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: __UpperCAmelCase : Union[str, Any] = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): __UpperCAmelCase : List[Any] = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: __UpperCAmelCase : Union[str, Any] = temp return maximum if __name__ == "__main__": print(solution())
16
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _A : @staticmethod def __A ( *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' pass @is_pipeline_test @require_vision @require_torch class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Optional[int] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) __UpperCAmelCase : Optional[int] = [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Optional[int] = object_detector(examples[0] , threshold=0.0 ) __UpperCAmelCase : Tuple = len(__UpperCAmelCase ) self.assertGreater(__UpperCAmelCase , 0 ) self.assertEqual( __UpperCAmelCase , [ { """score""": ANY(__UpperCAmelCase ), """label""": ANY(__UpperCAmelCase ), """box""": {"""xmin""": ANY(__UpperCAmelCase ), """ymin""": ANY(__UpperCAmelCase ), """xmax""": ANY(__UpperCAmelCase ), """ymax""": ANY(__UpperCAmelCase )}, } for i in range(__UpperCAmelCase ) ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __A ( self ) -> Tuple: '''simple docstring''' pass @require_torch def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) __UpperCAmelCase : Optional[int] = object_detector( """./tests/fixtures/tests_samples/COCO/000000039769.png""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=0.64 , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] , ) __UpperCAmelCase : str = object_detector( [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] ] , ) @require_torch @slow def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : List[Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ] , ) __UpperCAmelCase : Any = object_detector( [ { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, ] , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __A ( self ) -> List[str]: '''simple docstring''' pass @require_torch @slow def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = 0.2 __UpperCAmelCase : List[Any] = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : Optional[int] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, ] , ) @require_torch @slow def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 2 __UpperCAmelCase : Optional[int] = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : List[Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , top_k=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, ] , )
16
1
'''simple docstring''' import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Union[int, Iterable[int]] , lowerCAmelCase__ : bool , lowerCAmelCase__ : int ): """simple docstring""" def constraint_to_multiple_of(lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str]=0 , lowerCAmelCase__ : Any=None ): __UpperCAmelCase : Tuple = round(val / multiple ) * multiple if max_val is not None and x > max_val: __UpperCAmelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: __UpperCAmelCase : List[Any] = math.ceil(val / multiple ) * multiple return x __UpperCAmelCase : int = (output_size, output_size) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else output_size __UpperCAmelCase , __UpperCAmelCase : Dict = get_image_size(lowerCAmelCase__ ) __UpperCAmelCase , __UpperCAmelCase : Any = output_size # determine new height and width __UpperCAmelCase : Tuple = output_height / input_height __UpperCAmelCase : Optional[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __UpperCAmelCase : Optional[Any] = scale_width else: # fit height __UpperCAmelCase : str = scale_height __UpperCAmelCase : Optional[Any] = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCAmelCase__ ) __UpperCAmelCase : List[str] = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCAmelCase__ ) return (new_height, new_width) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = False , __UpperCAmelCase = 1 , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : List[str] = size if size is not None else {"""height""": 384, """width""": 384} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase ) __UpperCAmelCase : Dict = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : List[str] = keep_aspect_ratio __UpperCAmelCase : Dict = ensure_multiple_of __UpperCAmelCase : Any = resample __UpperCAmelCase : Any = do_rescale __UpperCAmelCase : str = rescale_factor __UpperCAmelCase : Any = do_normalize __UpperCAmelCase : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __UpperCAmelCase : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = False , __UpperCAmelCase = 1 , __UpperCAmelCase = PILImageResampling.BICUBIC , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Optional[int] = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) __UpperCAmelCase : List[Any] = get_resize_output_image_size( __UpperCAmelCase , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=__UpperCAmelCase , multiple=__UpperCAmelCase , ) return resize(__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> List[str]: '''simple docstring''' return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: '''simple docstring''' __UpperCAmelCase : Optional[Any] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : str = size if size is not None else self.size __UpperCAmelCase : Any = get_size_dict(__UpperCAmelCase ) __UpperCAmelCase : str = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __UpperCAmelCase : List[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __UpperCAmelCase : int = resample if resample is not None else self.resample __UpperCAmelCase : List[str] = do_rescale if do_rescale is not None else self.do_rescale __UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCAmelCase : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Dict = image_mean if image_mean is not None else self.image_mean __UpperCAmelCase : Optional[int] = image_std if image_std is not None else self.image_std __UpperCAmelCase : Dict = make_list_of_images(__UpperCAmelCase ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Optional[Any] = [to_numpy_array(__UpperCAmelCase ) for image in images] if do_resize: __UpperCAmelCase : Optional[int] = [self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase ) for image in images] if do_rescale: __UpperCAmelCase : Any = [self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase ) for image in images] if do_normalize: __UpperCAmelCase : Tuple = [self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) for image in images] __UpperCAmelCase : List[str] = [to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) for image in images] __UpperCAmelCase : List[str] = {"""pixel_values""": images} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__UpperCAmelCase ) != len(__UpperCAmelCase ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(__UpperCAmelCase ): __UpperCAmelCase : Any = target_sizes.numpy() __UpperCAmelCase : Optional[Any] = [] for idx in range(len(__UpperCAmelCase ) ): __UpperCAmelCase : str = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__UpperCAmelCase ) else: __UpperCAmelCase : Dict = logits.argmax(dim=1 ) __UpperCAmelCase : Optional[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
16
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'''vocab_file''': '''vocab.txt'''} _UpperCamelCase = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } _UpperCamelCase = { '''YituTech/conv-bert-base''': 512, '''YituTech/conv-bert-medium-small''': 512, '''YituTech/conv-bert-small''': 512, } _UpperCamelCase = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : List[Any] = ConvBertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Optional[Any]: '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCAmelCase ) != tokenize_chinese_chars ): __UpperCAmelCase : Dict = getattr(__UpperCAmelCase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : Union[str, Any] = do_lower_case __UpperCAmelCase : str = strip_accents __UpperCAmelCase : Union[str, Any] = tokenize_chinese_chars __UpperCAmelCase : List[Any] = normalizer_class(**__UpperCAmelCase ) __UpperCAmelCase : List[Any] = do_lower_case def __A ( self , __UpperCAmelCase , __UpperCAmelCase=None ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
16
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _UpperCamelCase = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''OwlViTFeatureExtractor'''] _UpperCamelCase = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _UpperCamelCase = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''OwlViTFeatureExtractor'''] _UpperCamelCase = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _UpperCamelCase = 8 def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str]=BITS ): """simple docstring""" __UpperCAmelCase : Tuple = x.device __UpperCAmelCase : Union[str, Any] = (x * 255).int().clamp(0 , 255 ) __UpperCAmelCase : Any = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = rearrange(lowerCAmelCase__ , """d -> d 1 1""" ) __UpperCAmelCase : List[str] = rearrange(lowerCAmelCase__ , """b c h w -> b c 1 h w""" ) __UpperCAmelCase : List[Any] = ((x & mask) != 0).float() __UpperCAmelCase : Optional[Any] = rearrange(lowerCAmelCase__ , """b c d h w -> b (c d) h w""" ) __UpperCAmelCase : Union[str, Any] = bits * 2 - 1 return bits def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int=BITS ): """simple docstring""" __UpperCAmelCase : Any = x.device __UpperCAmelCase : Optional[int] = (x > 0).int() __UpperCAmelCase : Optional[Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCAmelCase__ , dtype=torch.intaa ) __UpperCAmelCase : Dict = rearrange(lowerCAmelCase__ , """d -> d 1 1""" ) __UpperCAmelCase : Optional[int] = rearrange(lowerCAmelCase__ , """b (c d) h w -> b c d h w""" , d=8 ) __UpperCAmelCase : int = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 255).clamp(0.0 , 1.0 ) def lowercase_ ( self : Dict , lowerCAmelCase__ : torch.FloatTensor , lowerCAmelCase__ : int , lowerCAmelCase__ : torch.FloatTensor , lowerCAmelCase__ : float = 0.0 , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : bool = True , ): """simple docstring""" if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) __UpperCAmelCase : List[str] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas __UpperCAmelCase : Dict = self.alphas_cumprod[timestep] __UpperCAmelCase : Any = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod __UpperCAmelCase : Optional[Any] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCAmelCase : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" __UpperCAmelCase : int = self.bit_scale if self.config.clip_sample: __UpperCAmelCase : Optional[int] = torch.clamp(lowerCAmelCase__ , -scale , lowerCAmelCase__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) __UpperCAmelCase : List[str] = self._get_variance(lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide __UpperCAmelCase : Optional[int] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCAmelCase : Any = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCAmelCase : Any = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 __UpperCAmelCase : Optional[Any] = model_output.device if torch.is_tensor(lowerCAmelCase__ ) else """cpu""" __UpperCAmelCase : str = torch.randn(model_output.shape , dtype=model_output.dtype , generator=lowerCAmelCase__ ).to(lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = self._get_variance(lowerCAmelCase__ , lowerCAmelCase__ ) ** 0.5 * eta * noise __UpperCAmelCase : int = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=lowerCAmelCase__ , pred_original_sample=lowerCAmelCase__ ) def lowercase_ ( self : int , lowerCAmelCase__ : torch.FloatTensor , lowerCAmelCase__ : int , lowerCAmelCase__ : torch.FloatTensor , lowerCAmelCase__ : List[str]="epsilon" , lowerCAmelCase__ : Tuple=None , lowerCAmelCase__ : bool = True , ): """simple docstring""" __UpperCAmelCase : List[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: __UpperCAmelCase , __UpperCAmelCase : List[Any] = torch.split(lowerCAmelCase__ , sample.shape[1] , dim=1 ) else: __UpperCAmelCase : Optional[int] = None # 1. compute alphas, betas __UpperCAmelCase : Dict = self.alphas_cumprod[t] __UpperCAmelCase : List[Any] = self.alphas_cumprod[t - 1] if t > 0 else self.one __UpperCAmelCase : int = 1 - alpha_prod_t __UpperCAmelCase : Dict = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": __UpperCAmelCase : Any = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": __UpperCAmelCase : Optional[Any] = model_output else: raise ValueError(f'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" __UpperCAmelCase : Optional[Any] = self.bit_scale if self.config.clip_sample: __UpperCAmelCase : Any = torch.clamp(lowerCAmelCase__ , -scale , lowerCAmelCase__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __UpperCAmelCase : List[Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t __UpperCAmelCase : List[str] = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __UpperCAmelCase : Union[str, Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __UpperCAmelCase : Optional[int] = 0 if t > 0: __UpperCAmelCase : Optional[int] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=lowerCAmelCase__ ).to(model_output.device ) __UpperCAmelCase : List[str] = (self._get_variance(lowerCAmelCase__ , predicted_variance=lowerCAmelCase__ ) ** 0.5) * noise __UpperCAmelCase : Tuple = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=lowerCAmelCase__ , pred_original_sample=lowerCAmelCase__ ) class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1.0 , ) -> Tuple: '''simple docstring''' super().__init__() __UpperCAmelCase : Union[str, Any] = bit_scale __UpperCAmelCase : Union[str, Any] = ( ddim_bit_scheduler_step if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else ddpm_bit_scheduler_step ) self.register_modules(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) @torch.no_grad() def __call__( self , __UpperCAmelCase = 256 , __UpperCAmelCase = 256 , __UpperCAmelCase = 50 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , **__UpperCAmelCase , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' __UpperCAmelCase : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=__UpperCAmelCase , ) __UpperCAmelCase : Dict = decimal_to_bits(__UpperCAmelCase ) * self.bit_scale __UpperCAmelCase : Any = latents.to(self.device ) self.scheduler.set_timesteps(__UpperCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual __UpperCAmelCase : Tuple = self.unet(__UpperCAmelCase , __UpperCAmelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __UpperCAmelCase : Union[str, Any] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample __UpperCAmelCase : List[str] = bits_to_decimal(__UpperCAmelCase ) if output_type == "pil": __UpperCAmelCase : str = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase )
16
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _UpperCamelCase = logging.get_logger(__name__) class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> None: '''simple docstring''' warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("""Input value must be a 'int' type""" ) return bin(lowerCAmelCase__ ).count("""1""" ) if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _UpperCamelCase = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _SCREAMING_SNAKE_CASE : int = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _SCREAMING_SNAKE_CASE : int = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __UpperCAmelCase : List[Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : int = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __UpperCAmelCase : Optional[int] = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : Dict = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __UpperCAmelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' import torch __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = pipeline("""text-classification""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : Any = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = pipeline("""text-classification""" , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : int = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = TextClassificationPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) return text_classifier, ["HuggingFace is in", "This is another test"] def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : int = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __UpperCAmelCase : Union[str, Any] = """HuggingFace is in""" __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __UpperCAmelCase : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}, {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase , top_k=__UpperCAmelCase ) __UpperCAmelCase : Any = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N, [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N] , ) __UpperCAmelCase : str = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __UpperCAmelCase : Optional[int] = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __UpperCAmelCase : Union[str, Any] = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(__UpperCAmelCase ): text_classifier(__UpperCAmelCase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __UpperCAmelCase : Tuple = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
16
1
'''simple docstring''' # Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def lowercase_ ( lowerCAmelCase__ : Optional[Any] ): """simple docstring""" return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" __UpperCAmelCase : str = create_tensor(lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = gather(lowerCAmelCase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : Dict = [state.process_index] __UpperCAmelCase : int = gather_object(lowerCAmelCase__ ) assert len(lowerCAmelCase__ ) == state.num_processes, f'{gathered_obj}, {len(lowerCAmelCase__ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), f'{gathered_obj} != {list(range(state.num_processes ) )}' def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : Any = create_tensor(lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = broadcast(lowerCAmelCase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def lowercase_ ( lowerCAmelCase__ : Optional[Any] ): """simple docstring""" if state.is_main_process: __UpperCAmelCase : Optional[Any] = torch.arange(state.num_processes + 1 ).to(state.device ) else: __UpperCAmelCase : List[str] = torch.arange(state.num_processes ).to(state.device ) __UpperCAmelCase : int = pad_across_processes(lowerCAmelCase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" if state.num_processes != 2: return __UpperCAmelCase : Any = create_tensor(lowerCAmelCase__ ) __UpperCAmelCase : str = reduce(lowerCAmelCase__ , """sum""" ) __UpperCAmelCase : Tuple = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ), f'{reduced_tensor} != {truth_tensor}' def lowercase_ ( lowerCAmelCase__ : Tuple ): """simple docstring""" if state.num_processes != 2: return __UpperCAmelCase : int = create_tensor(lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = reduce(lowerCAmelCase__ , """mean""" ) __UpperCAmelCase : int = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ), f'{reduced_tensor} != {truth_tensor}' def lowercase_ ( lowerCAmelCase__ : List[Any] ): """simple docstring""" main() def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : List[Any] = PartialState() state.print(f'State: {state}' ) state.print("""testing gather""" ) test_gather(lowerCAmelCase__ ) state.print("""testing gather_object""" ) test_gather_object(lowerCAmelCase__ ) state.print("""testing broadcast""" ) test_broadcast(lowerCAmelCase__ ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(lowerCAmelCase__ ) state.print("""testing reduce_sum""" ) test_reduce_sum(lowerCAmelCase__ ) state.print("""testing reduce_mean""" ) test_reduce_mean(lowerCAmelCase__ ) if __name__ == "__main__": main()
16
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] )
16
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''uw-madison/mra-base-512-4''': '''https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json''', } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : int = "mra" def __init__( self , __UpperCAmelCase=50_265 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3_072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=1 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase="absolute" , __UpperCAmelCase=4 , __UpperCAmelCase="full" , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=2 , **__UpperCAmelCase , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : List[str] = vocab_size __UpperCAmelCase : Optional[int] = max_position_embeddings __UpperCAmelCase : Dict = hidden_size __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : int = num_attention_heads __UpperCAmelCase : str = intermediate_size __UpperCAmelCase : Optional[int] = hidden_act __UpperCAmelCase : Union[str, Any] = hidden_dropout_prob __UpperCAmelCase : Any = attention_probs_dropout_prob __UpperCAmelCase : Any = initializer_range __UpperCAmelCase : List[str] = type_vocab_size __UpperCAmelCase : List[str] = layer_norm_eps __UpperCAmelCase : List[str] = position_embedding_type __UpperCAmelCase : Union[str, Any] = block_per_row __UpperCAmelCase : Union[str, Any] = approx_mode __UpperCAmelCase : Dict = initial_prior_first_n_blocks __UpperCAmelCase : Tuple = initial_prior_diagonal_n_blocks
16
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class _A : def __init__( self , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=64 , __UpperCAmelCase=None ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = np.random.default_rng(__UpperCAmelCase ) __UpperCAmelCase : List[str] = length __UpperCAmelCase : List[Any] = rng.normal(size=(length,) ).astype(np.floataa ) __UpperCAmelCase : Union[str, Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Dict: '''simple docstring''' return self.length def __getitem__( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> int: '''simple docstring''' super().__init__() __UpperCAmelCase : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Optional[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Any = True def __A ( self , __UpperCAmelCase=None ) -> str: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : Optional[int] = False return x * self.a[0] + self.b[0] class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> Optional[Any]: '''simple docstring''' super().__init__() __UpperCAmelCase : Tuple = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : List[str] = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : str = True def __A ( self , __UpperCAmelCase=None ) -> Tuple: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : int = False return x * self.a + self.b def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int = 16 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __UpperCAmelCase : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __UpperCAmelCase : List[str] = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} __UpperCAmelCase : Tuple = load_dataset("""csv""" , data_files=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = datasets["""train"""].unique("""label""" ) __UpperCAmelCase : str = {v: i for i, v in enumerate(lowerCAmelCase__ )} def tokenize_function(lowerCAmelCase__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __UpperCAmelCase : List[Any] = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding="""max_length""" ) if "label" in examples: __UpperCAmelCase : Optional[Any] = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __UpperCAmelCase : Tuple = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. __UpperCAmelCase : Optional[Any] = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=2 ) __UpperCAmelCase : List[Any] = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=1 ) return train_dataloader, eval_dataloader
16
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _UpperCamelCase = { '''configuration_mask2former''': [ '''MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Mask2FormerConfig''', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''Mask2FormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Mask2FormerForUniversalSegmentation''', '''Mask2FormerModel''', '''Mask2FormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ViTImageProcessor if is_vision_available() else None @property def __A ( self ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = (3, 32, 128) __UpperCAmelCase : Tuple = tempfile.mkdtemp() # fmt: off __UpperCAmelCase : Any = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __UpperCAmelCase : Optional[int] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) __UpperCAmelCase : List[Any] = { """do_normalize""": False, """do_resize""": True, """image_processor_type""": """ViTImageProcessor""", """resample""": 3, """size""": {"""height""": 32, """width""": 128}, } __UpperCAmelCase : Tuple = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __UpperCAmelCase : Dict = Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) return image_input def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.get_tokenizer() __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Tuple = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Dict = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __UpperCAmelCase : Union[str, Any] = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) __UpperCAmelCase : List[Any] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Tuple = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.prepare_image_inputs() __UpperCAmelCase : str = image_processor(__UpperCAmelCase , return_tensors="""np""" ) __UpperCAmelCase : int = processor(images=__UpperCAmelCase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : int = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Dict = """test""" __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Optional[int] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = """test""" __UpperCAmelCase : int = self.prepare_image_inputs() __UpperCAmelCase : Tuple = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """labels"""] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : List[str] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __UpperCAmelCase : Optional[Any] = processor.char_decode(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = tokenizer.batch_decode(__UpperCAmelCase ) __UpperCAmelCase : int = [seq.replace(""" """ , """""" ) for seq in decoded_tok] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : Any = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : str = None __UpperCAmelCase : Dict = self.prepare_image_inputs() __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Any = self.get_image_processor() __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : str = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = torch.randn(1 , 27 , 38 ) __UpperCAmelCase : Union[str, Any] = torch.randn(1 , 27 , 50_257 ) __UpperCAmelCase : Any = torch.randn(1 , 27 , 30_522 ) __UpperCAmelCase : Tuple = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["""generated_text""", """scores""", """char_preds""", """bpe_preds""", """wp_preds"""] )
16
1
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('''Googling.....''') _UpperCamelCase = '''https://www.google.com/search?q=''' + ''' '''.join(sys.argv[1:]) _UpperCamelCase = requests.get(url, headers={'''UserAgent''': UserAgent().random}) # res.raise_for_status() with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class for data in res.iter_content(1_0000): out_file.write(data) _UpperCamelCase = BeautifulSoup(res.text, '''html.parser''') _UpperCamelCase = list(soup.select('''.eZt8xd'''))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('''href''')) else: webbrowser.open(F'https://google.com{link.get("href")}')
16
'''simple docstring''' from collections.abc import Sequence def lowercase_ ( lowerCAmelCase__ : Sequence[int] | None = None ): """simple docstring""" if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) __UpperCAmelCase : Any = nums[0] for i in range(1 , len(lowerCAmelCase__ ) ): __UpperCAmelCase : Union[str, Any] = nums[i] __UpperCAmelCase : List[Any] = max(lowerCAmelCase__ , ans + num , lowerCAmelCase__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _UpperCamelCase = int(input('''Enter number of elements : ''').strip()) _UpperCamelCase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n] print(max_subsequence_sum(array))
16
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''microsoft/wavlm-base''': '''https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json''', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = "wavlm" def __init__( self , __UpperCAmelCase=32 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3_072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase="group" , __UpperCAmelCase="gelu" , __UpperCAmelCase=(512, 512, 512, 512, 512, 512, 512) , __UpperCAmelCase=(5, 2, 2, 2, 2, 2, 2) , __UpperCAmelCase=(10, 3, 3, 3, 3, 2, 2) , __UpperCAmelCase=False , __UpperCAmelCase=128 , __UpperCAmelCase=16 , __UpperCAmelCase=320 , __UpperCAmelCase=800 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.05 , __UpperCAmelCase=10 , __UpperCAmelCase=2 , __UpperCAmelCase=0.0 , __UpperCAmelCase=10 , __UpperCAmelCase=320 , __UpperCAmelCase=2 , __UpperCAmelCase=0.1 , __UpperCAmelCase=100 , __UpperCAmelCase=256 , __UpperCAmelCase=256 , __UpperCAmelCase=0.1 , __UpperCAmelCase="mean" , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=256 , __UpperCAmelCase=(512, 512, 512, 512, 1_500) , __UpperCAmelCase=(5, 3, 3, 1, 1) , __UpperCAmelCase=(1, 2, 3, 1, 1) , __UpperCAmelCase=512 , __UpperCAmelCase=80 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , __UpperCAmelCase=2 , __UpperCAmelCase=False , __UpperCAmelCase=3 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' super().__init__(**__UpperCAmelCase , pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase ) __UpperCAmelCase : int = hidden_size __UpperCAmelCase : Optional[int] = feat_extract_norm __UpperCAmelCase : Optional[Any] = feat_extract_activation __UpperCAmelCase : List[str] = list(__UpperCAmelCase ) __UpperCAmelCase : Tuple = list(__UpperCAmelCase ) __UpperCAmelCase : List[str] = list(__UpperCAmelCase ) __UpperCAmelCase : List[str] = conv_bias __UpperCAmelCase : Any = num_buckets __UpperCAmelCase : List[Any] = max_bucket_distance __UpperCAmelCase : List[Any] = num_conv_pos_embeddings __UpperCAmelCase : Optional[Any] = num_conv_pos_embedding_groups __UpperCAmelCase : List[Any] = len(self.conv_dim ) __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : List[str] = intermediate_size __UpperCAmelCase : Tuple = hidden_act __UpperCAmelCase : str = num_attention_heads __UpperCAmelCase : Tuple = hidden_dropout __UpperCAmelCase : Optional[Any] = attention_dropout __UpperCAmelCase : Any = activation_dropout __UpperCAmelCase : Optional[int] = feat_proj_dropout __UpperCAmelCase : List[Any] = final_dropout __UpperCAmelCase : str = layerdrop __UpperCAmelCase : Optional[Any] = layer_norm_eps __UpperCAmelCase : int = initializer_range __UpperCAmelCase : List[Any] = num_ctc_classes __UpperCAmelCase : Union[str, Any] = vocab_size __UpperCAmelCase : Optional[int] = do_stable_layer_norm __UpperCAmelCase : Dict = use_weighted_layer_sum __UpperCAmelCase : Any = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' f' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __UpperCAmelCase : Dict = apply_spec_augment __UpperCAmelCase : Union[str, Any] = mask_time_prob __UpperCAmelCase : List[str] = mask_time_length __UpperCAmelCase : Union[str, Any] = mask_time_min_masks __UpperCAmelCase : Dict = mask_feature_prob __UpperCAmelCase : Any = mask_feature_length # parameters for pretraining with codevector quantized representations __UpperCAmelCase : int = num_codevectors_per_group __UpperCAmelCase : Tuple = num_codevector_groups __UpperCAmelCase : List[str] = contrastive_logits_temperature __UpperCAmelCase : List[str] = num_negatives __UpperCAmelCase : Any = codevector_dim __UpperCAmelCase : str = proj_codevector_dim __UpperCAmelCase : Any = diversity_loss_weight # ctc loss __UpperCAmelCase : Dict = ctc_loss_reduction __UpperCAmelCase : List[str] = ctc_zero_infinity # adapter __UpperCAmelCase : Optional[Any] = add_adapter __UpperCAmelCase : List[Any] = adapter_kernel_size __UpperCAmelCase : int = adapter_stride __UpperCAmelCase : List[Any] = num_adapter_layers __UpperCAmelCase : List[str] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCAmelCase : Dict = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCAmelCase : List[Any] = list(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = list(__UpperCAmelCase ) __UpperCAmelCase : Dict = list(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = xvector_output_dim @property def __A ( self ) -> Any: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
16
'''simple docstring''' class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : int = data __UpperCAmelCase : int = previous __UpperCAmelCase : Union[str, Any] = next_node def __str__( self ) -> str: '''simple docstring''' return f'{self.data}' def __A ( self ) -> int: '''simple docstring''' return self.data def __A ( self ) -> List[str]: '''simple docstring''' return self.next def __A ( self ) -> str: '''simple docstring''' return self.previous class _A : def __init__( self , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = head def __iter__( self ) -> str: '''simple docstring''' return self def __A ( self ) -> str: '''simple docstring''' if not self.current: raise StopIteration else: __UpperCAmelCase : List[str] = self.current.get_data() __UpperCAmelCase : int = self.current.get_next() return value class _A : def __init__( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = None # First node in list __UpperCAmelCase : List[str] = None # Last node in list def __str__( self ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = self.head __UpperCAmelCase : Optional[int] = [] while current is not None: nodes.append(current.get_data() ) __UpperCAmelCase : Any = current.get_next() return " ".join(str(__UpperCAmelCase ) for node in nodes ) def __contains__( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.head while current: if current.get_data() == value: return True __UpperCAmelCase : Optional[Any] = current.get_next() return False def __iter__( self ) -> str: '''simple docstring''' return LinkedListIterator(self.head ) def __A ( self ) -> List[Any]: '''simple docstring''' if self.head: return self.head.get_data() return None def __A ( self ) -> Optional[Any]: '''simple docstring''' if self.tail: return self.tail.get_data() return None def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: __UpperCAmelCase : str = node __UpperCAmelCase : List[str] = node else: self.insert_before_node(self.head , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: self.set_head(__UpperCAmelCase ) else: self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[int] = Node(__UpperCAmelCase ) if self.head is None: self.set_head(__UpperCAmelCase ) else: self.set_tail(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Tuple = node __UpperCAmelCase : List[Any] = node.previous if node.get_previous() is None: __UpperCAmelCase : str = node_to_insert else: __UpperCAmelCase : Optional[Any] = node_to_insert __UpperCAmelCase : List[Any] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : List[str] = node __UpperCAmelCase : Union[str, Any] = node.next if node.get_next() is None: __UpperCAmelCase : Dict = node_to_insert else: __UpperCAmelCase : Any = node_to_insert __UpperCAmelCase : List[str] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Optional[Any] = Node(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.head while node: if current_position == position: self.insert_before_node(__UpperCAmelCase , __UpperCAmelCase ) return current_position += 1 __UpperCAmelCase : int = node.next self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Node: '''simple docstring''' __UpperCAmelCase : Dict = self.head while node: if node.get_data() == item: return node __UpperCAmelCase : List[str] = node.get_next() raise Exception("""Node not found""" ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' if (node := self.get_node(__UpperCAmelCase )) is not None: if node == self.head: __UpperCAmelCase : Optional[int] = self.head.get_next() if node == self.tail: __UpperCAmelCase : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(__UpperCAmelCase ) @staticmethod def __A ( __UpperCAmelCase ) -> None: '''simple docstring''' if node.get_next(): __UpperCAmelCase : Optional[Any] = node.previous if node.get_previous(): __UpperCAmelCase : int = node.next __UpperCAmelCase : Tuple = None __UpperCAmelCase : Union[str, Any] = None def __A ( self ) -> List[Any]: '''simple docstring''' return self.head is None def lowercase_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Any = generate_pascal_triangle(lowerCAmelCase__ ) for row_idx in range(lowerCAmelCase__ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=""" """ ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=""" """ ) else: print(triangle[row_idx][col_idx] , end="""""" ) print() def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("""The input value of 'num_rows' should be 'int'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of 'num_rows' should be greater than or equal to 0""" ) __UpperCAmelCase : list[list[int]] = [] for current_row_idx in range(lowerCAmelCase__ ): __UpperCAmelCase : Optional[int] = populate_current_row(lowerCAmelCase__ , lowerCAmelCase__ ) triangle.append(lowerCAmelCase__ ) return triangle def lowercase_ ( lowerCAmelCase__ : list[list[int]] , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : List[Any] = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 __UpperCAmelCase , __UpperCAmelCase : Tuple = 1, 1 for current_col_idx in range(1 , lowerCAmelCase__ ): calculate_current_element( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return current_row def lowercase_ ( lowerCAmelCase__ : list[list[int]] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = triangle[current_row_idx - 1][current_col_idx - 1] __UpperCAmelCase : Dict = triangle[current_row_idx - 1][current_col_idx] __UpperCAmelCase : List[str] = above_to_left_elt + above_to_right_elt def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("""The input value of 'num_rows' should be 'int'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of 'num_rows' should be greater than or equal to 0""" ) __UpperCAmelCase : list[list[int]] = [[1]] for row_index in range(1 , lowerCAmelCase__ ): __UpperCAmelCase : Optional[int] = [0] + result[-1] + [0] __UpperCAmelCase : str = row_index + 1 # Calculate the number of distinct elements in a row __UpperCAmelCase : Dict = sum(divmod(lowerCAmelCase__ , 2 ) ) __UpperCAmelCase : Tuple = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] __UpperCAmelCase : str = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() __UpperCAmelCase : Any = row_first_half + row_second_half result.append(lowerCAmelCase__ ) return result def lowercase_ ( ): """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(lowerCAmelCase__ : Callable , lowerCAmelCase__ : int ) -> None: __UpperCAmelCase : Optional[int] = f'{func.__name__}({value})' __UpperCAmelCase : Optional[Any] = timeit(f'__main__.{call}' , setup="""import __main__""" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'{call:38} -- {timing:.4f} seconds' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(lowerCAmelCase__ , lowerCAmelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
16
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class _A : _SCREAMING_SNAKE_CASE : List[str] _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="Translation" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ) -> Any: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class _A : _SCREAMING_SNAKE_CASE : Optional[List] = None _SCREAMING_SNAKE_CASE : Optional[int] = None _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="TranslationVariableLanguages" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = sorted(set(self.languages ) ) if self.languages else None __UpperCAmelCase : int = len(self.languages ) if self.languages else None def __call__( self ) -> Optional[Any]: '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def __A ( self , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = set(self.languages ) if self.languages and set(__UpperCAmelCase ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(__UpperCAmelCase ) - lang_set ) )}) are not in valid set ({", ".join(__UpperCAmelCase )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __UpperCAmelCase : Dict = [] for lang, text in translation_dict.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = zip(*sorted(__UpperCAmelCase ) ) return {"language": languages, "translation": translations} def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
16
1
'''simple docstring''' import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): # TODO: is there an appropriate internal test set? _SCREAMING_SNAKE_CASE : List[str] = "ssube/stable-diffusion-x4-upscaler-onnx" def __A ( self , __UpperCAmelCase=0 ) -> Tuple: '''simple docstring''' __UpperCAmelCase : str = floats_tensor((1, 3, 128, 128) , rng=random.Random(__UpperCAmelCase ) ) __UpperCAmelCase : int = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_dummy_inputs() __UpperCAmelCase : Optional[Any] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Any = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) __UpperCAmelCase : Optional[Any] = np.array( [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase : int = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : str = self.get_dummy_inputs() __UpperCAmelCase : Tuple = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase : Union[str, Any] = np.array( [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : str = self.get_dummy_inputs() __UpperCAmelCase : List[Any] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase : Dict = np.array( [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase : Tuple = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.get_dummy_inputs() __UpperCAmelCase : Optional[int] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase : Optional[int] = np.array( [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __UpperCAmelCase : Any = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs() __UpperCAmelCase : Any = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase : Optional[int] = np.array( [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): @property def __A ( self ) -> Any: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ort.SessionOptions() __UpperCAmelCase : Any = False return options def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase : Optional[int] = init_image.resize((128, 128) ) # using the PNDM scheduler by default __UpperCAmelCase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = """A fantasy landscape, trending on artstation""" __UpperCAmelCase : str = torch.manual_seed(0 ) __UpperCAmelCase : Any = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=10 , generator=__UpperCAmelCase , output_type="""np""" , ) __UpperCAmelCase : Any = output.images __UpperCAmelCase : Union[str, Any] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) __UpperCAmelCase : List[Any] = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __UpperCAmelCase : Tuple = init_image.resize((128, 128) ) __UpperCAmelCase : Any = LMSDiscreteScheduler.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , subfolder="""scheduler""" ) __UpperCAmelCase : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , scheduler=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : str = """A fantasy landscape, trending on artstation""" __UpperCAmelCase : int = torch.manual_seed(0 ) __UpperCAmelCase : Union[str, Any] = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=20 , generator=__UpperCAmelCase , output_type="""np""" , ) __UpperCAmelCase : Any = output.images __UpperCAmelCase : int = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) __UpperCAmelCase : List[str] = np.array( [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
16
'''simple docstring''' from statistics import mean import numpy as np def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Tuple = 0 # Number of processes finished __UpperCAmelCase : Optional[int] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. __UpperCAmelCase : Tuple = [0] * no_of_process # List to include calculation results __UpperCAmelCase : int = [0] * no_of_process # Sort by arrival time. __UpperCAmelCase : Dict = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] __UpperCAmelCase : Union[str, Any] = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: __UpperCAmelCase : Dict = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: __UpperCAmelCase : Any = arrival_time[i] __UpperCAmelCase : Any = 0 # Index showing the location of the process being performed __UpperCAmelCase : Any = 0 # Saves the current response ratio. __UpperCAmelCase : List[str] = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: __UpperCAmelCase : Dict = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: __UpperCAmelCase : Tuple = temp __UpperCAmelCase : List[str] = i # Calculate the turn around time __UpperCAmelCase : Tuple = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. __UpperCAmelCase : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[int] = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): __UpperCAmelCase : List[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _UpperCamelCase = 5 _UpperCamelCase = ['''A''', '''B''', '''C''', '''D''', '''E'''] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _UpperCamelCase = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
16
1
'''simple docstring''' import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class _A ( __SCREAMING_SNAKE_CASE ): def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : List[str] = tempfile.mkdtemp() __UpperCAmelCase : List[str] = 8 # DPR tok __UpperCAmelCase : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __UpperCAmelCase : Optional[int] = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(__UpperCAmelCase , exist_ok=__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = os.path.join(__UpperCAmelCase , DPR_VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) # BART tok __UpperCAmelCase : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __UpperCAmelCase : int = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : Union[str, Any] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __UpperCAmelCase : Tuple = {"""unk_token""": """<unk>"""} __UpperCAmelCase : str = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(__UpperCAmelCase , exist_ok=__UpperCAmelCase ) __UpperCAmelCase : List[str] = os.path.join(__UpperCAmelCase , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) __UpperCAmelCase : Optional[int] = os.path.join(__UpperCAmelCase , BART_VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__UpperCAmelCase ) ) def __A ( self ) -> DPRQuestionEncoderTokenizer: '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def __A ( self ) -> DPRContextEncoderTokenizer: '''simple docstring''' return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def __A ( self ) -> BartTokenizer: '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def __A ( self ) -> Tuple: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self.get_dummy_dataset() __UpperCAmelCase : Union[str, Any] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: __UpperCAmelCase : Union[str, Any] = dataset __UpperCAmelCase : List[Any] = RagRetriever( __UpperCAmelCase , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def __A ( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = self.get_dummy_dataset() __UpperCAmelCase : Optional[int] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""custom""" , ) if from_disk: __UpperCAmelCase : List[Any] = os.path.join(self.tmpdirname , """dataset""" ) __UpperCAmelCase : Dict = os.path.join(self.tmpdirname , """index.faiss""" ) dataset.get_index("""embeddings""" ).save(os.path.join(self.tmpdirname , """index.faiss""" ) ) dataset.drop_index("""embeddings""" ) dataset.save_to_disk(os.path.join(self.tmpdirname , """dataset""" ) ) del dataset __UpperCAmelCase : Any = RagRetriever( __UpperCAmelCase , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: __UpperCAmelCase : Tuple = RagRetriever( __UpperCAmelCase , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , __UpperCAmelCase ) , ) return retriever def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : int = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) __UpperCAmelCase : str = os.path.join(self.tmpdirname , """hf_bert_base.hnswSQ8_correct_phi_128.c_index""" ) dataset.save_faiss_index("""embeddings""" , index_file_name + """.index.dpr""" ) pickle.dump(dataset["""id"""] , open(index_file_name + """.index_meta.dpr""" , """wb""" ) ) __UpperCAmelCase : Any = os.path.join(self.tmpdirname , """psgs_w100.tsv.pkl""" ) __UpperCAmelCase : Optional[int] = {sample["""id"""]: [sample["""text"""], sample["""title"""]] for sample in dataset} pickle.dump(__UpperCAmelCase , open(__UpperCAmelCase , """wb""" ) ) __UpperCAmelCase : Union[str, Any] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""legacy""" , index_path=self.tmpdirname , ) __UpperCAmelCase : str = RagRetriever( __UpperCAmelCase , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = 1 __UpperCAmelCase : Optional[Any] = self.get_dummy_canonical_hf_index_retriever() __UpperCAmelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : int = retriever.retrieve(__UpperCAmelCase , n_docs=__UpperCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__UpperCAmelCase ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __UpperCAmelCase ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Any = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: __UpperCAmelCase : List[Any] = self.get_dummy_dataset() retriever.save_pretrained(__UpperCAmelCase ) __UpperCAmelCase : List[str] = RagRetriever.from_pretrained(__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Dict = retriever.retrieve(__UpperCAmelCase , n_docs=1 ) self.assertTrue(out is not None ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : List[str] = 1 __UpperCAmelCase : Optional[Any] = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase ) __UpperCAmelCase : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Optional[int] = retriever.retrieve(__UpperCAmelCase , n_docs=__UpperCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__UpperCAmelCase ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __UpperCAmelCase ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__UpperCAmelCase ) __UpperCAmelCase : Any = RagRetriever.from_pretrained(__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : Dict = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Dict = retriever.retrieve(__UpperCAmelCase , n_docs=1 ) self.assertTrue(out is not None ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = 1 __UpperCAmelCase : Any = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase ) __UpperCAmelCase : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Any = retriever.retrieve(__UpperCAmelCase , n_docs=__UpperCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__UpperCAmelCase ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __UpperCAmelCase ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__UpperCAmelCase ) __UpperCAmelCase : int = RagRetriever.from_pretrained(__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Optional[int] = retriever.retrieve(__UpperCAmelCase , n_docs=1 ) self.assertTrue(out is not None ) def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Any = 1 __UpperCAmelCase : Tuple = self.get_dummy_legacy_index_retriever() __UpperCAmelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Optional[int] = retriever.retrieve(__UpperCAmelCase , n_docs=__UpperCAmelCase ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__UpperCAmelCase ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""text"""] ) , __UpperCAmelCase ) self.assertEqual(doc_dicts[0]["""text"""][0] , """bar""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""text"""][0] , """foo""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__UpperCAmelCase ) __UpperCAmelCase : int = RagRetriever.from_pretrained(__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Any = retriever.retrieve(__UpperCAmelCase , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def __A ( self ) -> Union[str, Any]: '''simple docstring''' import torch __UpperCAmelCase : Any = 1 __UpperCAmelCase : Dict = self.get_dummy_canonical_hf_index_retriever() __UpperCAmelCase : Tuple = [[5, 7], [10, 11]] __UpperCAmelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Union[str, Any] = retriever(__UpperCAmelCase , __UpperCAmelCase , prefix=retriever.config.generator.prefix , n_docs=__UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Tuple = ( out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , np.ndarray ) __UpperCAmelCase : str = retriever( __UpperCAmelCase , __UpperCAmelCase , prefix=retriever.config.generator.prefix , n_docs=__UpperCAmelCase , return_tensors="""pt""" , ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = ( # noqa: F841 out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], out["""doc_ids"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_dpr_ctx_encoder_tokenizer() __UpperCAmelCase : List[str] = 1 __UpperCAmelCase : Tuple = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase ) retriever.set_ctx_encoder_tokenizer(__UpperCAmelCase ) __UpperCAmelCase : List[str] = [[5, 7], [10, 11]] __UpperCAmelCase : Dict = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __UpperCAmelCase : Any = retriever(__UpperCAmelCase , __UpperCAmelCase , prefix=retriever.config.generator.prefix , n_docs=__UpperCAmelCase ) self.assertEqual( len(__UpperCAmelCase ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("""tokenized_doc_ids""", """tokenized_doc_attention_mask""") ) , __UpperCAmelCase ) # check for doc token related keys in dictionary.
16
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=2 , __UpperCAmelCase=8 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=16 , __UpperCAmelCase=5 , __UpperCAmelCase=2 , __UpperCAmelCase=36 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = parent __UpperCAmelCase : Any = batch_size __UpperCAmelCase : Union[str, Any] = seq_length __UpperCAmelCase : int = is_training __UpperCAmelCase : Union[str, Any] = use_input_mask __UpperCAmelCase : List[str] = use_token_type_ids __UpperCAmelCase : List[str] = use_labels __UpperCAmelCase : Optional[Any] = vocab_size __UpperCAmelCase : Tuple = hidden_size __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : Optional[int] = num_attention_heads __UpperCAmelCase : str = intermediate_size __UpperCAmelCase : List[Any] = hidden_act __UpperCAmelCase : Optional[Any] = hidden_dropout_prob __UpperCAmelCase : List[Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[Any] = max_position_embeddings __UpperCAmelCase : List[Any] = type_vocab_size __UpperCAmelCase : Dict = type_sequence_label_size __UpperCAmelCase : Optional[Any] = initializer_range __UpperCAmelCase : Optional[Any] = num_labels __UpperCAmelCase : Optional[Any] = num_choices __UpperCAmelCase : int = scope def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : List[Any] = None if self.use_input_mask: __UpperCAmelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Any = None if self.use_token_type_ids: __UpperCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Tuple = None __UpperCAmelCase : Optional[int] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ) -> List[str]: '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_config() __UpperCAmelCase : List[Any] = 300 return config def __A ( self ) -> Dict: '''simple docstring''' ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = self.prepare_config_and_inputs() __UpperCAmelCase : Tuple = True __UpperCAmelCase : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = MraModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[str] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : Any = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : List[str] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : List[str] = True __UpperCAmelCase : List[Any] = MraModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) __UpperCAmelCase : List[Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Any = MraForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[int] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: '''simple docstring''' __UpperCAmelCase : str = MraForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[Any] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = self.num_labels __UpperCAmelCase : int = MraForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = self.num_labels __UpperCAmelCase : str = MraForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = self.num_choices __UpperCAmelCase : int = MraForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[str] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : List[Any] = config_and_inputs __UpperCAmelCase : Tuple = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : int = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Dict = () def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = MraModelTester(self ) __UpperCAmelCase : Optional[Any] = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __A ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : List[Any] = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Any: '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Tuple = MraModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip(reason="""MRA does not output attentions""" ) def __A ( self ) -> List[Any]: '''simple docstring''' return @require_torch class _A ( unittest.TestCase ): @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Tuple = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : str = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : List[Any] = model(__UpperCAmelCase )[0] __UpperCAmelCase : Optional[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : Union[str, Any] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : int = model(__UpperCAmelCase )[0] __UpperCAmelCase : Union[str, Any] = 50_265 __UpperCAmelCase : Union[str, Any] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) __UpperCAmelCase : Dict = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : Any = model(__UpperCAmelCase )[0] __UpperCAmelCase : Dict = 50_265 __UpperCAmelCase : Optional[int] = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : str = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int = 100 ): """simple docstring""" __UpperCAmelCase : int = (n * (n + 1) // 2) ** 2 __UpperCAmelCase : str = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'{solution() = }')
16
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=32 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=16 , __UpperCAmelCase=[1, 2, 1] , __UpperCAmelCase=[2, 2, 4] , __UpperCAmelCase=2 , __UpperCAmelCase=2.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=10 , __UpperCAmelCase=8 , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = parent __UpperCAmelCase : Union[str, Any] = batch_size __UpperCAmelCase : Any = image_size __UpperCAmelCase : Dict = patch_size __UpperCAmelCase : Dict = num_channels __UpperCAmelCase : List[Any] = embed_dim __UpperCAmelCase : str = depths __UpperCAmelCase : Dict = num_heads __UpperCAmelCase : str = window_size __UpperCAmelCase : int = mlp_ratio __UpperCAmelCase : Union[str, Any] = qkv_bias __UpperCAmelCase : Dict = hidden_dropout_prob __UpperCAmelCase : str = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = drop_path_rate __UpperCAmelCase : List[str] = hidden_act __UpperCAmelCase : Optional[int] = use_absolute_embeddings __UpperCAmelCase : Any = patch_norm __UpperCAmelCase : Union[str, Any] = layer_norm_eps __UpperCAmelCase : Optional[int] = initializer_range __UpperCAmelCase : Tuple = is_training __UpperCAmelCase : Any = scope __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : Optional[int] = type_sequence_label_size __UpperCAmelCase : int = encoder_stride def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase : Tuple = None if self.use_labels: __UpperCAmelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __A ( self ) -> Dict: '''simple docstring''' return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase ) __UpperCAmelCase : Tuple = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Any = SwinvaForMaskedImageModeling(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model(__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Dict = SwinvaForMaskedImageModeling(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase : str = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = self.type_sequence_label_size __UpperCAmelCase : str = SwinvaForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Any = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = config_and_inputs __UpperCAmelCase : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : List[str] = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : List[str] = SwinvaModelTester(self ) __UpperCAmelCase : Any = ConfigTester(self , config_class=__UpperCAmelCase , embed_dim=37 ) def __A ( self ) -> Any: '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def __A ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def __A ( self ) -> Dict: '''simple docstring''' pass def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Tuple = model_class(__UpperCAmelCase ) __UpperCAmelCase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : str = [*signature.parameters.keys()] __UpperCAmelCase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[Any] = True for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : int = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : str = outputs.attentions __UpperCAmelCase : Any = len(self.model_tester.depths ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase : Dict = True __UpperCAmelCase : int = config.window_size**2 __UpperCAmelCase : Any = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : int = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : Dict = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase : Dict = len(__UpperCAmelCase ) # Check attention is always last and order is fine __UpperCAmelCase : Any = True __UpperCAmelCase : Any = True __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[str] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase : Any = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase : Optional[int] = 2 self.assertEqual(out_len + added_hidden_states , len(__UpperCAmelCase ) ) __UpperCAmelCase : Tuple = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : List[Any] = outputs.hidden_states __UpperCAmelCase : List[Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # Swinv2 has a different seq_length __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase : int = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : str = reshaped_hidden_states[0].shape __UpperCAmelCase : Any = ( reshaped_hidden_states[0].view(__UpperCAmelCase , __UpperCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = 3 __UpperCAmelCase : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase : Union[str, Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase : int = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Tuple = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Dict = SwinvaModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = _config_zero_init(__UpperCAmelCase ) for model_class in self.all_model_classes: __UpperCAmelCase : List[Any] = model_class(config=__UpperCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class _A ( unittest.TestCase ): @cached_property def __A ( self ) -> int: '''simple docstring''' return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __UpperCAmelCase ) __UpperCAmelCase : Tuple = self.default_image_processor __UpperCAmelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase : Any = image_processor(images=__UpperCAmelCase , return_tensors="""pt""" ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): __UpperCAmelCase : Optional[int] = model(**__UpperCAmelCase ) # verify the logits __UpperCAmelCase : int = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str = " " ): """simple docstring""" __UpperCAmelCase : Optional[int] = [] __UpperCAmelCase : Dict = 0 for index, char in enumerate(lowerCAmelCase__ ): if char == separator: split_words.append(string[last_index:index] ) __UpperCAmelCase : Union[str, Any] = index + 1 elif index + 1 == len(lowerCAmelCase__ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
16
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase__ ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : int = size if size is not None else {"""shortest_edge""": 256} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) __UpperCAmelCase : int = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : Any = do_center_crop __UpperCAmelCase : Any = crop_size __UpperCAmelCase : Optional[Any] = resample __UpperCAmelCase : Dict = do_rescale __UpperCAmelCase : List[str] = rescale_factor __UpperCAmelCase : Dict = offset __UpperCAmelCase : List[str] = do_normalize __UpperCAmelCase : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __UpperCAmelCase : str = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : List[str] = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" in size: __UpperCAmelCase : Union[str, Any] = get_resize_output_image_size(__UpperCAmelCase , size["""shortest_edge"""] , default_to_square=__UpperCAmelCase ) elif "height" in size and "width" in size: __UpperCAmelCase : Any = (size["""height"""], size["""width"""]) else: raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}' ) return resize(__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Any = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}' ) return center_crop(__UpperCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = image.astype(np.floataa ) if offset: __UpperCAmelCase : Tuple = image - (scale / 2) return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Optional[Any] = to_numpy_array(__UpperCAmelCase ) if do_resize: __UpperCAmelCase : Optional[int] = self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase ) if do_center_crop: __UpperCAmelCase : Optional[int] = self.center_crop(__UpperCAmelCase , size=__UpperCAmelCase ) if do_rescale: __UpperCAmelCase : int = self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase , offset=__UpperCAmelCase ) if do_normalize: __UpperCAmelCase : List[str] = self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) return image def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: '''simple docstring''' __UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : List[Any] = resample if resample is not None else self.resample __UpperCAmelCase : str = do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCAmelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCAmelCase : List[Any] = offset if offset is not None else self.offset __UpperCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Optional[Any] = image_mean if image_mean is not None else self.image_mean __UpperCAmelCase : int = image_std if image_std is not None else self.image_std __UpperCAmelCase : Any = size if size is not None else self.size __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size __UpperCAmelCase : str = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) __UpperCAmelCase : int = make_batched(__UpperCAmelCase ) __UpperCAmelCase : Tuple = [ [ self._preprocess_image( image=__UpperCAmelCase , do_resize=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , do_center_crop=__UpperCAmelCase , crop_size=__UpperCAmelCase , do_rescale=__UpperCAmelCase , rescale_factor=__UpperCAmelCase , offset=__UpperCAmelCase , do_normalize=__UpperCAmelCase , image_mean=__UpperCAmelCase , image_std=__UpperCAmelCase , data_format=__UpperCAmelCase , ) for img in video ] for video in videos ] __UpperCAmelCase : Tuple = {"""pixel_values""": videos} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" return x if y == 0 else greatest_common_divisor(lowerCAmelCase__ , x % y ) def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" return (x * y) // greatest_common_divisor(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase_ ( lowerCAmelCase__ : int = 20 ): """simple docstring""" __UpperCAmelCase : int = 1 for i in range(1 , n + 1 ): __UpperCAmelCase : Optional[Any] = lcm(lowerCAmelCase__ , lowerCAmelCase__ ) return g if __name__ == "__main__": print(F'{solution() = }')
16
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = LDMTextToImagePipeline _SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } _SCREAMING_SNAKE_CASE : List[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } _SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE : List[str] = False def __A ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __UpperCAmelCase : List[Any] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) __UpperCAmelCase : Any = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCAmelCase : Tuple = CLIPTextModel(__UpperCAmelCase ) __UpperCAmelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCAmelCase : Dict = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , __UpperCAmelCase , __UpperCAmelCase=0 ) -> Any: '''simple docstring''' if str(__UpperCAmelCase ).startswith("""mps""" ): __UpperCAmelCase : int = torch.manual_seed(__UpperCAmelCase ) else: __UpperCAmelCase : List[str] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : Dict = self.get_dummy_components() __UpperCAmelCase : Tuple = LDMTextToImagePipeline(**__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __UpperCAmelCase : Dict = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : int = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Any = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : int = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __UpperCAmelCase : Tuple = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) __UpperCAmelCase : Union[str, Any] = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = pipe(**__UpperCAmelCase ).images[0] __UpperCAmelCase : Tuple = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) __UpperCAmelCase : Dict = np.abs(expected_image - image ).max() assert max_diff < 1E-3
16
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] )
16
'''simple docstring''' from __future__ import annotations from typing import Any class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 0 ) -> None: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = row, column __UpperCAmelCase : Union[str, Any] = [[default_value for c in range(__UpperCAmelCase )] for r in range(__UpperCAmelCase )] def __str__( self ) -> str: '''simple docstring''' __UpperCAmelCase : Dict = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __UpperCAmelCase : Optional[Any] = 0 for row_vector in self.array: for obj in row_vector: __UpperCAmelCase : Union[str, Any] = max(__UpperCAmelCase , len(str(__UpperCAmelCase ) ) ) __UpperCAmelCase : Optional[int] = f'%{max_element_length}s' # Make string and return def single_line(__UpperCAmelCase ) -> str: nonlocal string_format_identifier __UpperCAmelCase : Any = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__UpperCAmelCase ) for row_vector in self.array ) return s def __repr__( self ) -> str: '''simple docstring''' return str(self ) def __A ( self , __UpperCAmelCase ) -> bool: '''simple docstring''' if not (isinstance(__UpperCAmelCase , (list, tuple) ) and len(__UpperCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , __UpperCAmelCase ) -> Any: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = value def __add__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == another.row and self.column == another.column # Add __UpperCAmelCase : Dict = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] + another[r, c] return result def __neg__( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : Dict = -self[r, c] return result def __sub__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' return self + (-another) def __mul__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' if isinstance(__UpperCAmelCase , (int, float) ): # Scalar multiplication __UpperCAmelCase : Optional[int] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] * another return result elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # Matrix multiplication assert self.column == another.row __UpperCAmelCase : Dict = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __UpperCAmelCase : List[Any] = f'Unsupported type given for another ({type(__UpperCAmelCase )})' raise TypeError(__UpperCAmelCase ) def __A ( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Dict = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[str] = self[r, c] return result def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __UpperCAmelCase : Optional[Any] = v.transpose() __UpperCAmelCase : List[Any] = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Dict = Matrix(3 , 3 , 0 ) for i in range(3 ): __UpperCAmelCase : Tuple = 1 print(f'a^(-1) is {ainv}' ) # u, v __UpperCAmelCase : Dict = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = 1, 2, -3 __UpperCAmelCase : Union[str, Any] = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : int = 4, -2, 5 print(f'u is {u}' ) print(f'v is {v}' ) print(f'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCAmelCase__ , lowerCAmelCase__ )}' ) def lowercase_ ( ): """simple docstring""" import doctest doctest.testmod() testa()
16
1
'''simple docstring''' from __future__ import annotations import math class _A : def __init__( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[Any] = size # approximate the overall size of segment tree with given value __UpperCAmelCase : Dict = [0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCAmelCase : str = [0 for i in range(0 , 4 * size )] __UpperCAmelCase : List[str] = [0 for i in range(0 , 4 * size )] # flag for lazy update def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' return idx * 2 def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' return idx * 2 + 1 def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' if left_element == right_element: __UpperCAmelCase : Optional[Any] = a[left_element - 1] else: __UpperCAmelCase : int = (left_element + right_element) // 2 self.build(self.left(__UpperCAmelCase ) , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.build(self.right(__UpperCAmelCase ) , mid + 1 , __UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : List[Any] = max( self.segment_tree[self.left(__UpperCAmelCase )] , self.segment_tree[self.right(__UpperCAmelCase )] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> bool: '''simple docstring''' if self.flag[idx] is True: __UpperCAmelCase : Tuple = self.lazy[idx] __UpperCAmelCase : List[Any] = False if left_element != right_element: __UpperCAmelCase : Any = self.lazy[idx] __UpperCAmelCase : Optional[Any] = self.lazy[idx] __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : Any = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCAmelCase : Optional[int] = val if left_element != right_element: __UpperCAmelCase : Tuple = val __UpperCAmelCase : Dict = val __UpperCAmelCase : List[Any] = True __UpperCAmelCase : int = True return True __UpperCAmelCase : List[str] = (left_element + right_element) // 2 self.update(self.left(__UpperCAmelCase ) , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.update(self.right(__UpperCAmelCase ) , mid + 1 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : List[str] = max( self.segment_tree[self.left(__UpperCAmelCase )] , self.segment_tree[self.right(__UpperCAmelCase )] ) return True def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int | float: '''simple docstring''' if self.flag[idx] is True: __UpperCAmelCase : Dict = self.lazy[idx] __UpperCAmelCase : List[str] = False if left_element != right_element: __UpperCAmelCase : int = self.lazy[idx] __UpperCAmelCase : Optional[int] = self.lazy[idx] __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : Dict = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCAmelCase : List[str] = (left_element + right_element) // 2 __UpperCAmelCase : List[str] = self.query(self.left(__UpperCAmelCase ) , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : int = self.query(self.right(__UpperCAmelCase ) , mid + 1 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return max(__UpperCAmelCase , __UpperCAmelCase ) def __str__( self ) -> str: '''simple docstring''' return str([self.query(1 , 1 , self.size , __UpperCAmelCase , __UpperCAmelCase ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _UpperCamelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _UpperCamelCase = 15 _UpperCamelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _UpperCamelCase = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple def lowercase_ ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ): """simple docstring""" __UpperCAmelCase : str = namedtuple("""result""" , """name value""" ) if (voltage, current, power).count(0 ) != 1: raise ValueError("""Only one argument must be 0""" ) elif power < 0: raise ValueError( """Power cannot be negative in any electrical/electronics system""" ) elif voltage == 0: return result("""voltage""" , power / current ) elif current == 0: return result("""current""" , power / voltage ) elif power == 0: return result("""power""" , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = MODEL_FOR_MASKED_LM_MAPPING _SCREAMING_SNAKE_CASE : Tuple = TF_MODEL_FOR_MASKED_LM_MAPPING def __A ( self ) -> Any: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser"""}, ] , ) __UpperCAmelCase : List[str] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser""", }, ] , ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9E-05, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : Dict = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : str = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2E-05, """token""": 2_941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask> <mask>""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" ) # convert model to fp16 pipe.model.half() __UpperCAmelCase : str = pipe("""Paris is the [MASK] of France.""" ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) @slow @require_torch def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Any = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" ) self.run_large_test(__UpperCAmelCase ) @slow @require_tf def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : int = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" ) self.run_large_test(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1_573, """token_str""": """ Chris"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.251, """token""": 2_201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.214, """token""": 12_790, """token_str""": """ Lyon""", }, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" ) __UpperCAmelCase : Tuple = None __UpperCAmelCase : int = None self.run_pipeline_test(__UpperCAmelCase , [] ) @require_tf def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : str = None self.run_pipeline_test(__UpperCAmelCase , [] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" ) __UpperCAmelCase : str = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = [ f'This is another {tokenizer.mask_token} test', ] return fill_masker, examples def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = fill_masker.tokenizer __UpperCAmelCase : Union[str, Any] = fill_masker.model __UpperCAmelCase : Tuple = fill_masker( f'This is a {tokenizer.mask_token}' , ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : int = fill_masker([f'This is a {tokenizer.mask_token}'] ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Union[str, Any] = fill_masker([f'This is a {tokenizer.mask_token}', f'Another {tokenizer.mask_token} great test.'] ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , ) with self.assertRaises(__UpperCAmelCase ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(__UpperCAmelCase ): fill_masker("""This is""" ) self.run_test_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_targets(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_top_k_targets(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_duplicate_targets_and_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_multiple_masks(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Dict = tokenizer.get_vocab() __UpperCAmelCase : Dict = sorted(vocab.keys() )[:2] # Pipeline argument __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , targets=__UpperCAmelCase ) __UpperCAmelCase : List[str] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Any = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : int = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Call argument __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Tuple = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : List[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Score equivalence __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : Dict = [top_mask["""token_str"""] for top_mask in outputs] __UpperCAmelCase : str = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ) == set(__UpperCAmelCase ): __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : int = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) # Raises with invalid with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Any = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[""""""] ) with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , targets="""""" ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , top_k=2 ) __UpperCAmelCase : Optional[int] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : int = tokenizer.get_vocab() __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) # top_k=2, ntargets=3 __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 , targets=__UpperCAmelCase ) # If we use the most probably targets, and filter differently, we should still # have the same results __UpperCAmelCase : Tuple = [el["""token_str"""] for el in sorted(__UpperCAmelCase , key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ).issubset(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=3 , targets=__UpperCAmelCase ) # They should yield exactly the same result self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = tokenizer.get_vocab() # String duplicates + id duplicates __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : Dict = [targets[0], targets[1], targets[0], targets[2], targets[1]] __UpperCAmelCase : Optional[int] = fill_masker(f'My name is {tokenizer.mask_token}' , targets=__UpperCAmelCase , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(__UpperCAmelCase ) , 3 ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Dict = fill_masker( f'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , )
16
1
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : Optional[int]=None , lowerCAmelCase__ : Optional[int]=None ): """simple docstring""" return field(default_factory=lambda: default , metadata=lowerCAmelCase__ ) @dataclass class _A : _SCREAMING_SNAKE_CASE : List[str] = list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) _SCREAMING_SNAKE_CASE : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) _SCREAMING_SNAKE_CASE : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Use FP16 to accelerate inference."} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Benchmark training of model"} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Verbose memory tracing"} ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Trace memory line by line"} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Save result to a CSV file"} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Save all print statements in a log file"} ) _SCREAMING_SNAKE_CASE : bool = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to print environment information"} ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) _SCREAMING_SNAKE_CASE : str = field( default=f'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) _SCREAMING_SNAKE_CASE : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) _SCREAMING_SNAKE_CASE : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def __A ( self ) -> Any: '''simple docstring''' warnings.warn( f'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils' """ are deprecated in general and it is advised to use external Benchmarking libraries """ """ to benchmark Transformer models.""" , __UpperCAmelCase , ) def __A ( self ) -> List[str]: '''simple docstring''' return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def __A ( self ) -> List[str]: '''simple docstring''' if len(self.models ) <= 0: raise ValueError( """Please make sure you provide at least one model name / model identifier, *e.g.* `--models""" """ bert-base-cased` or `args.models = ['bert-base-cased'].""" ) return self.models @property def __A ( self ) -> Optional[int]: '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info("""Multiprocessing is currently not possible on TPU.""" ) return False else: return True
16
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"image": Image()} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"labels": ClassLabel} ) _SCREAMING_SNAKE_CASE : str = "image" _SCREAMING_SNAKE_CASE : str = "labels" def __A ( self , __UpperCAmelCase ) -> str: '''simple docstring''' if self.label_column not in features: raise ValueError(f'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] , __UpperCAmelCase ): raise ValueError(f'Column {self.label_column} is not a ClassLabel.' ) __UpperCAmelCase : int = copy.deepcopy(self ) __UpperCAmelCase : str = self.label_schema.copy() __UpperCAmelCase : Optional[Any] = features[self.label_column] __UpperCAmelCase : Optional[int] = label_schema return task_template @property def __A ( self ) -> Dict[str, str]: '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
16
1
'''simple docstring''' class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : int = data __UpperCAmelCase : int = previous __UpperCAmelCase : Union[str, Any] = next_node def __str__( self ) -> str: '''simple docstring''' return f'{self.data}' def __A ( self ) -> int: '''simple docstring''' return self.data def __A ( self ) -> List[str]: '''simple docstring''' return self.next def __A ( self ) -> str: '''simple docstring''' return self.previous class _A : def __init__( self , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = head def __iter__( self ) -> str: '''simple docstring''' return self def __A ( self ) -> str: '''simple docstring''' if not self.current: raise StopIteration else: __UpperCAmelCase : List[str] = self.current.get_data() __UpperCAmelCase : int = self.current.get_next() return value class _A : def __init__( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = None # First node in list __UpperCAmelCase : List[str] = None # Last node in list def __str__( self ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = self.head __UpperCAmelCase : Optional[int] = [] while current is not None: nodes.append(current.get_data() ) __UpperCAmelCase : Any = current.get_next() return " ".join(str(__UpperCAmelCase ) for node in nodes ) def __contains__( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.head while current: if current.get_data() == value: return True __UpperCAmelCase : Optional[Any] = current.get_next() return False def __iter__( self ) -> str: '''simple docstring''' return LinkedListIterator(self.head ) def __A ( self ) -> List[Any]: '''simple docstring''' if self.head: return self.head.get_data() return None def __A ( self ) -> Optional[Any]: '''simple docstring''' if self.tail: return self.tail.get_data() return None def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: __UpperCAmelCase : str = node __UpperCAmelCase : List[str] = node else: self.insert_before_node(self.head , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: self.set_head(__UpperCAmelCase ) else: self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[int] = Node(__UpperCAmelCase ) if self.head is None: self.set_head(__UpperCAmelCase ) else: self.set_tail(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Tuple = node __UpperCAmelCase : List[Any] = node.previous if node.get_previous() is None: __UpperCAmelCase : str = node_to_insert else: __UpperCAmelCase : Optional[Any] = node_to_insert __UpperCAmelCase : List[Any] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : List[str] = node __UpperCAmelCase : Union[str, Any] = node.next if node.get_next() is None: __UpperCAmelCase : Dict = node_to_insert else: __UpperCAmelCase : Any = node_to_insert __UpperCAmelCase : List[str] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Optional[Any] = Node(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.head while node: if current_position == position: self.insert_before_node(__UpperCAmelCase , __UpperCAmelCase ) return current_position += 1 __UpperCAmelCase : int = node.next self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Node: '''simple docstring''' __UpperCAmelCase : Dict = self.head while node: if node.get_data() == item: return node __UpperCAmelCase : List[str] = node.get_next() raise Exception("""Node not found""" ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' if (node := self.get_node(__UpperCAmelCase )) is not None: if node == self.head: __UpperCAmelCase : Optional[int] = self.head.get_next() if node == self.tail: __UpperCAmelCase : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(__UpperCAmelCase ) @staticmethod def __A ( __UpperCAmelCase ) -> None: '''simple docstring''' if node.get_next(): __UpperCAmelCase : Optional[Any] = node.previous if node.get_previous(): __UpperCAmelCase : int = node.next __UpperCAmelCase : Tuple = None __UpperCAmelCase : Union[str, Any] = None def __A ( self ) -> List[Any]: '''simple docstring''' return self.head is None def lowercase_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = parent __UpperCAmelCase : Union[str, Any] = batch_size __UpperCAmelCase : Tuple = seq_length __UpperCAmelCase : str = is_training __UpperCAmelCase : Union[str, Any] = use_input_mask __UpperCAmelCase : List[Any] = use_token_type_ids __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : str = vocab_size __UpperCAmelCase : Union[str, Any] = hidden_size __UpperCAmelCase : Optional[int] = num_hidden_layers __UpperCAmelCase : str = num_attention_heads __UpperCAmelCase : Optional[Any] = intermediate_size __UpperCAmelCase : Optional[int] = hidden_act __UpperCAmelCase : List[str] = hidden_dropout_prob __UpperCAmelCase : List[str] = attention_probs_dropout_prob __UpperCAmelCase : Tuple = max_position_embeddings __UpperCAmelCase : Dict = type_vocab_size __UpperCAmelCase : List[Any] = type_sequence_label_size __UpperCAmelCase : List[Any] = initializer_range __UpperCAmelCase : List[str] = num_labels __UpperCAmelCase : str = num_choices __UpperCAmelCase : List[Any] = scope def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Dict = None if self.use_input_mask: __UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : int = None if self.use_token_type_ids: __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : List[Any] = None __UpperCAmelCase : Union[str, Any] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Any = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ) -> Optional[Any]: '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = LlamaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Dict = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = True __UpperCAmelCase : List[str] = LlamaModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) __UpperCAmelCase : Tuple = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = LlamaForCausalLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : int = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Any = True __UpperCAmelCase : Tuple = LlamaForCausalLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() # first forward pass __UpperCAmelCase : Optional[int] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase , ) __UpperCAmelCase : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __UpperCAmelCase : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCAmelCase : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __UpperCAmelCase : str = torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCAmelCase : Union[str, Any] = torch.cat([input_mask, next_mask] , dim=-1 ) __UpperCAmelCase : int = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["""hidden_states"""][0] __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , output_hidden_states=__UpperCAmelCase , )["""hidden_states"""][0] # select random slice __UpperCAmelCase : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCAmelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() __UpperCAmelCase : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-3 ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Any = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = config_and_inputs __UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _SCREAMING_SNAKE_CASE : Any = (LlamaForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE : List[str] = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : List[str] = False def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = LlamaModelTester(self ) __UpperCAmelCase : Tuple = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __A ( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : str = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Any = 3 __UpperCAmelCase : Optional[Any] = input_dict["""input_ids"""] __UpperCAmelCase : int = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCAmelCase : Dict = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[int] = 3 __UpperCAmelCase : Optional[Any] = """single_label_classification""" __UpperCAmelCase : int = input_dict["""input_ids"""] __UpperCAmelCase : List[Any] = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCAmelCase : Tuple = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[Any] = 3 __UpperCAmelCase : str = """multi_label_classification""" __UpperCAmelCase : Union[str, Any] = input_dict["""input_ids"""] __UpperCAmelCase : int = input_ids.ne(1 ).to(__UpperCAmelCase ) __UpperCAmelCase : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __UpperCAmelCase : Dict = LlamaForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""LLaMA buffers include complex numbers, which breaks this test""" ) def __A ( self ) -> Dict: '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def __A ( self , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : List[Any] = ids_tensor([1, 10] , config.vocab_size ) __UpperCAmelCase : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCAmelCase : Optional[Any] = LlamaModel(__UpperCAmelCase ) original_model.to(__UpperCAmelCase ) original_model.eval() __UpperCAmelCase : int = original_model(__UpperCAmelCase ).last_hidden_state __UpperCAmelCase : List[str] = original_model(__UpperCAmelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCAmelCase : Dict = {"""type""": scaling_type, """factor""": 10.0} __UpperCAmelCase : Optional[Any] = LlamaModel(__UpperCAmelCase ) scaled_model.to(__UpperCAmelCase ) scaled_model.eval() __UpperCAmelCase : Optional[Any] = scaled_model(__UpperCAmelCase ).last_hidden_state __UpperCAmelCase : List[str] = scaled_model(__UpperCAmelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-5 ) ) @require_torch class _A ( unittest.TestCase ): @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Optional[int] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : Optional[int] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf""" , device_map="""auto""" ) __UpperCAmelCase : int = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __UpperCAmelCase : str = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : List[Any] = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Any = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : int = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf""" , device_map="""auto""" ) __UpperCAmelCase : str = model(torch.tensor(__UpperCAmelCase ) ) # Expected mean on dim = -1 __UpperCAmelCase : str = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : List[str] = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!""" ) @slow def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : Union[str, Any] = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" , device_map="""auto""" ) __UpperCAmelCase : Union[str, Any] = model(torch.tensor(__UpperCAmelCase ) ) # Expected mean on dim = -1 __UpperCAmelCase : Dict = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off __UpperCAmelCase : Any = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) @unittest.skip( """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test""" ) @slow def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Any = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] __UpperCAmelCase : str = LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf""" , device_map="""auto""" ) __UpperCAmelCase : List[Any] = model(torch.tensor(__UpperCAmelCase ) ) __UpperCAmelCase : Dict = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , __UpperCAmelCase , atol=1E-2 , rtol=1E-2 ) # fmt: off __UpperCAmelCase : List[str] = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , __UpperCAmelCase , atol=1E-5 , rtol=1E-5 ) @unittest.skip("""Model is curently gated""" ) @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi""" __UpperCAmelCase : Dict = """Simply put, the theory of relativity states that """ __UpperCAmelCase : int = LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""" ) __UpperCAmelCase : int = tokenizer.encode(__UpperCAmelCase , return_tensors="""pt""" ) __UpperCAmelCase : int = LlamaForCausalLM.from_pretrained( """meta-llama/Llama-2-13b-chat-hf""" , device_map="""sequential""" , use_safetensors=__UpperCAmelCase ) # greedy generation outputs __UpperCAmelCase : Tuple = model.generate(__UpperCAmelCase , max_new_tokens=64 , top_p=__UpperCAmelCase , temperature=1 , do_sample=__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = tokenizer.decode(generated_ids[0] , skip_special_tokens=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
16
1
'''simple docstring''' from __future__ import annotations def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] | None = None ): """simple docstring""" __UpperCAmelCase : Any = word_bank or [] # create a table __UpperCAmelCase : int = len(lowerCAmelCase__ ) + 1 __UpperCAmelCase : list[list[list[str]]] = [] for _ in range(lowerCAmelCase__ ): table.append([] ) # seed value __UpperCAmelCase : Optional[int] = [[]] # because empty string has empty combination # iterate through the indices for i in range(lowerCAmelCase__ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowerCAmelCase__ )] == word: __UpperCAmelCase : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(lowerCAmelCase__ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowerCAmelCase__ )]: combination.reverse() return table[len(lowerCAmelCase__ )] if __name__ == "__main__": print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa'''])) print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t'''])) print( all_construct( '''hexagonosaurus''', ['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''], ) )
16
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip _UpperCamelCase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ): """simple docstring""" return max(metric_fn(lowerCAmelCase__ , lowerCAmelCase__ ) for gt in ground_truths ) def lowercase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = [] if args.gold_data_mode == "qa": __UpperCAmelCase : Tuple = pd.read_csv(lowerCAmelCase__ , sep="""\t""" , header=lowerCAmelCase__ ) for answer_list in data[1]: __UpperCAmelCase : Optional[int] = ast.literal_eval(lowerCAmelCase__ ) answers.append(lowerCAmelCase__ ) else: __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : str = [[reference] for reference in references] __UpperCAmelCase : Optional[int] = 0 for prediction, ground_truths in zip(lowerCAmelCase__ , lowerCAmelCase__ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) fa += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : int = 100.0 * em / total __UpperCAmelCase : Dict = 100.0 * fa / total logger.info(f'F1: {fa:.2f}' ) logger.info(f'EM: {em:.2f}' ) def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" __UpperCAmelCase : Tuple = args.k __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = 0 for hypo, reference in zip(lowerCAmelCase__ , lowerCAmelCase__ ): __UpperCAmelCase : List[str] = set(hypo.split("""\t""" )[:k] ) __UpperCAmelCase : List[Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k __UpperCAmelCase : List[str] = 100.0 * em / total logger.info(f'Precision@{k}: {em: .2f}' ) def lowercase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ): """simple docstring""" def strip_title(lowerCAmelCase__ : Optional[int] ): if title.startswith("""\"""" ): __UpperCAmelCase : List[Any] = title[1:] if title.endswith("""\"""" ): __UpperCAmelCase : int = title[:-1] return title __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , )["""input_ids"""].to(args.device ) __UpperCAmelCase : str = rag_model.rag.question_encoder(lowerCAmelCase__ ) __UpperCAmelCase : int = question_enc_outputs[0] __UpperCAmelCase : Dict = rag_model.retriever( lowerCAmelCase__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) __UpperCAmelCase : Union[str, Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) __UpperCAmelCase : Union[str, Any] = [] for docs in all_docs: __UpperCAmelCase : int = [strip_title(lowerCAmelCase__ ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(lowerCAmelCase__ ) ) return provenance_strings def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ): """simple docstring""" with torch.no_grad(): __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ ) __UpperCAmelCase : List[str] = inputs_dict.input_ids.to(args.device ) __UpperCAmelCase : List[Any] = inputs_dict.attention_mask.to(args.device ) __UpperCAmelCase : List[str] = rag_model.generate( # rag_model overwrites generate lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) __UpperCAmelCase : str = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) if args.print_predictions: for q, a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): logger.info("""Q: {} - A: {}""".format(lowerCAmelCase__ , lowerCAmelCase__ ) ) return answers def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=lowerCAmelCase__ , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=lowerCAmelCase__ , choices=["""exact""", """compressed""", """legacy"""] , type=lowerCAmelCase__ , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=lowerCAmelCase__ , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=lowerCAmelCase__ , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=lowerCAmelCase__ , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=lowerCAmelCase__ , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=lowerCAmelCase__ , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=lowerCAmelCase__ , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=lowerCAmelCase__ , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=lowerCAmelCase__ , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=lowerCAmelCase__ , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) __UpperCAmelCase : str = parser.parse_args() __UpperCAmelCase : Optional[Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowercase_ ( lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[Any] = {} if args.model_type is None: __UpperCAmelCase : str = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Tuple = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration __UpperCAmelCase : Dict = args.n_docs if args.index_name is not None: __UpperCAmelCase : Union[str, Any] = args.index_name if args.index_path is not None: __UpperCAmelCase : Dict = args.index_path else: __UpperCAmelCase : str = BartForConditionalGeneration __UpperCAmelCase : str = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = get_scores if args.eval_mode == """e2e""" else get_precision_at_k __UpperCAmelCase : Any = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(lowerCAmelCase__ ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Optional[int] = RagRetriever.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) __UpperCAmelCase : Any = model_class.from_pretrained(lowerCAmelCase__ , retriever=lowerCAmelCase__ , **lowerCAmelCase__ ) model.retriever.init_retrieval() else: __UpperCAmelCase : Tuple = model_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: __UpperCAmelCase : Union[str, Any] = [] for line in tqdm(lowerCAmelCase__ ): questions.append(line.strip() ) if len(lowerCAmelCase__ ) == args.eval_batch_size: __UpperCAmelCase : Any = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) + """\n""" ) preds_file.flush() __UpperCAmelCase : List[str] = [] if len(lowerCAmelCase__ ) > 0: __UpperCAmelCase : Optional[Any] = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) ) preds_file.flush() score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": _UpperCamelCase = get_args() main(args)
16
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class _A ( unittest.TestCase ): def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = tempfile.mkdtemp() # fmt: off __UpperCAmelCase : Optional[int] = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __UpperCAmelCase : List[Any] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : str = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __UpperCAmelCase : str = {"""unk_token""": """<unk>"""} __UpperCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __UpperCAmelCase : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__UpperCAmelCase ) ) __UpperCAmelCase : List[str] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], } __UpperCAmelCase : Tuple = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> List[Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCAmelCase : int = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : int = self.get_tokenizer() __UpperCAmelCase : Optional[int] = self.get_rust_tokenizer() __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Union[str, Any] = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Optional[Any] = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) __UpperCAmelCase : int = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) __UpperCAmelCase : List[str] = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , __UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , __UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Optional[int] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __UpperCAmelCase : Tuple = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) __UpperCAmelCase : Any = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : int = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = self.prepare_image_inputs() __UpperCAmelCase : Dict = image_processor(__UpperCAmelCase , return_tensors="""np""" ) __UpperCAmelCase : Dict = processor(images=__UpperCAmelCase , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = self.get_image_processor() __UpperCAmelCase : Optional[int] = self.get_tokenizer() __UpperCAmelCase : Any = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = """lower newer""" __UpperCAmelCase : List[str] = processor(text=__UpperCAmelCase ) __UpperCAmelCase : Any = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : List[str] = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Any = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : str = """lower newer""" __UpperCAmelCase : Union[str, Any] = self.prepare_image_inputs() __UpperCAmelCase : List[str] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Any = self.get_image_processor() __UpperCAmelCase : int = self.get_tokenizer() __UpperCAmelCase : Any = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = self.prepare_image_inputs() __UpperCAmelCase : Optional[int] = self.prepare_image_inputs() __UpperCAmelCase : int = processor(images=__UpperCAmelCase , visual_prompt=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """conditional_pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : Union[str, Any] = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __UpperCAmelCase : List[str] = processor.batch_decode(__UpperCAmelCase ) __UpperCAmelCase : str = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
16
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _A : @staticmethod def __A ( *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' pass @is_pipeline_test @require_vision @require_torch class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Optional[int] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) __UpperCAmelCase : Optional[int] = [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Optional[int] = object_detector(examples[0] , threshold=0.0 ) __UpperCAmelCase : Tuple = len(__UpperCAmelCase ) self.assertGreater(__UpperCAmelCase , 0 ) self.assertEqual( __UpperCAmelCase , [ { """score""": ANY(__UpperCAmelCase ), """label""": ANY(__UpperCAmelCase ), """box""": {"""xmin""": ANY(__UpperCAmelCase ), """ymin""": ANY(__UpperCAmelCase ), """xmax""": ANY(__UpperCAmelCase ), """ymax""": ANY(__UpperCAmelCase )}, } for i in range(__UpperCAmelCase ) ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __A ( self ) -> Tuple: '''simple docstring''' pass @require_torch def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) __UpperCAmelCase : Optional[int] = object_detector( """./tests/fixtures/tests_samples/COCO/000000039769.png""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=0.64 , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] , ) __UpperCAmelCase : str = object_detector( [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] ] , ) @require_torch @slow def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : List[Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ] , ) __UpperCAmelCase : Any = object_detector( [ { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, ] , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __A ( self ) -> List[str]: '''simple docstring''' pass @require_torch @slow def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = 0.2 __UpperCAmelCase : List[Any] = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : Optional[int] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, ] , ) @require_torch @slow def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 2 __UpperCAmelCase : Optional[int] = pipeline("""zero-shot-object-detection""" ) __UpperCAmelCase : List[Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , top_k=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=4 ) , [ {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, ] , )
16
1
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE : Optional[Any] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Optional[Any] = True def __A ( self ) -> Dict: '''simple docstring''' super().setUp() __UpperCAmelCase : List[Any] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __UpperCAmelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __A ( self , **__UpperCAmelCase ) -> int: '''simple docstring''' return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : str = """UNwant\u00E9d,running""" __UpperCAmelCase : Optional[Any] = """unwanted, running""" return input_text, output_text def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.tokenizer_class(self.vocab_file ) __UpperCAmelCase : int = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(__UpperCAmelCase , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [7, 4, 5, 10, 8, 9] ) def __A ( self ) -> str: '''simple docstring''' pass
16
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'''vocab_file''': '''vocab.txt'''} _UpperCamelCase = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } _UpperCamelCase = { '''YituTech/conv-bert-base''': 512, '''YituTech/conv-bert-medium-small''': 512, '''YituTech/conv-bert-small''': 512, } _UpperCamelCase = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : List[Any] = ConvBertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Optional[Any]: '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCAmelCase ) != tokenize_chinese_chars ): __UpperCAmelCase : Dict = getattr(__UpperCAmelCase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : Union[str, Any] = do_lower_case __UpperCAmelCase : str = strip_accents __UpperCAmelCase : Union[str, Any] = tokenize_chinese_chars __UpperCAmelCase : List[Any] = normalizer_class(**__UpperCAmelCase ) __UpperCAmelCase : List[Any] = do_lower_case def __A ( self , __UpperCAmelCase , __UpperCAmelCase=None ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : list ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = 0 while len(lowerCAmelCase__ ) > 1: __UpperCAmelCase : Dict = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): __UpperCAmelCase : Optional[Any] = files.index(min(lowerCAmelCase__ ) ) temp += files[min_index] files.pop(lowerCAmelCase__ ) files.append(lowerCAmelCase__ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _UpperCamelCase = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''OwlViTFeatureExtractor'''] _UpperCamelCase = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
'''simple docstring''' print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))'''))
16
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _UpperCamelCase = logging.get_logger(__name__) class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> None: '''simple docstring''' warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
16
1
'''simple docstring''' import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) _UpperCamelCase = logging.getLogger(__name__) def lowercase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Any ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = np.argmax(lowerCAmelCase__ , axis=1 ) return np.sum(outputs == labels ) def lowercase_ ( lowerCAmelCase__ : Optional[Any] ): """simple docstring""" with open(lowerCAmelCase__ , encoding="""utf_8""" ) as f: __UpperCAmelCase : Union[str, Any] = csv.reader(lowerCAmelCase__ ) __UpperCAmelCase : Any = [] next(lowerCAmelCase__ ) # skip the first line for line in tqdm(lowerCAmelCase__ ): output.append((""" """.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple ): """simple docstring""" __UpperCAmelCase : str = [] for dataset in encoded_datasets: __UpperCAmelCase : List[str] = len(lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCAmelCase : Optional[Any] = np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCAmelCase : Optional[Any] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __UpperCAmelCase : Dict = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(lowerCAmelCase__ ): __UpperCAmelCase : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCAmelCase : int = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCAmelCase : Tuple = with_conta __UpperCAmelCase : str = with_conta __UpperCAmelCase : Dict = len(lowerCAmelCase__ ) - 1 __UpperCAmelCase : Tuple = len(lowerCAmelCase__ ) - 1 __UpperCAmelCase : Tuple = with_conta __UpperCAmelCase : Optional[Any] = with_conta __UpperCAmelCase : Dict = mc_label __UpperCAmelCase : Tuple = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(lowerCAmelCase__ ) for t in all_inputs ) ) return tensor_datasets def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Dict = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=lowerCAmelCase__ , default="""openai-gpt""" , help="""pretrained model name""" ) parser.add_argument("""--do_train""" , action="""store_true""" , help="""Whether to run training.""" ) parser.add_argument("""--do_eval""" , action="""store_true""" , help="""Whether to run eval on the dev set.""" ) parser.add_argument( """--output_dir""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""The output directory where the model predictions and checkpoints will be written.""" , ) parser.add_argument("""--train_dataset""" , type=lowerCAmelCase__ , default="""""" ) parser.add_argument("""--eval_dataset""" , type=lowerCAmelCase__ , default="""""" ) parser.add_argument("""--seed""" , type=lowerCAmelCase__ , default=42 ) parser.add_argument("""--num_train_epochs""" , type=lowerCAmelCase__ , default=3 ) parser.add_argument("""--train_batch_size""" , type=lowerCAmelCase__ , default=8 ) parser.add_argument("""--eval_batch_size""" , type=lowerCAmelCase__ , default=16 ) parser.add_argument("""--adam_epsilon""" , default=1E-8 , type=lowerCAmelCase__ , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , type=lowerCAmelCase__ , default=1 ) parser.add_argument( """--max_steps""" , default=-1 , type=lowerCAmelCase__ , help=( """If > 0: set total number of training steps to perform. Override num_train_epochs.""" ) , ) parser.add_argument( """--gradient_accumulation_steps""" , type=lowerCAmelCase__ , default=1 , help="""Number of updates steps to accumulate before performing a backward/update pass.""" , ) parser.add_argument("""--learning_rate""" , type=lowerCAmelCase__ , default=6.25E-5 ) parser.add_argument("""--warmup_steps""" , default=0 , type=lowerCAmelCase__ , help="""Linear warmup over warmup_steps.""" ) parser.add_argument("""--lr_schedule""" , type=lowerCAmelCase__ , default="""warmup_linear""" ) parser.add_argument("""--weight_decay""" , type=lowerCAmelCase__ , default=0.01 ) parser.add_argument("""--lm_coef""" , type=lowerCAmelCase__ , default=0.9 ) parser.add_argument("""--n_valid""" , type=lowerCAmelCase__ , default=374 ) parser.add_argument("""--server_ip""" , type=lowerCAmelCase__ , default="""""" , help="""Can be used for distant debugging.""" ) parser.add_argument("""--server_port""" , type=lowerCAmelCase__ , default="""""" , help="""Can be used for distant debugging.""" ) __UpperCAmelCase : Union[str, Any] = parser.parse_args() print(lowerCAmelCase__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("""Waiting for debugger attach""" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCAmelCase__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCAmelCase : Optional[Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __UpperCAmelCase : Tuple = torch.cuda.device_count() logger.info("""device: {}, n_gpu {}""".format(lowerCAmelCase__ , lowerCAmelCase__ ) ) if not args.do_train and not args.do_eval: raise ValueError("""At least one of `do_train` or `do_eval` must be True.""" ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCAmelCase : List[Any] = ["""_start_""", """_delimiter_""", """_classify_"""] __UpperCAmelCase : Dict = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(lowerCAmelCase__ ) ) model.to(lowerCAmelCase__ ) # Load and encode the datasets def tokenize_and_encode(lowerCAmelCase__ : List[str] ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(lowerCAmelCase__ ) ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): return obj return [tokenize_and_encode(lowerCAmelCase__ ) for o in obj] logger.info("""Encoding dataset...""" ) __UpperCAmelCase : Any = load_rocstories_dataset(args.train_dataset ) __UpperCAmelCase : Optional[Any] = load_rocstories_dataset(args.eval_dataset ) __UpperCAmelCase : Optional[int] = (train_dataset, eval_dataset) __UpperCAmelCase : str = tokenize_and_encode(lowerCAmelCase__ ) # Compute the max input length for the Transformer __UpperCAmelCase : Optional[Any] = model.config.n_positions // 2 - 2 __UpperCAmelCase : Dict = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCAmelCase : Any = min(lowerCAmelCase__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCAmelCase : Any = pre_process_datasets(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = tensor_datasets[0], tensor_datasets[1] __UpperCAmelCase : Optional[Any] = TensorDataset(*lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = RandomSampler(lowerCAmelCase__ ) __UpperCAmelCase : int = DataLoader(lowerCAmelCase__ , sampler=lowerCAmelCase__ , batch_size=args.train_batch_size ) __UpperCAmelCase : Optional[int] = TensorDataset(*lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = SequentialSampler(lowerCAmelCase__ ) __UpperCAmelCase : Any = DataLoader(lowerCAmelCase__ , sampler=lowerCAmelCase__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCAmelCase : Dict = args.max_steps __UpperCAmelCase : str = args.max_steps // (len(lowerCAmelCase__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCAmelCase : Optional[int] = len(lowerCAmelCase__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCAmelCase : Union[str, Any] = list(model.named_parameters() ) __UpperCAmelCase : Dict = ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""] __UpperCAmelCase : List[str] = [ { """params""": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], """weight_decay""": args.weight_decay, }, {"""params""": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], """weight_decay""": 0.0}, ] __UpperCAmelCase : Union[str, Any] = AdamW(lowerCAmelCase__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCAmelCase : Dict = get_linear_schedule_with_warmup( lowerCAmelCase__ , num_warmup_steps=args.warmup_steps , num_training_steps=lowerCAmelCase__ ) if args.do_train: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[str] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="""Epoch""" ): __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : Any = 0 __UpperCAmelCase : Optional[int] = tqdm(lowerCAmelCase__ , desc="""Training""" ) for step, batch in enumerate(lowerCAmelCase__ ): __UpperCAmelCase : Optional[Any] = tuple(t.to(lowerCAmelCase__ ) for t in batch ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : str = batch __UpperCAmelCase : List[str] = model(lowerCAmelCase__ , mc_token_ids=lowerCAmelCase__ , lm_labels=lowerCAmelCase__ , mc_labels=lowerCAmelCase__ ) __UpperCAmelCase : List[str] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCAmelCase : Tuple = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCAmelCase : Optional[Any] = """Training loss: {:.2e} lr: {:.2e}""".format(lowerCAmelCase__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCAmelCase : Dict = model.module if hasattr(lowerCAmelCase__ , """module""" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCAmelCase : Any = os.path.join(args.output_dir , lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = os.path.join(args.output_dir , lowerCAmelCase__ ) torch.save(model_to_save.state_dict() , lowerCAmelCase__ ) model_to_save.config.to_json_file(lowerCAmelCase__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCAmelCase : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCAmelCase : Union[str, Any] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(lowerCAmelCase__ ) if args.do_eval: model.eval() __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = 0, 0 __UpperCAmelCase , __UpperCAmelCase : int = 0, 0 for batch in tqdm(lowerCAmelCase__ , desc="""Evaluating""" ): __UpperCAmelCase : str = tuple(t.to(lowerCAmelCase__ ) for t in batch ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Dict = batch with torch.no_grad(): __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[str] = model( lowerCAmelCase__ , mc_token_ids=lowerCAmelCase__ , lm_labels=lowerCAmelCase__ , mc_labels=lowerCAmelCase__ ) __UpperCAmelCase : str = mc_logits.detach().cpu().numpy() __UpperCAmelCase : str = mc_labels.to("""cpu""" ).numpy() __UpperCAmelCase : Dict = accuracy(lowerCAmelCase__ , lowerCAmelCase__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCAmelCase : Optional[Any] = eval_loss / nb_eval_steps __UpperCAmelCase : Any = eval_accuracy / nb_eval_examples __UpperCAmelCase : Any = tr_loss / nb_tr_steps if args.do_train else None __UpperCAmelCase : Optional[int] = {"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss} __UpperCAmelCase : List[str] = os.path.join(args.output_dir , """eval_results.txt""" ) with open(lowerCAmelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , lowerCAmelCase__ , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) if __name__ == "__main__": main()
16
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _UpperCamelCase = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _SCREAMING_SNAKE_CASE : int = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _SCREAMING_SNAKE_CASE : int = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __UpperCAmelCase : List[Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : int = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __UpperCAmelCase : Optional[int] = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __UpperCAmelCase : Dict = text_classifier("""This is great !""" , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __UpperCAmelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __UpperCAmelCase : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' import torch __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = pipeline("""text-classification""" ) __UpperCAmelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : Any = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = pipeline("""text-classification""" , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __UpperCAmelCase : int = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __UpperCAmelCase : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = TextClassificationPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) return text_classifier, ["HuggingFace is in", "This is another test"] def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : int = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __UpperCAmelCase : Union[str, Any] = """HuggingFace is in""" __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __UpperCAmelCase : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}, {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __UpperCAmelCase : Any = text_classifier(__UpperCAmelCase , top_k=__UpperCAmelCase ) __UpperCAmelCase : Any = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [[{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N, [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] * N] , ) __UpperCAmelCase : str = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __UpperCAmelCase : Optional[int] = text_classifier(__UpperCAmelCase ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , {"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __UpperCAmelCase : Union[str, Any] = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(__UpperCAmelCase ): text_classifier(__UpperCAmelCase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __UpperCAmelCase : Tuple = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [{"""label""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
16
1
'''simple docstring''' import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch _UpperCamelCase = '''sshleifer/bart-tiny-random''' _UpperCamelCase = '''patrickvonplaten/t5-tiny-random''' @require_torch class _A ( unittest.TestCase ): @cached_property def __A ( self ) -> Tuple: '''simple docstring''' return AutoConfig.from_pretrained(__UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase , *__UpperCAmelCase : Union[str, Any] = create_student_by_copying_alternating_layers(__UpperCAmelCase , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , *__UpperCAmelCase : Optional[Any] = create_student_by_copying_alternating_layers(__UpperCAmelCase , tempfile.mkdtemp() , e=1 , d=__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase , *__UpperCAmelCase : Tuple = create_student_by_copying_alternating_layers(__UpperCAmelCase , tempfile.mkdtemp() , e=1 , d=__UpperCAmelCase ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase , *__UpperCAmelCase : str = create_student_by_copying_alternating_layers(__UpperCAmelCase , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def __A ( self ) -> List[Any]: '''simple docstring''' with self.assertRaises(__UpperCAmelCase ): create_student_by_copying_alternating_layers(__UpperCAmelCase , tempfile.mkdtemp() , e=__UpperCAmelCase , d=__UpperCAmelCase )
16
'''simple docstring''' from ..utils import DummyObject, requires_backends class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> str: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Tuple = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[str] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> int: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Any = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] ) class _A ( metaclass=__SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = ["sentencepiece"] def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' requires_backends(self , ["""sentencepiece"""] )
16
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule _UpperCamelCase = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class _A : def __init__( self , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=64 , __UpperCAmelCase=None ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = np.random.default_rng(__UpperCAmelCase ) __UpperCAmelCase : List[str] = length __UpperCAmelCase : List[Any] = rng.normal(size=(length,) ).astype(np.floataa ) __UpperCAmelCase : Union[str, Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Dict: '''simple docstring''' return self.length def __getitem__( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> int: '''simple docstring''' super().__init__() __UpperCAmelCase : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Optional[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __UpperCAmelCase : Any = True def __A ( self , __UpperCAmelCase=None ) -> str: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : Optional[int] = False return x * self.a[0] + self.b[0] class _A ( torch.nn.Module ): def __init__( self , __UpperCAmelCase=0 , __UpperCAmelCase=0 , __UpperCAmelCase=False ) -> Optional[Any]: '''simple docstring''' super().__init__() __UpperCAmelCase : Tuple = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : List[str] = torch.nn.Parameter(torch.tensor(__UpperCAmelCase ).float() ) __UpperCAmelCase : str = True def __A ( self , __UpperCAmelCase=None ) -> Tuple: '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __UpperCAmelCase : int = False return x * self.a + self.b def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int = 16 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __UpperCAmelCase : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __UpperCAmelCase : List[str] = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} __UpperCAmelCase : Tuple = load_dataset("""csv""" , data_files=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = datasets["""train"""].unique("""label""" ) __UpperCAmelCase : str = {v: i for i, v in enumerate(lowerCAmelCase__ )} def tokenize_function(lowerCAmelCase__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __UpperCAmelCase : List[Any] = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding="""max_length""" ) if "label" in examples: __UpperCAmelCase : Optional[Any] = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __UpperCAmelCase : Tuple = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. __UpperCAmelCase : Optional[Any] = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=2 ) __UpperCAmelCase : List[Any] = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=1 ) return train_dataloader, eval_dataloader
16
1
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig _UpperCamelCase = logging.get_logger(__name__) # General docstring _UpperCamelCase = '''PoolFormerConfig''' # Base docstring _UpperCamelCase = '''sail/poolformer_s12''' _UpperCamelCase = [1, 512, 7, 7] # Image classification docstring _UpperCamelCase = '''sail/poolformer_s12''' _UpperCamelCase = '''tabby, tabby cat''' _UpperCamelCase = [ '''sail/poolformer_s12''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : float = 0.0 , lowerCAmelCase__ : bool = False ): """simple docstring""" if drop_prob == 0.0 or not training: return input __UpperCAmelCase : Dict = 1 - drop_prob __UpperCAmelCase : str = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets __UpperCAmelCase : List[Any] = keep_prob + torch.rand(lowerCAmelCase__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize __UpperCAmelCase : Optional[int] = input.div(lowerCAmelCase__ ) * random_tensor return output class _A ( nn.Module ): def __init__( self , __UpperCAmelCase = None ) -> None: '''simple docstring''' super().__init__() __UpperCAmelCase : Optional[Any] = drop_prob def __A ( self , __UpperCAmelCase ) -> torch.Tensor: '''simple docstring''' return drop_path(__UpperCAmelCase , self.drop_prob , self.training ) def __A ( self ) -> str: '''simple docstring''' return "p={}".format(self.drop_prob ) class _A ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ) -> Any: '''simple docstring''' super().__init__() __UpperCAmelCase : List[Any] = patch_size if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (patch_size, patch_size) __UpperCAmelCase : Any = stride if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (stride, stride) __UpperCAmelCase : Optional[int] = padding if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (padding, padding) __UpperCAmelCase : Dict = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , kernel_size=__UpperCAmelCase , stride=__UpperCAmelCase , padding=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = norm_layer(__UpperCAmelCase ) if norm_layer else nn.Identity() def __A ( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = self.projection(__UpperCAmelCase ) __UpperCAmelCase : Tuple = self.norm(__UpperCAmelCase ) return embeddings class _A ( nn.GroupNorm ): def __init__( self , __UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' super().__init__(1 , __UpperCAmelCase , **__UpperCAmelCase ) class _A ( nn.Module ): def __init__( self , __UpperCAmelCase ) -> Any: '''simple docstring''' super().__init__() __UpperCAmelCase : Dict = nn.AvgPoolad(__UpperCAmelCase , stride=1 , padding=pool_size // 2 , count_include_pad=__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Any: '''simple docstring''' return self.pool(__UpperCAmelCase ) - hidden_states class _A ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' super().__init__() __UpperCAmelCase : Optional[Any] = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , 1 ) __UpperCAmelCase : Dict = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , 1 ) __UpperCAmelCase : int = PoolFormerDropPath(__UpperCAmelCase ) if isinstance(config.hidden_act , __UpperCAmelCase ): __UpperCAmelCase : Optional[Any] = ACTaFN[config.hidden_act] else: __UpperCAmelCase : str = config.hidden_act def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = self.conva(__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.act_fn(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.drop(__UpperCAmelCase ) __UpperCAmelCase : int = self.conva(__UpperCAmelCase ) __UpperCAmelCase : Tuple = self.drop(__UpperCAmelCase ) return hidden_states class _A ( nn.Module ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' super().__init__() __UpperCAmelCase : List[str] = PoolFormerPooling(__UpperCAmelCase ) __UpperCAmelCase : Any = PoolFormerOutput(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : Optional[int] = PoolFormerGroupNorm(__UpperCAmelCase ) __UpperCAmelCase : int = PoolFormerGroupNorm(__UpperCAmelCase ) # Useful for training neural nets __UpperCAmelCase : Optional[int] = PoolFormerDropPath(__UpperCAmelCase ) if drop_path > 0.0 else nn.Identity() __UpperCAmelCase : Optional[Any] = config.use_layer_scale if config.use_layer_scale: __UpperCAmelCase : Union[str, Any] = nn.Parameter( config.layer_scale_init_value * torch.ones((__UpperCAmelCase) ) , requires_grad=__UpperCAmelCase ) __UpperCAmelCase : int = nn.Parameter( config.layer_scale_init_value * torch.ones((__UpperCAmelCase) ) , requires_grad=__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' if self.use_layer_scale: __UpperCAmelCase : int = self.pooling(self.before_norm(__UpperCAmelCase ) ) __UpperCAmelCase : str = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection __UpperCAmelCase : List[str] = hidden_states + self.drop_path(__UpperCAmelCase ) __UpperCAmelCase : List[str] = () __UpperCAmelCase : Union[str, Any] = self.output(self.after_norm(__UpperCAmelCase ) ) __UpperCAmelCase : Optional[Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection __UpperCAmelCase : int = hidden_states + self.drop_path(__UpperCAmelCase ) __UpperCAmelCase : List[str] = (output,) + outputs return outputs else: __UpperCAmelCase : Dict = self.drop_path(self.pooling(self.before_norm(__UpperCAmelCase ) ) ) # First residual connection __UpperCAmelCase : Dict = pooling_output + hidden_states __UpperCAmelCase : Any = () # Second residual connection inside the PoolFormerOutput block __UpperCAmelCase : Optional[int] = self.drop_path(self.output(self.after_norm(__UpperCAmelCase ) ) ) __UpperCAmelCase : Tuple = hidden_states + layer_output __UpperCAmelCase : int = (output,) + outputs return outputs class _A ( nn.Module ): def __init__( self , __UpperCAmelCase ) -> Any: '''simple docstring''' super().__init__() __UpperCAmelCase : Tuple = config # stochastic depth decay rule __UpperCAmelCase : str = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings __UpperCAmelCase : int = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) __UpperCAmelCase : int = nn.ModuleList(__UpperCAmelCase ) # Transformer blocks __UpperCAmelCase : List[Any] = [] __UpperCAmelCase : List[Any] = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers __UpperCAmelCase : Any = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __UpperCAmelCase , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__UpperCAmelCase ) ) __UpperCAmelCase : List[Any] = nn.ModuleList(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase=False , __UpperCAmelCase=True ) -> Any: '''simple docstring''' __UpperCAmelCase : Optional[int] = () if output_hidden_states else None __UpperCAmelCase : Optional[int] = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): __UpperCAmelCase , __UpperCAmelCase : List[str] = layers # Get patch embeddings from hidden_states __UpperCAmelCase : List[str] = embedding_layer(__UpperCAmelCase ) # Send the embeddings through the blocks for _, blk in enumerate(__UpperCAmelCase ): __UpperCAmelCase : Dict = blk(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = layer_outputs[0] if output_hidden_states: __UpperCAmelCase : int = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__UpperCAmelCase , hidden_states=__UpperCAmelCase ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = PoolFormerConfig _SCREAMING_SNAKE_CASE : Optional[int] = "poolformer" _SCREAMING_SNAKE_CASE : Union[str, Any] = "pixel_values" _SCREAMING_SNAKE_CASE : Optional[int] = True def __A ( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' if isinstance(__UpperCAmelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__UpperCAmelCase , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase=False ) -> Optional[Any]: '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCAmelCase : Any = value _UpperCamelCase = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' _UpperCamelCase = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. ''' @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase ) -> Dict: '''simple docstring''' super().__init__(__UpperCAmelCase ) __UpperCAmelCase : List[str] = config __UpperCAmelCase : Optional[int] = PoolFormerEncoder(__UpperCAmelCase ) # Initialize weights and apply final processing self.post_init() def __A ( self ) -> Dict: '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: '''simple docstring''' __UpperCAmelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __UpperCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) __UpperCAmelCase : List[str] = self.encoder( __UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase , ) __UpperCAmelCase : Tuple = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , ) class _A ( nn.Module ): def __init__( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' super().__init__() __UpperCAmelCase : Union[str, Any] = nn.Linear(config.hidden_size , config.hidden_size ) def __A ( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.dense(__UpperCAmelCase ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , __SCREAMING_SNAKE_CASE , ) class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase ) -> List[str]: '''simple docstring''' super().__init__(__UpperCAmelCase ) __UpperCAmelCase : Tuple = config.num_labels __UpperCAmelCase : List[str] = PoolFormerModel(__UpperCAmelCase ) # Final norm __UpperCAmelCase : List[Any] = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head __UpperCAmelCase : Union[str, Any] = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: '''simple docstring''' __UpperCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __UpperCAmelCase : List[str] = self.poolformer( __UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase , ) __UpperCAmelCase : Any = outputs[0] __UpperCAmelCase : Any = self.classifier(self.norm(__UpperCAmelCase ).mean([-2, -1] ) ) __UpperCAmelCase : List[Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __UpperCAmelCase : Union[str, Any] = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __UpperCAmelCase : Optional[int] = """single_label_classification""" else: __UpperCAmelCase : str = """multi_label_classification""" if self.config.problem_type == "regression": __UpperCAmelCase : Optional[int] = MSELoss() if self.num_labels == 1: __UpperCAmelCase : str = loss_fct(logits.squeeze() , labels.squeeze() ) else: __UpperCAmelCase : int = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) elif self.config.problem_type == "single_label_classification": __UpperCAmelCase : str = CrossEntropyLoss() __UpperCAmelCase : List[str] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __UpperCAmelCase : Any = BCEWithLogitsLoss() __UpperCAmelCase : Union[str, Any] = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) if not return_dict: __UpperCAmelCase : Any = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase , logits=__UpperCAmelCase , hidden_states=outputs.hidden_states )
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ViTImageProcessor if is_vision_available() else None @property def __A ( self ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = (3, 32, 128) __UpperCAmelCase : Tuple = tempfile.mkdtemp() # fmt: off __UpperCAmelCase : Any = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __UpperCAmelCase : Optional[int] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) __UpperCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) __UpperCAmelCase : List[Any] = { """do_normalize""": False, """do_resize""": True, """image_processor_type""": """ViTImageProcessor""", """resample""": 3, """size""": {"""height""": 32, """width""": 128}, } __UpperCAmelCase : Tuple = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> Tuple: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __UpperCAmelCase : Dict = Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) return image_input def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.get_tokenizer() __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : Optional[Any] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Tuple = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Dict = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) __UpperCAmelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __UpperCAmelCase : Union[str, Any] = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) __UpperCAmelCase : List[Any] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Tuple = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.prepare_image_inputs() __UpperCAmelCase : str = image_processor(__UpperCAmelCase , return_tensors="""np""" ) __UpperCAmelCase : int = processor(images=__UpperCAmelCase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : int = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Dict = """test""" __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.get_image_processor() __UpperCAmelCase : Tuple = self.get_tokenizer() __UpperCAmelCase : Optional[int] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = """test""" __UpperCAmelCase : int = self.prepare_image_inputs() __UpperCAmelCase : Tuple = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """labels"""] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_image_processor() __UpperCAmelCase : List[Any] = self.get_tokenizer() __UpperCAmelCase : List[str] = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __UpperCAmelCase : Optional[Any] = processor.char_decode(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = tokenizer.batch_decode(__UpperCAmelCase ) __UpperCAmelCase : int = [seq.replace(""" """ , """""" ) for seq in decoded_tok] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = self.get_image_processor() __UpperCAmelCase : Optional[Any] = self.get_tokenizer() __UpperCAmelCase : Any = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : str = None __UpperCAmelCase : Dict = self.prepare_image_inputs() __UpperCAmelCase : Union[str, Any] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : Any = self.get_image_processor() __UpperCAmelCase : List[str] = self.get_tokenizer() __UpperCAmelCase : str = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) __UpperCAmelCase : Tuple = torch.randn(1 , 27 , 38 ) __UpperCAmelCase : Union[str, Any] = torch.randn(1 , 27 , 50_257 ) __UpperCAmelCase : Any = torch.randn(1 , 27 , 30_522 ) __UpperCAmelCase : Tuple = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["""generated_text""", """scores""", """char_preds""", """bpe_preds""", """wp_preds"""] )
16
1
'''simple docstring''' from math import sqrt def lowercase_ ( lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : int = 0 for i in range(1 , int(sqrt(lowerCAmelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase__ ): total += i + n // i elif i == sqrt(lowerCAmelCase__ ): total += i return total - n def lowercase_ ( lowerCAmelCase__ : int = 10000 ): """simple docstring""" __UpperCAmelCase : List[Any] = sum( i for i in range(1 , lowerCAmelCase__ ) if sum_of_divisors(sum_of_divisors(lowerCAmelCase__ ) ) == i and sum_of_divisors(lowerCAmelCase__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
16
'''simple docstring''' from collections.abc import Sequence def lowercase_ ( lowerCAmelCase__ : Sequence[int] | None = None ): """simple docstring""" if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) __UpperCAmelCase : Any = nums[0] for i in range(1 , len(lowerCAmelCase__ ) ): __UpperCAmelCase : Union[str, Any] = nums[i] __UpperCAmelCase : List[Any] = max(lowerCAmelCase__ , ans + num , lowerCAmelCase__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _UpperCamelCase = int(input('''Enter number of elements : ''').strip()) _UpperCamelCase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n] print(max_subsequence_sum(array))
16
1
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: _UpperCamelCase = None _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} _UpperCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/tokenizer.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/tokenizer.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/tokenizer.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/tokenizer.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/tokenizer.json''', }, } # TODO(PVP) - this should be removed in Transformers v5 _UpperCamelCase = { '''t5-small''': 512, '''t5-base''': 512, '''t5-large''': 512, '''t5-3b''': 512, '''t5-11b''': 512, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : Dict = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : List[Any] = TaTokenizer _SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="</s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase=100 , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Optional[Any]: '''simple docstring''' # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __UpperCAmelCase : str = [f'<extra_id_{i}>' for i in range(__UpperCAmelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens __UpperCAmelCase : Union[str, Any] = len(set(filter(lambda __UpperCAmelCase : bool("""extra_id_""" in str(__UpperCAmelCase ) ) , __UpperCAmelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , extra_ids=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Union[str, Any] = vocab_file __UpperCAmelCase : Any = False if not self.vocab_file else True __UpperCAmelCase : Tuple = extra_ids @staticmethod def __A ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: __UpperCAmelCase : Optional[int] = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" f' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" f' {pretrained_model_name_or_path} automatically truncating your input to' f' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' f' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __UpperCAmelCase , ) return max_model_length def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__UpperCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCAmelCase : Optional[int] = os.path.join( __UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) logger.info(f'Copy vocab file to {out_vocab_file}' ) return (out_vocab_file,) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Any = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: __UpperCAmelCase : Optional[int] = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Dict = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self ) -> int: '''simple docstring''' return list( set(filter(lambda __UpperCAmelCase : bool(re.search(r"""<extra_id_\d+>""" , __UpperCAmelCase ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self ) -> Optional[Any]: '''simple docstring''' return [self.convert_tokens_to_ids(__UpperCAmelCase ) for token in self.get_sentinel_tokens()]
16
'''simple docstring''' class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : int = data __UpperCAmelCase : int = previous __UpperCAmelCase : Union[str, Any] = next_node def __str__( self ) -> str: '''simple docstring''' return f'{self.data}' def __A ( self ) -> int: '''simple docstring''' return self.data def __A ( self ) -> List[str]: '''simple docstring''' return self.next def __A ( self ) -> str: '''simple docstring''' return self.previous class _A : def __init__( self , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = head def __iter__( self ) -> str: '''simple docstring''' return self def __A ( self ) -> str: '''simple docstring''' if not self.current: raise StopIteration else: __UpperCAmelCase : List[str] = self.current.get_data() __UpperCAmelCase : int = self.current.get_next() return value class _A : def __init__( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = None # First node in list __UpperCAmelCase : List[str] = None # Last node in list def __str__( self ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = self.head __UpperCAmelCase : Optional[int] = [] while current is not None: nodes.append(current.get_data() ) __UpperCAmelCase : Any = current.get_next() return " ".join(str(__UpperCAmelCase ) for node in nodes ) def __contains__( self , __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.head while current: if current.get_data() == value: return True __UpperCAmelCase : Optional[Any] = current.get_next() return False def __iter__( self ) -> str: '''simple docstring''' return LinkedListIterator(self.head ) def __A ( self ) -> List[Any]: '''simple docstring''' if self.head: return self.head.get_data() return None def __A ( self ) -> Optional[Any]: '''simple docstring''' if self.tail: return self.tail.get_data() return None def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: __UpperCAmelCase : str = node __UpperCAmelCase : List[str] = node else: self.insert_before_node(self.head , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' if self.head is None: self.set_head(__UpperCAmelCase ) else: self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[int] = Node(__UpperCAmelCase ) if self.head is None: self.set_head(__UpperCAmelCase ) else: self.set_tail(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Tuple = node __UpperCAmelCase : List[Any] = node.previous if node.get_previous() is None: __UpperCAmelCase : str = node_to_insert else: __UpperCAmelCase : Optional[Any] = node_to_insert __UpperCAmelCase : List[Any] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : List[str] = node __UpperCAmelCase : Union[str, Any] = node.next if node.get_next() is None: __UpperCAmelCase : Dict = node_to_insert else: __UpperCAmelCase : Any = node_to_insert __UpperCAmelCase : List[str] = node_to_insert def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Optional[Any] = Node(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.head while node: if current_position == position: self.insert_before_node(__UpperCAmelCase , __UpperCAmelCase ) return current_position += 1 __UpperCAmelCase : int = node.next self.insert_after_node(self.tail , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Node: '''simple docstring''' __UpperCAmelCase : Dict = self.head while node: if node.get_data() == item: return node __UpperCAmelCase : List[str] = node.get_next() raise Exception("""Node not found""" ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' if (node := self.get_node(__UpperCAmelCase )) is not None: if node == self.head: __UpperCAmelCase : Optional[int] = self.head.get_next() if node == self.tail: __UpperCAmelCase : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(__UpperCAmelCase ) @staticmethod def __A ( __UpperCAmelCase ) -> None: '''simple docstring''' if node.get_next(): __UpperCAmelCase : Optional[Any] = node.previous if node.get_previous(): __UpperCAmelCase : int = node.next __UpperCAmelCase : Tuple = None __UpperCAmelCase : Union[str, Any] = None def __A ( self ) -> List[Any]: '''simple docstring''' return self.head is None def lowercase_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
16
1
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : List[str] = 3 __UpperCAmelCase : Dict = (32, 32) __UpperCAmelCase : Optional[int] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__UpperCAmelCase ) return image @property def __A ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) return model @property def __A ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __A ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(__UpperCAmelCase ) @property def __A ( self ) -> Tuple: '''simple docstring''' def extract(*__UpperCAmelCase , **__UpperCAmelCase ): class _A : def __init__( self ) -> Any: '''simple docstring''' __UpperCAmelCase : str = torch.ones([0] ) def __A ( self , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' self.pixel_values.to(__UpperCAmelCase ) return self return Out() return extract def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Any = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : Union[str, Any] = self.dummy_cond_unet __UpperCAmelCase : Optional[int] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) __UpperCAmelCase : int = self.dummy_vae __UpperCAmelCase : Tuple = self.dummy_text_encoder __UpperCAmelCase : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCAmelCase : List[str] = StableDiffusionPipeline( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=self.dummy_extractor , ) __UpperCAmelCase : str = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = """A painting of a squirrel eating a burger""" __UpperCAmelCase : str = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) __UpperCAmelCase : List[Any] = sd_pipe([prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCAmelCase : Union[str, Any] = output.images __UpperCAmelCase : Tuple = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) __UpperCAmelCase : str = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=__UpperCAmelCase , )[0] __UpperCAmelCase : str = image[0, -3:, -3:, -1] __UpperCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCAmelCase : List[Any] = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : List[str] = self.dummy_cond_unet __UpperCAmelCase : Union[str, Any] = PNDMScheduler(skip_prk_steps=__UpperCAmelCase ) __UpperCAmelCase : str = self.dummy_vae __UpperCAmelCase : List[str] = self.dummy_text_encoder __UpperCAmelCase : Optional[int] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCAmelCase : str = StableDiffusionPipeline( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=self.dummy_extractor , ) __UpperCAmelCase : Union[str, Any] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Tuple = """A painting of a squirrel eating a burger""" __UpperCAmelCase : Union[str, Any] = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) __UpperCAmelCase : List[Any] = sd_pipe([prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCAmelCase : Any = output.images __UpperCAmelCase : Tuple = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) __UpperCAmelCase : Optional[Any] = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=__UpperCAmelCase , )[0] __UpperCAmelCase : str = image[0, -3:, -3:, -1] __UpperCAmelCase : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCAmelCase : List[str] = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[Any] = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=__UpperCAmelCase ) assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert isinstance(pipe.scheduler , __UpperCAmelCase ) assert pipe.safety_checker is None __UpperCAmelCase : List[Any] = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__UpperCAmelCase ) __UpperCAmelCase : Dict = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCAmelCase : int = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : List[str] = self.dummy_cond_unet __UpperCAmelCase : Optional[int] = PNDMScheduler(skip_prk_steps=__UpperCAmelCase ) __UpperCAmelCase : List[str] = self.dummy_vae __UpperCAmelCase : str = self.dummy_text_encoder __UpperCAmelCase : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCAmelCase : List[Any] = unet.half() __UpperCAmelCase : List[Any] = vae.half() __UpperCAmelCase : List[Any] = bert.half() # make sure here that pndm scheduler skips prk __UpperCAmelCase : int = StableDiffusionPipeline( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=self.dummy_extractor , ) __UpperCAmelCase : Any = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : str = """A painting of a squirrel eating a burger""" __UpperCAmelCase : str = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Optional[int]: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=__UpperCAmelCase ) __UpperCAmelCase : List[str] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCAmelCase : List[Any] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Tuple = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCAmelCase : int = 4_003_660_346 __UpperCAmelCase : List[str] = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCAmelCase : List[str] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Tuple = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) __UpperCAmelCase : Union[str, Any] = output.images __UpperCAmelCase : Dict = image[0, -3:, -3:, -1] __UpperCAmelCase : Union[str, Any] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCAmelCase : str = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Tuple = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCAmelCase : Optional[int] = output.images __UpperCAmelCase : Dict = image[0, -3:, -3:, -1] __UpperCAmelCase : List[str] = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=__UpperCAmelCase ) __UpperCAmelCase : Any = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCAmelCase : int = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Dict = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCAmelCase : Optional[Any] = 2_734_971_755 __UpperCAmelCase : Any = 7 __UpperCAmelCase : List[Any] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : int = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) __UpperCAmelCase : Optional[Any] = output.images __UpperCAmelCase : Dict = image[0, -3:, -3:, -1] __UpperCAmelCase : Optional[Any] = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCAmelCase : Any = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : str = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCAmelCase : str = output.images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] __UpperCAmelCase : List[Any] = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCAmelCase : List[Any] = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCAmelCase : Optional[int] = 1_044_355_234 __UpperCAmelCase : int = 12 __UpperCAmelCase : Any = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) __UpperCAmelCase : int = output.images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] __UpperCAmelCase : List[Any] = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCAmelCase : List[str] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = sd_pipe( [prompt] , generator=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCAmelCase : Tuple = output.images __UpperCAmelCase : int = image[0, -3:, -3:, -1] __UpperCAmelCase : List[str] = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
16
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class _A : _SCREAMING_SNAKE_CASE : List[str] _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="Translation" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ) -> Any: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class _A : _SCREAMING_SNAKE_CASE : Optional[List] = None _SCREAMING_SNAKE_CASE : Optional[int] = None _SCREAMING_SNAKE_CASE : Optional[str] = None # Automatically constructed _SCREAMING_SNAKE_CASE : ClassVar[str] = "dict" _SCREAMING_SNAKE_CASE : ClassVar[Any] = None _SCREAMING_SNAKE_CASE : str = field(default="TranslationVariableLanguages" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = sorted(set(self.languages ) ) if self.languages else None __UpperCAmelCase : int = len(self.languages ) if self.languages else None def __call__( self ) -> Optional[Any]: '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def __A ( self , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = set(self.languages ) if self.languages and set(__UpperCAmelCase ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(__UpperCAmelCase ) - lang_set ) )}) are not in valid set ({", ".join(__UpperCAmelCase )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __UpperCAmelCase : Dict = [] for lang, text in translation_dict.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = zip(*sorted(__UpperCAmelCase ) ) return {"language": languages, "translation": translations} def __A ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
16
1
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class _A ( __SCREAMING_SNAKE_CASE ): @staticmethod @abstractmethod def __A ( __UpperCAmelCase ) -> str: '''simple docstring''' raise NotImplementedError() @abstractmethod def __A ( self ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError()
16
'''simple docstring''' from statistics import mean import numpy as np def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Tuple = 0 # Number of processes finished __UpperCAmelCase : Optional[int] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. __UpperCAmelCase : Tuple = [0] * no_of_process # List to include calculation results __UpperCAmelCase : int = [0] * no_of_process # Sort by arrival time. __UpperCAmelCase : Dict = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] __UpperCAmelCase : Union[str, Any] = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: __UpperCAmelCase : Dict = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: __UpperCAmelCase : Any = arrival_time[i] __UpperCAmelCase : Any = 0 # Index showing the location of the process being performed __UpperCAmelCase : Any = 0 # Saves the current response ratio. __UpperCAmelCase : List[str] = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: __UpperCAmelCase : Dict = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: __UpperCAmelCase : Tuple = temp __UpperCAmelCase : List[str] = i # Calculate the turn around time __UpperCAmelCase : Tuple = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. __UpperCAmelCase : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase_ ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[int] = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): __UpperCAmelCase : List[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _UpperCamelCase = 5 _UpperCamelCase = ['''A''', '''B''', '''C''', '''D''', '''E'''] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = [1, 2, 3, 4, 5] _UpperCamelCase = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _UpperCamelCase = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
16
1
'''simple docstring''' import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A ( unittest.TestCase ): def __A ( self ) -> List[Any]: '''simple docstring''' debug_launcher(test_script.main ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' debug_launcher(test_ops.main )
16
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=2 , __UpperCAmelCase=8 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=16 , __UpperCAmelCase=5 , __UpperCAmelCase=2 , __UpperCAmelCase=36 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> List[str]: '''simple docstring''' __UpperCAmelCase : int = parent __UpperCAmelCase : Any = batch_size __UpperCAmelCase : Union[str, Any] = seq_length __UpperCAmelCase : int = is_training __UpperCAmelCase : Union[str, Any] = use_input_mask __UpperCAmelCase : List[str] = use_token_type_ids __UpperCAmelCase : List[str] = use_labels __UpperCAmelCase : Optional[Any] = vocab_size __UpperCAmelCase : Tuple = hidden_size __UpperCAmelCase : Union[str, Any] = num_hidden_layers __UpperCAmelCase : Optional[int] = num_attention_heads __UpperCAmelCase : str = intermediate_size __UpperCAmelCase : List[Any] = hidden_act __UpperCAmelCase : Optional[Any] = hidden_dropout_prob __UpperCAmelCase : List[Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[Any] = max_position_embeddings __UpperCAmelCase : List[Any] = type_vocab_size __UpperCAmelCase : Dict = type_sequence_label_size __UpperCAmelCase : Optional[Any] = initializer_range __UpperCAmelCase : Optional[Any] = num_labels __UpperCAmelCase : Optional[Any] = num_choices __UpperCAmelCase : int = scope def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : List[Any] = None if self.use_input_mask: __UpperCAmelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCAmelCase : Any = None if self.use_token_type_ids: __UpperCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Tuple = None __UpperCAmelCase : Optional[int] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __UpperCAmelCase : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ) -> List[str]: '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.get_config() __UpperCAmelCase : List[Any] = 300 return config def __A ( self ) -> Dict: '''simple docstring''' ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = self.prepare_config_and_inputs() __UpperCAmelCase : Tuple = True __UpperCAmelCase : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = MraModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[str] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : Any = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) __UpperCAmelCase : List[str] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : List[str] = True __UpperCAmelCase : List[Any] = MraModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , ) __UpperCAmelCase : Dict = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , ) __UpperCAmelCase : List[Any] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Any = MraForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[int] = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: '''simple docstring''' __UpperCAmelCase : str = MraForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Optional[Any] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> str: '''simple docstring''' __UpperCAmelCase : int = self.num_labels __UpperCAmelCase : int = MraForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = self.num_labels __UpperCAmelCase : str = MraForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Tuple = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = self.num_choices __UpperCAmelCase : int = MraForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCAmelCase : List[str] = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : List[Any] = config_and_inputs __UpperCAmelCase : Tuple = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : int = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : Dict = () def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = MraModelTester(self ) __UpperCAmelCase : Optional[Any] = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __A ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : List[Any] = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase ) def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Any: '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Tuple = MraModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip(reason="""MRA does not output attentions""" ) def __A ( self ) -> List[Any]: '''simple docstring''' return @require_torch class _A ( unittest.TestCase ): @slow def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Tuple = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : str = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : List[Any] = model(__UpperCAmelCase )[0] __UpperCAmelCase : Optional[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) __UpperCAmelCase : Union[str, Any] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : int = model(__UpperCAmelCase )[0] __UpperCAmelCase : Union[str, Any] = 50_265 __UpperCAmelCase : Union[str, Any] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : int = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) __UpperCAmelCase : Dict = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __UpperCAmelCase : Any = model(__UpperCAmelCase )[0] __UpperCAmelCase : Dict = 50_265 __UpperCAmelCase : Optional[int] = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) __UpperCAmelCase : str = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int = 50 ): """simple docstring""" __UpperCAmelCase : Any = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F'{solution() = }')
16
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=32 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=16 , __UpperCAmelCase=[1, 2, 1] , __UpperCAmelCase=[2, 2, 4] , __UpperCAmelCase=2 , __UpperCAmelCase=2.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=10 , __UpperCAmelCase=8 , ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = parent __UpperCAmelCase : Union[str, Any] = batch_size __UpperCAmelCase : Any = image_size __UpperCAmelCase : Dict = patch_size __UpperCAmelCase : Dict = num_channels __UpperCAmelCase : List[Any] = embed_dim __UpperCAmelCase : str = depths __UpperCAmelCase : Dict = num_heads __UpperCAmelCase : str = window_size __UpperCAmelCase : int = mlp_ratio __UpperCAmelCase : Union[str, Any] = qkv_bias __UpperCAmelCase : Dict = hidden_dropout_prob __UpperCAmelCase : str = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = drop_path_rate __UpperCAmelCase : List[str] = hidden_act __UpperCAmelCase : Optional[int] = use_absolute_embeddings __UpperCAmelCase : Any = patch_norm __UpperCAmelCase : Union[str, Any] = layer_norm_eps __UpperCAmelCase : Optional[int] = initializer_range __UpperCAmelCase : Tuple = is_training __UpperCAmelCase : Any = scope __UpperCAmelCase : Optional[Any] = use_labels __UpperCAmelCase : Optional[int] = type_sequence_label_size __UpperCAmelCase : int = encoder_stride def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase : Tuple = None if self.use_labels: __UpperCAmelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __A ( self ) -> Dict: '''simple docstring''' return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Union[str, Any] = model(__UpperCAmelCase ) __UpperCAmelCase : Tuple = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __UpperCAmelCase : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Any = SwinvaForMaskedImageModeling(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : List[Any] = model(__UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCAmelCase : Optional[Any] = 1 __UpperCAmelCase : Dict = SwinvaForMaskedImageModeling(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCAmelCase : str = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : str = self.type_sequence_label_size __UpperCAmelCase : str = SwinvaForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() __UpperCAmelCase : Any = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[Any] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = config_and_inputs __UpperCAmelCase : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : List[str] = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : List[str] = SwinvaModelTester(self ) __UpperCAmelCase : Any = ConfigTester(self , config_class=__UpperCAmelCase , embed_dim=37 ) def __A ( self ) -> Any: '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def __A ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def __A ( self ) -> Dict: '''simple docstring''' pass def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = model_class(__UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCAmelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCAmelCase , nn.Linear ) ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Tuple = model_class(__UpperCAmelCase ) __UpperCAmelCase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : str = [*signature.parameters.keys()] __UpperCAmelCase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Optional[Any] = True for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : int = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : str = outputs.attentions __UpperCAmelCase : Any = len(self.model_tester.depths ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase : Dict = True __UpperCAmelCase : int = config.window_size**2 __UpperCAmelCase : Any = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : int = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : Dict = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) __UpperCAmelCase : Dict = len(__UpperCAmelCase ) # Check attention is always last and order is fine __UpperCAmelCase : Any = True __UpperCAmelCase : Any = True __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[str] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): __UpperCAmelCase : Any = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states __UpperCAmelCase : Optional[int] = 2 self.assertEqual(out_len + added_hidden_states , len(__UpperCAmelCase ) ) __UpperCAmelCase : Tuple = outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : Optional[Any] = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) __UpperCAmelCase : List[Any] = outputs.hidden_states __UpperCAmelCase : List[Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) # Swinv2 has a different seq_length __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __UpperCAmelCase : int = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCAmelCase ) , __UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : str = reshaped_hidden_states[0].shape __UpperCAmelCase : Any = ( reshaped_hidden_states[0].view(__UpperCAmelCase , __UpperCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Union[str, Any] = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = 3 __UpperCAmelCase : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __UpperCAmelCase : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __UpperCAmelCase : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __UpperCAmelCase : Union[str, Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __UpperCAmelCase : int = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Tuple = True self.check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , (padded_height, padded_width) ) def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCAmelCase ) def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def __A ( self ) -> Optional[Any]: '''simple docstring''' for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Dict = SwinvaModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __A ( self ) -> Any: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Tuple = _config_zero_init(__UpperCAmelCase ) for model_class in self.all_model_classes: __UpperCAmelCase : List[Any] = model_class(config=__UpperCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class _A ( unittest.TestCase ): @cached_property def __A ( self ) -> int: '''simple docstring''' return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Tuple = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __UpperCAmelCase ) __UpperCAmelCase : Tuple = self.default_image_processor __UpperCAmelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __UpperCAmelCase : Any = image_processor(images=__UpperCAmelCase , return_tensors="""pt""" ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): __UpperCAmelCase : Optional[int] = model(**__UpperCAmelCase ) # verify the logits __UpperCAmelCase : int = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCAmelCase , atol=1E-4 ) )
16
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _A ( __SCREAMING_SNAKE_CASE ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: '''simple docstring''' super().__init__() self.register_modules(vqvae=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) @torch.no_grad() def __call__( self , __UpperCAmelCase = 1 , __UpperCAmelCase = None , __UpperCAmelCase = 0.0 , __UpperCAmelCase = 50 , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , **__UpperCAmelCase , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' __UpperCAmelCase : List[str] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=__UpperCAmelCase , ) __UpperCAmelCase : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __UpperCAmelCase : Dict = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(__UpperCAmelCase ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature __UpperCAmelCase : List[Any] = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __UpperCAmelCase : int = {} if accepts_eta: __UpperCAmelCase : Union[str, Any] = eta for t in self.progress_bar(self.scheduler.timesteps ): __UpperCAmelCase : List[Any] = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) # predict the noise residual __UpperCAmelCase : Dict = self.unet(__UpperCAmelCase , __UpperCAmelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __UpperCAmelCase : List[str] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample # decode the image latents with the VAE __UpperCAmelCase : Tuple = self.vqvae.decode(__UpperCAmelCase ).sample __UpperCAmelCase : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) __UpperCAmelCase : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCAmelCase : List[str] = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase )
16
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase__ ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : int = size if size is not None else {"""shortest_edge""": 256} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) __UpperCAmelCase : int = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : Any = do_center_crop __UpperCAmelCase : Any = crop_size __UpperCAmelCase : Optional[Any] = resample __UpperCAmelCase : Dict = do_rescale __UpperCAmelCase : List[str] = rescale_factor __UpperCAmelCase : Dict = offset __UpperCAmelCase : List[str] = do_normalize __UpperCAmelCase : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __UpperCAmelCase : str = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : List[str] = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" in size: __UpperCAmelCase : Union[str, Any] = get_resize_output_image_size(__UpperCAmelCase , size["""shortest_edge"""] , default_to_square=__UpperCAmelCase ) elif "height" in size and "width" in size: __UpperCAmelCase : Any = (size["""height"""], size["""width"""]) else: raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}' ) return resize(__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Any = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}' ) return center_crop(__UpperCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = image.astype(np.floataa ) if offset: __UpperCAmelCase : Tuple = image - (scale / 2) return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Optional[Any] = to_numpy_array(__UpperCAmelCase ) if do_resize: __UpperCAmelCase : Optional[int] = self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase ) if do_center_crop: __UpperCAmelCase : Optional[int] = self.center_crop(__UpperCAmelCase , size=__UpperCAmelCase ) if do_rescale: __UpperCAmelCase : int = self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase , offset=__UpperCAmelCase ) if do_normalize: __UpperCAmelCase : List[str] = self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) return image def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: '''simple docstring''' __UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : List[Any] = resample if resample is not None else self.resample __UpperCAmelCase : str = do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCAmelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCAmelCase : List[Any] = offset if offset is not None else self.offset __UpperCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Optional[Any] = image_mean if image_mean is not None else self.image_mean __UpperCAmelCase : int = image_std if image_std is not None else self.image_std __UpperCAmelCase : Any = size if size is not None else self.size __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size __UpperCAmelCase : str = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) __UpperCAmelCase : int = make_batched(__UpperCAmelCase ) __UpperCAmelCase : Tuple = [ [ self._preprocess_image( image=__UpperCAmelCase , do_resize=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , do_center_crop=__UpperCAmelCase , crop_size=__UpperCAmelCase , do_rescale=__UpperCAmelCase , rescale_factor=__UpperCAmelCase , offset=__UpperCAmelCase , do_normalize=__UpperCAmelCase , image_mean=__UpperCAmelCase , image_std=__UpperCAmelCase , data_format=__UpperCAmelCase , ) for img in video ] for video in videos ] __UpperCAmelCase : Tuple = {"""pixel_values""": videos} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
16
1
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _UpperCamelCase = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= version.Version('''3.6.4'''): from nltk import word_tokenize _UpperCamelCase = '''\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } ''' _UpperCamelCase = '''\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. ''' _UpperCamelCase = ''' Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: \'meteor\': meteor score. Examples: >>> meteor = datasets.load_metric(\'meteor\') >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"] >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results["meteor"], 4)) 0.6944 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _A ( datasets.Metric ): def __A ( self ) -> Union[str, Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""] , reference_urls=[ """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""", """https://en.wikipedia.org/wiki/METEOR""", ] , ) def __A ( self , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' import nltk nltk.download("""wordnet""" ) if NLTK_VERSION >= version.Version("""3.6.5""" ): nltk.download("""punkt""" ) if NLTK_VERSION >= version.Version("""3.6.6""" ): nltk.download("""omw-1.4""" ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=0.9 , __UpperCAmelCase=3 , __UpperCAmelCase=0.5 ) -> List[Any]: '''simple docstring''' if NLTK_VERSION >= version.Version("""3.6.5""" ): __UpperCAmelCase : int = [ meteor_score.single_meteor_score( word_tokenize(__UpperCAmelCase ) , word_tokenize(__UpperCAmelCase ) , alpha=__UpperCAmelCase , beta=__UpperCAmelCase , gamma=__UpperCAmelCase ) for ref, pred in zip(__UpperCAmelCase , __UpperCAmelCase ) ] else: __UpperCAmelCase : Dict = [ meteor_score.single_meteor_score(__UpperCAmelCase , __UpperCAmelCase , alpha=__UpperCAmelCase , beta=__UpperCAmelCase , gamma=__UpperCAmelCase ) for ref, pred in zip(__UpperCAmelCase , __UpperCAmelCase ) ] return {"meteor": np.mean(__UpperCAmelCase )}
16
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _A ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = LDMTextToImagePipeline _SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_PARAMS - { "negative_prompt", "negative_prompt_embeds", "cross_attention_kwargs", "prompt_embeds", } _SCREAMING_SNAKE_CASE : List[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "callback", "callback_steps", } _SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE : List[str] = False def __A ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __UpperCAmelCase : List[Any] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) __UpperCAmelCase : Any = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __UpperCAmelCase : Tuple = CLIPTextModel(__UpperCAmelCase ) __UpperCAmelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCAmelCase : Dict = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def __A ( self , __UpperCAmelCase , __UpperCAmelCase=0 ) -> Any: '''simple docstring''' if str(__UpperCAmelCase ).startswith("""mps""" ): __UpperCAmelCase : int = torch.manual_seed(__UpperCAmelCase ) else: __UpperCAmelCase : List[str] = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) __UpperCAmelCase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : Dict = self.get_dummy_components() __UpperCAmelCase : Tuple = LDMTextToImagePipeline(**__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_dummy_inputs(__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __UpperCAmelCase : Dict = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> int: '''simple docstring''' __UpperCAmelCase : Tuple = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : int = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> str: '''simple docstring''' __UpperCAmelCase : Any = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : int = pipe(**__UpperCAmelCase ).images __UpperCAmelCase : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __UpperCAmelCase : Tuple = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) __UpperCAmelCase : Union[str, Any] = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class _A ( unittest.TestCase ): def __A ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self , __UpperCAmelCase , __UpperCAmelCase=torch.floataa , __UpperCAmelCase=0 ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Optional[Any] = torch.manual_seed(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = np.random.RandomState(__UpperCAmelCase ).standard_normal((1, 4, 32, 32) ) __UpperCAmelCase : int = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase , dtype=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __A ( self ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = self.get_inputs(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = pipe(**__UpperCAmelCase ).images[0] __UpperCAmelCase : Tuple = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) __UpperCAmelCase : Dict = np.abs(expected_image - image ).max() assert max_diff < 1E-3
16
1
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowercase_ ( lowerCAmelCase__ : ndarray ): """simple docstring""" return np.dot(lowerCAmelCase__ , lowerCAmelCase__ ) class _A : def __init__( self , *, __UpperCAmelCase = np.inf , __UpperCAmelCase = "linear" , __UpperCAmelCase = 0.0 , ) -> None: '''simple docstring''' __UpperCAmelCase : str = regularization __UpperCAmelCase : int = gamma if kernel == "linear": __UpperCAmelCase : Dict = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) __UpperCAmelCase : Tuple = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: __UpperCAmelCase : str = f'Unknown kernel: {kernel}' raise ValueError(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> float: '''simple docstring''' return np.dot(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' __UpperCAmelCase : Tuple = observations __UpperCAmelCase : Optional[Any] = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((__UpperCAmelCase) , ) : Dict = np.shape(__UpperCAmelCase ) def to_minimize(__UpperCAmelCase ) -> float: __UpperCAmelCase : List[Any] = 0 ((__UpperCAmelCase) , ) : Dict = np.shape(__UpperCAmelCase ) for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__UpperCAmelCase ) __UpperCAmelCase : int = LinearConstraint(__UpperCAmelCase , 0 , 0 ) __UpperCAmelCase : Optional[Any] = Bounds(0 , self.regularization ) __UpperCAmelCase : List[str] = minimize( __UpperCAmelCase , np.ones(__UpperCAmelCase ) , bounds=__UpperCAmelCase , constraints=[ly_contraint] ).x __UpperCAmelCase : Tuple = l_star # calculating mean offset of separation plane to points __UpperCAmelCase : Optional[Any] = 0 for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) __UpperCAmelCase : Union[str, Any] = s / n def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' __UpperCAmelCase : Optional[Any] = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __UpperCAmelCase ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' from __future__ import annotations from typing import Any class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 0 ) -> None: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = row, column __UpperCAmelCase : Union[str, Any] = [[default_value for c in range(__UpperCAmelCase )] for r in range(__UpperCAmelCase )] def __str__( self ) -> str: '''simple docstring''' __UpperCAmelCase : Dict = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __UpperCAmelCase : Optional[Any] = 0 for row_vector in self.array: for obj in row_vector: __UpperCAmelCase : Union[str, Any] = max(__UpperCAmelCase , len(str(__UpperCAmelCase ) ) ) __UpperCAmelCase : Optional[int] = f'%{max_element_length}s' # Make string and return def single_line(__UpperCAmelCase ) -> str: nonlocal string_format_identifier __UpperCAmelCase : Any = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__UpperCAmelCase ) for row_vector in self.array ) return s def __repr__( self ) -> str: '''simple docstring''' return str(self ) def __A ( self , __UpperCAmelCase ) -> bool: '''simple docstring''' if not (isinstance(__UpperCAmelCase , (list, tuple) ) and len(__UpperCAmelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , __UpperCAmelCase ) -> Any: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self , __UpperCAmelCase , __UpperCAmelCase ) -> None: '''simple docstring''' assert self.validate_indicies(__UpperCAmelCase ) __UpperCAmelCase : List[Any] = value def __add__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == another.row and self.column == another.column # Add __UpperCAmelCase : Dict = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] + another[r, c] return result def __neg__( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : Dict = -self[r, c] return result def __sub__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' return self + (-another) def __mul__( self , __UpperCAmelCase ) -> Matrix: '''simple docstring''' if isinstance(__UpperCAmelCase , (int, float) ): # Scalar multiplication __UpperCAmelCase : Optional[int] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[Any] = self[r, c] * another return result elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # Matrix multiplication assert self.column == another.row __UpperCAmelCase : Dict = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __UpperCAmelCase : List[Any] = f'Unsupported type given for another ({type(__UpperCAmelCase )})' raise TypeError(__UpperCAmelCase ) def __A ( self ) -> Matrix: '''simple docstring''' __UpperCAmelCase : Dict = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __UpperCAmelCase : List[str] = self[r, c] return result def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(__UpperCAmelCase , __UpperCAmelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __UpperCAmelCase : Optional[Any] = v.transpose() __UpperCAmelCase : List[Any] = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Dict = Matrix(3 , 3 , 0 ) for i in range(3 ): __UpperCAmelCase : Tuple = 1 print(f'a^(-1) is {ainv}' ) # u, v __UpperCAmelCase : Dict = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = 1, 2, -3 __UpperCAmelCase : Union[str, Any] = Matrix(3 , 1 , 0 ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : int = 4, -2, 5 print(f'u is {u}' ) print(f'v is {v}' ) print(f'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCAmelCase__ , lowerCAmelCase__ )}' ) def lowercase_ ( ): """simple docstring""" import doctest doctest.testmod() testa()
16
1
'''simple docstring''' def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) __UpperCAmelCase : int = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(lowerCAmelCase__ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _UpperCamelCase = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip _UpperCamelCase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ): """simple docstring""" return max(metric_fn(lowerCAmelCase__ , lowerCAmelCase__ ) for gt in ground_truths ) def lowercase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = [] if args.gold_data_mode == "qa": __UpperCAmelCase : Tuple = pd.read_csv(lowerCAmelCase__ , sep="""\t""" , header=lowerCAmelCase__ ) for answer_list in data[1]: __UpperCAmelCase : Optional[int] = ast.literal_eval(lowerCAmelCase__ ) answers.append(lowerCAmelCase__ ) else: __UpperCAmelCase : Optional[int] = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : str = [[reference] for reference in references] __UpperCAmelCase : Optional[int] = 0 for prediction, ground_truths in zip(lowerCAmelCase__ , lowerCAmelCase__ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) fa += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : int = 100.0 * em / total __UpperCAmelCase : Dict = 100.0 * fa / total logger.info(f'F1: {fa:.2f}' ) logger.info(f'EM: {em:.2f}' ) def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ): """simple docstring""" __UpperCAmelCase : Tuple = args.k __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Dict = [line.strip() for line in open(lowerCAmelCase__ , """r""" ).readlines()] __UpperCAmelCase : Union[str, Any] = 0 for hypo, reference in zip(lowerCAmelCase__ , lowerCAmelCase__ ): __UpperCAmelCase : List[str] = set(hypo.split("""\t""" )[:k] ) __UpperCAmelCase : List[Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k __UpperCAmelCase : List[str] = 100.0 * em / total logger.info(f'Precision@{k}: {em: .2f}' ) def lowercase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ): """simple docstring""" def strip_title(lowerCAmelCase__ : Optional[int] ): if title.startswith("""\"""" ): __UpperCAmelCase : List[Any] = title[1:] if title.endswith("""\"""" ): __UpperCAmelCase : int = title[:-1] return title __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , )["""input_ids"""].to(args.device ) __UpperCAmelCase : str = rag_model.rag.question_encoder(lowerCAmelCase__ ) __UpperCAmelCase : int = question_enc_outputs[0] __UpperCAmelCase : Dict = rag_model.retriever( lowerCAmelCase__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) __UpperCAmelCase : Union[str, Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) __UpperCAmelCase : Union[str, Any] = [] for docs in all_docs: __UpperCAmelCase : int = [strip_title(lowerCAmelCase__ ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(lowerCAmelCase__ ) ) return provenance_strings def lowercase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ): """simple docstring""" with torch.no_grad(): __UpperCAmelCase : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors="""pt""" , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ ) __UpperCAmelCase : List[str] = inputs_dict.input_ids.to(args.device ) __UpperCAmelCase : List[Any] = inputs_dict.attention_mask.to(args.device ) __UpperCAmelCase : List[str] = rag_model.generate( # rag_model overwrites generate lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) __UpperCAmelCase : str = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) if args.print_predictions: for q, a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): logger.info("""Q: {} - A: {}""".format(lowerCAmelCase__ , lowerCAmelCase__ ) ) return answers def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=lowerCAmelCase__ , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=lowerCAmelCase__ , choices=["""exact""", """compressed""", """legacy"""] , type=lowerCAmelCase__ , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=lowerCAmelCase__ , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=lowerCAmelCase__ , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=lowerCAmelCase__ , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=lowerCAmelCase__ , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=lowerCAmelCase__ , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=lowerCAmelCase__ , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=lowerCAmelCase__ , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=lowerCAmelCase__ , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=lowerCAmelCase__ , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) __UpperCAmelCase : str = parser.parse_args() __UpperCAmelCase : Optional[Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def lowercase_ ( lowerCAmelCase__ : List[Any] ): """simple docstring""" __UpperCAmelCase : Optional[Any] = {} if args.model_type is None: __UpperCAmelCase : str = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Tuple = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration __UpperCAmelCase : Dict = args.n_docs if args.index_name is not None: __UpperCAmelCase : Union[str, Any] = args.index_name if args.index_path is not None: __UpperCAmelCase : Dict = args.index_path else: __UpperCAmelCase : str = BartForConditionalGeneration __UpperCAmelCase : str = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , lowerCAmelCase__ ) __UpperCAmelCase : Optional[int] = get_scores if args.eval_mode == """e2e""" else get_precision_at_k __UpperCAmelCase : Any = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(lowerCAmelCase__ ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): __UpperCAmelCase : Optional[int] = RagRetriever.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) __UpperCAmelCase : Any = model_class.from_pretrained(lowerCAmelCase__ , retriever=lowerCAmelCase__ , **lowerCAmelCase__ ) model.retriever.init_retrieval() else: __UpperCAmelCase : Tuple = model_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: __UpperCAmelCase : Union[str, Any] = [] for line in tqdm(lowerCAmelCase__ ): questions.append(line.strip() ) if len(lowerCAmelCase__ ) == args.eval_batch_size: __UpperCAmelCase : Any = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) + """\n""" ) preds_file.flush() __UpperCAmelCase : List[str] = [] if len(lowerCAmelCase__ ) > 0: __UpperCAmelCase : Optional[Any] = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write("""\n""".join(lowerCAmelCase__ ) ) preds_file.flush() score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": _UpperCamelCase = get_args() main(args)
16
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _A ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = MODEL_FOR_MASKED_LM_MAPPING _SCREAMING_SNAKE_CASE : Tuple = TF_MODEL_FOR_MASKED_LM_MAPPING def __A ( self ) -> Any: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser"""}, ] , ) __UpperCAmelCase : List[str] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1E-05, """token""": 38_015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1E-05, """token""": 25_506, """token_str""": """ accuser""", }, ] , ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9E-05, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> Dict: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" ) __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : Dict = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) __UpperCAmelCase : str = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1E-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2E-05, """token""": 2_941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 13_606, """token_str""": """ Clara"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask> <mask>""" , top_k=2 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=6 ) , [ [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2E-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2E-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def __A ( self ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : List[str] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" ) # convert model to fp16 pipe.model.half() __UpperCAmelCase : str = pipe("""Paris is the [MASK] of France.""" ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) @slow @require_torch def __A ( self ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Any = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" ) self.run_large_test(__UpperCAmelCase ) @slow @require_tf def __A ( self ) -> int: '''simple docstring''' __UpperCAmelCase : int = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" ) self.run_large_test(__UpperCAmelCase ) def __A ( self , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1_573, """token_str""": """ Chris"""}, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.251, """token""": 2_201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.214, """token""": 12_790, """token_str""": """ Lyon""", }, ] , ) __UpperCAmelCase : Optional[int] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , [ {"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" ) __UpperCAmelCase : Tuple = None __UpperCAmelCase : int = None self.run_pipeline_test(__UpperCAmelCase , [] ) @require_tf def __A ( self ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" ) __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : str = None self.run_pipeline_test(__UpperCAmelCase , [] ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" ) __UpperCAmelCase : str = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = [ f'This is another {tokenizer.mask_token} test', ] return fill_masker, examples def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = fill_masker.tokenizer __UpperCAmelCase : Union[str, Any] = fill_masker.model __UpperCAmelCase : Tuple = fill_masker( f'This is a {tokenizer.mask_token}' , ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : int = fill_masker([f'This is a {tokenizer.mask_token}'] ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Union[str, Any] = fill_masker([f'This is a {tokenizer.mask_token}', f'Another {tokenizer.mask_token} great test.'] ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , ) with self.assertRaises(__UpperCAmelCase ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(__UpperCAmelCase ): fill_masker("""This is""" ) self.run_test_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_targets(__UpperCAmelCase , __UpperCAmelCase ) self.run_test_top_k_targets(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_duplicate_targets_and_top_k(__UpperCAmelCase , __UpperCAmelCase ) self.fill_mask_with_multiple_masks(__UpperCAmelCase , __UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' __UpperCAmelCase : Dict = tokenizer.get_vocab() __UpperCAmelCase : Dict = sorted(vocab.keys() )[:2] # Pipeline argument __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , targets=__UpperCAmelCase ) __UpperCAmelCase : List[str] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : Any = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : int = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Call argument __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Tuple = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , __UpperCAmelCase ) __UpperCAmelCase : List[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(__UpperCAmelCase ) ) # Score equivalence __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : Dict = [top_mask["""token_str"""] for top_mask in outputs] __UpperCAmelCase : str = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ) == set(__UpperCAmelCase ): __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , targets=__UpperCAmelCase ) __UpperCAmelCase : int = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) # Raises with invalid with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Any = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Dict = fill_masker(f'This is a {tokenizer.mask_token}' , targets=[""""""] ) with self.assertRaises(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , targets="""""" ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Dict = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , top_k=2 ) __UpperCAmelCase : Optional[int] = fill_masker(f'This is a {tokenizer.mask_token}' ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : int = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ] , ) self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: '''simple docstring''' __UpperCAmelCase : int = tokenizer.get_vocab() __UpperCAmelCase : List[Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) # top_k=2, ntargets=3 __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : str = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=2 , targets=__UpperCAmelCase ) # If we use the most probably targets, and filter differently, we should still # have the same results __UpperCAmelCase : Tuple = [el["""token_str"""] for el in sorted(__UpperCAmelCase , key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__UpperCAmelCase ).issubset(__UpperCAmelCase ): __UpperCAmelCase : Union[str, Any] = fill_masker(f'This is a {tokenizer.mask_token}' , top_k=3 , targets=__UpperCAmelCase ) # They should yield exactly the same result self.assertEqual(nested_simplify(__UpperCAmelCase ) , nested_simplify(__UpperCAmelCase ) ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = tokenizer.get_vocab() # String duplicates + id duplicates __UpperCAmelCase : Dict = sorted(vocab.keys() )[:3] __UpperCAmelCase : Dict = [targets[0], targets[1], targets[0], targets[2], targets[1]] __UpperCAmelCase : Optional[int] = fill_masker(f'My name is {tokenizer.mask_token}' , targets=__UpperCAmelCase , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(__UpperCAmelCase ) , 3 ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[str] = FillMaskPipeline(model=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) __UpperCAmelCase : Dict = fill_masker( f'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2 ) self.assertEqual( __UpperCAmelCase , [ [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], [ {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, {"""sequence""": ANY(__UpperCAmelCase ), """score""": ANY(__UpperCAmelCase ), """token""": ANY(__UpperCAmelCase ), """token_str""": ANY(__UpperCAmelCase )}, ], ] , )
16
1
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _A : def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""" ) __UpperCAmelCase : Tuple = img __UpperCAmelCase : str = img.shape[1] __UpperCAmelCase : Union[str, Any] = img.shape[0] __UpperCAmelCase : List[Any] = dst_width __UpperCAmelCase : List[str] = dst_height __UpperCAmelCase : str = self.src_w / self.dst_w __UpperCAmelCase : Optional[Any] = self.src_h / self.dst_h __UpperCAmelCase : Tuple = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def __A ( self ) -> str: '''simple docstring''' for i in range(self.dst_h ): for j in range(self.dst_w ): __UpperCAmelCase : str = self.img[self.get_y(__UpperCAmelCase )][self.get_x(__UpperCAmelCase )] def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' return int(self.ratio_x * x ) def __A ( self , __UpperCAmelCase ) -> int: '''simple docstring''' return int(self.ratio_y * y ) if __name__ == "__main__": _UpperCamelCase , _UpperCamelCase = 800, 600 _UpperCamelCase = imread('''image_data/lena.jpg''', 1) _UpperCamelCase = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
16
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"image": Image()} ) _SCREAMING_SNAKE_CASE : ClassVar[Features] = Features({"labels": ClassLabel} ) _SCREAMING_SNAKE_CASE : str = "image" _SCREAMING_SNAKE_CASE : str = "labels" def __A ( self , __UpperCAmelCase ) -> str: '''simple docstring''' if self.label_column not in features: raise ValueError(f'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] , __UpperCAmelCase ): raise ValueError(f'Column {self.label_column} is not a ClassLabel.' ) __UpperCAmelCase : int = copy.deepcopy(self ) __UpperCAmelCase : str = self.label_schema.copy() __UpperCAmelCase : Optional[Any] = features[self.label_column] __UpperCAmelCase : Optional[int] = label_schema return task_template @property def __A ( self ) -> Dict[str, str]: '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
16
1