code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
import qiskit
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase ) ->qiskit.result.counts.Counts:
_UpperCAmelCase =qiskit.Aer.get_backend("aer_simulator" )
# Create a Quantum Circuit acting on the q register
_UpperCAmelCase =qiskit.QuantumCircuit(_lowerCamelCase , _lowerCamelCase )
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0 )
circuit.x(1 )
# Map the quantum measurement to the classical bits
circuit.measure([0, 1] , [0, 1] )
# Execute the circuit on the qasm simulator
_UpperCAmelCase =qiskit.execute(_lowerCamelCase , _lowerCamelCase , shots=1000 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(_lowerCamelCase )
if __name__ == "__main__":
snake_case__ : str = single_qubit_measure(2, 2)
print(F"""Total count for various states are: {counts}""")
| 408 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
snake_case__ : Dict = logging.get_logger(__name__)
snake_case__ : Any = {
'google/mobilenet_v2_1.4_224': 'https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json',
'google/mobilenet_v2_1.0_224': 'https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json',
'google/mobilenet_v2_0.75_160': 'https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json',
'google/mobilenet_v2_0.35_96': 'https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json',
# See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}
class _a ( A__ ):
"""simple docstring"""
snake_case ="""mobilenet_v2"""
def __init__( self , _snake_case=3 , _snake_case=224 , _snake_case=1.0 , _snake_case=8 , _snake_case=8 , _snake_case=6 , _snake_case=32 , _snake_case=True , _snake_case=True , _snake_case="relu6" , _snake_case=True , _snake_case=0.8 , _snake_case=0.02 , _snake_case=0.001 , _snake_case=255 , **_snake_case , ):
super().__init__(**_snake_case )
if depth_multiplier <= 0:
raise ValueError("depth_multiplier must be greater than zero." )
_UpperCAmelCase =num_channels
_UpperCAmelCase =image_size
_UpperCAmelCase =depth_multiplier
_UpperCAmelCase =depth_divisible_by
_UpperCAmelCase =min_depth
_UpperCAmelCase =expand_ratio
_UpperCAmelCase =output_stride
_UpperCAmelCase =first_layer_is_expansion
_UpperCAmelCase =finegrained_output
_UpperCAmelCase =hidden_act
_UpperCAmelCase =tf_padding
_UpperCAmelCase =classifier_dropout_prob
_UpperCAmelCase =initializer_range
_UpperCAmelCase =layer_norm_eps
_UpperCAmelCase =semantic_loss_ignore_index
class _a ( A__ ):
"""simple docstring"""
snake_case =version.parse("""1.11""" )
@property
def SCREAMING_SNAKE_CASE ( self ):
return OrderedDict([("pixel_values", {0: "batch"})] )
@property
def SCREAMING_SNAKE_CASE ( self ):
if self.task == "image-classification":
return OrderedDict([("logits", {0: "batch"})] )
else:
return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] )
@property
def SCREAMING_SNAKE_CASE ( self ):
return 1E-4
| 408 | 1 |
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import SPIECE_UNDERLINE, is_sentencepiece_available
from transformers.models.speech_to_text import SpeechaTextTokenizer
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
UpperCAmelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""")
if is_sentencepiece_available():
import sentencepiece as sp
UpperCAmelCase_ = 5
UpperCAmelCase_ = 10
@require_sentencepiece
@require_tokenizers
class UpperCamelCase_ ( _snake_case , unittest.TestCase ):
lowerCAmelCase_ = SpeechaTextTokenizer
lowerCAmelCase_ = False
lowerCAmelCase_ = True
def lowerCAmelCase ( self ) -> List[str]:
super().setUp()
_snake_case = sp.SentencePieceProcessor()
spm_model.Load(snake_case_ )
_snake_case = ["<s>", "<pad>", "</s>", "<unk>"]
vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(snake_case_ ) )]
_snake_case = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) )
_snake_case = Path(self.tmpdirname )
save_json(snake_case_ , save_dir / VOCAB_FILES_NAMES['vocab_file'] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(snake_case_ , save_dir / VOCAB_FILES_NAMES['spm_file'] )
_snake_case = SpeechaTextTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def lowerCAmelCase ( self ) -> int:
_snake_case = "<pad>"
_snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case_ ) , snake_case_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case_ ) , snake_case_ )
def lowerCAmelCase ( self ) -> Any:
_snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<s>' )
self.assertEqual(vocab_keys[1] , '<pad>' )
self.assertEqual(vocab_keys[-1] , 'j' )
self.assertEqual(len(snake_case_ ) , 1001 )
def lowerCAmelCase ( self ) -> Any:
self.assertEqual(self.get_tokenizer().vocab_size , 1001 )
def lowerCAmelCase ( self ) -> Optional[int]:
_snake_case = SpeechaTextTokenizer.from_pretrained(self.tmpdirname )
_snake_case = tokenizer.tokenize('This is a test' )
self.assertListEqual(snake_case_ , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(snake_case_ ) , [289, 50, 14, 174, 386] , )
_snake_case = tokenizer.tokenize('I was born in 92000, and this is falsé.' )
self.assertListEqual(
snake_case_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , )
_snake_case = tokenizer.convert_tokens_to_ids(snake_case_ )
self.assertListEqual(snake_case_ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] )
_snake_case = tokenizer.convert_ids_to_tokens(snake_case_ )
self.assertListEqual(
snake_case_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , )
@slow
def lowerCAmelCase ( self ) -> Union[str, Any]:
# fmt: off
_snake_case = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 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], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "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, 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, 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, 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, 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=snake_case_ , model_name='facebook/s2t-small-mustc-en-de-st' , revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' , )
@require_sentencepiece
class UpperCamelCase_ ( unittest.TestCase ):
lowerCAmelCase_ = """valhalla/s2t_mustc_multilinguial_medium"""
lowerCAmelCase_ = """C'est trop cool"""
lowerCAmelCase_ = """Esto es genial"""
@classmethod
def lowerCAmelCase ( cls ) -> int:
_snake_case = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name )
return cls
def lowerCAmelCase ( self ) -> Union[str, Any]:
self.assertEqual(self.tokenizer.lang_code_to_id['pt'] , 4 )
self.assertEqual(self.tokenizer.lang_code_to_id['ru'] , 6 )
self.assertEqual(self.tokenizer.lang_code_to_id['it'] , 9 )
self.assertEqual(self.tokenizer.lang_code_to_id['de'] , 11 )
def lowerCAmelCase ( self ) -> int:
self.assertEqual(self.tokenizer.vocab_size , 1_0000 )
def lowerCAmelCase ( self ) -> Union[str, Any]:
self.assertIn(snake_case_ , self.tokenizer.all_special_ids )
_snake_case = [ES_CODE, 4, 1601, 47, 7647, 2]
_snake_case = self.tokenizer.decode(snake_case_ , skip_special_tokens=snake_case_ )
_snake_case = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertNotIn(self.tokenizer.eos_token , snake_case_ )
def lowerCAmelCase ( self ) -> str:
_snake_case = "fr"
_snake_case = self.tokenizer(self.french_text ).input_ids
self.assertEqual(encoded[0] , snake_case_ )
self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id )
def lowerCAmelCase ( self ) -> List[Any]:
_snake_case = "fr"
self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] )
_snake_case = "es"
self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
| 721 |
import copy
import tempfile
import unittest
from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError
from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
@parameterized.expand([(None,), ('foo.json',)] )
def lowerCAmelCase ( self , lowerCAmelCase_ ) -> str:
_snake_case = GenerationConfig(
do_sample=lowerCAmelCase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(lowerCAmelCase_ , config_name=lowerCAmelCase_ )
_snake_case = GenerationConfig.from_pretrained(lowerCAmelCase_ , config_name=lowerCAmelCase_ )
# Checks parameters that were specified
self.assertEqual(loaded_config.do_sample , lowerCAmelCase_ )
self.assertEqual(loaded_config.temperature , 0.7 )
self.assertEqual(loaded_config.length_penalty , 1.0 )
self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] )
# Checks parameters that were not specified (defaults)
self.assertEqual(loaded_config.top_k , 50 )
self.assertEqual(loaded_config.max_length , 20 )
self.assertEqual(loaded_config.max_time , lowerCAmelCase_ )
def lowerCAmelCase ( self ) -> Optional[int]:
_snake_case = AutoConfig.from_pretrained('gpt2' )
_snake_case = GenerationConfig.from_model_config(lowerCAmelCase_ )
_snake_case = GenerationConfig()
# The generation config has loaded a few non-default parameters from the model config
self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ )
# One of those parameters is eos_token_id -- check if it matches
self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id )
self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id )
def lowerCAmelCase ( self ) -> Tuple:
_snake_case = GenerationConfig()
_snake_case = {
'max_new_tokens': 1024,
'foo': 'bar',
}
_snake_case = copy.deepcopy(lowerCAmelCase_ )
_snake_case = generation_config.update(**lowerCAmelCase_ )
# update_kwargs was not modified (no side effects)
self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(generation_config.max_new_tokens , 1024 )
# `.update()` returns a dictionary of unused kwargs
self.assertEqual(lowerCAmelCase_ , {'foo': 'bar'} )
def lowerCAmelCase ( self ) -> Optional[int]:
_snake_case = GenerationConfig()
_snake_case = 'bar'
with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir:
generation_config.save_pretrained(lowerCAmelCase_ )
_snake_case = GenerationConfig.from_pretrained(lowerCAmelCase_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(new_config.foo , 'bar' )
_snake_case = GenerationConfig.from_model_config(lowerCAmelCase_ )
assert not hasattr(lowerCAmelCase_ , 'foo' ) # no new kwargs should be initialized if from config
def lowerCAmelCase ( self ) -> List[Any]:
_snake_case = GenerationConfig()
self.assertEqual(default_config.temperature , 1.0 )
self.assertEqual(default_config.do_sample , lowerCAmelCase_ )
self.assertEqual(default_config.num_beams , 1 )
_snake_case = GenerationConfig(
do_sample=lowerCAmelCase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
self.assertEqual(config.temperature , 0.7 )
self.assertEqual(config.do_sample , lowerCAmelCase_ )
self.assertEqual(config.num_beams , 1 )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(lowerCAmelCase_ )
_snake_case = GenerationConfig.from_pretrained(lowerCAmelCase_ , temperature=1.0 )
self.assertEqual(loaded_config.temperature , 1.0 )
self.assertEqual(loaded_config.do_sample , lowerCAmelCase_ )
self.assertEqual(loaded_config.num_beams , 1 ) # default value
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
@classmethod
def lowerCAmelCase ( cls ) -> List[str]:
_snake_case = TOKEN
HfFolder.save_token(lowerCAmelCase_ )
@classmethod
def lowerCAmelCase ( cls ) -> Union[str, Any]:
try:
delete_repo(token=cls._token , repo_id='test-generation-config' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' )
except HTTPError:
pass
def lowerCAmelCase ( self ) -> int:
_snake_case = GenerationConfig(
do_sample=lowerCAmelCase_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('test-generation-config' , use_auth_token=self._token )
_snake_case = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='test-generation-config' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
lowerCAmelCase_ , repo_id='test-generation-config' , push_to_hub=lowerCAmelCase_ , use_auth_token=self._token )
_snake_case = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) )
def lowerCAmelCase ( self ) -> List[str]:
_snake_case = GenerationConfig(
do_sample=lowerCAmelCase_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token )
_snake_case = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
lowerCAmelCase_ , repo_id='valid_org/test-generation-config-org' , push_to_hub=lowerCAmelCase_ , use_auth_token=self._token )
_snake_case = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(lowerCAmelCase_ , getattr(lowerCAmelCase_ , lowerCAmelCase_ ) )
| 541 | 0 |
"""simple docstring"""
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __magic_name__ ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self , _a , _a , _a , _a = None , ):
"""simple docstring"""
super().__init__()
self.register_modules(transformer=_a , vae=_a , scheduler=_a )
# create a imagenet -> id dictionary for easier use
lowerCamelCase = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(""",""" ):
lowerCamelCase = int(_a )
lowerCamelCase = dict(sorted(self.labels.items() ) )
def _lowerCAmelCase ( self , _a ):
"""simple docstring"""
if not isinstance(_a , _a ):
lowerCamelCase = list(_a )
for l in label:
if l not in self.labels:
raise ValueError(
f'{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.' )
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _a , _a = 4.0 , _a = None , _a = 50 , _a = "pil" , _a = True , ):
"""simple docstring"""
lowerCamelCase = len(_a )
lowerCamelCase = self.transformer.config.sample_size
lowerCamelCase = self.transformer.config.in_channels
lowerCamelCase = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_a , device=self.device , dtype=self.transformer.dtype , )
lowerCamelCase = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents
lowerCamelCase = torch.tensor(_a , device=self.device ).reshape(-1 )
lowerCamelCase = torch.tensor([1_000] * batch_size , device=self.device )
lowerCamelCase = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_a )
for t in self.progress_bar(self.scheduler.timesteps ):
if guidance_scale > 1:
lowerCamelCase = latent_model_input[: len(_a ) // 2]
lowerCamelCase = torch.cat([half, half] , dim=0 )
lowerCamelCase = self.scheduler.scale_model_input(_a , _a )
lowerCamelCase = t
if not torch.is_tensor(_a ):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
lowerCamelCase = latent_model_input.device.type == """mps"""
if isinstance(_a , _a ):
lowerCamelCase = torch.floataa if is_mps else torch.floataa
else:
lowerCamelCase = torch.intaa if is_mps else torch.intaa
lowerCamelCase = torch.tensor([timesteps] , dtype=_a , device=latent_model_input.device )
elif len(timesteps.shape ) == 0:
lowerCamelCase = timesteps[None].to(latent_model_input.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
lowerCamelCase = timesteps.expand(latent_model_input.shape[0] )
# predict noise model_output
lowerCamelCase = self.transformer(
_a , timestep=_a , class_labels=_a ).sample
# perform guidance
if guidance_scale > 1:
lowerCamelCase , lowerCamelCase = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
lowerCamelCase , lowerCamelCase = torch.split(_a , len(_a ) // 2 , dim=0 )
lowerCamelCase = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
lowerCamelCase = torch.cat([half_eps, half_eps] , dim=0 )
lowerCamelCase = torch.cat([eps, rest] , dim=1 )
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
lowerCamelCase , lowerCamelCase = torch.split(_a , _a , dim=1 )
else:
lowerCamelCase = noise_pred
# compute previous image: x_t -> x_t-1
lowerCamelCase = self.scheduler.step(_a , _a , _a ).prev_sample
if guidance_scale > 1:
lowerCamelCase , lowerCamelCase = latent_model_input.chunk(2 , dim=0 )
else:
lowerCamelCase = latent_model_input
lowerCamelCase = 1 / self.vae.config.scaling_factor * latents
lowerCamelCase = self.vae.decode(_a ).sample
lowerCamelCase = (samples / 2 + 0.5).clamp(0 , 1 )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
lowerCamelCase = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
lowerCamelCase = self.numpy_to_pil(_a )
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_a )
| 543 |
"""simple docstring"""
import gc
import unittest
import numpy as np
import torch
from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class __magic_name__ ( UpperCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
__UpperCamelCase = DiTPipeline
__UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
__UpperCamelCase = PipelineTesterMixin.required_optional_params - {
"latents",
"num_images_per_prompt",
"callback",
"callback_steps",
}
__UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
__UpperCamelCase = False
def _lowerCAmelCase ( self ):
"""simple docstring"""
torch.manual_seed(0 )
lowerCamelCase = TransformeraDModel(
sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_a , activation_fn="""gelu-approximate""" , num_embeds_ada_norm=1_000 , norm_type="""ada_norm_zero""" , norm_elementwise_affine=_a , )
lowerCamelCase = AutoencoderKL()
lowerCamelCase = DDIMScheduler()
lowerCamelCase = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
return components
def _lowerCAmelCase ( self , _a , _a=0 ):
"""simple docstring"""
if str(_a ).startswith("""mps""" ):
lowerCamelCase = torch.manual_seed(_a )
else:
lowerCamelCase = torch.Generator(device=_a ).manual_seed(_a )
lowerCamelCase = {
"""class_labels""": [1],
"""generator""": generator,
"""num_inference_steps""": 2,
"""output_type""": """numpy""",
}
return inputs
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = """cpu"""
lowerCamelCase = self.get_dummy_components()
lowerCamelCase = self.pipeline_class(**_a )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
lowerCamelCase = self.get_dummy_inputs(_a )
lowerCamelCase = pipe(**_a ).images
lowerCamelCase = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 16, 16, 3) )
lowerCamelCase = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] )
lowerCamelCase = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(_a , 1e-3 )
def _lowerCAmelCase ( self ):
"""simple docstring"""
self._test_inference_batch_single_identical(relax_max_difference=_a , expected_max_diff=1e-3 )
@unittest.skipIf(
torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , )
def _lowerCAmelCase ( self ):
"""simple docstring"""
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 )
@require_torch_gpu
@slow
class __magic_name__ ( unittest.TestCase ):
'''simple docstring'''
def _lowerCAmelCase ( self ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = torch.manual_seed(0 )
lowerCamelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" )
pipe.to("""cuda""" )
lowerCamelCase = ["""vase""", """umbrella""", """white shark""", """white wolf"""]
lowerCamelCase = pipe.get_label_ids(_a )
lowerCamelCase = pipe(_a , generator=_a , num_inference_steps=40 , output_type="""np""" ).images
for word, image in zip(_a , _a ):
lowerCamelCase = load_numpy(
f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' )
assert np.abs((expected_image - image).max() ) < 1e-2
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" )
lowerCamelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.to("""cuda""" )
lowerCamelCase = ["""vase""", """umbrella"""]
lowerCamelCase = pipe.get_label_ids(_a )
lowerCamelCase = torch.manual_seed(0 )
lowerCamelCase = pipe(_a , generator=_a , num_inference_steps=25 , output_type="""np""" ).images
for word, image in zip(_a , _a ):
lowerCamelCase = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
f'/dit/{word}_512.npy' )
assert np.abs((expected_image - image).max() ) < 1e-1
| 543 | 1 |
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional
from torch.utils.data import ConcatDataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_WITH_LM_HEAD_MAPPING,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
DataCollatorForLanguageModeling,
DataCollatorForPermutationLanguageModeling,
DataCollatorForWholeWordMask,
HfArgumentParser,
LineByLineTextDataset,
LineByLineWithRefDataset,
PreTrainedTokenizer,
TextDataset,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
SCREAMING_SNAKE_CASE : List[Any] = logging.getLogger(__name__)
SCREAMING_SNAKE_CASE : Optional[int] = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
SCREAMING_SNAKE_CASE : List[str] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class UpperCamelCase :
'''simple docstring'''
lowercase : Optional[str] =field(
default=lowercase__ , metadata={
"""help""": (
"""The model checkpoint for weights initialization. Leave None if you want to train a model from"""
""" scratch."""
)
} , )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(lowercase__ )} , )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
@dataclass
class UpperCamelCase :
'''simple docstring'''
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """The input training data file (a text file)."""} )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={
"""help""": (
"""The input training data files (multiple files in glob format). """
"""Very often splitting large files to smaller files can prevent tokenizer going out of memory"""
)
} , )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """An optional input train ref data file for whole word mask in Chinese."""} , )
lowercase : Optional[str] =field(
default=lowercase__ , metadata={"""help""": """An optional input eval ref data file for whole word mask in Chinese."""} , )
lowercase : bool =field(
default=lowercase__ , metadata={"""help""": """Whether distinct lines of text in the dataset are to be handled as distinct sequences."""} , )
lowercase : bool =field(
default=lowercase__ , metadata={"""help""": """Train with masked-language modeling loss instead of language modeling."""} )
lowercase : bool =field(default=lowercase__ , metadata={"""help""": """Whether ot not to use whole word mask."""} )
lowercase : float =field(
default=0.15 , metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""} )
lowercase : float =field(
default=1 / 6 , metadata={
"""help""": (
"""Ratio of length of a span of masked tokens to surrounding context length for permutation language"""
""" modeling."""
)
} , )
lowercase : int =field(
default=5 , metadata={"""help""": """Maximum length of a span of masked tokens for permutation language modeling."""} )
lowercase : int =field(
default=-1 , metadata={
"""help""": (
"""Optional input sequence length after tokenization."""
"""The training dataset will be truncated in block of this size for training."""
"""Default to the model max input length for single sentence inputs (take into account special tokens)."""
)
} , )
lowercase : bool =field(
default=lowercase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def UpperCamelCase ( _a , _a , _a = False , _a = None , ) -> Optional[Any]:
'''simple docstring'''
def _dataset(_a , _a=None ):
if args.line_by_line:
if ref_path is not None:
if not args.whole_word_mask or not args.mlm:
raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask''' )
return LineByLineWithRefDataset(
tokenizer=_a , file_path=_a , block_size=args.block_size , ref_path=_a , )
return LineByLineTextDataset(tokenizer=_a , file_path=_a , block_size=args.block_size )
else:
return TextDataset(
tokenizer=_a , file_path=_a , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_a , )
if evaluate:
return _dataset(args.eval_data_file , args.eval_ref_file )
elif args.train_data_files:
return ConcatDataset([_dataset(_a ) for f in glob(args.train_data_files )] )
else:
return _dataset(args.train_data_file , args.train_ref_file )
def UpperCamelCase ( ) -> List[str]:
'''simple docstring'''
lowercase_ :Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
lowercase_ :Tuple = parser.parse_args_into_dataclasses()
if data_args.eval_data_file is None and training_args.do_eval:
raise ValueError(
'''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
'''or remove the --do_eval argument.''' )
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
''' --overwrite_output_dir to overcome.''' )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
'''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info('''Training/evaluation parameters %s''' , _a )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
lowercase_ :Any = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
lowercase_ :Union[str, Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
lowercase_ :int = CONFIG_MAPPING[model_args.model_type]()
logger.warning('''You are instantiating a new config instance from scratch.''' )
if model_args.tokenizer_name:
lowercase_ :List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
lowercase_ :Any = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
''' script, save it,and load it from here, using --tokenizer_name''' )
if model_args.model_name_or_path:
lowercase_ :Optional[int] = AutoModelWithLMHead.from_pretrained(
model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_a , cache_dir=model_args.cache_dir , )
else:
logger.info('''Training new model from scratch''' )
lowercase_ :int = AutoModelWithLMHead.from_config(_a )
model.resize_token_embeddings(len(_a ) )
if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
raise ValueError(
'''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
'''--mlm flag (masked language modeling).''' )
if data_args.block_size <= 0:
lowercase_ :Optional[int] = tokenizer.max_len
# Our input block size will be the max possible for the model
else:
lowercase_ :Tuple = min(data_args.block_size , tokenizer.max_len )
# Get datasets
lowercase_ :Tuple = (
get_dataset(_a , tokenizer=_a , cache_dir=model_args.cache_dir ) if training_args.do_train else None
)
lowercase_ :Optional[int] = (
get_dataset(_a , tokenizer=_a , evaluate=_a , cache_dir=model_args.cache_dir )
if training_args.do_eval
else None
)
if config.model_type == "xlnet":
lowercase_ :Any = DataCollatorForPermutationLanguageModeling(
tokenizer=_a , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , )
else:
if data_args.mlm and data_args.whole_word_mask:
lowercase_ :List[Any] = DataCollatorForWholeWordMask(
tokenizer=_a , mlm_probability=data_args.mlm_probability )
else:
lowercase_ :Dict = DataCollatorForLanguageModeling(
tokenizer=_a , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability )
# Initialize our Trainer
lowercase_ :Union[str, Any] = Trainer(
model=_a , args=_a , data_collator=_a , train_dataset=_a , eval_dataset=_a , prediction_loss_only=_a , )
# Training
if training_args.do_train:
lowercase_ :Tuple = (
model_args.model_name_or_path
if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path )
else None
)
trainer.train(model_path=_a )
trainer.save_model()
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
if trainer.is_world_master():
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
lowercase_ :str = {}
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
lowercase_ :int = trainer.evaluate()
lowercase_ :Union[str, Any] = math.exp(eval_output['''eval_loss'''] )
lowercase_ :str = {'''perplexity''': perplexity}
lowercase_ :Tuple = os.path.join(training_args.output_dir , '''eval_results_lm.txt''' )
if trainer.is_world_master():
with open(_a , '''w''' ) as writer:
logger.info('''***** Eval results *****''' )
for key in sorted(result.keys() ):
logger.info(''' %s = %s''' , _a , str(result[key] ) )
writer.write('''%s = %s\n''' % (key, str(result[key] )) )
results.update(_a )
return results
def UpperCamelCase ( _a ) -> Any:
'''simple docstring'''
main()
if __name__ == "__main__":
main()
| 705 |
import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def UpperCamelCase ( _a , _a=0.999 , _a="cosine" , ) -> Dict:
'''simple docstring'''
if alpha_transform_type == "cosine":
def alpha_bar_fn(_a ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(_a ):
return math.exp(t * -12.0 )
else:
raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" )
lowercase_ :Any = []
for i in range(_a ):
lowercase_ :List[str] = i / num_diffusion_timesteps
lowercase_ :str = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(_a ) / alpha_bar_fn(_a ) , _a ) )
return torch.tensor(_a , dtype=torch.floataa )
class UpperCamelCase ( lowercase__ , lowercase__ ):
'''simple docstring'''
lowercase : Tuple =[e.name for e in KarrasDiffusionSchedulers]
lowercase : Tuple =2
@register_to_config
def __init__( self , UpperCamelCase_ = 1000 , UpperCamelCase_ = 0.0_0085 , UpperCamelCase_ = 0.012 , UpperCamelCase_ = "linear" , UpperCamelCase_ = None , UpperCamelCase_ = "epsilon" , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = 1.0 , UpperCamelCase_ = "linspace" , UpperCamelCase_ = 0 , ):
if trained_betas is not None:
lowercase_ :int = torch.tensor(UpperCamelCase_ , dtype=torch.floataa )
elif beta_schedule == "linear":
lowercase_ :List[str] = torch.linspace(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
lowercase_ :int = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , UpperCamelCase_ , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
lowercase_ :Optional[int] = betas_for_alpha_bar(UpperCamelCase_ , alpha_transform_type='''cosine''' )
elif beta_schedule == "exp":
lowercase_ :Dict = betas_for_alpha_bar(UpperCamelCase_ , alpha_transform_type='''exp''' )
else:
raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" )
lowercase_ :str = 1.0 - self.betas
lowercase_ :Optional[int] = torch.cumprod(self.alphas , dim=0 )
# set all values
self.set_timesteps(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
lowercase_ :str = use_karras_sigmas
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_=None ):
if schedule_timesteps is None:
lowercase_ :List[str] = self.timesteps
lowercase_ :int = (schedule_timesteps == timestep).nonzero()
# The sigma index that is taken for the **very** first `step`
# is always the second index (or the last index if there is only 1)
# This way we can ensure we don't accidentally skip a sigma in
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
if len(self._index_counter ) == 0:
lowercase_ :Dict = 1 if len(UpperCamelCase_ ) > 1 else 0
else:
lowercase_ :Any = timestep.cpu().item() if torch.is_tensor(UpperCamelCase_ ) else timestep
lowercase_ :Union[str, Any] = self._index_counter[timestep_int]
return indices[pos].item()
@property
def UpperCamelCase ( self ):
# standard deviation of the initial noise distribution
if self.config.timestep_spacing in ["linspace", "trailing"]:
return self.sigmas.max()
return (self.sigmas.max() ** 2 + 1) ** 0.5
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , ):
lowercase_ :List[str] = self.index_for_timestep(UpperCamelCase_ )
lowercase_ :Optional[Any] = self.sigmas[step_index]
lowercase_ :Union[str, Any] = sample / ((sigma**2 + 1) ** 0.5)
return sample
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , ):
lowercase_ :Optional[Any] = num_inference_steps
lowercase_ :Dict = num_train_timesteps or self.config.num_train_timesteps
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
lowercase_ :Union[str, Any] = np.linspace(0 , num_train_timesteps - 1 , UpperCamelCase_ , dtype=UpperCamelCase_ )[::-1].copy()
elif self.config.timestep_spacing == "leading":
lowercase_ :Any = num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowercase_ :List[Any] = (np.arange(0 , UpperCamelCase_ ) * step_ratio).round()[::-1].copy().astype(UpperCamelCase_ )
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
lowercase_ :Dict = num_train_timesteps / self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowercase_ :Dict = (np.arange(UpperCamelCase_ , 0 , -step_ratio )).round().copy().astype(UpperCamelCase_ )
timesteps -= 1
else:
raise ValueError(
f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." )
lowercase_ :Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
lowercase_ :Tuple = np.log(UpperCamelCase_ )
lowercase_ :Dict = np.interp(UpperCamelCase_ , np.arange(0 , len(UpperCamelCase_ ) ) , UpperCamelCase_ )
if self.config.use_karras_sigmas:
lowercase_ :int = self._convert_to_karras(in_sigmas=UpperCamelCase_ , num_inference_steps=self.num_inference_steps )
lowercase_ :Optional[int] = np.array([self._sigma_to_t(UpperCamelCase_ , UpperCamelCase_ ) for sigma in sigmas] )
lowercase_ :Tuple = np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
lowercase_ :Optional[int] = torch.from_numpy(UpperCamelCase_ ).to(device=UpperCamelCase_ )
lowercase_ :Tuple = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] )
lowercase_ :Any = torch.from_numpy(UpperCamelCase_ )
lowercase_ :List[str] = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] )
if str(UpperCamelCase_ ).startswith('''mps''' ):
# mps does not support float64
lowercase_ :int = timesteps.to(UpperCamelCase_ , dtype=torch.floataa )
else:
lowercase_ :Optional[Any] = timesteps.to(device=UpperCamelCase_ )
# empty dt and derivative
lowercase_ :List[str] = None
lowercase_ :List[Any] = None
# for exp beta schedules, such as the one for `pipeline_shap_e.py`
# we need an index counter
lowercase_ :int = defaultdict(UpperCamelCase_ )
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ):
# get log sigma
lowercase_ :Union[str, Any] = np.log(UpperCamelCase_ )
# get distribution
lowercase_ :Optional[Any] = log_sigma - log_sigmas[:, np.newaxis]
# get sigmas range
lowercase_ :List[Any] = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 )
lowercase_ :str = low_idx + 1
lowercase_ :Any = log_sigmas[low_idx]
lowercase_ :int = log_sigmas[high_idx]
# interpolate sigmas
lowercase_ :Dict = (low - log_sigma) / (low - high)
lowercase_ :str = np.clip(UpperCamelCase_ , 0 , 1 )
# transform interpolation to time range
lowercase_ :Dict = (1 - w) * low_idx + w * high_idx
lowercase_ :int = t.reshape(sigma.shape )
return t
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ):
lowercase_ :float = in_sigmas[-1].item()
lowercase_ :float = in_sigmas[0].item()
lowercase_ :int = 7.0 # 7.0 is the value used in the paper
lowercase_ :Optional[Any] = np.linspace(0 , 1 , UpperCamelCase_ )
lowercase_ :List[str] = sigma_min ** (1 / rho)
lowercase_ :List[Any] = sigma_max ** (1 / rho)
lowercase_ :Tuple = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return sigmas
@property
def UpperCamelCase ( self ):
return self.dt is None
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = True , ):
lowercase_ :Any = self.index_for_timestep(UpperCamelCase_ )
# advance index counter by 1
lowercase_ :Any = timestep.cpu().item() if torch.is_tensor(UpperCamelCase_ ) else timestep
self._index_counter[timestep_int] += 1
if self.state_in_first_order:
lowercase_ :Optional[int] = self.sigmas[step_index]
lowercase_ :List[Any] = self.sigmas[step_index + 1]
else:
# 2nd order / Heun's method
lowercase_ :Optional[int] = self.sigmas[step_index - 1]
lowercase_ :Dict = self.sigmas[step_index]
# currently only gamma=0 is supported. This usually works best anyways.
# We can support gamma in the future but then need to scale the timestep before
# passing it to the model which requires a change in API
lowercase_ :List[Any] = 0
lowercase_ :List[str] = sigma * (gamma + 1) # Note: sigma_hat == sigma for now
# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
if self.config.prediction_type == "epsilon":
lowercase_ :Union[str, Any] = sigma_hat if self.state_in_first_order else sigma_next
lowercase_ :List[Any] = sample - sigma_input * model_output
elif self.config.prediction_type == "v_prediction":
lowercase_ :Dict = sigma_hat if self.state_in_first_order else sigma_next
lowercase_ :Optional[Any] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
sample / (sigma_input**2 + 1)
)
elif self.config.prediction_type == "sample":
lowercase_ :List[str] = model_output
else:
raise ValueError(
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" )
if self.config.clip_sample:
lowercase_ :str = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
if self.state_in_first_order:
# 2. Convert to an ODE derivative for 1st order
lowercase_ :Optional[int] = (sample - pred_original_sample) / sigma_hat
# 3. delta timestep
lowercase_ :Optional[int] = sigma_next - sigma_hat
# store for 2nd order step
lowercase_ :str = derivative
lowercase_ :Union[str, Any] = dt
lowercase_ :Optional[int] = sample
else:
# 2. 2nd order / Heun's method
lowercase_ :str = (sample - pred_original_sample) / sigma_next
lowercase_ :List[str] = (self.prev_derivative + derivative) / 2
# 3. take prev timestep & sample
lowercase_ :Union[str, Any] = self.dt
lowercase_ :Any = self.sample
# free dt and derivative
# Note, this puts the scheduler in "first order mode"
lowercase_ :List[Any] = None
lowercase_ :List[str] = None
lowercase_ :Dict = None
lowercase_ :int = sample + derivative * dt
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=UpperCamelCase_ )
def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
# Make sure sigmas and timesteps have the same device and dtype as original_samples
lowercase_ :List[str] = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype )
if original_samples.device.type == "mps" and torch.is_floating_point(UpperCamelCase_ ):
# mps does not support float64
lowercase_ :Optional[Any] = self.timesteps.to(original_samples.device , dtype=torch.floataa )
lowercase_ :Tuple = timesteps.to(original_samples.device , dtype=torch.floataa )
else:
lowercase_ :Union[str, Any] = self.timesteps.to(original_samples.device )
lowercase_ :int = timesteps.to(original_samples.device )
lowercase_ :int = [self.index_for_timestep(UpperCamelCase_ , UpperCamelCase_ ) for t in timesteps]
lowercase_ :Tuple = sigmas[step_indices].flatten()
while len(sigma.shape ) < len(original_samples.shape ):
lowercase_ :List[str] = sigma.unsqueeze(-1 )
lowercase_ :List[str] = original_samples + noise * sigma
return noisy_samples
def __len__( self ):
return self.config.num_train_timesteps
| 441 | 0 |
"""simple docstring"""
from cva import destroyAllWindows, imread, imshow, waitKey
def lowerCamelCase_( _lowerCamelCase ) -> List[str]:
'''simple docstring'''
_lowerCamelCase, _lowerCamelCase : Tuple = img.shape[0], img.shape[1]
# converting each pixel's color to its negative
for i in range(lowerCAmelCase_ ):
for j in range(lowerCAmelCase_ ):
_lowerCamelCase : Tuple = [255, 255, 255] - img[i][j]
return img
if __name__ == "__main__":
# read original image
_lowerCAmelCase : str = imread('''image_data/lena.jpg''', 1)
# convert to its negative
_lowerCAmelCase : Any = convert_to_negative(img)
# show result image
imshow('''negative of original image''', img)
waitKey(0)
destroyAllWindows() | 46 |
"""simple docstring"""
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
a__ : int = '''
@inproceedings{xu-etal-2016-optimizing,
title = {Optimizing Statistical Machine Translation for Text Simplification},
authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
journal = {Transactions of the Association for Computational Linguistics},
volume = {4},
year={2016},
url = {https://www.aclweb.org/anthology/Q16-1029},
pages = {401--415
},
@inproceedings{post-2018-call,
title = "A Call for Clarity in Reporting {BLEU} Scores",
author = "Post, Matt",
booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
month = oct,
year = "2018",
address = "Belgium, Brussels",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/W18-6319",
pages = "186--191",
}
'''
a__ : Union[str, Any] = '''\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
'''
a__ : Optional[Any] = '''
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
sources: list of source sentences where each sentence should be a string.
predictions: list of predicted sentences where each sentence should be a string.
references: list of lists of reference sentences where each sentence should be a string.
Returns:
sari: sari score
sacrebleu: sacrebleu score
exact: exact score
Examples:
>>> sources=["About 95 species are currently accepted ."]
>>> predictions=["About 95 you now get in ."]
>>> references=[["About 95 species are currently known ."]]
>>> wiki_split = datasets.load_metric("wiki_split")
>>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
>>> print(results)
{\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}
'''
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
def remove_articles(lowerCAmelCase_ ):
__SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE )
return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ )
def white_space_fix(lowerCAmelCase_ ):
return " ".join(text.split() )
def remove_punc(lowerCAmelCase_ ):
__SCREAMING_SNAKE_CASE = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowerCAmelCase_ ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) )
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) )
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )]
return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams]
__SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = Counter()
for sgram, scount in sgramcounter.items():
__SCREAMING_SNAKE_CASE = scount * numref
__SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = Counter()
for cgram, ccount in cgramcounter.items():
__SCREAMING_SNAKE_CASE = ccount * numref
# KEEP
__SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep
__SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter
__SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__SCREAMING_SNAKE_CASE = 1
__SCREAMING_SNAKE_CASE = 1
if len(lowerCAmelCase_ ) > 0:
__SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ )
if len(lowerCAmelCase_ ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
__SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() )
__SCREAMING_SNAKE_CASE = 0
if keepscore_precision > 0 or keepscore_recall > 0:
__SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
__SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep
__SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter
__SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__SCREAMING_SNAKE_CASE = 1
if len(lowerCAmelCase_ ) > 0:
__SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ )
# ADDITION
__SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__SCREAMING_SNAKE_CASE = 1
__SCREAMING_SNAKE_CASE = 1
if len(lowerCAmelCase_ ) > 0:
__SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ )
if len(lowerCAmelCase_ ) > 0:
__SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = 0
if addscore_precision > 0 or addscore_recall > 0:
__SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = ssent.split(" " )
__SCREAMING_SNAKE_CASE = csent.split(" " )
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
for rsent in rsents:
__SCREAMING_SNAKE_CASE = rsent.split(" " )
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
ragramslist.append(lowerCAmelCase_ )
for i in range(0 , len(lowerCAmelCase_ ) - 1 ):
if i < len(lowerCAmelCase_ ) - 1:
__SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1]
ragrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 2:
__SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2]
ragrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 3:
__SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3]
ragrams.append(lowerCAmelCase_ )
ragramslist.append(lowerCAmelCase_ )
ragramslist.append(lowerCAmelCase_ )
ragramslist.append(lowerCAmelCase_ )
for i in range(0 , len(lowerCAmelCase_ ) - 1 ):
if i < len(lowerCAmelCase_ ) - 1:
__SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1]
sagrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 2:
__SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2]
sagrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 3:
__SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3]
sagrams.append(lowerCAmelCase_ )
for i in range(0 , len(lowerCAmelCase_ ) - 1 ):
if i < len(lowerCAmelCase_ ) - 1:
__SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1]
cagrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 2:
__SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2]
cagrams.append(lowerCAmelCase_ )
if i < len(lowerCAmelCase_ ) - 3:
__SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3]
cagrams.append(lowerCAmelCase_ )
((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
__SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4
__SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4
__SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ):
'''simple docstring'''
if lowercase:
__SCREAMING_SNAKE_CASE = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
__SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ )
else:
__SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ )
elif tokenizer == "moses":
__SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ )
elif tokenizer == "penn":
__SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ )
else:
__SCREAMING_SNAKE_CASE = sentence
if not return_str:
__SCREAMING_SNAKE_CASE = normalized_sent.split()
return normalized_sent
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )):
raise ValueError("Sources length must match predictions and references lengths." )
__SCREAMING_SNAKE_CASE = 0
for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] )
__SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ )
return 100 * sari_score
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = len(references[0] )
if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ):
raise ValueError("Sacrebleu requires the same number of references for each prediction" )
__SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )]
__SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu(
lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION)
class UpperCamelCase_ ( datasets.Metric):
"""simple docstring"""
def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ),
} ) , codebase_urls=[
"https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py",
"https://github.com/cocoxu/simplification/blob/master/SARI.py",
"https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py",
"https://github.com/mjpost/sacreBLEU",
] , reference_urls=[
"https://www.aclweb.org/anthology/Q16-1029.pdf",
"https://github.com/mjpost/sacreBLEU",
"https://en.wikipedia.org/wiki/BLEU",
"https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
] , )
def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]:
__SCREAMING_SNAKE_CASE = {}
result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} )
result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} )
result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} )
return result
| 682 | 0 |
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401
from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
) | 705 |
from __future__ import annotations
import math
import random
from typing import Any
class _UpperCamelCase :
'''simple docstring'''
def __init__( self : Union[str, Any] ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : list[Any] = []
SCREAMING_SNAKE_CASE : int = 0
SCREAMING_SNAKE_CASE : int = 0
def __UpperCamelCase ( self : List[Any] ) -> bool:
"""simple docstring"""
return self.head == self.tail
def __UpperCamelCase ( self : Optional[int] , a : Any ) -> None:
"""simple docstring"""
self.data.append(a )
SCREAMING_SNAKE_CASE : List[str] = self.tail + 1
def __UpperCamelCase ( self : Tuple ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = self.data[self.head]
SCREAMING_SNAKE_CASE : List[str] = self.head + 1
return ret
def __UpperCamelCase ( self : List[str] ) -> int:
"""simple docstring"""
return self.tail - self.head
def __UpperCamelCase ( self : Optional[Any] ) -> None:
"""simple docstring"""
print(self.data )
print("**************" )
print(self.data[self.head : self.tail] )
class _UpperCamelCase :
'''simple docstring'''
def __init__( self : List[str] , a : Any ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = data
SCREAMING_SNAKE_CASE : MyNode | None = None
SCREAMING_SNAKE_CASE : MyNode | None = None
SCREAMING_SNAKE_CASE : int = 1
def __UpperCamelCase ( self : Tuple ) -> Any:
"""simple docstring"""
return self.data
def __UpperCamelCase ( self : Optional[int] ) -> MyNode | None:
"""simple docstring"""
return self.left
def __UpperCamelCase ( self : Union[str, Any] ) -> MyNode | None:
"""simple docstring"""
return self.right
def __UpperCamelCase ( self : Union[str, Any] ) -> int:
"""simple docstring"""
return self.height
def __UpperCamelCase ( self : Union[str, Any] , a : Any ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = data
def __UpperCamelCase ( self : Any , a : MyNode | None ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = node
def __UpperCamelCase ( self : List[str] , a : MyNode | None ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = node
def __UpperCamelCase ( self : Optional[int] , a : int ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = height
def lowerCamelCase__ ( _a):
if node is None:
return 0
return node.get_height()
def lowerCamelCase__ ( _a , _a):
if a > b:
return a
return b
def lowerCamelCase__ ( _a):
print("left rotation node:" , node.get_data())
SCREAMING_SNAKE_CASE : List[str] = node.get_left()
assert ret is not None
node.set_left(ret.get_right())
ret.set_right(_a)
SCREAMING_SNAKE_CASE : List[Any] = my_max(get_height(node.get_right()) , get_height(node.get_left())) + 1
node.set_height(_a)
SCREAMING_SNAKE_CASE : Optional[int] = my_max(get_height(ret.get_right()) , get_height(ret.get_left())) + 1
ret.set_height(_a)
return ret
def lowerCamelCase__ ( _a):
print("right rotation node:" , node.get_data())
SCREAMING_SNAKE_CASE : Dict = node.get_right()
assert ret is not None
node.set_right(ret.get_left())
ret.set_left(_a)
SCREAMING_SNAKE_CASE : Union[str, Any] = my_max(get_height(node.get_right()) , get_height(node.get_left())) + 1
node.set_height(_a)
SCREAMING_SNAKE_CASE : Tuple = my_max(get_height(ret.get_right()) , get_height(ret.get_left())) + 1
ret.set_height(_a)
return ret
def lowerCamelCase__ ( _a):
SCREAMING_SNAKE_CASE : List[Any] = node.get_left()
assert left_child is not None
node.set_left(left_rotation(_a))
return right_rotation(_a)
def lowerCamelCase__ ( _a):
SCREAMING_SNAKE_CASE : int = node.get_right()
assert right_child is not None
node.set_right(right_rotation(_a))
return left_rotation(_a)
def lowerCamelCase__ ( _a , _a):
if node is None:
return MyNode(_a)
if data < node.get_data():
node.set_left(insert_node(node.get_left() , _a))
if (
get_height(node.get_left()) - get_height(node.get_right()) == 2
): # an unbalance detected
SCREAMING_SNAKE_CASE : List[Any] = node.get_left()
assert left_child is not None
if (
data < left_child.get_data()
): # new node is the left child of the left child
SCREAMING_SNAKE_CASE : Tuple = right_rotation(_a)
else:
SCREAMING_SNAKE_CASE : int = lr_rotation(_a)
else:
node.set_right(insert_node(node.get_right() , _a))
if get_height(node.get_right()) - get_height(node.get_left()) == 2:
SCREAMING_SNAKE_CASE : Any = node.get_right()
assert right_child is not None
if data < right_child.get_data():
SCREAMING_SNAKE_CASE : Union[str, Any] = rl_rotation(_a)
else:
SCREAMING_SNAKE_CASE : int = left_rotation(_a)
SCREAMING_SNAKE_CASE : str = my_max(get_height(node.get_right()) , get_height(node.get_left())) + 1
node.set_height(_a)
return node
def lowerCamelCase__ ( _a):
while True:
SCREAMING_SNAKE_CASE : List[Any] = root.get_right()
if right_child is None:
break
SCREAMING_SNAKE_CASE : str = right_child
return root.get_data()
def lowerCamelCase__ ( _a):
while True:
SCREAMING_SNAKE_CASE : Optional[int] = root.get_left()
if left_child is None:
break
SCREAMING_SNAKE_CASE : List[str] = left_child
return root.get_data()
def lowerCamelCase__ ( _a , _a):
SCREAMING_SNAKE_CASE : Any = root.get_left()
SCREAMING_SNAKE_CASE : List[Any] = root.get_right()
if root.get_data() == data:
if left_child is not None and right_child is not None:
SCREAMING_SNAKE_CASE : Any = get_left_most(_a)
root.set_data(_a)
root.set_right(del_node(_a , _a))
elif left_child is not None:
SCREAMING_SNAKE_CASE : Dict = left_child
elif right_child is not None:
SCREAMING_SNAKE_CASE : str = right_child
else:
return None
elif root.get_data() > data:
if left_child is None:
print("No such data")
return root
else:
root.set_left(del_node(_a , _a))
else: # root.get_data() < data
if right_child is None:
return root
else:
root.set_right(del_node(_a , _a))
if get_height(_a) - get_height(_a) == 2:
assert right_child is not None
if get_height(right_child.get_right()) > get_height(right_child.get_left()):
SCREAMING_SNAKE_CASE : List[str] = left_rotation(_a)
else:
SCREAMING_SNAKE_CASE : int = rl_rotation(_a)
elif get_height(_a) - get_height(_a) == -2:
assert left_child is not None
if get_height(left_child.get_left()) > get_height(left_child.get_right()):
SCREAMING_SNAKE_CASE : str = right_rotation(_a)
else:
SCREAMING_SNAKE_CASE : Optional[Any] = lr_rotation(_a)
SCREAMING_SNAKE_CASE : List[str] = my_max(get_height(root.get_right()) , get_height(root.get_left())) + 1
root.set_height(_a)
return root
class _UpperCamelCase :
'''simple docstring'''
def __init__( self : str ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE : MyNode | None = None
def __UpperCamelCase ( self : Any ) -> int:
"""simple docstring"""
return get_height(self.root )
def __UpperCamelCase ( self : List[Any] , a : Any ) -> None:
"""simple docstring"""
print("insert:" + str(a ) )
SCREAMING_SNAKE_CASE : Any = insert_node(self.root , a )
def __UpperCamelCase ( self : List[Any] , a : Any ) -> None:
"""simple docstring"""
print("delete:" + str(a ) )
if self.root is None:
print("Tree is empty!" )
return
SCREAMING_SNAKE_CASE : Optional[int] = del_node(self.root , a )
def __str__( self : Optional[int] , ) -> str: # a level traversale, gives a more intuitive look on the tree
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = ""
SCREAMING_SNAKE_CASE : Optional[int] = MyQueue()
q.push(self.root )
SCREAMING_SNAKE_CASE : Any = self.get_height()
if layer == 0:
return output
SCREAMING_SNAKE_CASE : Dict = 0
while not q.is_empty():
SCREAMING_SNAKE_CASE : Dict = q.pop()
SCREAMING_SNAKE_CASE : List[Any] = " " * int(math.pow(2 , layer - 1 ) )
output += space
if node is None:
output += "*"
q.push(a )
q.push(a )
else:
output += str(node.get_data() )
q.push(node.get_left() )
q.push(node.get_right() )
output += space
SCREAMING_SNAKE_CASE : List[str] = cnt + 1
for i in range(100 ):
if cnt == math.pow(2 , a ) - 1:
SCREAMING_SNAKE_CASE : List[str] = layer - 1
if layer == 0:
output += "\n*************************************"
return output
output += "\n"
break
output += "\n*************************************"
return output
def lowerCamelCase__ ( ):
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
a_ = AVLtree()
a_ = list(range(10))
random.shuffle(lst)
for i in lst:
t.insert(i)
print(str(t))
random.shuffle(lst)
for i in lst:
t.del_node(i)
print(str(t)) | 193 | 0 |
import cva
import numpy as np
class _snake_case :
def __init__( self , _lowerCamelCase , _lowerCamelCase ):
if k in (0.04, 0.06):
a :Tuple = k
a :Optional[int] = window_size
else:
raise ValueError('''invalid k value''' )
def __str__( self ):
return str(self.k )
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ):
a :Union[str, Any] = cva.imread(_lowerCamelCase , 0 )
a , a :Optional[Any] = img.shape
a :list[list[int]] = []
a :Optional[Any] = img.copy()
a :Tuple = cva.cvtColor(_lowerCamelCase , cva.COLOR_GRAY2RGB )
a , a :Any = np.gradient(_lowerCamelCase )
a :List[Any] = dx**2
a :List[Any] = dy**2
a :Any = dx * dy
a :List[Any] = 0.04
a :Any = self.window_size // 2
for y in range(_lowerCamelCase , h - offset ):
for x in range(_lowerCamelCase , w - offset ):
a :Optional[Any] = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
a :Union[str, Any] = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
a :str = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
a :str = (wxx * wyy) - (wxy**2)
a :str = wxx + wyy
a :Tuple = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r] )
color_img.itemset((y, x, 0) , 0 )
color_img.itemset((y, x, 1) , 0 )
color_img.itemset((y, x, 2) , 255 )
return color_img, corner_list
if __name__ == "__main__":
snake_case : Optional[int] = HarrisCorner(0.04, 3)
snake_case , snake_case : int = edge_detect.detect('''path_to_image''')
cva.imwrite('''detect.png''', color_img)
| 445 |
import qiskit
def __lowerCamelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ):
"""simple docstring"""
a :Tuple = qiskit.Aer.get_backend('''aer_simulator''' )
# Create a Quantum Circuit acting on the q register
a :str = qiskit.QuantumCircuit(UpperCAmelCase_ , UpperCAmelCase_ )
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0 )
circuit.x(1 )
# Map the quantum measurement to the classical bits
circuit.measure([0, 1] , [0, 1] )
# Execute the circuit on the qasm simulator
a :Optional[Any] = qiskit.execute(UpperCAmelCase_ , UpperCAmelCase_ , shots=1000 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(UpperCAmelCase_ )
if __name__ == "__main__":
snake_case : Any = single_qubit_measure(2, 2)
print(F"""Total count for various states are: {counts}""")
| 445 | 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.
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
a_ : Dict = {
'''configuration_vivit''': ['''VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VivitConfig'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : int = ['''VivitImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : Optional[Any] = [
'''VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''VivitModel''',
'''VivitPreTrainedModel''',
'''VivitForVideoClassification''',
]
if TYPE_CHECKING:
from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_vivit import VivitImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vivit import (
VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
VivitForVideoClassification,
VivitModel,
VivitPreTrainedModel,
)
else:
import sys
a_ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 263 |
"""simple docstring"""
import json
import os
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a_ : Dict = logging.get_logger(__name__)
a_ : List[Any] = {
'''vocab_file''': '''vocab.json''',
'''tokenizer_config_file''': '''tokenizer_config.json''',
'''merges_file''': '''merges.txt''',
}
a_ : Tuple = {
'''vocab_file''': {
'''facebook/s2t-wav2vec2-large-en-de''': (
'''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json'''
),
},
'''tokenizer_config_file''': {
'''facebook/s2t-wav2vec2-large-en-de''': (
'''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json'''
),
},
'''merges_file''': {
'''facebook/s2t-wav2vec2-large-en-de''': (
'''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt'''
),
},
}
a_ : Optional[Any] = '''</w>'''
a_ : Dict = '''@@ '''
def UpperCAmelCase ( A__: Optional[Any] ) -> Optional[int]:
__lowerCamelCase : Any = set()
__lowerCamelCase : Optional[int] = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__lowerCamelCase : Optional[int] = char
return pairs
# Speech2Text2 has no max input length
a_ : Union[str, Any] = {'''facebook/s2t-wav2vec2-large-en-de''': 10_24}
class __lowercase( lowercase__ ):
'''simple docstring'''
__a : List[str] = VOCAB_FILES_NAMES
__a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
__a : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a : Dict = ['input_ids', 'attention_mask']
def __init__( self , __a , __a="<s>" , __a="<pad>" , __a="</s>" , __a="<unk>" , __a=False , __a=None , **__a , ):
super().__init__(
unk_token=__a , bos_token=__a , eos_token=__a , pad_token=__a , do_lower_case=__a , **__a , )
__lowerCamelCase : List[Any] = do_lower_case
with open(__a , encoding='utf-8' ) as vocab_handle:
__lowerCamelCase : str = json.load(__a )
__lowerCamelCase : int = {v: k for k, v in self.encoder.items()}
if merges_file is None:
logger.info(f'''No merges files provided. {self.__class__.__name__} can only be used for decoding.''' )
__lowerCamelCase : str = None
__lowerCamelCase : Optional[int] = None
else:
with open(__a , encoding='utf-8' ) as merges_handle:
__lowerCamelCase : Optional[int] = merges_handle.read().split('\n' )[:-1]
__lowerCamelCase : List[str] = [tuple(merge.split()[:2] ) for merge in merges]
__lowerCamelCase : Any = dict(zip(__a , range(len(__a ) ) ) )
__lowerCamelCase : List[str] = {}
@property
def snake_case_ ( self ):
return len(self.decoder )
def snake_case_ ( self ):
return dict(self.encoder , **self.added_tokens_encoder )
def snake_case_ ( self , __a ):
__lowerCamelCase : Optional[Any] = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,)
if token in self.cache:
return self.cache[token]
__lowerCamelCase : Union[str, Any] = get_pairs(__a )
if not pairs:
return token
while True:
__lowerCamelCase : Dict = min(__a , key=lambda __a : self.bpe_ranks.get(__a , float('inf' ) ) )
if bigram not in self.bpe_ranks:
break
__lowerCamelCase , __lowerCamelCase : Optional[Any] = bigram
__lowerCamelCase : Tuple = []
__lowerCamelCase : Union[str, Any] = 0
while i < len(__a ):
try:
__lowerCamelCase : Union[str, Any] = word.index(__a , __a )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
__lowerCamelCase : Any = 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
__lowerCamelCase : List[str] = tuple(__a )
__lowerCamelCase : Any = new_word
if len(__a ) == 1:
break
else:
__lowerCamelCase : Tuple = get_pairs(__a )
__lowerCamelCase : Optional[int] = ' '.join(__a )
if word == "\n " + BPE_TOKEN_MERGES:
__lowerCamelCase : str = '\n' + BPE_TOKEN_MERGES
if word.endswith(__a ):
__lowerCamelCase : Tuple = word.replace(__a , '' )
__lowerCamelCase : Optional[Any] = word.replace(' ' , __a )
__lowerCamelCase : Union[str, Any] = word
return word
def snake_case_ ( self , __a ):
if self.bpe_ranks is None:
raise ValueError(
'This tokenizer was instantiated without a `merges.txt` file, so'
' that it can only be used for decoding, not for encoding.'
'Make sure to provide `merges.txt` file at instantiation to enable '
'encoding.' )
if self.do_lower_case:
__lowerCamelCase : Any = text.lower()
__lowerCamelCase : Union[str, Any] = text.split()
__lowerCamelCase : str = []
for token in text:
if token:
split_tokens.extend(list(self.bpe(__a ).split(' ' ) ) )
return split_tokens
def snake_case_ ( self , __a ):
return self.encoder.get(__a , self.encoder.get(self.unk_token ) )
def snake_case_ ( self , __a ):
__lowerCamelCase : int = self.decoder.get(__a , self.unk_token )
return result
def snake_case_ ( self , __a ):
__lowerCamelCase : Any = ' '.join(__a )
# make sure @@ tokens are concatenated
__lowerCamelCase : Union[str, Any] = ''.join(string.split(__a ) )
return string
def snake_case_ ( self , __a , __a = None ):
if not os.path.isdir(__a ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__lowerCamelCase : int = os.path.join(
__a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
__lowerCamelCase : 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' )
__lowerCamelCase : Optional[int] = 0
if self.bpe_ranks is None:
return (vocab_file,)
with open(__a , 'w' , encoding='utf-8' ) as writer:
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 {merges_file}: BPE merge indices are not consecutive.'''
' Please check that the tokenizer is not corrupted!' )
__lowerCamelCase : Optional[int] = token_index
writer.write(' '.join(__a ) + '\n' )
index += 1
return (vocab_file, merges_file)
| 263 | 1 |
'''simple docstring'''
import gc
import random
import unittest
import torch
from diffusers import (
IFImgaImgPipeline,
IFImgaImgSuperResolutionPipeline,
IFInpaintingPipeline,
IFInpaintingSuperResolutionPipeline,
IFPipeline,
IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin
@skip_mps
class lowercase_ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
__lowerCAmelCase = IFPipeline
__lowerCAmelCase = TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
__lowerCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS
__lowerCAmelCase = PipelineTesterMixin.required_optional_params - {"latents"}
def __UpperCAmelCase ( self : int ) -> Tuple:
return self._get_dummy_components()
def __UpperCAmelCase ( self : Dict, UpperCamelCase__ : str, UpperCamelCase__ : Any=0 ) -> List[str]:
if str(UpperCamelCase__ ).startswith('mps' ):
_A = torch.manual_seed(UpperCamelCase__ )
else:
_A = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ )
_A = {
'prompt': 'A painting of a squirrel eating a burger',
'generator': generator,
'num_inference_steps': 2,
'output_type': 'numpy',
}
return inputs
def __UpperCAmelCase ( self : List[Any] ) -> int:
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != 'cuda', reason='float16 requires CUDA' )
def __UpperCAmelCase ( self : List[str] ) -> Optional[Any]:
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
super().test_save_load_floataa(expected_max_diff=1e-1 )
def __UpperCAmelCase ( self : Optional[int] ) -> List[str]:
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 )
def __UpperCAmelCase ( self : str ) -> str:
self._test_save_load_local()
def __UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]:
self._test_inference_batch_single_identical(
expected_max_diff=1e-2, )
@unittest.skipIf(
torch_device != 'cuda' or not is_xformers_available(), reason='XFormers attention is only available with CUDA and `xformers` installed', )
def __UpperCAmelCase ( self : Optional[int] ) -> List[str]:
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 )
@slow
@require_torch_gpu
class lowercase_ ( unittest.TestCase ):
"""simple docstring"""
def __UpperCAmelCase ( self : List[str] ) -> Tuple:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __UpperCAmelCase ( self : Dict ) -> Dict:
# if
_A = IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0', variant='fp16', torch_dtype=torch.floataa )
_A = IFSuperResolutionPipeline.from_pretrained(
'DeepFloyd/IF-II-L-v1.0', variant='fp16', torch_dtype=torch.floataa, text_encoder=UpperCamelCase__, tokenizer=UpperCamelCase__ )
# pre compute text embeddings and remove T5 to save memory
pipe_a.text_encoder.to('cuda' )
_A , _A = pipe_a.encode_prompt('anime turtle', device='cuda' )
del pipe_a.tokenizer
del pipe_a.text_encoder
gc.collect()
_A = None
_A = None
pipe_a.enable_model_cpu_offload()
pipe_a.enable_model_cpu_offload()
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
self._test_if(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
pipe_a.remove_all_hooks()
pipe_a.remove_all_hooks()
# img2img
_A = IFImgaImgPipeline(**pipe_a.components )
_A = IFImgaImgSuperResolutionPipeline(**pipe_a.components )
pipe_a.enable_model_cpu_offload()
pipe_a.enable_model_cpu_offload()
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
self._test_if_imgaimg(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
pipe_a.remove_all_hooks()
pipe_a.remove_all_hooks()
# inpainting
_A = IFInpaintingPipeline(**pipe_a.components )
_A = IFInpaintingSuperResolutionPipeline(**pipe_a.components )
pipe_a.enable_model_cpu_offload()
pipe_a.enable_model_cpu_offload()
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() )
self._test_if_inpainting(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
def __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : Dict, UpperCamelCase__ : int, UpperCamelCase__ : Dict, UpperCamelCase__ : Dict ) -> List[Any]:
# pipeline 1
_start_torch_memory_measurement()
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, num_inference_steps=2, generator=UpperCamelCase__, output_type='np', )
_A = output.images[0]
assert image.shape == (64, 64, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 13 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
# pipeline 2
_start_torch_memory_measurement()
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, image=UpperCamelCase__, generator=UpperCamelCase__, num_inference_steps=2, output_type='np', )
_A = output.images[0]
assert image.shape == (2_56, 2_56, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 4 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
def __UpperCAmelCase ( self : List[Any], UpperCamelCase__ : List[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : int ) -> str:
# pipeline 1
_start_torch_memory_measurement()
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, image=UpperCamelCase__, num_inference_steps=2, generator=UpperCamelCase__, output_type='np', )
_A = output.images[0]
assert image.shape == (64, 64, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 10 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
# pipeline 2
_start_torch_memory_measurement()
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = floats_tensor((1, 3, 2_56, 2_56), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, image=UpperCamelCase__, original_image=UpperCamelCase__, generator=UpperCamelCase__, num_inference_steps=2, output_type='np', )
_A = output.images[0]
assert image.shape == (2_56, 2_56, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 4 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
def __UpperCAmelCase ( self : Optional[Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : List[str] ) -> Tuple:
# pipeline 1
_start_torch_memory_measurement()
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(1 ) ).to(UpperCamelCase__ )
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, image=UpperCamelCase__, mask_image=UpperCamelCase__, num_inference_steps=2, generator=UpperCamelCase__, output_type='np', )
_A = output.images[0]
assert image.shape == (64, 64, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 10 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
# pipeline 2
_start_torch_memory_measurement()
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = floats_tensor((1, 3, 64, 64), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = floats_tensor((1, 3, 2_56, 2_56), rng=random.Random(0 ) ).to(UpperCamelCase__ )
_A = floats_tensor((1, 3, 2_56, 2_56), rng=random.Random(1 ) ).to(UpperCamelCase__ )
_A = pipe_a(
prompt_embeds=UpperCamelCase__, negative_prompt_embeds=UpperCamelCase__, image=UpperCamelCase__, mask_image=UpperCamelCase__, original_image=UpperCamelCase__, generator=UpperCamelCase__, num_inference_steps=2, output_type='np', )
_A = output.images[0]
assert image.shape == (2_56, 2_56, 3)
_A = torch.cuda.max_memory_allocated()
assert mem_bytes < 4 * 10**9
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy' )
assert_mean_pixel_difference(UpperCamelCase__, UpperCamelCase__ )
def _SCREAMING_SNAKE_CASE ( ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
| 107 |
'''simple docstring'''
import unittest
from transformers import BigBirdTokenizer, BigBirdTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__UpperCAmelCase = """▁"""
__UpperCAmelCase = get_tests_dir("""fixtures/test_sentencepiece.model""")
@require_sentencepiece
@require_tokenizers
class UpperCamelCase__ ( lowercase_ , unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = BigBirdTokenizer
SCREAMING_SNAKE_CASE__ = BigBirdTokenizerFast
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = True
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
super().setUp()
SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class(lowerCamelCase_ , keep_accents=lowerCamelCase_ )
tokenizer.save_pretrained(self.tmpdirname )
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = """<s>"""
SCREAMING_SNAKE_CASE : str = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase_ ) , lowerCamelCase_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase_ ) , lowerCamelCase_ )
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , """<unk>""" )
self.assertEqual(vocab_keys[1] , """<s>""" )
self.assertEqual(vocab_keys[-1] , """[MASK]""" )
self.assertEqual(len(lowerCamelCase_ ) , 10_04 )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 10_00 )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
if not self.test_rust_tokenizer:
return
SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
SCREAMING_SNAKE_CASE : str = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE : Optional[Any] = """I was born in 92000, and this is falsé."""
SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : List[str] = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.encode(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = BigBirdTokenizer(lowerCamelCase_ , keep_accents=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(lowerCamelCase_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [2_85, 46, 10, 1_70, 3_82] , )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
lowerCamelCase_ , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""9""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""é""",
""".""",
] , )
SCREAMING_SNAKE_CASE : int = tokenizer.convert_tokens_to_ids(lowerCamelCase_ )
self.assertListEqual(
lowerCamelCase_ , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
SCREAMING_SNAKE_CASE : int = tokenizer.convert_ids_to_tokens(lowerCamelCase_ )
self.assertListEqual(
lowerCamelCase_ , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""<unk>""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""<unk>""",
""".""",
] , )
@cached_property
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
return BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""" )
@slow
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = """Hello World!"""
SCREAMING_SNAKE_CASE : Tuple = [65, 1_85_36, 22_60, 1_01, 66]
self.assertListEqual(lowerCamelCase_ , self.big_tokenizer.encode(lowerCamelCase_ ) )
@slow
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = (
"""This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"""
""" add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"""
)
# fmt: off
SCREAMING_SNAKE_CASE : Dict = [65, 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, 66] # noqa: E231
# fmt: on
self.assertListEqual(lowerCamelCase_ , self.big_tokenizer.encode(lowerCamelCase_ ) )
@require_torch
@slow
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
import torch
from transformers import BigBirdConfig, BigBirdModel
# Build sequence
SCREAMING_SNAKE_CASE : int = list(self.big_tokenizer.get_vocab().keys() )[:10]
SCREAMING_SNAKE_CASE : List[str] = """ """.join(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = self.big_tokenizer.encode_plus(lowerCamelCase_ , return_tensors="""pt""" , return_token_type_ids=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Any = self.big_tokenizer.batch_encode_plus(
[sequence + """ """ + sequence] , return_tensors="""pt""" , return_token_type_ids=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = BigBirdConfig(attention_type="""original_full""" )
SCREAMING_SNAKE_CASE : Tuple = BigBirdModel(lowerCamelCase_ )
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**lowerCamelCase_ )
model(**lowerCamelCase_ )
@slow
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""" )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.decode(tokenizer("""Paris is the [MASK].""" ).input_ids )
self.assertTrue(decoded_text == """[CLS] Paris is the[MASK].[SEP]""" )
@slow
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = {"""input_ids""": [[65, 3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14, 66], [65, 4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 66, 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], [65, 4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 66, 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]], """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, 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]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCamelCase_ , model_name="""google/bigbird-roberta-base""" , revision="""215c99f1600e06f83acce68422f2035b2b5c3510""" , )
| 379 | 0 |
'''simple docstring'''
from math import ceil
def lowercase ( __magic_name__ , __magic_name__ ):
'''simple docstring'''
UpperCAmelCase : str = list(range(0 , __magic_name__ ) )
UpperCAmelCase : str = [item for sublist in list(device_map.values() ) for item in sublist]
# Duplicate check
UpperCAmelCase : Optional[Any] = []
for i in device_map_blocks:
if device_map_blocks.count(__magic_name__ ) > 1 and i not in duplicate_blocks:
duplicate_blocks.append(__magic_name__ )
# Missing blocks
UpperCAmelCase : Optional[int] = [i for i in blocks if i not in device_map_blocks]
UpperCAmelCase : Dict = [i for i in device_map_blocks if i not in blocks]
if len(__magic_name__ ) != 0:
raise ValueError(
"Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
" These attention blocks were specified more than once: " + str(__magic_name__ ) )
if len(__magic_name__ ) != 0:
raise ValueError(
"There are attention blocks for this model that are not specified in the device_map. Add these attention "
"blocks to a device on the device_map: " + str(__magic_name__ ) )
if len(__magic_name__ ) != 0:
raise ValueError(
"The device_map contains more attention blocks than this model has. Remove these from the device_map:"
+ str(__magic_name__ ) )
def lowercase ( __magic_name__ , __magic_name__ ):
'''simple docstring'''
UpperCAmelCase : int = list(range(__magic_name__ ) )
UpperCAmelCase : Union[str, Any] = int(ceil(n_layers / len(__magic_name__ ) ) )
UpperCAmelCase : Union[str, Any] = [layers[i : i + n_blocks] for i in range(0 , __magic_name__ , __magic_name__ )]
return dict(zip(__magic_name__ , __magic_name__ ) )
| 609 |
'''simple docstring'''
import unittest
from transformers import XLMConfig, is_torch_available
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 (
XLMForMultipleChoice,
XLMForQuestionAnswering,
XLMForQuestionAnsweringSimple,
XLMForSequenceClassification,
XLMForTokenClassification,
XLMModel,
XLMWithLMHeadModel,
)
from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST
class UpperCamelCase__ :
"""simple docstring"""
def __init__( self , snake_case , snake_case=1_3 , snake_case=7 , snake_case=True , snake_case=True , snake_case=True , snake_case=True , snake_case=True , snake_case=False , snake_case=False , snake_case=False , snake_case=2 , snake_case=9_9 , snake_case=0 , snake_case=3_2 , snake_case=5 , snake_case=4 , snake_case=0.1 , snake_case=0.1 , snake_case=5_1_2 , snake_case=2 , snake_case=0.02 , snake_case=2 , snake_case=4 , snake_case="last" , snake_case=True , snake_case=None , snake_case=0 , ):
'''simple docstring'''
UpperCAmelCase : str = parent
UpperCAmelCase : str = batch_size
UpperCAmelCase : Union[str, Any] = seq_length
UpperCAmelCase : int = is_training
UpperCAmelCase : Any = use_input_lengths
UpperCAmelCase : str = use_token_type_ids
UpperCAmelCase : List[str] = use_labels
UpperCAmelCase : Any = gelu_activation
UpperCAmelCase : str = sinusoidal_embeddings
UpperCAmelCase : List[Any] = causal
UpperCAmelCase : Union[str, Any] = asm
UpperCAmelCase : List[str] = n_langs
UpperCAmelCase : Optional[int] = vocab_size
UpperCAmelCase : str = n_special
UpperCAmelCase : str = hidden_size
UpperCAmelCase : Union[str, Any] = num_hidden_layers
UpperCAmelCase : Dict = num_attention_heads
UpperCAmelCase : List[Any] = hidden_dropout_prob
UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob
UpperCAmelCase : str = max_position_embeddings
UpperCAmelCase : Optional[int] = type_sequence_label_size
UpperCAmelCase : Optional[int] = initializer_range
UpperCAmelCase : Union[str, Any] = num_labels
UpperCAmelCase : Union[str, Any] = num_choices
UpperCAmelCase : Dict = summary_type
UpperCAmelCase : Dict = use_proj
UpperCAmelCase : List[Any] = scope
UpperCAmelCase : Optional[int] = bos_token_id
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase : Optional[Any] = None
if self.use_input_lengths:
UpperCAmelCase : Dict = (
ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2
) # small variation of seq_length
UpperCAmelCase : Union[str, Any] = None
if self.use_token_type_ids:
UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs )
UpperCAmelCase : Any = None
UpperCAmelCase : Optional[Any] = None
UpperCAmelCase : Tuple = None
if self.use_labels:
UpperCAmelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCAmelCase : Dict = ids_tensor([self.batch_size] , 2 ).float()
UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices )
UpperCAmelCase : List[str] = self.get_config()
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def A_ ( self ):
'''simple docstring'''
return XLMConfig(
vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Any = XLMModel(config=snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : Any = model(snake_case , lengths=snake_case , langs=snake_case )
UpperCAmelCase : Any = model(snake_case , langs=snake_case )
UpperCAmelCase : Union[str, Any] = model(snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : int = XLMWithLMHeadModel(snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : Tuple = model(snake_case , token_type_ids=snake_case , labels=snake_case )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Optional[int] = XLMForQuestionAnsweringSimple(snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : List[str] = model(snake_case )
UpperCAmelCase : List[str] = model(snake_case , start_positions=snake_case , end_positions=snake_case )
UpperCAmelCase : List[str] = outputs
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 , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = XLMForQuestionAnswering(snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : Union[str, Any] = model(snake_case )
UpperCAmelCase : List[str] = model(
snake_case , start_positions=snake_case , end_positions=snake_case , cls_index=snake_case , is_impossible=snake_case , p_mask=snake_case , )
UpperCAmelCase : Optional[Any] = model(
snake_case , start_positions=snake_case , end_positions=snake_case , cls_index=snake_case , is_impossible=snake_case , )
((UpperCAmelCase) , ) : str = result_with_labels.to_tuple()
UpperCAmelCase : List[str] = model(snake_case , start_positions=snake_case , end_positions=snake_case )
((UpperCAmelCase) , ) : str = result_with_labels.to_tuple()
self.parent.assertEqual(result_with_labels.loss.shape , () )
self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(
result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(
result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Any = XLMForSequenceClassification(snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : Optional[int] = model(snake_case )
UpperCAmelCase : int = model(snake_case , labels=snake_case )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.num_labels
UpperCAmelCase : Optional[int] = XLMForTokenClassification(snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : List[Any] = model(snake_case , attention_mask=snake_case , labels=snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.num_choices
UpperCAmelCase : Tuple = XLMForMultipleChoice(config=snake_case )
model.to(snake_case )
model.eval()
UpperCAmelCase : Optional[int] = 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 : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCAmelCase : Tuple = model(
snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : str = self.prepare_config_and_inputs()
(
(
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) ,
) : Union[str, Any] = config_and_inputs
UpperCAmelCase : List[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths}
return config, inputs_dict
@require_torch
class UpperCamelCase__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = (
(
XLMModel,
XLMWithLMHeadModel,
XLMForQuestionAnswering,
XLMForSequenceClassification,
XLMForQuestionAnsweringSimple,
XLMForTokenClassification,
XLMForMultipleChoice,
)
if is_torch_available()
else ()
)
SCREAMING_SNAKE_CASE__ : str = (
(XLMWithLMHeadModel,) if is_torch_available() else ()
) # TODO (PVP): Check other models whether language generation is also applicable
SCREAMING_SNAKE_CASE__ : Tuple = (
{
"feature-extraction": XLMModel,
"fill-mask": XLMWithLMHeadModel,
"question-answering": XLMForQuestionAnsweringSimple,
"text-classification": XLMForSequenceClassification,
"text-generation": XLMWithLMHeadModel,
"token-classification": XLMForTokenClassification,
"zero-shot": XLMForSequenceClassification,
}
if is_torch_available()
else {}
)
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case ):
'''simple docstring'''
if (
pipeline_test_casse_name == "QAPipelineTests"
and tokenizer_name is not None
and not tokenizer_name.endswith("Fast" )
):
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
return True
return False
def A_ ( self , snake_case , snake_case , snake_case=False ):
'''simple docstring'''
UpperCAmelCase : Any = super()._prepare_for_class(snake_case , snake_case , return_labels=snake_case )
if return_labels:
if model_class.__name__ == "XLMForQuestionAnswering":
UpperCAmelCase : int = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=snake_case )
UpperCAmelCase : List[str] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=snake_case )
return inputs_dict
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Dict = XLMModelTester(self )
UpperCAmelCase : str = ConfigTester(self , config_class=snake_case , emb_dim=3_7 )
def A_ ( self ):
'''simple docstring'''
self.config_tester.run_common_tests()
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_model(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_lm_head(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_simple_qa(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_qa(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_sequence_classif(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_token_classif(*snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_for_multiple_choice(*snake_case )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=False , snake_case=1 ):
'''simple docstring'''
self.assertIsInstance(snake_case , snake_case )
self.assertListEqual(
[isinstance(snake_case , snake_case ) for iter_attentions in attentions] , [True] * len(snake_case ) )
self.assertEqual(len(snake_case ) , (max_length - min_length) * num_beam_groups )
for idx, iter_attentions in enumerate(snake_case ):
# adds PAD dummy token
UpperCAmelCase : str = min_length + idx + 1
UpperCAmelCase : List[Any] = min_length + idx + 1
UpperCAmelCase : List[Any] = (
batch_size * num_beam_groups,
config.num_attention_heads,
tgt_len,
src_len,
)
# check attn size
self.assertListEqual(
[layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(snake_case ) )
def A_ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=False , snake_case=1 ):
'''simple docstring'''
self.assertIsInstance(snake_case , snake_case )
self.assertListEqual(
[isinstance(snake_case , snake_case ) for iter_hidden_states in hidden_states] , [True] * len(snake_case ) , )
self.assertEqual(len(snake_case ) , (max_length - min_length) * num_beam_groups )
for idx, iter_hidden_states in enumerate(snake_case ):
# adds PAD dummy token
UpperCAmelCase : List[Any] = min_length + idx + 1
UpperCAmelCase : Dict = (batch_size * num_beam_groups, seq_len, config.hidden_size)
# check hidden size
self.assertListEqual(
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(snake_case ) , )
pass
@slow
def A_ ( self ):
'''simple docstring'''
for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase : Tuple = XLMModel.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
@require_torch
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
@slow
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : int = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" )
model.to(snake_case )
UpperCAmelCase : Optional[int] = torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=snake_case ) # the president
UpperCAmelCase : Tuple = [
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
] # the president the president the president the president the president the president the president the president the president the president
# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
UpperCAmelCase : Dict = model.generate(snake_case , do_sample=snake_case )
self.assertListEqual(output_ids[0].cpu().numpy().tolist() , snake_case )
| 609 | 1 |
"""simple docstring"""
def _snake_case ( __snake_case : int = 200 ):
"""simple docstring"""
_lowerCamelCase : Dict = [1, 2, 5, 10, 20, 50, 100, 200]
_lowerCamelCase : Union[str, Any] = [0] * (pence + 1)
_lowerCamelCase : List[Any] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(__snake_case , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 7_3682
| 88 |
import inspect
import unittest
from transformers import ConvNextConfig
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 transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class lowerCamelCase :
'''simple docstring'''
def __init__( self , _UpperCamelCase , _UpperCamelCase=1_3 , _UpperCamelCase=3_2 , _UpperCamelCase=3 , _UpperCamelCase=4 , _UpperCamelCase=[1_0, 2_0, 3_0, 4_0] , _UpperCamelCase=[2, 2, 3, 2] , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=3_7 , _UpperCamelCase="gelu" , _UpperCamelCase=1_0 , _UpperCamelCase=0.02 , _UpperCamelCase=["stage2", "stage3", "stage4"] , _UpperCamelCase=[2, 3, 4] , _UpperCamelCase=None , ) -> str:
UpperCAmelCase_ : Union[str, Any] = parent
UpperCAmelCase_ : int = batch_size
UpperCAmelCase_ : List[Any] = image_size
UpperCAmelCase_ : List[str] = num_channels
UpperCAmelCase_ : List[Any] = num_stages
UpperCAmelCase_ : str = hidden_sizes
UpperCAmelCase_ : Any = depths
UpperCAmelCase_ : str = is_training
UpperCAmelCase_ : Tuple = use_labels
UpperCAmelCase_ : List[str] = intermediate_size
UpperCAmelCase_ : List[Any] = hidden_act
UpperCAmelCase_ : Union[str, Any] = num_labels
UpperCAmelCase_ : Union[str, Any] = initializer_range
UpperCAmelCase_ : List[str] = out_features
UpperCAmelCase_ : Optional[int] = out_indices
UpperCAmelCase_ : List[Any] = scope
def __UpperCAmelCase ( self ) -> Optional[Any]:
UpperCAmelCase_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase_ : List[str] = None
if self.use_labels:
UpperCAmelCase_ : Dict = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase_ : Optional[Any] = self.get_config()
return config, pixel_values, labels
def __UpperCAmelCase ( self ) -> List[str]:
return ConvNextConfig(
num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_UpperCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , )
def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]:
UpperCAmelCase_ : Any = ConvNextModel(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Optional[Any] = model(_UpperCamelCase )
# expected last hidden states: B, C, H // 32, W // 32
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 __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]:
UpperCAmelCase_ : List[str] = ConvNextForImageClassification(_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Any = model(_UpperCamelCase , labels=_UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]:
UpperCAmelCase_ : List[str] = ConvNextBackbone(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : int = model(_UpperCamelCase )
# verify hidden states
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
UpperCAmelCase_ : Optional[Any] = None
UpperCAmelCase_ : Tuple = ConvNextBackbone(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Tuple = model(_UpperCamelCase )
# 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 __UpperCAmelCase ( self ) -> Dict:
UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs()
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = config_and_inputs
UpperCAmelCase_ : List[Any] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase (_snake_case , _snake_case , unittest.TestCase ):
'''simple docstring'''
_snake_case : str = (
(
ConvNextModel,
ConvNextForImageClassification,
ConvNextBackbone,
)
if is_torch_available()
else ()
)
_snake_case : int = (
{'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
if is_torch_available()
else {}
)
_snake_case : Any = True
_snake_case : Optional[int] = False
_snake_case : Optional[int] = False
_snake_case : Union[str, Any] = False
_snake_case : List[str] = False
def __UpperCAmelCase ( self ) -> Tuple:
UpperCAmelCase_ : Dict = ConvNextModelTester(self )
UpperCAmelCase_ : Tuple = ConfigTester(self , config_class=_UpperCamelCase , has_text_modality=_UpperCamelCase , hidden_size=3_7 )
def __UpperCAmelCase ( self ) -> Tuple:
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 __UpperCAmelCase ( self ) -> List[str]:
return
@unittest.skip(reason='ConvNext does not use inputs_embeds' )
def __UpperCAmelCase ( self ) -> Tuple:
pass
@unittest.skip(reason='ConvNext does not support input and output embeddings' )
def __UpperCAmelCase ( self ) -> Optional[Any]:
pass
@unittest.skip(reason='ConvNext does not use feedforward chunking' )
def __UpperCAmelCase ( self ) -> Optional[Any]:
pass
def __UpperCAmelCase ( self ) -> List[Any]:
UpperCAmelCase_ , UpperCAmelCase_ : 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_ : List[str] = ['pixel_values']
self.assertListEqual(arg_names[:1] , _UpperCamelCase )
def __UpperCAmelCase ( self ) -> List[str]:
UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_UpperCamelCase )
def __UpperCAmelCase ( self ) -> List[Any]:
UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*_UpperCamelCase )
def __UpperCAmelCase ( self ) -> Optional[int]:
def check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
UpperCAmelCase_ : List[str] = model_class(_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
with torch.no_grad():
UpperCAmelCase_ : str = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) )
UpperCAmelCase_ : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
UpperCAmelCase_ : Dict = self.model_tester.num_stages
self.assertEqual(len(_UpperCamelCase ) , expected_num_stages + 1 )
# ConvNext'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] , )
UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : List[Any] = True
check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase_ : int = True
check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
def __UpperCAmelCase ( self ) -> Tuple:
UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase )
@slow
def __UpperCAmelCase ( self ) -> int:
for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase_ : Any = ConvNextModel.from_pretrained(_UpperCamelCase )
self.assertIsNotNone(_UpperCamelCase )
def lowercase__ ( ):
'''simple docstring'''
UpperCAmelCase_ : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowerCamelCase (unittest.TestCase ):
'''simple docstring'''
@cached_property
def __UpperCAmelCase ( self ) -> int:
return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None
@slow
def __UpperCAmelCase ( self ) -> List[str]:
UpperCAmelCase_ : Union[str, Any] = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(_UpperCamelCase )
UpperCAmelCase_ : Optional[Any] = self.default_image_processor
UpperCAmelCase_ : Union[str, Any] = prepare_img()
UpperCAmelCase_ : Tuple = image_processor(images=_UpperCamelCase , return_tensors='pt' ).to(_UpperCamelCase )
# forward pass
with torch.no_grad():
UpperCAmelCase_ : Any = model(**_UpperCamelCase )
# verify the logits
UpperCAmelCase_ : int = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , _UpperCamelCase )
UpperCAmelCase_ : int = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(_UpperCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _UpperCamelCase , atol=1E-4 ) )
@require_torch
class lowerCamelCase (unittest.TestCase , _snake_case ):
'''simple docstring'''
_snake_case : Optional[int] = (ConvNextBackbone,) if is_torch_available() else ()
_snake_case : Union[str, Any] = ConvNextConfig
_snake_case : Tuple = False
def __UpperCAmelCase ( self ) -> Dict:
UpperCAmelCase_ : Union[str, Any] = ConvNextModelTester(self )
| 406 | 0 |
from __future__ import annotations
import unittest
from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.distilbert.modeling_tf_distilbert import (
TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDistilBertForMaskedLM,
TFDistilBertForMultipleChoice,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertModel,
)
class __UpperCamelCase :
def __init__( self : Optional[Any] , lowerCAmelCase : str , ):
'''simple docstring'''
UpperCAmelCase_ = parent
UpperCAmelCase_ = 13
UpperCAmelCase_ = 7
UpperCAmelCase_ = True
UpperCAmelCase_ = True
UpperCAmelCase_ = False
UpperCAmelCase_ = True
UpperCAmelCase_ = 99
UpperCAmelCase_ = 32
UpperCAmelCase_ = 2
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
def __A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCAmelCase_ = None
if self.use_input_mask:
UpperCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase_ = None
UpperCAmelCase_ = None
UpperCAmelCase_ = None
if self.use_labels:
UpperCAmelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCAmelCase_ = ids_tensor([self.batch_size] , self.num_choices )
UpperCAmelCase_ = 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 , )
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def __A ( self : List[Any] , lowerCAmelCase : int , lowerCAmelCase : List[Any] , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[int] ):
'''simple docstring'''
UpperCAmelCase_ = TFDistilBertModel(config=lowerCAmelCase )
UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask}
UpperCAmelCase_ = model(lowerCAmelCase )
UpperCAmelCase_ = [input_ids, input_mask]
UpperCAmelCase_ = model(lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __A ( self : List[str] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : int , lowerCAmelCase : List[str] , lowerCAmelCase : Any , lowerCAmelCase : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase_ = TFDistilBertForMaskedLM(config=lowerCAmelCase )
UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask}
UpperCAmelCase_ = model(lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __A ( self : Union[str, Any] , lowerCAmelCase : Any , lowerCAmelCase : List[str] , lowerCAmelCase : int , lowerCAmelCase : str , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = TFDistilBertForQuestionAnswering(config=lowerCAmelCase )
UpperCAmelCase_ = {
"input_ids": input_ids,
"attention_mask": input_mask,
}
UpperCAmelCase_ = model(lowerCAmelCase )
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 : Dict , lowerCAmelCase : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.num_labels
UpperCAmelCase_ = TFDistilBertForSequenceClassification(lowerCAmelCase )
UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask}
UpperCAmelCase_ = model(lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __A ( self : Dict , lowerCAmelCase : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : Any , lowerCAmelCase : List[Any] , lowerCAmelCase : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = self.num_choices
UpperCAmelCase_ = TFDistilBertForMultipleChoice(lowerCAmelCase )
UpperCAmelCase_ = tf.tile(tf.expand_dims(lowerCAmelCase , 1 ) , (1, self.num_choices, 1) )
UpperCAmelCase_ = tf.tile(tf.expand_dims(lowerCAmelCase , 1 ) , (1, self.num_choices, 1) )
UpperCAmelCase_ = {
"input_ids": multiple_choice_inputs_ids,
"attention_mask": multiple_choice_input_mask,
}
UpperCAmelCase_ = model(lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def __A ( self : Any , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : List[str] , lowerCAmelCase : str ):
'''simple docstring'''
UpperCAmelCase_ = self.num_labels
UpperCAmelCase_ = TFDistilBertForTokenClassification(lowerCAmelCase )
UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask}
UpperCAmelCase_ = model(lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __A ( self : Any ):
'''simple docstring'''
UpperCAmelCase_ = self.prepare_config_and_inputs()
((UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_)) = config_and_inputs
UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class __UpperCamelCase ( lowercase , lowercase , unittest.TestCase ):
SCREAMING_SNAKE_CASE__ = (
(
TFDistilBertModel,
TFDistilBertForMaskedLM,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertForMultipleChoice,
)
if is_tf_available()
else None
)
SCREAMING_SNAKE_CASE__ = (
{
'feature-extraction': TFDistilBertModel,
'fill-mask': TFDistilBertForMaskedLM,
'question-answering': TFDistilBertForQuestionAnswering,
'text-classification': TFDistilBertForSequenceClassification,
'token-classification': TFDistilBertForTokenClassification,
'zero-shot': TFDistilBertForSequenceClassification,
}
if is_tf_available()
else {}
)
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
def __A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = TFDistilBertModelTester(self )
UpperCAmelCase_ = ConfigTester(self , config_class=lowerCAmelCase , dim=37 )
def __A ( self : List[Any] ):
'''simple docstring'''
self.config_tester.run_common_tests()
def __A ( self : str ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase )
def __A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase )
def __A ( self : Optional[int] ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase )
def __A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase )
def __A ( self : Any ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase )
def __A ( self : Any ):
'''simple docstring'''
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase )
@slow
def __A ( self : str ):
'''simple docstring'''
for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ):
UpperCAmelCase_ = TFDistilBertModel.from_pretrained(lowerCAmelCase )
self.assertIsNotNone(lowerCAmelCase )
@require_tf
class __UpperCamelCase ( unittest.TestCase ):
@slow
def __A ( self : str ):
'''simple docstring'''
UpperCAmelCase_ = TFDistilBertModel.from_pretrained("distilbert-base-uncased" )
UpperCAmelCase_ = tf.constant([[0, 1, 2, 3, 4, 5]] )
UpperCAmelCase_ = model(lowerCAmelCase )[0]
UpperCAmelCase_ = [1, 6, 768]
self.assertEqual(output.shape , lowerCAmelCase )
UpperCAmelCase_ = tf.constant(
[
[
[0.19_261_885, -0.13_732_955, 0.4_119_799],
[0.22_150_156, -0.07_422_661, 0.39_037_204],
[0.22_756_018, -0.0_896_414, 0.3_701_467],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , lowerCAmelCase , atol=1e-4 ) | 268 |
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_a: List[Any] = logging.get_logger(__name__)
_a: List[str] = """▁"""
_a: Union[str, Any] = {
"""vocab_file""": """vocab.json""",
"""spm_file""": """sentencepiece.bpe.model""",
}
_a: Tuple = {
"""vocab_file""": {
"""facebook/s2t-small-librispeech-asr""": (
"""https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
),
},
"""spm_file""": {
"""facebook/s2t-small-librispeech-asr""": (
"""https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
)
},
}
_a: Optional[int] = {
"""facebook/s2t-small-librispeech-asr""": 1024,
}
_a: List[Any] = ["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]
_a: Tuple = {"""mustc""": MUSTC_LANGS}
class __UpperCamelCase ( lowercase ):
SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE__ = MAX_MODEL_INPUT_SIZES
SCREAMING_SNAKE_CASE__ = ['input_ids', 'attention_mask']
SCREAMING_SNAKE_CASE__ = []
def __init__( self : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : Tuple="<s>" , lowerCAmelCase : Optional[int]="</s>" , lowerCAmelCase : Any="<pad>" , lowerCAmelCase : Union[str, Any]="<unk>" , lowerCAmelCase : Tuple=False , lowerCAmelCase : List[Any]=False , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : List[str]=None , lowerCAmelCase : Optional[Dict[str, Any]] = None , **lowerCAmelCase : Any , ):
'''simple docstring'''
UpperCAmelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , unk_token=lowerCAmelCase , pad_token=lowerCAmelCase , do_upper_case=lowerCAmelCase , do_lower_case=lowerCAmelCase , tgt_lang=lowerCAmelCase , lang_codes=lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase , )
UpperCAmelCase_ = do_upper_case
UpperCAmelCase_ = do_lower_case
UpperCAmelCase_ = load_json(lowerCAmelCase )
UpperCAmelCase_ = {v: k for k, v in self.encoder.items()}
UpperCAmelCase_ = spm_file
UpperCAmelCase_ = load_spm(lowerCAmelCase , self.sp_model_kwargs )
if lang_codes is not None:
UpperCAmelCase_ = lang_codes
UpperCAmelCase_ = LANGUAGES[lang_codes]
UpperCAmelCase_ = [F"<lang:{lang}>" for lang in self.langs]
UpperCAmelCase_ = {lang: self.sp_model.PieceToId(F"<lang:{lang}>" ) for lang in self.langs}
UpperCAmelCase_ = self.lang_tokens
UpperCAmelCase_ = tgt_lang if tgt_lang is not None else self.langs[0]
self.set_tgt_lang_special_tokens(self._tgt_lang )
else:
UpperCAmelCase_ = {}
@property
def __A ( self : List[Any] ):
'''simple docstring'''
return len(self.encoder )
@property
def __A ( self : Any ):
'''simple docstring'''
return self._tgt_lang
@tgt_lang.setter
def __A ( self : int , lowerCAmelCase : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase_ = new_tgt_lang
self.set_tgt_lang_special_tokens(lowerCAmelCase )
def __A ( self : List[Any] , lowerCAmelCase : str ):
'''simple docstring'''
UpperCAmelCase_ = self.lang_code_to_id[tgt_lang]
UpperCAmelCase_ = [lang_code_id]
def __A ( self : List[str] , lowerCAmelCase : str ):
'''simple docstring'''
return self.sp_model.encode(lowerCAmelCase , out_type=lowerCAmelCase )
def __A ( self : str , lowerCAmelCase : int ):
'''simple docstring'''
return self.encoder.get(lowerCAmelCase , self.encoder[self.unk_token] )
def __A ( self : Optional[Any] , lowerCAmelCase : int ):
'''simple docstring'''
return self.decoder.get(lowerCAmelCase , self.unk_token )
def __A ( self : Dict , lowerCAmelCase : List[str] ):
'''simple docstring'''
UpperCAmelCase_ = []
UpperCAmelCase_ = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
UpperCAmelCase_ = self.sp_model.decode(lowerCAmelCase )
out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
UpperCAmelCase_ = []
else:
current_sub_tokens.append(lowerCAmelCase )
UpperCAmelCase_ = self.sp_model.decode(lowerCAmelCase )
out_string += decoded.upper() if self.do_upper_case else decoded
return out_string.strip()
def __A ( self : Optional[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int]=None ):
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]
def __A ( self : Any , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : bool = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase , token_ids_a=lowerCAmelCase , already_has_special_tokens=lowerCAmelCase )
UpperCAmelCase_ = [1] * len(self.prefix_tokens )
UpperCAmelCase_ = [1]
if token_ids_a is None:
return prefix_ones + ([0] * len(lowerCAmelCase )) + suffix_ones
return prefix_ones + ([0] * len(lowerCAmelCase )) + ([0] * len(lowerCAmelCase )) + suffix_ones
def __A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.encoder.copy()
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.__dict__.copy()
UpperCAmelCase_ = None
return state
def __setstate__( self : Tuple , lowerCAmelCase : Dict ):
'''simple docstring'''
UpperCAmelCase_ = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
UpperCAmelCase_ = {}
UpperCAmelCase_ = load_spm(self.spm_file , self.sp_model_kwargs )
def __A ( self : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ):
'''simple docstring'''
UpperCAmelCase_ = Path(lowerCAmelCase )
assert save_dir.is_dir(), F"{save_directory} should be a directory"
UpperCAmelCase_ = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
)
UpperCAmelCase_ = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
)
save_json(self.encoder , lowerCAmelCase )
if os.path.abspath(self.spm_file ) != os.path.abspath(lowerCAmelCase ) and os.path.isfile(self.spm_file ):
copyfile(self.spm_file , lowerCAmelCase )
elif not os.path.isfile(self.spm_file ):
with open(lowerCAmelCase , "wb" ) as fi:
UpperCAmelCase_ = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase )
return (str(lowerCAmelCase ), str(lowerCAmelCase ))
def __lowerCAmelCase ( A , A ):
UpperCAmelCase_ = sentencepiece.SentencePieceProcessor(**A )
spm.Load(str(A ) )
return spm
def __lowerCAmelCase ( A ):
with open(A , "r" ) as f:
return json.load(A )
def __lowerCAmelCase ( A , A ):
with open(A , "w" ) as f:
json.dump(A , A , indent=2 ) | 268 | 1 |
import unittest
import numpy as np
from transformers import BertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
from transformers.models.bert.modeling_flax_bert import (
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForNextSentencePrediction,
FlaxBertForPreTraining,
FlaxBertForQuestionAnswering,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertModel,
)
class __lowercase (unittest.TestCase ):
"""simple docstring"""
def __init__( self , A , A=1_3 , A=7 , A=True , A=True , A=True , A=True , A=9_9 , A=3_2 , A=5 , A=4 , A=3_7 , A="gelu" , A=0.1 , A=0.1 , A=5_1_2 , A=1_6 , A=2 , A=0.02 , A=4 , ) -> Dict:
snake_case : Union[str, Any] = parent
snake_case : List[Any] = batch_size
snake_case : List[Any] = seq_length
snake_case : Optional[Any] = is_training
snake_case : Union[str, Any] = use_attention_mask
snake_case : Optional[Any] = use_token_type_ids
snake_case : List[Any] = use_labels
snake_case : str = vocab_size
snake_case : int = hidden_size
snake_case : Any = num_hidden_layers
snake_case : str = num_attention_heads
snake_case : Any = intermediate_size
snake_case : List[str] = hidden_act
snake_case : List[str] = hidden_dropout_prob
snake_case : Optional[Any] = attention_probs_dropout_prob
snake_case : List[str] = max_position_embeddings
snake_case : str = type_vocab_size
snake_case : str = type_sequence_label_size
snake_case : List[str] = initializer_range
snake_case : str = num_choices
def UpperCAmelCase ( self ) -> int:
snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case : Dict = None
if self.use_attention_mask:
snake_case : int = random_attention_mask([self.batch_size, self.seq_length] )
snake_case : Dict = None
if self.use_token_type_ids:
snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
snake_case : Dict = BertConfig(
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=A , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def UpperCAmelCase ( self ) -> Optional[int]:
snake_case : int = self.prepare_config_and_inputs()
snake_case , snake_case , snake_case , snake_case : int = config_and_inputs
snake_case : str = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
return config, inputs_dict
def UpperCAmelCase ( self ) -> int:
snake_case : Optional[Any] = self.prepare_config_and_inputs()
snake_case , snake_case , snake_case , snake_case : Tuple = config_and_inputs
snake_case : List[Any] = True
snake_case : List[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
attention_mask,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
class __lowercase (UpperCamelCase__ , unittest.TestCase ):
"""simple docstring"""
_snake_case = True
_snake_case = (
(
FlaxBertModel,
FlaxBertForPreTraining,
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForQuestionAnswering,
FlaxBertForNextSentencePrediction,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def UpperCAmelCase ( self ) -> str:
snake_case : Tuple = FlaxBertModelTester(self )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
# Only check this for base model, not necessary for all model classes.
# This will also help speed-up tests.
snake_case : Tuple = FlaxBertModel.from_pretrained("""bert-base-cased""" )
snake_case : Tuple = model(np.ones((1, 1) ) )
self.assertIsNotNone(A )
| 587 |
from math import factorial
def SCREAMING_SNAKE_CASE__ ( lowercase = 20 ) -> int:
snake_case : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
snake_case : Dict = n // 2
return int(factorial(lowercase ) / (factorial(lowercase ) * factorial(n - k )) )
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(2_0))
else:
try:
lowerCamelCase : List[Any] = int(sys.argv[1])
print(solution(n))
except ValueError:
print('Invalid entry - please enter a number.')
| 587 | 1 |
import argparse
import re
import requests
import torch
# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from transformers import (
BertTokenizer,
BlipConfig,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
)
def __lowercase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int ):
a__ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg'
a__ = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ).convert('RGB' )
a__ = transforms.Compose(
[
transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ),
transforms.ToTensor(),
transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ),
] )
a__ = transform(__lowerCAmelCase ).unsqueeze(0 ).to(__lowerCAmelCase )
return image
def __lowercase ( __lowerCAmelCase : Optional[int] ):
if "visual_encoder" in key:
a__ = re.sub('visual_encoder*' , 'vision_model.encoder' , __lowerCAmelCase )
if "blocks" in key:
a__ = re.sub(R'blocks' , 'layers' , __lowerCAmelCase )
if "attn" in key:
a__ = re.sub(R'attn' , 'self_attn' , __lowerCAmelCase )
if "norm1" in key:
a__ = re.sub(R'norm1' , 'layer_norm1' , __lowerCAmelCase )
if "norm2" in key:
a__ = re.sub(R'norm2' , 'layer_norm2' , __lowerCAmelCase )
if "encoder.norm" in key:
a__ = re.sub(R'encoder.norm' , 'post_layernorm' , __lowerCAmelCase )
if "encoder.patch_embed.proj" in key:
a__ = re.sub(R'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , __lowerCAmelCase )
if "encoder.pos_embed" in key:
a__ = re.sub(R'encoder.pos_embed' , 'embeddings.position_embedding' , __lowerCAmelCase )
if "encoder.cls_token" in key:
a__ = re.sub(R'encoder.cls_token' , 'embeddings.class_embedding' , __lowerCAmelCase )
if "self_attn" in key:
a__ = re.sub(R'self_attn.proj' , 'self_attn.projection' , __lowerCAmelCase )
return key
@torch.no_grad()
def __lowercase ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str]=None ):
if config_path is not None:
a__ = BlipConfig.from_pretrained(__lowerCAmelCase )
else:
a__ = BlipConfig(projection_dim=5_1_2 , text_config={} , vision_config={} )
a__ = BlipForConditionalGeneration(__lowerCAmelCase ).eval()
a__ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth'
a__ = blip_decoder(pretrained=__lowerCAmelCase , image_size=3_8_4 , vit='base' )
a__ = pt_model.eval()
a__ = pt_model.state_dict()
for key in modified_state_dict.copy():
a__ = modified_state_dict.pop(__lowerCAmelCase )
a__ = rename_key(__lowerCAmelCase )
a__ = value
hf_model.load_state_dict(__lowerCAmelCase )
a__ = 3_8_4
a__ = load_demo_image(image_size=__lowerCAmelCase , device='cpu' )
a__ = BertTokenizer.from_pretrained('bert-base-uncased' )
a__ = tokenizer(['a picture of'] ).input_ids
a__ = hf_model.generate(__lowerCAmelCase , __lowerCAmelCase )
assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 3_8_6_1, 1_9_9_7, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2]
a__ = hf_model.generate(__lowerCAmelCase )
assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2]
if pytorch_dump_folder_path is not None:
hf_model.save_pretrained(__lowerCAmelCase )
# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
a__ = (
'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'
)
a__ = blip_vqa(pretrained=__lowerCAmelCase , image_size=__lowerCAmelCase , vit='base' )
vqa_model.eval()
a__ = vqa_model.state_dict()
for key in modified_state_dict.copy():
a__ = modified_state_dict.pop(__lowerCAmelCase )
a__ = rename_key(__lowerCAmelCase )
a__ = value
a__ = BlipForQuestionAnswering(__lowerCAmelCase )
hf_vqa_model.load_state_dict(__lowerCAmelCase )
a__ = ['How many dogs are in this image?']
a__ = tokenizer(__lowerCAmelCase , return_tensors='pt' ).input_ids
a__ = hf_vqa_model.generate(__lowerCAmelCase , __lowerCAmelCase )
print(tokenizer.decode(answer[0] ) )
assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]"
if pytorch_dump_folder_path is not None:
hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa' )
a__ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
a__ = blip_itm(pretrained=__lowerCAmelCase , image_size=__lowerCAmelCase , vit='base' )
itm_model.eval()
a__ = itm_model.state_dict()
for key in modified_state_dict.copy():
a__ = modified_state_dict.pop(__lowerCAmelCase )
a__ = rename_key(__lowerCAmelCase )
a__ = value
a__ = BlipForImageTextRetrieval(__lowerCAmelCase )
a__ = ['A picture of a woman with a dog sitting in a beach']
a__ = tokenizer(
__lowerCAmelCase , return_tensors='pt' , padding='max_length' , truncation=__lowerCAmelCase , max_length=3_5 , ).input_ids
hf_itm_model.load_state_dict(__lowerCAmelCase )
hf_itm_model.eval()
a__ = hf_itm_model(__lowerCAmelCase , __lowerCAmelCase , use_itm_head=__lowerCAmelCase )
a__ = hf_itm_model(__lowerCAmelCase , __lowerCAmelCase , use_itm_head=__lowerCAmelCase )
assert out[0].item() == 0.2_110_687_494_277_954
assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127
if pytorch_dump_folder_path is not None:
hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm' )
if __name__ == "__main__":
snake_case : Optional[int] = argparse.ArgumentParser()
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
snake_case : int = parser.parse_args()
convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
| 657 |
from decimal import Decimal, getcontext
from math import ceil, factorial
def __lowercase ( __lowerCAmelCase : int ):
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise TypeError('Undefined for non-integers' )
elif precision < 1:
raise ValueError('Undefined for non-natural numbers' )
a__ = precision
a__ = ceil(precision / 1_4 )
a__ = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt()
a__ = 1
a__ = 1_3_5_9_1_4_0_9
a__ = Decimal(__lowerCAmelCase )
for k in range(1 , __lowerCAmelCase ):
a__ = factorial(6 * k ) // (factorial(3 * k ) * factorial(__lowerCAmelCase ) ** 3)
linear_term += 5_4_5_1_4_0_1_3_4
exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0
partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term
return str(constant_term / partial_sum )[:-1]
if __name__ == "__main__":
snake_case : Tuple = 50
print(f"""The first {n} digits of pi is: {pi(n)}""")
| 657 | 1 |
'''simple docstring'''
import os
def _lowercase ( lowerCamelCase__ : str = "matrix.txt" ):
with open(os.path.join(os.path.dirname(lowerCamelCase__ ), lowerCamelCase__ ) ) as in_file:
_a = in_file.read()
_a = [[int(lowerCamelCase__ ) for cell in row.split("," )] for row in data.strip().splitlines()]
_a = [[0 for cell in row] for row in grid]
_a = len(grid[0] )
_a = [[0 for i in range(lowerCamelCase__ )] for j in range(lowerCamelCase__ )]
_a = grid[0][0]
for i in range(1, lowerCamelCase__ ):
_a = grid[0][i] + dp[0][i - 1]
for i in range(1, lowerCamelCase__ ):
_a = grid[i][0] + dp[i - 1][0]
for i in range(1, lowerCamelCase__ ):
for j in range(1, lowerCamelCase__ ):
_a = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1] )
return dp[-1][-1]
if __name__ == "__main__":
print(f'''{solution() = }''')
| 131 |
'''simple docstring'''
from io import BytesIO
from typing import List, Union
import requests
from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_decord_available():
import numpy as np
from decord import VideoReader
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
__snake_case : Dict = logging.get_logger(__name__)
@add_end_docstrings(a )
class A ( a ):
def __init__( self , *snake_case_ , **snake_case_ ) -> int:
super().__init__(*snake_case_ , **snake_case_ )
requires_backends(self , "decord" )
self.check_model_type(snake_case_ )
def __lowerCAmelCase ( self , snake_case_=None , snake_case_=None , snake_case_=None ) -> Optional[Any]:
_a = {}
if frame_sampling_rate is not None:
_a = frame_sampling_rate
if num_frames is not None:
_a = num_frames
_a = {}
if top_k is not None:
_a = top_k
return preprocess_params, {}, postprocess_params
def __call__( self , snake_case_ , **snake_case_ ) -> int:
return super().__call__(snake_case_ , **snake_case_ )
def __lowerCAmelCase ( self , snake_case_ , snake_case_=None , snake_case_=1 ) -> List[str]:
if num_frames is None:
_a = self.model.config.num_frames
if video.startswith("http://" ) or video.startswith("https://" ):
_a = BytesIO(requests.get(snake_case_ ).content )
_a = VideoReader(snake_case_ )
videoreader.seek(0 )
_a = 0
_a = num_frames * frame_sampling_rate - 1
_a = np.linspace(snake_case_ , snake_case_ , num=snake_case_ , dtype=np.intaa )
_a = videoreader.get_batch(snake_case_ ).asnumpy()
_a = list(snake_case_ )
_a = self.image_processor(snake_case_ , return_tensors=self.framework )
return model_inputs
def __lowerCAmelCase ( self , snake_case_ ) -> Dict:
_a = self.model(**snake_case_ )
return model_outputs
def __lowerCAmelCase ( self , snake_case_ , snake_case_=5 ) -> Optional[Any]:
if top_k > self.model.config.num_labels:
_a = self.model.config.num_labels
if self.framework == "pt":
_a = model_outputs.logits.softmax(-1 )[0]
_a , _a = probs.topk(snake_case_ )
else:
raise ValueError(F'''Unsupported framework: {self.framework}''' )
_a = scores.tolist()
_a = ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case_ , snake_case_ )]
| 131 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
_lowercase : int =logging.get_logger(__name__)
_lowercase : List[str] ={
"""microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""",
}
class lowerCAmelCase_ ( A_ ,A_ ):
'''simple docstring'''
A_ : Optional[Any] = 'resnet'
A_ : Any = ['basic', 'bottleneck']
def __init__( self , lowerCamelCase=3 , lowerCamelCase=64 , lowerCamelCase=[256, 512, 1024, 2048] , lowerCamelCase=[3, 4, 6, 3] , lowerCamelCase="bottleneck" , lowerCamelCase="relu" , lowerCamelCase=False , lowerCamelCase=None , lowerCamelCase=None , **lowerCamelCase , ):
'''simple docstring'''
super().__init__(**lowerCamelCase )
if layer_type not in self.layer_types:
raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types )}' )
a__ = num_channels
a__ = embedding_size
a__ = hidden_sizes
a__ = depths
a__ = layer_type
a__ = hidden_act
a__ = downsample_in_first_stage
a__ = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(lowerCamelCase ) + 1 )]
a__ , a__ = get_aligned_output_features_output_indices(
out_features=lowerCamelCase , out_indices=lowerCamelCase , stage_names=self.stage_names )
class lowerCAmelCase_ ( A_ ):
'''simple docstring'''
A_ : int = version.parse('1.11' )
@property
def _A ( self ):
'''simple docstring'''
return OrderedDict(
[
("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
] )
@property
def _A ( self ):
'''simple docstring'''
return 1e-3
| 701 |
import math
def UpperCAmelCase ( lowercase__ : list , lowercase__ : int ):
'''simple docstring'''
a__ = len(lowercase__ )
a__ = int(math.floor(math.sqrt(lowercase__ ) ) )
a__ = 0
while arr[min(lowercase__ , lowercase__ ) - 1] < x:
a__ = step
step += int(math.floor(math.sqrt(lowercase__ ) ) )
if prev >= n:
return -1
while arr[prev] < x:
a__ = prev + 1
if prev == min(lowercase__ , lowercase__ ):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
_lowercase : Any =input("""Enter numbers separated by a comma:\n""").strip()
_lowercase : Any =[int(item) for item in user_input.split(""",""")]
_lowercase : Any =int(input("""Enter the number to be searched:\n"""))
_lowercase : Optional[int] =jump_search(arr, x)
if res == -1:
print("""Number not found!""")
else:
print(f'''Number {x} is at index {res}''')
| 412 | 0 |
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel
from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class _a ( unittest.TestCase ):
"""simple docstring"""
@property
def __A ( self : List[Any] ):
torch.manual_seed(0 )
A_ = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , )
return model
@property
def __A ( self : int ):
torch.manual_seed(0 )
A_ = VQModel(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=3 , )
return model
@property
def __A ( self : Optional[Any] ):
torch.manual_seed(0 )
A_ = 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=1000 , )
return CLIPTextModel(UpperCAmelCase )
def __A ( self : Optional[int] ):
A_ = self.dummy_uncond_unet
A_ = DDIMScheduler()
A_ = self.dummy_vq_model
A_ = LDMPipeline(unet=UpperCAmelCase , vqvae=UpperCAmelCase , scheduler=UpperCAmelCase )
ldm.to(UpperCAmelCase )
ldm.set_progress_bar_config(disable=UpperCAmelCase )
A_ = torch.manual_seed(0 )
A_ = ldm(generator=UpperCAmelCase , num_inference_steps=2 , output_type="numpy" ).images
A_ = torch.manual_seed(0 )
A_ = ldm(generator=UpperCAmelCase , num_inference_steps=2 , output_type="numpy" , return_dict=UpperCAmelCase )[0]
A_ = image[0, -3:, -3:, -1]
A_ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172] )
A_ = 1E-2 if torch_device != "mps" else 3E-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance
@slow
@require_torch
class _a ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ):
A_ = LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256" )
ldm.to(UpperCAmelCase )
ldm.set_progress_bar_config(disable=UpperCAmelCase )
A_ = torch.manual_seed(0 )
A_ = ldm(generator=UpperCAmelCase , num_inference_steps=5 , output_type="numpy" ).images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
A_ = np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447] )
A_ = 1E-2 if torch_device != "mps" else 3E-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance | 86 |
'''simple docstring'''
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class a__:
def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=16 , _UpperCAmelCase=36 , _UpperCAmelCase=6 , _UpperCAmelCase=6 , _UpperCAmelCase=6 , _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 , ) -> Dict:
snake_case__ =parent
snake_case__ =batch_size
snake_case__ =seq_length
snake_case__ =is_training
snake_case__ =use_input_mask
snake_case__ =use_token_type_ids
snake_case__ =use_labels
snake_case__ =vocab_size
snake_case__ =embedding_size
snake_case__ =hidden_size
snake_case__ =num_hidden_layers
snake_case__ =num_hidden_groups
snake_case__ =num_attention_heads
snake_case__ =intermediate_size
snake_case__ =hidden_act
snake_case__ =hidden_dropout_prob
snake_case__ =attention_probs_dropout_prob
snake_case__ =max_position_embeddings
snake_case__ =type_vocab_size
snake_case__ =type_sequence_label_size
snake_case__ =initializer_range
snake_case__ =num_labels
snake_case__ =num_choices
snake_case__ =scope
def _lowercase ( self ) -> Tuple:
snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case__ =None
if self.use_input_mask:
snake_case__ =random_attention_mask([self.batch_size, self.seq_length] )
snake_case__ =None
if self.use_token_type_ids:
snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
snake_case__ =None
snake_case__ =None
snake_case__ =None
if self.use_labels:
snake_case__ =ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case__ =ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
snake_case__ =ids_tensor([self.batch_size] , self.num_choices )
snake_case__ =self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowercase ( self ) -> Union[str, Any]:
return AlbertConfig(
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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]:
snake_case__ =AlbertModel(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase )
snake_case__ =model(_UpperCAmelCase , token_type_ids=_UpperCAmelCase )
snake_case__ =model(_UpperCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict:
snake_case__ =AlbertForPreTraining(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =model(
_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , sentence_order_label=_UpperCAmelCase , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) )
def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]:
snake_case__ =AlbertForMaskedLM(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =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 _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]:
snake_case__ =AlbertForQuestionAnswering(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =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 _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]:
snake_case__ =self.num_labels
snake_case__ =AlbertForSequenceClassification(_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Any:
snake_case__ =self.num_labels
snake_case__ =AlbertForTokenClassification(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =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 _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict:
snake_case__ =self.num_choices
snake_case__ =AlbertForMultipleChoice(config=_UpperCAmelCase )
model.to(_UpperCAmelCase )
model.eval()
snake_case__ =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ =model(
_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self ) -> List[Any]:
snake_case__ =self.prepare_config_and_inputs()
(
(
snake_case__
) , (
snake_case__
) , (
snake_case__
) , (
snake_case__
) , (
snake_case__
) , (
snake_case__
) , (
snake_case__
) ,
) =config_and_inputs
snake_case__ ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class a__( snake_case__ , snake_case__ , unittest.TestCase ):
a_ : Optional[int] = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
a_ : List[str] = (
{
'''feature-extraction''': AlbertModel,
'''fill-mask''': AlbertForMaskedLM,
'''question-answering''': AlbertForQuestionAnswering,
'''text-classification''': AlbertForSequenceClassification,
'''token-classification''': AlbertForTokenClassification,
'''zero-shot''': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
a_ : int = True
def _lowercase ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ) -> Any:
snake_case__ =super()._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase , return_labels=_UpperCAmelCase )
if return_labels:
if model_class in get_values(_UpperCAmelCase ):
snake_case__ =torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_UpperCAmelCase )
snake_case__ =torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=_UpperCAmelCase )
return inputs_dict
def _lowercase ( self ) -> int:
snake_case__ =AlbertModelTester(self )
snake_case__ =ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37 )
def _lowercase ( self ) -> Dict:
self.config_tester.run_common_tests()
def _lowercase ( self ) -> str:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_UpperCAmelCase )
def _lowercase ( self ) -> Optional[int]:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*_UpperCAmelCase )
def _lowercase ( self ) -> Optional[Any]:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase )
def _lowercase ( self ) -> Tuple:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase )
def _lowercase ( self ) -> List[str]:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase )
def _lowercase ( self ) -> Optional[int]:
snake_case__ =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase )
def _lowercase ( self ) -> List[str]:
snake_case__ =self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
snake_case__ =type
self.model_tester.create_and_check_model(*_UpperCAmelCase )
@slow
def _lowercase ( self ) -> Union[str, Any]:
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case__ =AlbertModel.from_pretrained(_UpperCAmelCase )
self.assertIsNotNone(_UpperCAmelCase )
@require_torch
class a__( unittest.TestCase ):
@slow
def _lowercase ( self ) -> str:
snake_case__ =AlbertModel.from_pretrained('albert-base-v2' )
snake_case__ =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
snake_case__ =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
snake_case__ =model(_UpperCAmelCase , attention_mask=_UpperCAmelCase )[0]
snake_case__ =torch.Size((1, 11, 768) )
self.assertEqual(output.shape , _UpperCAmelCase )
snake_case__ =torch.tensor(
[[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _UpperCAmelCase , atol=1E-4 ) )
| 538 | 0 |
from collections.abc import Sequence
def UpperCAmelCase ( _snake_case , _snake_case = False ):
if not arr:
return 0
lowerCAmelCase = 0 if allow_empty_subarrays else float('''-inf''' )
lowerCAmelCase = 0.0
for num in arr:
lowerCAmelCase = max(0 if allow_empty_subarrays else num , curr_sum + num )
lowerCAmelCase = max(_snake_case , _snake_case )
return max_sum
if __name__ == "__main__":
from doctest import testmod
testmod()
UpperCAmelCase_ =[-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(F'''{max_subarray_sum(nums) = }''')
| 33 |
import torch
from diffusers import StableDiffusionPipeline
UpperCAmelCase_ ="""path-to-your-trained-model"""
UpperCAmelCase_ =StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("""cuda""")
UpperCAmelCase_ ="""A photo of sks dog in a bucket"""
UpperCAmelCase_ =pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
image.save("""dog-bucket.png""")
| 33 | 1 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class __A :
'''simple docstring'''
def __init__(self , A=None , A=None ) -> Any:
"""simple docstring"""
_a = list(poly_a or [0] )[:]
_a = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
_a = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
_a = len(self.polyB )
# Add 0 to make lengths equal a power of 2
_a = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
_a = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
_a = self.__multiply()
def a__ (self , A ) -> Tuple:
"""simple docstring"""
_a = [[x] for x in self.polyA] if which == '''A''' else [[x] for x in self.polyB]
# Corner case
if len(A ) <= 1:
return dft[0]
#
_a = self.c_max_length // 2
while next_ncol > 0:
_a = [[] for i in range(A )]
_a = self.root**next_ncol
# First half of next step
_a = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(A ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
_a = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(A ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
_a = new_dft
_a = next_ncol // 2
return dft[0]
def a__ (self ) -> Union[str, Any]:
"""simple docstring"""
_a = self.__dft('''A''' )
_a = self.__dft('''B''' )
_a = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
_a = 2
while next_ncol <= self.c_max_length:
_a = [[] for i in range(A )]
_a = self.root ** (next_ncol // 2)
_a = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
_a = new_inverse_c
next_ncol *= 2
# Unpack
_a = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1J for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__(self ) -> Union[str, Any]:
"""simple docstring"""
_a = '''A = ''' + ''' + '''.join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
_a = '''B = ''' + ''' + '''.join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
_a = '''A*B = ''' + ''' + '''.join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 11 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__UpperCamelCase : int = {
'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Any = [
'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST',
'PegasusXForConditionalGeneration',
'PegasusXModel',
'PegasusXPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pegasus_x import (
PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST,
PegasusXForConditionalGeneration,
PegasusXModel,
PegasusXPreTrainedModel,
)
else:
import sys
__UpperCamelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 519 | 0 |
import math
from datetime import datetime, timedelta
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ):
lowercase__ = year % 19
lowercase__ = year % 4
lowercase__ = year % 7
lowercase__ = math.floor(year / 100 )
lowercase__ = math.floor((13 + 8 * leap_day_inhibits) / 25 )
lowercase__ = leap_day_inhibits / 4
lowercase__ = (
15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number
) % 30
lowercase__ = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7
# days to be added to March 21
lowercase__ = (19 * metonic_cycle + secular_moon_shift) % 30
# PHM -> Paschal Full Moon
lowercase__ = (
2 * julian_leap_year
+ 4 * non_leap_year
+ 6 * days_to_add
+ century_starting_point
) % 7
if days_to_add == 29 and days_from_phm_to_sunday == 6:
return datetime(SCREAMING_SNAKE_CASE_ , 4 , 19 )
elif days_to_add == 28 and days_from_phm_to_sunday == 6:
return datetime(SCREAMING_SNAKE_CASE_ , 4 , 18 )
else:
return datetime(SCREAMING_SNAKE_CASE_ , 3 , 22 ) + timedelta(
days=int(days_to_add + days_from_phm_to_sunday ) )
if __name__ == "__main__":
for year in (1994, 2000, 2010, 2021, 2023):
lowercase_ = """will be""" if year > datetime.now().year else """was"""
print(F'Easter in {year} {tense} {gauss_easter(year)}')
| 37 |
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ):
if upper_limit < 0:
raise ValueError("Limit for the Catalan sequence must be ≥ 0" )
lowercase__ = [0] * (upper_limit + 1)
# Base case: C(0) = C(1) = 1
lowercase__ = 1
if upper_limit > 0:
lowercase__ = 1
# Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
for i in range(2 , upper_limit + 1 ):
for j in range(SCREAMING_SNAKE_CASE_ ):
catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]
return catalan_list
if __name__ == "__main__":
print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""")
print("""\n*** Enter -1 at any time to quit ***""")
print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""")
try:
while True:
lowercase_ = int(input().strip())
if N < 0:
print("""\n********* Goodbye!! ************""")
break
else:
print(F'The Catalan numbers from 0 through {N} are:')
print(catalan_numbers(N))
print("""Try another upper limit for the sequence: """, end="""""")
except (NameError, ValueError):
print("""\n********* Invalid input, goodbye! ************\n""")
import doctest
doctest.testmod()
| 37 | 1 |
from __future__ import annotations
from collections.abc import MutableSequence
class __UpperCamelCase :
"""simple docstring"""
def __init__( self : int , _A : int , _A : MutableSequence[float] ):
"""simple docstring"""
if len(_A ) != degree + 1:
raise ValueError(
'''The number of coefficients should be equal to the degree + 1.''' )
__SCREAMING_SNAKE_CASE : list[float] = list(_A )
__SCREAMING_SNAKE_CASE : Any = degree
def __add__( self : Union[str, Any] , _A : Polynomial ):
"""simple docstring"""
if self.degree > polynomial_a.degree:
__SCREAMING_SNAKE_CASE : Any = self.coefficients[:]
for i in range(polynomial_a.degree + 1 ):
coefficients[i] += polynomial_a.coefficients[i]
return Polynomial(self.degree , _A )
else:
__SCREAMING_SNAKE_CASE : List[str] = polynomial_a.coefficients[:]
for i in range(self.degree + 1 ):
coefficients[i] += self.coefficients[i]
return Polynomial(polynomial_a.degree , _A )
def __sub__( self : Any , _A : Polynomial ):
"""simple docstring"""
return self + polynomial_a * Polynomial(0 , [-1] )
def __neg__( self : int ):
"""simple docstring"""
return Polynomial(self.degree , [-c for c in self.coefficients] )
def __mul__( self : Tuple , _A : Polynomial ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : list[float] = [0] * (self.degree + polynomial_a.degree + 1)
for i in range(self.degree + 1 ):
for j in range(polynomial_a.degree + 1 ):
coefficients[i + j] += (
self.coefficients[i] * polynomial_a.coefficients[j]
)
return Polynomial(self.degree + polynomial_a.degree , _A )
def UpperCAmelCase__ ( self : int , _A : int | float ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : int | float = 0
for i in range(self.degree + 1 ):
result += self.coefficients[i] * (substitution**i)
return result
def __str__( self : Tuple ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : str = ''''''
for i in range(self.degree , -1 , -1 ):
if self.coefficients[i] == 0:
continue
elif self.coefficients[i] > 0:
if polynomial:
polynomial += " + "
else:
polynomial += " - "
if i == 0:
polynomial += str(abs(self.coefficients[i] ) )
elif i == 1:
polynomial += str(abs(self.coefficients[i] ) ) + "x"
else:
polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(_A )
return polynomial
def __repr__( self : Any ):
"""simple docstring"""
return self.__str__()
def UpperCAmelCase__ ( self : Optional[Any] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : list[float] = [0] * self.degree
for i in range(self.degree ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1 , _A )
def UpperCAmelCase__ ( self : Union[str, Any] , _A : int | float = 0 ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : list[float] = [0] * (self.degree + 2)
__SCREAMING_SNAKE_CASE : List[Any] = constant
for i in range(self.degree + 1 ):
__SCREAMING_SNAKE_CASE : Dict = self.coefficients[i] / (i + 1)
return Polynomial(self.degree + 1 , _A )
def __eq__( self : Tuple , _A : object ):
"""simple docstring"""
if not isinstance(_A , _A ):
return False
if self.degree != polynomial_a.degree:
return False
for i in range(self.degree + 1 ):
if self.coefficients[i] != polynomial_a.coefficients[i]:
return False
return True
def __ne__( self : Optional[Any] , _A : object ):
"""simple docstring"""
return not self.__eq__(_A )
| 74 |
"""simple docstring"""
from __future__ import annotations
import math
def __A (_SCREAMING_SNAKE_CASE ) ->bool:
"""simple docstring"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
__A = [num for num in range(3, 10_0001, 2) if not is_prime(num)]
def __A (_SCREAMING_SNAKE_CASE ) ->list[int]:
"""simple docstring"""
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise ValueError('n must be an integer' )
if n <= 0:
raise ValueError('n must be >= 0' )
lowerCAmelCase__ :Tuple = []
for num in range(len(_SCREAMING_SNAKE_CASE ) ):
lowerCAmelCase__ :int = 0
while 2 * i * i <= odd_composites[num]:
lowerCAmelCase__ :int = odd_composites[num] - 2 * i * i
if is_prime(_SCREAMING_SNAKE_CASE ):
break
i += 1
else:
list_nums.append(odd_composites[num] )
if len(_SCREAMING_SNAKE_CASE ) == n:
return list_nums
return []
def __A () ->int:
"""simple docstring"""
return compute_nums(1 )[0]
if __name__ == "__main__":
print(F'''{solution() = }''')
| 93 | 0 |
from __future__ import annotations
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> float:
_UpperCAmelCase = 0.00
_UpperCAmelCase = 0
for resistor in resistors:
if resistor <= 0:
_UpperCAmelCase = f"""Resistor at index {index} has a negative or zero value!"""
raise ValueError(__snake_case )
first_sum += 1 / float(__snake_case )
index += 1
return 1 / first_sum
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> float:
_UpperCAmelCase = 0.00
_UpperCAmelCase = 0
for resistor in resistors:
sum_r += resistor
if resistor < 0:
_UpperCAmelCase = f"""Resistor at index {index} has a negative value!"""
raise ValueError(__snake_case )
index += 1
return sum_r
if __name__ == "__main__":
import doctest
doctest.testmod() | 718 |
import logging
import os
import threading
import time
try:
import warnings
except ImportError:
__a: Dict = None
try:
import msvcrt
except ImportError:
__a: List[str] = None
try:
import fcntl
except ImportError:
__a: List[str] = None
# Backward compatibility
# ------------------------------------------------
try:
TimeoutError
except NameError:
__a: Union[str, Any] = OSError
# Data
# ------------------------------------------------
__a: Optional[Any] = [
'''Timeout''',
'''BaseFileLock''',
'''WindowsFileLock''',
'''UnixFileLock''',
'''SoftFileLock''',
'''FileLock''',
]
__a: Tuple = '''3.0.12'''
__a: Union[str, Any] = None
def _SCREAMING_SNAKE_CASE ( ) -> Dict:
global _logger
_UpperCAmelCase = _logger or logging.getLogger(__name__ )
return _logger
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
def __init__( self : Any , lowerCamelCase : Union[str, Any] ) -> Dict:
"""simple docstring"""
_UpperCAmelCase = lock_file
return None
def __str__( self : List[Any] ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = f"""The file lock '{self.lock_file}' could not be acquired."""
return temp
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self : str , lowerCamelCase : List[Any] ) -> Dict:
"""simple docstring"""
_UpperCAmelCase = lock
return None
def __enter__( self : Dict ) -> List[str]:
"""simple docstring"""
return self.lock
def __exit__( self : Optional[Any] , lowerCamelCase : str , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[int] ) -> Optional[int]:
"""simple docstring"""
self.lock.release()
return None
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self : Dict , lowerCamelCase : int , lowerCamelCase : Optional[int]=-1 , lowerCamelCase : Union[str, Any]=None ) -> Optional[Any]:
"""simple docstring"""
_UpperCAmelCase = max_filename_length if max_filename_length is not None else 255
# Hash the filename if it's too long
_UpperCAmelCase = self.hash_filename_if_too_long(lowerCamelCase , lowerCamelCase )
# The path to the lock file.
_UpperCAmelCase = lock_file
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
_UpperCAmelCase = None
# The default timeout value.
_UpperCAmelCase = timeout
# We use this lock primarily for the lock counter.
_UpperCAmelCase = threading.Lock()
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
_UpperCAmelCase = 0
return None
@property
def lowerCamelCase ( self : Tuple ) -> Any:
"""simple docstring"""
return self._lock_file
@property
def lowerCamelCase ( self : Any ) -> Optional[Any]:
"""simple docstring"""
return self._timeout
@timeout.setter
def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Optional[int] ) -> str:
"""simple docstring"""
_UpperCAmelCase = float(lowerCamelCase )
return None
def lowerCamelCase ( self : Any ) -> List[Any]:
"""simple docstring"""
raise NotImplementedError()
def lowerCamelCase ( self : int ) -> Optional[Any]:
"""simple docstring"""
raise NotImplementedError()
@property
def lowerCamelCase ( self : Optional[Any] ) -> List[Any]:
"""simple docstring"""
return self._lock_file_fd is not None
def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : Union[str, Any]=None , lowerCamelCase : int=0.05 ) -> Optional[Any]:
"""simple docstring"""
# Use the default timeout, if no timeout is provided.
if timeout is None:
_UpperCAmelCase = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
with self._thread_lock:
self._lock_counter += 1
_UpperCAmelCase = id(self )
_UpperCAmelCase = self._lock_file
_UpperCAmelCase = time.time()
try:
while True:
with self._thread_lock:
if not self.is_locked:
logger().debug(f"""Attempting to acquire lock {lock_id} on {lock_filename}""" )
self._acquire()
if self.is_locked:
logger().debug(f"""Lock {lock_id} acquired on {lock_filename}""" )
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger().debug(f"""Timeout on acquiring lock {lock_id} on {lock_filename}""" )
raise Timeout(self._lock_file )
else:
logger().debug(
f"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" )
time.sleep(lowerCamelCase )
except: # noqa
# Something did go wrong, so decrement the counter.
with self._thread_lock:
_UpperCAmelCase = max(0 , self._lock_counter - 1 )
raise
return _Acquire_ReturnProxy(lock=self )
def lowerCamelCase ( self : Any , lowerCamelCase : Any=False ) -> List[str]:
"""simple docstring"""
with self._thread_lock:
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
_UpperCAmelCase = id(self )
_UpperCAmelCase = self._lock_file
logger().debug(f"""Attempting to release lock {lock_id} on {lock_filename}""" )
self._release()
_UpperCAmelCase = 0
logger().debug(f"""Lock {lock_id} released on {lock_filename}""" )
return None
def __enter__( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
self.acquire()
return self
def __exit__( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : Dict , lowerCamelCase : str ) -> Any:
"""simple docstring"""
self.release()
return None
def __del__( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
self.release(force=lowerCamelCase )
return None
def lowerCamelCase ( self : int , lowerCamelCase : str , lowerCamelCase : int ) -> str:
"""simple docstring"""
_UpperCAmelCase = os.path.basename(lowerCamelCase )
if len(lowerCamelCase ) > max_length and max_length > 0:
_UpperCAmelCase = os.path.dirname(lowerCamelCase )
_UpperCAmelCase = str(hash(lowerCamelCase ) )
_UpperCAmelCase = filename[: max_length - len(lowerCamelCase ) - 8] + """...""" + hashed_filename + """.lock"""
return os.path.join(lowerCamelCase , lowerCamelCase )
else:
return path
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
def __init__( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Any=-1 , lowerCamelCase : Optional[int]=None ) -> str:
"""simple docstring"""
from .file_utils import relative_to_absolute_path
super().__init__(lowerCamelCase , timeout=lowerCamelCase , max_filename_length=lowerCamelCase )
_UpperCAmelCase = """\\\\?\\""" + relative_to_absolute_path(self.lock_file )
def lowerCamelCase ( self : Dict ) -> Optional[int]:
"""simple docstring"""
_UpperCAmelCase = os.O_RDWR | os.O_CREAT | os.O_TRUNC
try:
_UpperCAmelCase = os.open(self._lock_file , lowerCamelCase )
except OSError:
pass
else:
try:
msvcrt.locking(lowerCamelCase , msvcrt.LK_NBLCK , 1 )
except OSError:
os.close(lowerCamelCase )
else:
_UpperCAmelCase = fd
return None
def lowerCamelCase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = self._lock_file_fd
_UpperCAmelCase = None
msvcrt.locking(lowerCamelCase , msvcrt.LK_UNLCK , 1 )
os.close(lowerCamelCase )
try:
os.remove(self._lock_file )
# Probably another instance of the application
# that acquired the file lock.
except OSError:
pass
return None
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
def __init__( self : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : List[str]=-1 , lowerCamelCase : int=None ) -> List[Any]:
"""simple docstring"""
_UpperCAmelCase = os.statvfs(os.path.dirname(lowerCamelCase ) ).f_namemax
super().__init__(lowerCamelCase , timeout=lowerCamelCase , max_filename_length=lowerCamelCase )
def lowerCamelCase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase = os.O_RDWR | os.O_CREAT | os.O_TRUNC
_UpperCAmelCase = os.open(self._lock_file , lowerCamelCase )
try:
fcntl.flock(lowerCamelCase , fcntl.LOCK_EX | fcntl.LOCK_NB )
except OSError:
os.close(lowerCamelCase )
else:
_UpperCAmelCase = fd
return None
def lowerCamelCase ( self : List[str] ) -> List[Any]:
"""simple docstring"""
# Do not remove the lockfile:
#
# https://github.com/benediktschmitt/py-filelock/issues/31
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
_UpperCAmelCase = self._lock_file_fd
_UpperCAmelCase = None
fcntl.flock(lowerCamelCase , fcntl.LOCK_UN )
os.close(lowerCamelCase )
return None
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
def lowerCamelCase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
try:
_UpperCAmelCase = os.open(self._lock_file , lowerCamelCase )
except OSError:
pass
else:
_UpperCAmelCase = fd
return None
def lowerCamelCase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
os.close(self._lock_file_fd )
_UpperCAmelCase = None
try:
os.remove(self._lock_file )
# The file is already deleted and that's what we want.
except OSError:
pass
return None
__a: List[Any] = None
if msvcrt:
__a: Optional[int] = WindowsFileLock
elif fcntl:
__a: Any = UnixFileLock
else:
__a: Tuple = SoftFileLock
if warnings is not None:
warnings.warn('''only soft file lock is available''') | 402 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable
UpperCAmelCase_ : Tuple = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : str = ['GPTNeoXTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : List[Any] = [
'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST',
'GPTNeoXForCausalLM',
'GPTNeoXForQuestionAnswering',
'GPTNeoXForSequenceClassification',
'GPTNeoXForTokenClassification',
'GPTNeoXLayer',
'GPTNeoXModel',
'GPTNeoXPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox import (
GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXForCausalLM,
GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
GPTNeoXLayer,
GPTNeoXModel,
GPTNeoXPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 365 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCAmelCase_ : Optional[Any] = {
'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'],
'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Any = [
'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST',
'AdaptiveEmbedding',
'TransfoXLForSequenceClassification',
'TransfoXLLMHeadModel',
'TransfoXLModel',
'TransfoXLPreTrainedModel',
'load_tf_weights_in_transfo_xl',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Optional[Any] = [
'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFAdaptiveEmbedding',
'TFTransfoXLForSequenceClassification',
'TFTransfoXLLMHeadModel',
'TFTransfoXLMainLayer',
'TFTransfoXLModel',
'TFTransfoXLPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_transfo_xl import (
TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
AdaptiveEmbedding,
TransfoXLForSequenceClassification,
TransfoXLLMHeadModel,
TransfoXLModel,
TransfoXLPreTrainedModel,
load_tf_weights_in_transfo_xl,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_transfo_xl import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAdaptiveEmbedding,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLMainLayer,
TFTransfoXLModel,
TFTransfoXLPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 365 | 1 |
'''simple docstring'''
import json
from typing import TYPE_CHECKING, 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_blenderbot import BlenderbotTokenizer
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
a : int = logging.get_logger(__name__)
a : List[str] = {
'''vocab_file''': '''vocab.json''',
'''merges_file''': '''merges.txt''',
'''tokenizer_config_file''': '''tokenizer_config.json''',
}
a : Optional[Any] = {
'''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''},
'''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''},
'''tokenizer_config_file''': {
'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json'''
},
}
a : Union[str, Any] = {'''facebook/blenderbot-3B''': 128}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""]
__SCREAMING_SNAKE_CASE = BlenderbotTokenizer
def __init__( self : Optional[Any] , a_ : Optional[Any]=None , a_ : Optional[int]=None , a_ : Tuple=None , a_ : Optional[int]="replace" , a_ : int="<s>" , a_ : int="</s>" , a_ : Union[str, Any]="</s>" , a_ : List[Any]="<s>" , a_ : List[Any]="<unk>" , a_ : Tuple="<pad>" , a_ : Union[str, Any]="<mask>" , a_ : Dict=False , a_ : Union[str, Any]=True , **a_ : Any , ):
"""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_ , )
__snake_case = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , a_ ) != add_prefix_space:
__snake_case = getattr(a_ , pre_tok_state.pop("type" ) )
__snake_case = add_prefix_space
__snake_case = pre_tok_class(**a_ )
__snake_case = add_prefix_space
__snake_case = "post_processor"
__snake_case = getattr(self.backend_tokenizer , a_ , a_ )
if tokenizer_component_instance:
__snake_case = 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:
__snake_case = tuple(state["sep"] )
if "cls" in state:
__snake_case = tuple(state["cls"] )
__snake_case = False
if state.get("add_prefix_space" , a_ ) != add_prefix_space:
__snake_case = add_prefix_space
__snake_case = True
if state.get("trim_offsets" , a_ ) != trim_offsets:
__snake_case = trim_offsets
__snake_case = True
if changes_to_apply:
__snake_case = getattr(a_ , state.pop("type" ) )
__snake_case = component_class(**a_ )
setattr(self.backend_tokenizer , a_ , a_ )
@property
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
def A ( self : Dict ):
"""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 A ( self : List[Any] , a_ : int ):
"""simple docstring"""
__snake_case = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else value
__snake_case = value
def A ( self : str , *a_ : int , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.get("is_split_into_words" , a_ )
assert self.add_prefix_space or not is_split_into_words, (
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 A ( self : Any , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.get("is_split_into_words" , a_ )
assert self.add_prefix_space or not is_split_into_words, (
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 A ( self : str , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
__snake_case = self._tokenizer.model.save(a_ , name=a_ )
return tuple(a_ )
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [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]
def A ( self : List[Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
return token_ids_a + [self.eos_token_id]
def A ( self : Optional[Any] , a_ : "Conversation" ):
"""simple docstring"""
__snake_case = []
for is_user, text in conversation.iter_texts():
if is_user:
# We need to space prefix as it's being done within blenderbot
inputs.append(" " + text )
else:
# Generated responses should contain them already.
inputs.append(a_ )
__snake_case = " ".join(a_ )
__snake_case = self.encode(a_ )
if len(a_ ) > self.model_max_length:
__snake_case = input_ids[-self.model_max_length :]
logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.''' )
return input_ids
| 680 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> str:
if number > 0:
raise ValueError("input must be a negative integer" )
__snake_case = len(bin(_UpperCAmelCase )[3:] )
__snake_case = bin(abs(_UpperCAmelCase ) - (1 << binary_number_length) )[3:]
__snake_case = (
(
"1"
+ "0" * (binary_number_length - len(_UpperCAmelCase ))
+ twos_complement_number
)
if number < 0
else "0"
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| 680 | 1 |
import timeit
import numpy as np
import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD
def _UpperCamelCase (a__ :List[Any] ):
"""simple docstring"""
def wrapper(*a__ :Tuple , **a__ :str ):
UpperCamelCase__ = timeit.default_timer()
UpperCamelCase__ = func(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = timeit.default_timer() - starttime
return delta
UpperCamelCase__ = func.__name__
return wrapper
def _UpperCamelCase (a__ :Optional[Any] , a__ :Tuple=100 , a__ :Dict=None ):
"""simple docstring"""
UpperCamelCase__ = []
UpperCamelCase__ = seq_shapes or {}
for i in range(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase__ = {}
for col_id, (k, v) in enumerate(features.items() ):
if isinstance(SCREAMING_SNAKE_CASE_ , _ArrayXD ):
UpperCamelCase__ = np.random.rand(*v.shape ).astype(v.dtype )
elif isinstance(SCREAMING_SNAKE_CASE_ , datasets.Value ):
if v.dtype == "string":
UpperCamelCase__ = """The small grey turtle was surprisingly fast when challenged."""
else:
UpperCamelCase__ = np.random.randint(10 , size=1 ).astype(v.dtype ).item()
elif isinstance(SCREAMING_SNAKE_CASE_ , datasets.Sequence ):
while isinstance(SCREAMING_SNAKE_CASE_ , datasets.Sequence ):
UpperCamelCase__ = v.feature
UpperCamelCase__ = seq_shapes[k]
UpperCamelCase__ = np.random.rand(*SCREAMING_SNAKE_CASE_ ).astype(v.dtype )
UpperCamelCase__ = data
dummy_data.append((i, example) )
return dummy_data
def _UpperCamelCase (a__ :Any , a__ :Dict , a__ :Optional[Any]=100 , a__ :List[str]=None ):
"""simple docstring"""
UpperCamelCase__ = generate_examples(SCREAMING_SNAKE_CASE_ , num_examples=SCREAMING_SNAKE_CASE_ , seq_shapes=SCREAMING_SNAKE_CASE_ )
with ArrowWriter(features=SCREAMING_SNAKE_CASE_ , path=SCREAMING_SNAKE_CASE_ ) as writer:
for key, record in dummy_data:
UpperCamelCase__ = features.encode_example(SCREAMING_SNAKE_CASE_ )
writer.write(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ , UpperCamelCase__ = writer.finalize()
if not num_final_examples == num_examples:
raise ValueError(
f"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" )
UpperCamelCase__ = datasets.Dataset.from_file(filename=SCREAMING_SNAKE_CASE_ , info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE_ ) )
return dataset
| 619 | '''simple docstring'''
import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter
from transformers import HfArgumentParser
def A_ ( SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) ->str:
return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ )
@dataclass
class _a :
"""simple docstring"""
A_ = field(
metadata={'''help''': '''The csv file to plot.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , )
A_ = field(
default=__a , metadata={
'''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.'''
} , )
A_ = field(
default=__a , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , )
A_ = list_field(
default=__a , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} )
def A_ ( SCREAMING_SNAKE_CASE_ ) ->Dict:
try:
int(SCREAMING_SNAKE_CASE_ )
return True
except ValueError:
return False
def A_ ( SCREAMING_SNAKE_CASE_ ) ->int:
try:
float(SCREAMING_SNAKE_CASE_ )
return True
except ValueError:
return False
class _a :
"""simple docstring"""
def __init__( self : str , lowercase_ : List[str] ):
'''simple docstring'''
lowercase_ = args
lowercase_ = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} )
with open(self.args.csv_file , newline="""""" ) as csv_file:
lowercase_ = csv.DictReader(lowercase_ )
for row in reader:
lowercase_ = row["""model"""]
self.result_dict[model_name]["bsz"].append(int(row["""batch_size"""] ) )
self.result_dict[model_name]["seq_len"].append(int(row["""sequence_length"""] ) )
if can_convert_to_int(row["""result"""] ):
# value is not None
lowercase_ = int(row["""result"""] )
elif can_convert_to_float(row["""result"""] ):
# value is not None
lowercase_ = float(row["""result"""] )
def lowerCamelCase__ ( self : str ):
'''simple docstring'''
lowercase_ , lowercase_ = plt.subplots()
lowercase_ = """Time usage""" if self.args.is_time else """Memory usage"""
lowercase_ = title_str + """ for training""" if self.args.is_train else title_str + """ for inference"""
if not self.args.no_log_scale:
# set logarithm scales
ax.set_xscale("""log""" )
ax.set_yscale("""log""" )
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_formatter(ScalarFormatter() )
for model_name_idx, model_name in enumerate(self.result_dict.keys() ):
lowercase_ = sorted(set(self.result_dict[model_name]["""bsz"""] ) )
lowercase_ = sorted(set(self.result_dict[model_name]["""seq_len"""] ) )
lowercase_ = self.result_dict[model_name]["""result"""]
((lowercase_) , (lowercase_)) = (
(batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
)
lowercase_ = (
model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
)
for inner_loop_value in inner_loop_array:
if self.args.plot_along_batch:
lowercase_ = np.asarray(
[results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=lowercase_ , )
else:
lowercase_ = np.asarray(
[results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , )
((lowercase_) , (lowercase_)) = (
("""batch_size""", """len""") if self.args.plot_along_batch else ("""in #tokens""", """bsz""")
)
lowercase_ = np.asarray(lowercase_ , lowercase_ )[: len(lowercase_ )]
plt.scatter(
lowercase_ , lowercase_ , label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" )
plt.plot(lowercase_ , lowercase_ , """--""" )
title_str += F""" {label_model_name} vs."""
lowercase_ = title_str[:-4]
lowercase_ = """Time in s""" if self.args.is_time else """Memory in MB"""
# plot
plt.title(lowercase_ )
plt.xlabel(lowercase_ )
plt.ylabel(lowercase_ )
plt.legend()
if self.args.figure_png_file is not None:
plt.savefig(self.args.figure_png_file )
else:
plt.show()
def A_ ( ) ->Tuple:
lowercase_ = HfArgumentParser(SCREAMING_SNAKE_CASE_ )
lowercase_ = parser.parse_args_into_dataclasses()[0]
lowercase_ = Plot(args=SCREAMING_SNAKE_CASE_ )
plot.plot()
if __name__ == "__main__":
main()
| 451 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_lowerCAmelCase = logging.get_logger(__name__)
_lowerCAmelCase = {
"""bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""",
"""bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""",
"""bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""",
"""bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""",
"""bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""",
"""bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""",
"""bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""",
"""bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""",
"""bert-large-uncased-whole-word-masking""": (
"""https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json"""
),
"""bert-large-cased-whole-word-masking""": (
"""https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json"""
),
"""bert-large-uncased-whole-word-masking-finetuned-squad""": (
"""https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
),
"""bert-large-cased-whole-word-masking-finetuned-squad""": (
"""https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
),
"""bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""",
"""bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""",
"""bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""",
"""cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""",
"""cl-tohoku/bert-base-japanese-whole-word-masking""": (
"""https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json"""
),
"""cl-tohoku/bert-base-japanese-char""": (
"""https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json"""
),
"""cl-tohoku/bert-base-japanese-char-whole-word-masking""": (
"""https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json"""
),
"""TurkuNLP/bert-base-finnish-cased-v1""": (
"""https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json"""
),
"""TurkuNLP/bert-base-finnish-uncased-v1""": (
"""https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json"""
),
"""wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""",
# See all BERT models at https://huggingface.co/models?filter=bert
}
class _UpperCAmelCase ( _lowerCamelCase ):
a = '''bert'''
def __init__( self , a__=30522 , a__=768 , a__=12 , a__=12 , a__=3072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=2 , a__=0.02 , a__=1E-12 , a__=0 , a__="absolute" , a__=True , a__=None , **a__ , ):
super().__init__(pad_token_id=a__ , **a__ )
A_ : Dict = vocab_size
A_ : Dict = hidden_size
A_ : str = num_hidden_layers
A_ : Any = num_attention_heads
A_ : Optional[Any] = hidden_act
A_ : Union[str, Any] = intermediate_size
A_ : Union[str, Any] = hidden_dropout_prob
A_ : List[str] = attention_probs_dropout_prob
A_ : Dict = max_position_embeddings
A_ : str = type_vocab_size
A_ : List[Any] = initializer_range
A_ : int = layer_norm_eps
A_ : Any = position_embedding_type
A_ : Optional[Any] = use_cache
A_ : Dict = classifier_dropout
class _UpperCAmelCase ( _lowerCamelCase ):
@property
def _lowerCamelCase ( self ):
if self.task == "multiple-choice":
A_ : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""}
else:
A_ : List[str] = {0: """batch""", 1: """sequence"""}
return OrderedDict(
[
("""input_ids""", dynamic_axis),
("""attention_mask""", dynamic_axis),
("""token_type_ids""", dynamic_axis),
] ) | 719 |
import re
def _lowerCAmelCase ( _lowerCAmelCase ):
'''simple docstring'''
A_ : Any = re.compile(r"""^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$""" )
if match := re.search(_lowerCAmelCase ,_lowerCAmelCase ):
return match.string == phone
return False
if __name__ == "__main__":
print(indian_phone_validator("""+918827897895"""))
| 481 | 0 |
import json
import os
from pathlib import Path
import pytest
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename
__lowerCamelCase = 'http://www.mocksite.com/file1.txt'
__lowerCamelCase = '"text": ["foo", "foo"]'
__lowerCamelCase = '6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8'
class UpperCAmelCase :
A__ : int = 2_00
A__ : Union[str, Any] = {"Content-Length": "100"}
A__ : List[Any] = {}
def _SCREAMING_SNAKE_CASE (self : List[str] , **snake_case__ : List[Any] ) -> List[Any]:
'''simple docstring'''
return [bytes(A_ , "utf-8" )]
def UpperCamelCase ( *__lowerCamelCase : List[Any] , **__lowerCamelCase : Any ):
return MockResponse()
@pytest.mark.parametrize("urls_type" , [str, list, dict] )
def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] ):
import requests
monkeypatch.setattr(lowercase__ , "request" , lowercase__ )
snake_case : List[Any] = URL
if issubclass(lowercase__ , lowercase__ ):
snake_case : str = url
elif issubclass(lowercase__ , lowercase__ ):
snake_case : List[str] = [url]
elif issubclass(lowercase__ , lowercase__ ):
snake_case : str = {"train": url}
snake_case : Optional[Any] = "dummy"
snake_case : int = "downloads"
snake_case : List[Any] = tmp_path
snake_case : List[str] = DownloadConfig(
cache_dir=os.path.join(lowercase__ , lowercase__ ) , use_etag=lowercase__ , )
snake_case : Dict = DownloadManager(dataset_name=lowercase__ , download_config=lowercase__ )
snake_case : List[str] = dl_manager.download(lowercase__ )
snake_case : Dict = urls
for downloaded_paths in [downloaded_paths]:
if isinstance(lowercase__ , lowercase__ ):
snake_case : List[Any] = [downloaded_paths]
snake_case : Union[str, Any] = [urls]
elif isinstance(lowercase__ , lowercase__ ):
assert "train" in downloaded_paths.keys()
snake_case : Union[str, Any] = downloaded_paths.values()
snake_case : Optional[Any] = urls.values()
assert downloaded_paths
for downloaded_path, input_url in zip(lowercase__ , lowercase__ ):
assert downloaded_path == dl_manager.downloaded_paths[input_url]
snake_case : Union[str, Any] = Path(lowercase__ )
snake_case : int = downloaded_path.parts
assert parts[-1] == HASH
assert parts[-2] == cache_subdir
assert downloaded_path.exists()
snake_case : str = downloaded_path.read_text()
assert content == CONTENT
snake_case : List[Any] = downloaded_path.with_suffix(".json" )
assert metadata_downloaded_path.exists()
snake_case : Dict = json.loads(metadata_downloaded_path.read_text() )
assert metadata_content == {"url": URL, "etag": None}
@pytest.mark.parametrize("paths_type" , [str, list, dict] )
def UpperCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict ):
snake_case : Union[str, Any] = str(lowercase__ )
if issubclass(lowercase__ , lowercase__ ):
snake_case : Optional[int] = filename
elif issubclass(lowercase__ , lowercase__ ):
snake_case : List[Any] = [filename]
elif issubclass(lowercase__ , lowercase__ ):
snake_case : int = {"train": filename}
snake_case : Union[str, Any] = "dummy"
snake_case : List[Any] = xz_file.parent
snake_case : Optional[int] = "extracted"
snake_case : Any = DownloadConfig(
cache_dir=lowercase__ , use_etag=lowercase__ , )
snake_case : Any = DownloadManager(dataset_name=lowercase__ , download_config=lowercase__ )
snake_case : Optional[int] = dl_manager.extract(lowercase__ )
snake_case : List[Any] = paths
for extracted_paths in [extracted_paths]:
if isinstance(lowercase__ , lowercase__ ):
snake_case : int = [extracted_paths]
snake_case : Any = [paths]
elif isinstance(lowercase__ , lowercase__ ):
assert "train" in extracted_paths.keys()
snake_case : int = extracted_paths.values()
snake_case : Tuple = paths.values()
assert extracted_paths
for extracted_path, input_path in zip(lowercase__ , lowercase__ ):
assert extracted_path == dl_manager.extracted_paths[input_path]
snake_case : Tuple = Path(lowercase__ )
snake_case : List[str] = extracted_path.parts
assert parts[-1] == hash_url_to_filename(lowercase__ , etag=lowercase__ )
assert parts[-2] == extracted_subdir
assert extracted_path.exists()
snake_case : List[str] = extracted_path.read_text()
snake_case : str = text_file.read_text()
assert extracted_file_content == expected_file_content
def UpperCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : int ):
assert path.endswith(".jsonl" )
for num_items, line in enumerate(lowercase__ , start=1 ):
snake_case : Union[str, Any] = json.loads(line.decode("utf-8" ) )
assert item.keys() == {"col_1", "col_2", "col_3"}
assert num_items == 4
@pytest.mark.parametrize("archive_jsonl" , ["tar_jsonl_path", "zip_jsonl_path"] )
def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ):
snake_case : Optional[Any] = request.getfixturevalue(lowercase__ )
snake_case : Any = DownloadManager()
for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(lowercase__ ) , start=1 ):
_test_jsonl(lowercase__ , lowercase__ )
assert num_jsonl == 2
@pytest.mark.parametrize("archive_nested_jsonl" , ["tar_nested_jsonl_path", "zip_nested_jsonl_path"] )
def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] ):
snake_case : Optional[int] = request.getfixturevalue(lowercase__ )
snake_case : List[str] = DownloadManager()
for num_tar, (path, file) in enumerate(dl_manager.iter_archive(lowercase__ ) , start=1 ):
for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(lowercase__ ) , start=1 ):
_test_jsonl(lowercase__ , lowercase__ )
assert num_tar == 1
assert num_jsonl == 2
def UpperCamelCase ( __lowerCamelCase : Tuple ):
snake_case : Tuple = DownloadManager()
for num_file, file in enumerate(dl_manager.iter_files(lowercase__ ) , start=1 ):
assert os.path.basename(lowercase__ ) == ("test.txt" if num_file == 1 else "train.txt")
assert num_file == 2
| 204 |
"""simple docstring"""
import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def a_ ( lowercase__ :Optional[Any], lowercase__ :List[str]=0.999, lowercase__ :Optional[int]="cosine", ):
if alpha_transform_type == "cosine":
def alpha_bar_fn(lowercase__ :str ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(lowercase__ :Optional[Any] ):
return math.exp(t * -12.0 )
else:
raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}' )
__lowerCamelCase = []
for i in range(lowercase__ ):
__lowerCamelCase = i / num_diffusion_timesteps
__lowerCamelCase = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(lowercase__ ) / alpha_bar_fn(lowercase__ ), lowercase__ ) )
return torch.tensor(lowercase__, dtype=torch.floataa )
class __snake_case (lowerCamelCase , lowerCamelCase ):
__a = [e.name for e in KarrasDiffusionSchedulers]
__a = 2
@register_to_config
def __init__( self: Any , A_: int = 10_00 , A_: float = 0.00_085 , A_: float = 0.012 , A_: str = "linear" , A_: Optional[Union[np.ndarray, List[float]]] = None , A_: str = "epsilon" , A_: Optional[bool] = False , A_: Optional[bool] = False , A_: float = 1.0 , A_: str = "linspace" , A_: int = 0 , ):
if trained_betas is not None:
__lowerCamelCase = torch.tensor(A_ , dtype=torch.floataa )
elif beta_schedule == "linear":
__lowerCamelCase = torch.linspace(A_ , A_ , A_ , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
__lowerCamelCase = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , A_ , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
__lowerCamelCase = betas_for_alpha_bar(A_ , alpha_transform_type="""cosine""" )
elif beta_schedule == "exp":
__lowerCamelCase = betas_for_alpha_bar(A_ , alpha_transform_type="""exp""" )
else:
raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' )
__lowerCamelCase = 1.0 - self.betas
__lowerCamelCase = torch.cumprod(self.alphas , dim=0 )
# set all values
self.set_timesteps(A_ , A_ , A_ )
__lowerCamelCase = use_karras_sigmas
def __a ( self: Optional[Any] , A_: List[Any] , A_: Tuple=None ):
if schedule_timesteps is None:
__lowerCamelCase = self.timesteps
__lowerCamelCase = (schedule_timesteps == timestep).nonzero()
# The sigma index that is taken for the **very** first `step`
# is always the second index (or the last index if there is only 1)
# This way we can ensure we don't accidentally skip a sigma in
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
if len(self._index_counter ) == 0:
__lowerCamelCase = 1 if len(A_ ) > 1 else 0
else:
__lowerCamelCase = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep
__lowerCamelCase = self._index_counter[timestep_int]
return indices[pos].item()
@property
def __a ( self: Tuple ):
# standard deviation of the initial noise distribution
if self.config.timestep_spacing in ["linspace", "trailing"]:
return self.sigmas.max()
return (self.sigmas.max() ** 2 + 1) ** 0.5
def __a ( self: Union[str, Any] , A_: torch.FloatTensor , A_: Union[float, torch.FloatTensor] , ):
__lowerCamelCase = self.index_for_timestep(A_ )
__lowerCamelCase = self.sigmas[step_index]
__lowerCamelCase = sample / ((sigma**2 + 1) ** 0.5)
return sample
def __a ( self: str , A_: int , A_: Union[str, torch.device] = None , A_: Optional[int] = None , ):
__lowerCamelCase = num_inference_steps
__lowerCamelCase = num_train_timesteps or self.config.num_train_timesteps
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
__lowerCamelCase = np.linspace(0 , num_train_timesteps - 1 , A_ , dtype=A_ )[::-1].copy()
elif self.config.timestep_spacing == "leading":
__lowerCamelCase = num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
__lowerCamelCase = (np.arange(0 , A_ ) * step_ratio).round()[::-1].copy().astype(A_ )
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
__lowerCamelCase = num_train_timesteps / self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
__lowerCamelCase = (np.arange(A_ , 0 , -step_ratio )).round().copy().astype(A_ )
timesteps -= 1
else:
raise ValueError(
f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' )
__lowerCamelCase = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
__lowerCamelCase = np.log(A_ )
__lowerCamelCase = np.interp(A_ , np.arange(0 , len(A_ ) ) , A_ )
if self.config.use_karras_sigmas:
__lowerCamelCase = self._convert_to_karras(in_sigmas=A_ , num_inference_steps=self.num_inference_steps )
__lowerCamelCase = np.array([self._sigma_to_t(A_ , A_ ) for sigma in sigmas] )
__lowerCamelCase = np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
__lowerCamelCase = torch.from_numpy(A_ ).to(device=A_ )
__lowerCamelCase = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] )
__lowerCamelCase = torch.from_numpy(A_ )
__lowerCamelCase = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] )
if str(A_ ).startswith("""mps""" ):
# mps does not support float64
__lowerCamelCase = timesteps.to(A_ , dtype=torch.floataa )
else:
__lowerCamelCase = timesteps.to(device=A_ )
# empty dt and derivative
__lowerCamelCase = None
__lowerCamelCase = None
# for exp beta schedules, such as the one for `pipeline_shap_e.py`
# we need an index counter
__lowerCamelCase = defaultdict(A_ )
def __a ( self: Any , A_: int , A_: int ):
# get log sigma
__lowerCamelCase = np.log(A_ )
# get distribution
__lowerCamelCase = log_sigma - log_sigmas[:, np.newaxis]
# get sigmas range
__lowerCamelCase = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 )
__lowerCamelCase = low_idx + 1
__lowerCamelCase = log_sigmas[low_idx]
__lowerCamelCase = log_sigmas[high_idx]
# interpolate sigmas
__lowerCamelCase = (low - log_sigma) / (low - high)
__lowerCamelCase = np.clip(A_ , 0 , 1 )
# transform interpolation to time range
__lowerCamelCase = (1 - w) * low_idx + w * high_idx
__lowerCamelCase = t.reshape(sigma.shape )
return t
def __a ( self: Dict , A_: torch.FloatTensor , A_: Tuple ):
__lowerCamelCase = in_sigmas[-1].item()
__lowerCamelCase = in_sigmas[0].item()
__lowerCamelCase = 7.0 # 7.0 is the value used in the paper
__lowerCamelCase = np.linspace(0 , 1 , A_ )
__lowerCamelCase = sigma_min ** (1 / rho)
__lowerCamelCase = sigma_max ** (1 / rho)
__lowerCamelCase = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return sigmas
@property
def __a ( self: List[Any] ):
return self.dt is None
def __a ( self: Union[str, Any] , A_: Union[torch.FloatTensor, np.ndarray] , A_: Union[float, torch.FloatTensor] , A_: Union[torch.FloatTensor, np.ndarray] , A_: bool = True , ):
__lowerCamelCase = self.index_for_timestep(A_ )
# advance index counter by 1
__lowerCamelCase = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep
self._index_counter[timestep_int] += 1
if self.state_in_first_order:
__lowerCamelCase = self.sigmas[step_index]
__lowerCamelCase = self.sigmas[step_index + 1]
else:
# 2nd order / Heun's method
__lowerCamelCase = self.sigmas[step_index - 1]
__lowerCamelCase = self.sigmas[step_index]
# currently only gamma=0 is supported. This usually works best anyways.
# We can support gamma in the future but then need to scale the timestep before
# passing it to the model which requires a change in API
__lowerCamelCase = 0
__lowerCamelCase = sigma * (gamma + 1) # Note: sigma_hat == sigma for now
# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
if self.config.prediction_type == "epsilon":
__lowerCamelCase = sigma_hat if self.state_in_first_order else sigma_next
__lowerCamelCase = sample - sigma_input * model_output
elif self.config.prediction_type == "v_prediction":
__lowerCamelCase = sigma_hat if self.state_in_first_order else sigma_next
__lowerCamelCase = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
sample / (sigma_input**2 + 1)
)
elif self.config.prediction_type == "sample":
__lowerCamelCase = model_output
else:
raise ValueError(
f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' )
if self.config.clip_sample:
__lowerCamelCase = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
if self.state_in_first_order:
# 2. Convert to an ODE derivative for 1st order
__lowerCamelCase = (sample - pred_original_sample) / sigma_hat
# 3. delta timestep
__lowerCamelCase = sigma_next - sigma_hat
# store for 2nd order step
__lowerCamelCase = derivative
__lowerCamelCase = dt
__lowerCamelCase = sample
else:
# 2. 2nd order / Heun's method
__lowerCamelCase = (sample - pred_original_sample) / sigma_next
__lowerCamelCase = (self.prev_derivative + derivative) / 2
# 3. take prev timestep & sample
__lowerCamelCase = self.dt
__lowerCamelCase = self.sample
# free dt and derivative
# Note, this puts the scheduler in "first order mode"
__lowerCamelCase = None
__lowerCamelCase = None
__lowerCamelCase = None
__lowerCamelCase = sample + derivative * dt
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=A_ )
def __a ( self: str , A_: torch.FloatTensor , A_: torch.FloatTensor , A_: torch.FloatTensor , ):
# Make sure sigmas and timesteps have the same device and dtype as original_samples
__lowerCamelCase = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype )
if original_samples.device.type == "mps" and torch.is_floating_point(A_ ):
# mps does not support float64
__lowerCamelCase = self.timesteps.to(original_samples.device , dtype=torch.floataa )
__lowerCamelCase = timesteps.to(original_samples.device , dtype=torch.floataa )
else:
__lowerCamelCase = self.timesteps.to(original_samples.device )
__lowerCamelCase = timesteps.to(original_samples.device )
__lowerCamelCase = [self.index_for_timestep(A_ , A_ ) for t in timesteps]
__lowerCamelCase = sigmas[step_indices].flatten()
while len(sigma.shape ) < len(original_samples.shape ):
__lowerCamelCase = sigma.unsqueeze(-1 )
__lowerCamelCase = original_samples + noise * sigma
return noisy_samples
def __len__( self: Tuple ):
return self.config.num_train_timesteps
| 281 | 0 |
import inspect
import warnings
from typing import Any, Dict, Optional, Union
from packaging import version
def _a ( *SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : int=True , SCREAMING_SNAKE_CASE_ : Tuple=2 ):
from .. import __version__
__lowerCAmelCase = take_from
__lowerCAmelCase = ()
if not isinstance(args[0] , lowerCamelCase__ ):
__lowerCAmelCase = (args,)
for attribute, version_name, message in args:
if version.parse(version.parse(lowerCamelCase__ ).base_version ) >= version.parse(lowerCamelCase__ ):
raise ValueError(
F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'"""
F""" version {__version__} is >= {version_name}""" )
__lowerCAmelCase = None
if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and attribute in deprecated_kwargs:
values += (deprecated_kwargs.pop(lowerCamelCase__ ),)
__lowerCAmelCase = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}."""
elif hasattr(lowerCamelCase__ , lowerCamelCase__ ):
values += (getattr(lowerCamelCase__ , lowerCamelCase__ ),)
__lowerCAmelCase = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}."""
elif deprecated_kwargs is None:
__lowerCAmelCase = F"""`{attribute}` is deprecated and will be removed in version {version_name}."""
if warning is not None:
__lowerCAmelCase = warning + " " if standard_warn else ""
warnings.warn(warning + message , lowerCamelCase__ , stacklevel=lowerCamelCase__ )
if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and len(lowerCamelCase__ ) > 0:
__lowerCAmelCase = inspect.getouterframes(inspect.currentframe() )[1]
__lowerCAmelCase = call_frame.filename
__lowerCAmelCase = call_frame.lineno
__lowerCAmelCase = call_frame.function
__lowerCAmelCase = next(iter(deprecated_kwargs.items() ) )
raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" )
if len(lowerCamelCase__ ) == 0:
return
elif len(lowerCamelCase__ ) == 1:
return values[0]
return values
| 710 |
from math import sqrt
def _a ( SCREAMING_SNAKE_CASE_ : int ):
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(sqrt(SCREAMING_SNAKE_CASE_ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_01 ):
__lowerCAmelCase = 0
__lowerCAmelCase = 1
while count != nth and number < 3:
number += 1
if is_prime(SCREAMING_SNAKE_CASE_ ):
count += 1
while count != nth:
number += 2
if is_prime(SCREAMING_SNAKE_CASE_ ):
count += 1
return number
if __name__ == "__main__":
print(f'''{solution() = }''')
| 552 | 0 |
def UpperCamelCase ( _UpperCAmelCase : Any , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[Any]=False ) -> List[Any]:
'''simple docstring'''
if isinstance(_snake_case , _snake_case ) and isinstance(_snake_case , _snake_case ):
_lowercase : List[Any] = len(set_a.intersection(_snake_case ) )
if alternative_union:
_lowercase : List[str] = len(_snake_case ) + len(_snake_case )
else:
_lowercase : Union[str, Any] = len(set_a.union(_snake_case ) )
return intersection / union
if isinstance(_snake_case , (list, tuple) ) and isinstance(_snake_case , (list, tuple) ):
_lowercase : List[str] = [element for element in set_a if element in set_b]
if alternative_union:
_lowercase : Any = len(_snake_case ) + len(_snake_case )
return len(_snake_case ) / union
else:
_lowercase : int = set_a + [element for element in set_b if element not in set_a]
return len(_snake_case ) / len(_snake_case )
return len(_snake_case ) / len(_snake_case )
return None
if __name__ == "__main__":
UpperCamelCase_ : Optional[int] = {"""a""", """b""", """c""", """d""", """e"""}
UpperCamelCase_ : Tuple = {"""c""", """d""", """e""", """f""", """h""", """i"""}
print(jaccard_similarity(set_a, set_b))
| 461 |
"""simple docstring"""
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def _snake_case ( _snake_case : Dict ) -> Optional[Any]:
'''simple docstring'''
for param in module.parameters():
_A = False
def _snake_case ( ) -> Tuple:
'''simple docstring'''
_A = 'cuda' if torch.cuda.is_available() else 'cpu'
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
_A = 'mps'
if device == "mps":
print(
'WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch'
' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues'
' with generations.' )
return device
def _snake_case ( _snake_case : Dict ) -> Optional[Any]:
'''simple docstring'''
_A = plt.imshow(_snake_case )
fig.axes.get_xaxis().set_visible(_snake_case )
fig.axes.get_yaxis().set_visible(_snake_case )
plt.show()
def _snake_case ( ) -> Optional[Any]:
'''simple docstring'''
_A = datetime.now()
_A = current_time.strftime('%H:%M:%S' )
return timestamp
| 7 | 0 |
import os
try:
from .build_directory_md import good_file_paths
except ImportError:
from build_directory_md import good_file_paths # type: ignore
lowerCamelCase__ = list(good_file_paths())
assert filepaths, "good_file_paths() failed!"
lowerCamelCase__ = [file for file in filepaths if file != file.lower()]
if upper_files:
print(F"""{len(upper_files)} files contain uppercase characters:""")
print("""\n""".join(upper_files) + """\n""")
lowerCamelCase__ = [file for file in filepaths if """ """ in file]
if space_files:
print(F"""{len(space_files)} files contain space characters:""")
print("""\n""".join(space_files) + """\n""")
lowerCamelCase__ = [file for file in filepaths if """-""" in file]
if hyphen_files:
print(F"""{len(hyphen_files)} files contain hyphen characters:""")
print("""\n""".join(hyphen_files) + """\n""")
lowerCamelCase__ = [file for file in filepaths if os.sep not in file]
if nodir_files:
print(F"""{len(nodir_files)} files are not in a directory:""")
print("""\n""".join(nodir_files) + """\n""")
lowerCamelCase__ = len(upper_files + space_files + hyphen_files + nodir_files)
if bad_files:
import sys
sys.exit(bad_files)
| 702 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
lowerCamelCase__ = logging.get_logger(__name__)
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
__a = DPTConfig(embedding_type="""hybrid""" )
if "large" in checkpoint_url:
__a = 1024
__a = 4096
__a = 24
__a = 16
__a = [5, 11, 17, 23]
__a = [256, 512, 1024, 1024]
__a = (1, 384, 384)
if "nyu" or "midas" in checkpoint_url:
__a = 768
__a = [1, 1, 1, 0.5]
__a = [256, 512, 768, 768]
__a = 150
__a = 16
__a = (1, 384, 384)
__a = False
__a = """project"""
if "ade" in checkpoint_url:
__a = True
__a = 768
__a = [1, 1, 1, 0.5]
__a = 150
__a = 16
__a = """huggingface/label-files"""
__a = """ade20k-id2label.json"""
__a = json.load(open(cached_download(hf_hub_url(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) ) , """r""" ) )
__a = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
__a = idalabel
__a = {v: k for k, v in idalabel.items()}
__a = [1, 150, 480, 480]
return config, expected_shape
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
__a = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""]
for k in ignore_keys:
state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
__a = name.replace("""pretrained.model""" , """dpt.encoder""" )
if "pretrained.model" in name:
__a = name.replace("""pretrained.model""" , """dpt.embeddings""" )
if "patch_embed" in name:
__a = name.replace("""patch_embed""" , """""" )
if "pos_embed" in name:
__a = name.replace("""pos_embed""" , """position_embeddings""" )
if "attn.proj" in name:
__a = name.replace("""attn.proj""" , """attention.output.dense""" )
if "proj" in name and "project" not in name:
__a = name.replace("""proj""" , """projection""" )
if "blocks" in name:
__a = name.replace("""blocks""" , """layer""" )
if "mlp.fc1" in name:
__a = name.replace("""mlp.fc1""" , """intermediate.dense""" )
if "mlp.fc2" in name:
__a = name.replace("""mlp.fc2""" , """output.dense""" )
if "norm1" in name and "backbone" not in name:
__a = name.replace("""norm1""" , """layernorm_before""" )
if "norm2" in name and "backbone" not in name:
__a = name.replace("""norm2""" , """layernorm_after""" )
if "scratch.output_conv" in name:
__a = name.replace("""scratch.output_conv""" , """head""" )
if "scratch" in name:
__a = name.replace("""scratch""" , """neck""" )
if "layer1_rn" in name:
__a = name.replace("""layer1_rn""" , """convs.0""" )
if "layer2_rn" in name:
__a = name.replace("""layer2_rn""" , """convs.1""" )
if "layer3_rn" in name:
__a = name.replace("""layer3_rn""" , """convs.2""" )
if "layer4_rn" in name:
__a = name.replace("""layer4_rn""" , """convs.3""" )
if "refinenet" in name:
__a = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
__a = name.replace(f"refinenet{layer_idx}" , f"fusion_stage.layers.{abs(layer_idx-4 )}" )
if "out_conv" in name:
__a = name.replace("""out_conv""" , """projection""" )
if "resConfUnit1" in name:
__a = name.replace("""resConfUnit1""" , """residual_layer1""" )
if "resConfUnit2" in name:
__a = name.replace("""resConfUnit2""" , """residual_layer2""" )
if "conv1" in name:
__a = name.replace("""conv1""" , """convolution1""" )
if "conv2" in name:
__a = name.replace("""conv2""" , """convolution2""" )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
__a = name.replace("""pretrained.act_postprocess1.0.project.0""" , """neck.reassemble_stage.readout_projects.0.0""" )
if "pretrained.act_postprocess2.0.project.0" in name:
__a = name.replace("""pretrained.act_postprocess2.0.project.0""" , """neck.reassemble_stage.readout_projects.1.0""" )
if "pretrained.act_postprocess3.0.project.0" in name:
__a = name.replace("""pretrained.act_postprocess3.0.project.0""" , """neck.reassemble_stage.readout_projects.2.0""" )
if "pretrained.act_postprocess4.0.project.0" in name:
__a = name.replace("""pretrained.act_postprocess4.0.project.0""" , """neck.reassemble_stage.readout_projects.3.0""" )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
__a = name.replace("""pretrained.act_postprocess1.3""" , """neck.reassemble_stage.layers.0.projection""" )
if "pretrained.act_postprocess1.4" in name:
__a = name.replace("""pretrained.act_postprocess1.4""" , """neck.reassemble_stage.layers.0.resize""" )
if "pretrained.act_postprocess2.3" in name:
__a = name.replace("""pretrained.act_postprocess2.3""" , """neck.reassemble_stage.layers.1.projection""" )
if "pretrained.act_postprocess2.4" in name:
__a = name.replace("""pretrained.act_postprocess2.4""" , """neck.reassemble_stage.layers.1.resize""" )
if "pretrained.act_postprocess3.3" in name:
__a = name.replace("""pretrained.act_postprocess3.3""" , """neck.reassemble_stage.layers.2.projection""" )
if "pretrained.act_postprocess4.3" in name:
__a = name.replace("""pretrained.act_postprocess4.3""" , """neck.reassemble_stage.layers.3.projection""" )
if "pretrained.act_postprocess4.4" in name:
__a = name.replace("""pretrained.act_postprocess4.4""" , """neck.reassemble_stage.layers.3.resize""" )
if "pretrained" in name:
__a = name.replace("""pretrained""" , """dpt""" )
if "bn" in name:
__a = name.replace("""bn""" , """batch_norm""" )
if "head" in name:
__a = name.replace("""head""" , """head.head""" )
if "encoder.norm" in name:
__a = name.replace("""encoder.norm""" , """layernorm""" )
if "auxlayer" in name:
__a = name.replace("""auxlayer""" , """auxiliary_head.head""" )
if "backbone" in name:
__a = name.replace("""backbone""" , """backbone.bit.encoder""" )
if ".." in name:
__a = name.replace("""..""" , """.""" )
if "stem.conv" in name:
__a = name.replace("""stem.conv""" , """bit.embedder.convolution""" )
if "blocks" in name:
__a = name.replace("""blocks""" , """layers""" )
if "convolution" in name and "backbone" in name:
__a = name.replace("""convolution""" , """conv""" )
if "layer" in name and "backbone" in name:
__a = name.replace("""layer""" , """layers""" )
if "backbone.bit.encoder.bit" in name:
__a = name.replace("""backbone.bit.encoder.bit""" , """backbone.bit""" )
if "embedder.conv" in name:
__a = name.replace("""embedder.conv""" , """embedder.convolution""" )
if "backbone.bit.encoder.stem.norm" in name:
__a = name.replace("""backbone.bit.encoder.stem.norm""" , """backbone.bit.embedder.norm""" )
return name
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
__a = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.weight" )
__a = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.bias" )
# next, add query, keys and values (in that order) to the state dict
__a = in_proj_weight[: config.hidden_size, :]
__a = in_proj_bias[: config.hidden_size]
__a = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
__a = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
__a = in_proj_weight[
-config.hidden_size :, :
]
__a = in_proj_bias[-config.hidden_size :]
def lowerCAmelCase__ ( ):
"""simple docstring"""
__a = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__a = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
@torch.no_grad()
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
__a , __a = get_dpt_config(_SCREAMING_SNAKE_CASE )
# load original state_dict from URL
# state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
__a = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )
# remove certain keys
remove_ignore_keys_(_SCREAMING_SNAKE_CASE )
# rename keys
for key in state_dict.copy().keys():
__a = state_dict.pop(_SCREAMING_SNAKE_CASE )
__a = val
# read in qkv matrices
read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
__a = DPTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ) if """ade""" in checkpoint_url else DPTForDepthEstimation(_SCREAMING_SNAKE_CASE )
model.load_state_dict(_SCREAMING_SNAKE_CASE )
model.eval()
# Check outputs on an image
__a = 480 if """ade""" in checkpoint_url else 384
__a = DPTImageProcessor(size=_SCREAMING_SNAKE_CASE )
__a = prepare_img()
__a = image_processor(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" )
# forward pass
__a = model(**_SCREAMING_SNAKE_CASE ).logits if """ade""" in checkpoint_url else model(**_SCREAMING_SNAKE_CASE ).predicted_depth
if show_prediction:
__a = (
torch.nn.functional.interpolate(
outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode="""bicubic""" , align_corners=_SCREAMING_SNAKE_CASE , )
.squeeze()
.cpu()
.numpy()
)
Image.fromarray((prediction / prediction.max()) * 255 ).show()
if pytorch_dump_folder_path is not None:
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"Saving model to {pytorch_dump_folder_path}" )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
print(f"Saving image processor to {pytorch_dump_folder_path}" )
image_processor.save_pretrained(_SCREAMING_SNAKE_CASE )
if push_to_hub:
model.push_to_hub("""ybelkada/dpt-hybrid-midas""" )
image_processor.push_to_hub("""ybelkada/dpt-hybrid-midas""" )
if __name__ == "__main__":
lowerCamelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--checkpoint_url""",
default="""https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt""",
type=str,
help="""URL of the original DPT checkpoint you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default=None,
type=str,
required=False,
help="""Path to the output PyTorch model directory.""",
)
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
)
parser.add_argument(
"""--model_name""",
default="""dpt-large""",
type=str,
help="""Name of the model, in case you're pushing to the hub.""",
)
parser.add_argument(
"""--show_prediction""",
action="""store_true""",
)
lowerCamelCase__ = parser.parse_args()
convert_dpt_checkpoint(
args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction
)
| 547 | 0 |
"""simple docstring"""
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
# Register SEW's fairseq modules
from sew_asapp import tasks # noqa: F401
from transformers import (
SEWConfig,
SEWForCTC,
SEWModel,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {
'''post_extract_proj''': '''feature_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.upsample.0''': '''encoder.upsample.projection''',
'''encoder.layer_norm''': '''encoder.layer_norm''',
'''w2v_model.layer_norm''': '''layer_norm''',
'''w2v_encoder.proj''': '''lm_head''',
'''mask_emb''': '''masked_spec_embed''',
}
def lowercase__ ( lowerCAmelCase : Tuple , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
for attribute in key.split('.' ):
UpperCAmelCase = getattr(lowerCAmelCase , lowerCAmelCase )
if weight_type is not None:
UpperCAmelCase = getattr(lowerCAmelCase , lowerCAmelCase ).shape
else:
UpperCAmelCase = 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 = value
elif weight_type == "weight_g":
UpperCAmelCase = value
elif weight_type == "weight_v":
UpperCAmelCase = value
elif weight_type == "bias":
UpperCAmelCase = value
else:
UpperCAmelCase = 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 : Optional[int] , lowerCAmelCase : List[str] ) -> Optional[Any]:
"""simple docstring"""
UpperCAmelCase = []
UpperCAmelCase = fairseq_model.state_dict()
UpperCAmelCase = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor
for name, value in fairseq_dict.items():
UpperCAmelCase = False
if "conv_layers" in name:
load_conv_layer(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , hf_model.config.feat_extract_norm == 'group' , )
UpperCAmelCase = True
else:
for key, mapped_key in MAPPING.items():
UpperCAmelCase = "sew." + 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]:
UpperCAmelCase = True
if "*" in mapped_key:
UpperCAmelCase = name.split(lowerCAmelCase )[0].split('.' )[-2]
UpperCAmelCase = mapped_key.replace('*' , lowerCAmelCase )
if "weight_g" in name:
UpperCAmelCase = "weight_g"
elif "weight_v" in name:
UpperCAmelCase = "weight_v"
elif "weight" in name:
UpperCAmelCase = "weight"
elif "bias" in name:
UpperCAmelCase = "bias"
else:
UpperCAmelCase = None
set_recursively(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
continue
if not is_used:
unused_weights.append(lowerCAmelCase )
logger.warning(F"Unused weights: {unused_weights}" )
def lowercase__ ( lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : str , lowerCAmelCase : List[Any] , lowerCAmelCase : Tuple ) -> Tuple:
"""simple docstring"""
UpperCAmelCase = full_name.split('conv_layers.' )[-1]
UpperCAmelCase = name.split('.' )
UpperCAmelCase = int(items[0] )
UpperCAmelCase = 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 = 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 = 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 = 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 = value
logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
else:
unused_weights.append(lowerCAmelCase )
def lowercase__ ( lowerCAmelCase : Dict , lowerCAmelCase : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
UpperCAmelCase = SEWConfig()
if is_finetuned:
UpperCAmelCase = model.wav_encoder.wav_model.cfg
else:
UpperCAmelCase = model.cfg
UpperCAmelCase = fs_config.conv_bias
UpperCAmelCase = eval(fs_config.conv_feature_layers )
UpperCAmelCase = [x[0] for x in conv_layers]
UpperCAmelCase = [x[1] for x in conv_layers]
UpperCAmelCase = [x[2] for x in conv_layers]
UpperCAmelCase = "gelu"
UpperCAmelCase = "layer" if fs_config.extractor_mode == "layer_norm" else "group"
UpperCAmelCase = 0.0
UpperCAmelCase = fs_config.activation_fn.name
UpperCAmelCase = fs_config.encoder_embed_dim
UpperCAmelCase = 0.02
UpperCAmelCase = fs_config.encoder_ffn_embed_dim
UpperCAmelCase = 1E-5
UpperCAmelCase = fs_config.encoder_layerdrop
UpperCAmelCase = fs_config.encoder_attention_heads
UpperCAmelCase = fs_config.conv_pos_groups
UpperCAmelCase = fs_config.conv_pos
UpperCAmelCase = len(lowerCAmelCase )
UpperCAmelCase = fs_config.encoder_layers
UpperCAmelCase = fs_config.squeeze_factor
# take care of any params that are overridden by the Wav2VecCtc model
if is_finetuned:
UpperCAmelCase = model.cfg
UpperCAmelCase = fs_config.final_dropout
UpperCAmelCase = fs_config.layerdrop
UpperCAmelCase = fs_config.activation_dropout
UpperCAmelCase = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
UpperCAmelCase = fs_config.attention_dropout
UpperCAmelCase = fs_config.dropout_input
UpperCAmelCase = fs_config.dropout
UpperCAmelCase = fs_config.mask_channel_length
UpperCAmelCase = fs_config.mask_channel_prob
UpperCAmelCase = fs_config.mask_length
UpperCAmelCase = fs_config.mask_prob
UpperCAmelCase = "Wav2Vec2FeatureExtractor"
UpperCAmelCase = "Wav2Vec2CTCTokenizer"
return config
@torch.no_grad()
def lowercase__ ( lowerCAmelCase : int , lowerCAmelCase : Dict , lowerCAmelCase : List[Any]=None , lowerCAmelCase : Union[str, Any]=None , lowerCAmelCase : List[str]=True ) -> List[str]:
"""simple docstring"""
if is_finetuned:
UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
if config_path is not None:
UpperCAmelCase = SEWConfig.from_pretrained(lowerCAmelCase )
else:
UpperCAmelCase = convert_config(model[0] , lowerCAmelCase )
UpperCAmelCase = model[0].eval()
UpperCAmelCase = True if config.feat_extract_norm == "layer" else False
UpperCAmelCase = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=lowerCAmelCase , return_attention_mask=lowerCAmelCase , )
if is_finetuned:
if dict_path:
UpperCAmelCase = Dictionary.load(lowerCAmelCase )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
UpperCAmelCase = target_dict.pad_index
UpperCAmelCase = target_dict.bos_index
UpperCAmelCase = target_dict.pad_index
UpperCAmelCase = target_dict.bos_index
UpperCAmelCase = target_dict.eos_index
UpperCAmelCase = len(target_dict.symbols )
UpperCAmelCase = 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 )
with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as vocab_handle:
json.dump(target_dict.indices , lowerCAmelCase )
UpperCAmelCase = WavaVecaCTCTokenizer(
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 = WavaVecaProcessor(feature_extractor=lowerCAmelCase , tokenizer=lowerCAmelCase )
processor.save_pretrained(lowerCAmelCase )
UpperCAmelCase = SEWForCTC(lowerCAmelCase )
else:
UpperCAmelCase = SEWModel(lowerCAmelCase )
feature_extractor.save_pretrained(lowerCAmelCase )
recursively_load_weights(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
hf_model.save_pretrained(lowerCAmelCase )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = 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(
'''--is_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
convert_sew_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
)
| 373 |
'''simple docstring'''
import inspect
import unittest
import numpy as np
from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor
if is_flax_available():
import jax
from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , lowerCamelCase , lowerCamelCase=100 , lowerCamelCase=13 , lowerCamelCase=30 , lowerCamelCase=2 , lowerCamelCase=3 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=10 , lowerCamelCase=0.02 , lowerCamelCase=3 , ):
'''simple docstring'''
__A : Tuple = parent
__A : Dict = vocab_size
__A : Union[str, Any] = batch_size
__A : str = image_size
__A : Optional[Any] = patch_size
__A : Optional[Any] = num_channels
__A : Optional[Any] = is_training
__A : Any = use_labels
__A : List[str] = hidden_size
__A : Union[str, Any] = num_hidden_layers
__A : Optional[Any] = num_attention_heads
__A : Optional[int] = intermediate_size
__A : Optional[int] = hidden_act
__A : Dict = hidden_dropout_prob
__A : str = attention_probs_dropout_prob
__A : Optional[int] = type_sequence_label_size
__A : Optional[int] = initializer_range
# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
__A : Optional[int] = (image_size // patch_size) ** 2
__A : Union[str, Any] = num_patches + 1
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__A : str = None
if self.use_labels:
__A : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__A : Dict = BeitConfig(
vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , 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 , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , )
return config, pixel_values, labels
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
__A : Optional[int] = FlaxBeitModel(config=lowerCamelCase )
__A : Optional[Any] = model(lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
__A : Dict = FlaxBeitForMaskedImageModeling(config=lowerCamelCase )
__A : Union[str, Any] = model(lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) )
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
__A : Any = self.type_sequence_label_size
__A : List[str] = FlaxBeitForImageClassification(config=lowerCamelCase )
__A : Tuple = model(lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
__A : Tuple = 1
__A : Optional[Any] = FlaxBeitForImageClassification(lowerCamelCase )
__A : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__A : str = model(lowerCamelCase )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Tuple = self.prepare_config_and_inputs()
(
(
__A
) ,(
__A
) ,(
__A
) ,
) : Dict = config_and_inputs
__A : Dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_flax
class __magic_name__ ( lowerCAmelCase , unittest.TestCase ):
"""simple docstring"""
lowerCamelCase__ = (
(FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
)
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Optional[int] = FlaxBeitModelTester(self )
__A : List[Any] = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A ,__A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : int = model_class(lowerCamelCase )
__A : Dict = inspect.signature(model.__call__ )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__A : List[str] = [*signature.parameters.keys()]
__A : Optional[Any] = ["pixel_values"]
self.assertListEqual(arg_names[:1] , lowerCamelCase )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A ,__A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
__A : Optional[int] = self._prepare_for_class(lowerCamelCase , lowerCamelCase )
__A : Optional[int] = model_class(lowerCamelCase )
@jax.jit
def model_jitted(lowerCamelCase , **lowerCamelCase ):
return model(pixel_values=lowerCamelCase , **lowerCamelCase )
with self.subTest("JIT Enabled" ):
__A : Tuple = model_jitted(**lowerCamelCase ).to_tuple()
with self.subTest("JIT Disabled" ):
with jax.disable_jit():
__A : Dict = model_jitted(**lowerCamelCase ).to_tuple()
self.assertEqual(len(lowerCamelCase ) , len(lowerCamelCase ) )
for jitted_output, output in zip(lowerCamelCase , lowerCamelCase ):
self.assertEqual(jitted_output.shape , output.shape )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase )
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCamelCase )
@slow
def lowerCAmelCase__ ( self ):
'''simple docstring'''
for model_class_name in self.all_model_classes:
__A : Any = model_class_name.from_pretrained("microsoft/beit-base-patch16-224" )
__A : Optional[int] = model(np.ones((1, 3, 224, 224) ) )
self.assertIsNotNone(lowerCamelCase )
def _lowercase ():
'''simple docstring'''
__A : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_vision
@require_flax
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def lowerCAmelCase__ ( self ):
'''simple docstring'''
return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None
@slow
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Union[str, Any] = FlaxBeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" )
__A : List[Any] = self.default_image_processor
__A : Dict = prepare_img()
__A : str = image_processor(images=lowerCamelCase , return_tensors="np" ).pixel_values
# prepare bool_masked_pos
__A : List[Any] = np.ones((1, 196) , dtype=lowerCamelCase )
# forward pass
__A : Union[str, Any] = model(pixel_values=lowerCamelCase , bool_masked_pos=lowerCamelCase )
__A : Dict = outputs.logits
# verify the logits
__A : int = (1, 196, 8192)
self.assertEqual(logits.shape , lowerCamelCase )
__A : Optional[int] = np.array(
[[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] )
self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , lowerCamelCase , atol=1E-2 ) )
@slow
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Union[str, Any] = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" )
__A : Any = self.default_image_processor
__A : List[Any] = prepare_img()
__A : List[Any] = image_processor(images=lowerCamelCase , return_tensors="np" )
# forward pass
__A : int = model(**lowerCamelCase )
__A : Any = outputs.logits
# verify the logits
__A : str = (1, 1000)
self.assertEqual(logits.shape , lowerCamelCase )
__A : int = np.array([-1.2385, -1.0987, -1.0108] )
self.assertTrue(np.allclose(logits[0, :3] , lowerCamelCase , atol=1E-4 ) )
__A : Optional[int] = 281
self.assertEqual(logits.argmax(-1 ).item() , lowerCamelCase )
@slow
def lowerCAmelCase__ ( self ):
'''simple docstring'''
__A : Any = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" )
__A : Optional[int] = self.default_image_processor
__A : Tuple = prepare_img()
__A : List[str] = image_processor(images=lowerCamelCase , return_tensors="np" )
# forward pass
__A : List[Any] = model(**lowerCamelCase )
__A : Dict = outputs.logits
# verify the logits
__A : Union[str, Any] = (1, 2_1841)
self.assertEqual(logits.shape , lowerCamelCase )
__A : Tuple = np.array([1.6881, -0.2787, 0.5901] )
self.assertTrue(np.allclose(logits[0, :3] , lowerCamelCase , atol=1E-4 ) )
__A : Optional[int] = 2396
self.assertEqual(logits.argmax(-1 ).item() , lowerCamelCase )
| 111 | 0 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
__UpperCamelCase : Optional[int] = logging.get_logger(__name__)
__UpperCamelCase : Any = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}
# See all BART models at https://huggingface.co/models?filter=bart
__UpperCamelCase : Tuple = {
'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',
},
}
__UpperCamelCase : int = {
'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,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
__lowerCamelCase : Optional[int] = (
list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) )
)
__lowerCamelCase : Optional[int] = bs[:]
__lowerCamelCase : Dict = 0
for b in range(2**8 ):
if b not in bs:
bs.append(UpperCAmelCase )
cs.append(2**8 + n )
n += 1
__lowerCamelCase : str = [chr(UpperCAmelCase ) for n in cs]
return dict(zip(UpperCAmelCase , UpperCAmelCase ) )
def _UpperCAmelCase ( UpperCAmelCase : int ):
"""simple docstring"""
__lowerCamelCase : Any = set()
__lowerCamelCase : Dict = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__lowerCamelCase : Any = char
return pairs
class _UpperCamelCase ( A ):
'''simple docstring'''
a_ : str = VOCAB_FILES_NAMES
a_ : str = PRETRAINED_VOCAB_FILES_MAP
a_ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a_ : List[Any] = ["input_ids", "attention_mask"]
def __init__( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any]="replace" , _lowerCamelCase : Optional[Any]="<s>" , _lowerCamelCase : Union[str, Any]="</s>" , _lowerCamelCase : List[Any]="</s>" , _lowerCamelCase : List[Any]="<s>" , _lowerCamelCase : Union[str, Any]="<unk>" , _lowerCamelCase : str="<pad>" , _lowerCamelCase : List[str]="<mask>" , _lowerCamelCase : Union[str, Any]=False , **_lowerCamelCase : Union[str, Any] , ):
'''simple docstring'''
__lowerCamelCase : Any = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else bos_token
__lowerCamelCase : Optional[int] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else eos_token
__lowerCamelCase : Optional[Any] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else sep_token
__lowerCamelCase : Tuple = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else cls_token
__lowerCamelCase : int = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else unk_token
__lowerCamelCase : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
__lowerCamelCase : Optional[Any] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token
super().__init__(
errors=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , add_prefix_space=_lowerCamelCase , **_lowerCamelCase , )
with open(_lowerCamelCase , encoding="""utf-8""" ) as vocab_handle:
__lowerCamelCase : Union[str, Any] = json.load(_lowerCamelCase )
__lowerCamelCase : Optional[int] = {v: k for k, v in self.encoder.items()}
__lowerCamelCase : Optional[Any] = errors # how to handle errors in decoding
__lowerCamelCase : int = bytes_to_unicode()
__lowerCamelCase : List[str] = {v: k for k, v in self.byte_encoder.items()}
with open(_lowerCamelCase , encoding="""utf-8""" ) as merges_handle:
__lowerCamelCase : int = merges_handle.read().split("""\n""" )[1:-1]
__lowerCamelCase : Tuple = [tuple(merge.split() ) for merge in bpe_merges]
__lowerCamelCase : int = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) )
__lowerCamelCase : Optional[int] = {}
__lowerCamelCase : str = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
__lowerCamelCase : Optional[Any] = re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" )
@property
def _snake_case ( self : Any ):
'''simple docstring'''
return len(self.encoder )
def _snake_case ( self : Tuple ):
'''simple docstring'''
return dict(self.encoder , **self.added_tokens_encoder )
def _snake_case ( self : Optional[int] , _lowerCamelCase : Dict ):
'''simple docstring'''
if token in self.cache:
return self.cache[token]
__lowerCamelCase : List[str] = tuple(_lowerCamelCase )
__lowerCamelCase : Tuple = get_pairs(_lowerCamelCase )
if not pairs:
return token
while True:
__lowerCamelCase : Union[str, Any] = min(_lowerCamelCase , key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase , float("""inf""" ) ) )
if bigram not in self.bpe_ranks:
break
__lowerCamelCase , __lowerCamelCase : Union[str, Any] = bigram
__lowerCamelCase : Union[str, Any] = []
__lowerCamelCase : Dict = 0
while i < len(_lowerCamelCase ):
try:
__lowerCamelCase : str = word.index(_lowerCamelCase , _lowerCamelCase )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
__lowerCamelCase : List[Any] = j
if word[i] == first and i < len(_lowerCamelCase ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
__lowerCamelCase : Any = tuple(_lowerCamelCase )
__lowerCamelCase : List[str] = new_word
if len(_lowerCamelCase ) == 1:
break
else:
__lowerCamelCase : Tuple = get_pairs(_lowerCamelCase )
__lowerCamelCase : Union[str, Any] = """ """.join(_lowerCamelCase )
__lowerCamelCase : Dict = word
return word
def _snake_case ( self : Dict , _lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
__lowerCamelCase : Dict = []
for token in re.findall(self.pat , _lowerCamelCase ):
__lowerCamelCase : Any = """""".join(
self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase ).split(""" """ ) )
return bpe_tokens
def _snake_case ( self : Optional[Any] , _lowerCamelCase : Optional[int] ):
'''simple docstring'''
return self.encoder.get(_lowerCamelCase , self.encoder.get(self.unk_token ) )
def _snake_case ( self : Dict , _lowerCamelCase : Dict ):
'''simple docstring'''
return self.decoder.get(_lowerCamelCase )
def _snake_case ( self : Any , _lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
__lowerCamelCase : Union[str, Any] = """""".join(_lowerCamelCase )
__lowerCamelCase : List[Any] = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors )
return text
def _snake_case ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ):
'''simple docstring'''
if not os.path.isdir(_lowerCamelCase ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
__lowerCamelCase : Optional[int] = os.path.join(
_lowerCamelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
__lowerCamelCase : Optional[int] = os.path.join(
_lowerCamelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] )
with open(_lowerCamelCase , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + """\n""" )
__lowerCamelCase : int = 0
with open(_lowerCamelCase , """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 _lowerCamelCase : 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!""" )
__lowerCamelCase : int = token_index
writer.write(""" """.join(_lowerCamelCase ) + """\n""" )
index += 1
return vocab_file, merge_file
def _snake_case ( self : Dict , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ):
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
__lowerCamelCase : Optional[Any] = [self.cls_token_id]
__lowerCamelCase : str = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def _snake_case ( self : Optional[Any] , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None , _lowerCamelCase : bool = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
if token_ids_a is None:
return [1] + ([0] * len(_lowerCamelCase )) + [1]
return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1]
def _snake_case ( self : List[Any] , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ):
'''simple docstring'''
__lowerCamelCase : str = [self.sep_token_id]
__lowerCamelCase : List[Any] = [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]
def _snake_case ( self : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : str=False , **_lowerCamelCase : str ):
'''simple docstring'''
__lowerCamelCase : Any = kwargs.pop("""add_prefix_space""" , self.add_prefix_space )
if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase ) > 0 and not text[0].isspace()):
__lowerCamelCase : int = """ """ + text
return (text, kwargs)
| 458 |
import copy
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
__UpperCamelCase : Optional[int] = logging.get_logger(__name__)
__UpperCamelCase : Any = {
'microsoft/conditional-detr-resnet-50': (
'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'
),
}
class _UpperCamelCase ( A ):
'''simple docstring'''
a_ : Optional[int] = "conditional_detr"
a_ : Union[str, Any] = ["past_key_values"]
a_ : str = {
"hidden_size": "d_model",
"num_attention_heads": "encoder_attention_heads",
}
def __init__( self : Dict , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : int=None , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : Tuple=3_0_0 , _lowerCamelCase : Any=6 , _lowerCamelCase : Union[str, Any]=2_0_4_8 , _lowerCamelCase : List[str]=8 , _lowerCamelCase : Any=6 , _lowerCamelCase : Any=2_0_4_8 , _lowerCamelCase : List[Any]=8 , _lowerCamelCase : Optional[int]=0.0 , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Tuple=True , _lowerCamelCase : Union[str, Any]="relu" , _lowerCamelCase : str=2_5_6 , _lowerCamelCase : int=0.1 , _lowerCamelCase : List[str]=0.0 , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : List[str]=0.02 , _lowerCamelCase : Union[str, Any]=1.0 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]="sine" , _lowerCamelCase : Optional[Any]="resnet50" , _lowerCamelCase : List[str]=True , _lowerCamelCase : Dict=False , _lowerCamelCase : Optional[int]=2 , _lowerCamelCase : Dict=5 , _lowerCamelCase : List[Any]=2 , _lowerCamelCase : Any=1 , _lowerCamelCase : Any=1 , _lowerCamelCase : Dict=2 , _lowerCamelCase : Dict=5 , _lowerCamelCase : Dict=2 , _lowerCamelCase : Union[str, Any]=0.25 , **_lowerCamelCase : Tuple , ):
'''simple docstring'''
if backbone_config is not None and use_timm_backbone:
raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" )
if not use_timm_backbone:
if backbone_config is None:
logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" )
__lowerCamelCase : Any = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] )
elif isinstance(_lowerCamelCase , _lowerCamelCase ):
__lowerCamelCase : str = backbone_config.get("""model_type""" )
__lowerCamelCase : Optional[Any] = CONFIG_MAPPING[backbone_model_type]
__lowerCamelCase : Optional[Any] = config_class.from_dict(_lowerCamelCase )
__lowerCamelCase : Optional[int] = use_timm_backbone
__lowerCamelCase : Union[str, Any] = backbone_config
__lowerCamelCase : List[Any] = num_channels
__lowerCamelCase : str = num_queries
__lowerCamelCase : Dict = d_model
__lowerCamelCase : List[Any] = encoder_ffn_dim
__lowerCamelCase : Optional[Any] = encoder_layers
__lowerCamelCase : Any = encoder_attention_heads
__lowerCamelCase : Dict = decoder_ffn_dim
__lowerCamelCase : List[str] = decoder_layers
__lowerCamelCase : Tuple = decoder_attention_heads
__lowerCamelCase : List[Any] = dropout
__lowerCamelCase : Any = attention_dropout
__lowerCamelCase : Optional[Any] = activation_dropout
__lowerCamelCase : List[str] = activation_function
__lowerCamelCase : Optional[int] = init_std
__lowerCamelCase : Union[str, Any] = init_xavier_std
__lowerCamelCase : Union[str, Any] = encoder_layerdrop
__lowerCamelCase : int = decoder_layerdrop
__lowerCamelCase : Dict = encoder_layers
__lowerCamelCase : Tuple = auxiliary_loss
__lowerCamelCase : Any = position_embedding_type
__lowerCamelCase : Tuple = backbone
__lowerCamelCase : int = use_pretrained_backbone
__lowerCamelCase : Tuple = dilation
# Hungarian matcher
__lowerCamelCase : Dict = class_cost
__lowerCamelCase : Optional[Any] = bbox_cost
__lowerCamelCase : Any = giou_cost
# Loss coefficients
__lowerCamelCase : Union[str, Any] = mask_loss_coefficient
__lowerCamelCase : List[Any] = dice_loss_coefficient
__lowerCamelCase : Any = cls_loss_coefficient
__lowerCamelCase : str = bbox_loss_coefficient
__lowerCamelCase : Dict = giou_loss_coefficient
__lowerCamelCase : List[str] = focal_alpha
super().__init__(is_encoder_decoder=_lowerCamelCase , **_lowerCamelCase )
@property
def _snake_case ( self : Union[str, Any] ):
'''simple docstring'''
return self.encoder_attention_heads
@property
def _snake_case ( self : Optional[Any] ):
'''simple docstring'''
return self.d_model
def _snake_case ( self : int ):
'''simple docstring'''
__lowerCamelCase : int = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
__lowerCamelCase : Dict = self.backbone_config.to_dict()
__lowerCamelCase : int = self.__class__.model_type
return output
class _UpperCamelCase ( A ):
'''simple docstring'''
a_ : Dict = version.parse("1.11" )
@property
def _snake_case ( self : Any ):
'''simple docstring'''
return OrderedDict(
[
("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
("""pixel_mask""", {0: """batch"""}),
] )
@property
def _snake_case ( self : Union[str, Any] ):
'''simple docstring'''
return 1E-5
@property
def _snake_case ( self : Tuple ):
'''simple docstring'''
return 1_2
| 458 | 1 |
from collections import defaultdict
def a__ ( lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =1
UpperCAmelCase_ =True
for v in tree[start]:
if v not in visited:
ret += dfs(lowercase__ )
if ret % 2 == 0:
cuts.append(lowercase__ )
return ret
def a__ ( ):
'''simple docstring'''
dfs(1 )
if __name__ == "__main__":
__lowercase , __lowercase : Any =10, 9
__lowercase : str =defaultdict(list)
__lowercase : dict[int, bool] ={}
__lowercase : list[int] =[]
__lowercase : List[str] =0
__lowercase : int =[(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)]
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
even_tree()
print(len(cuts) - 1)
| 54 |
'''simple docstring'''
import string
def a_ ( _lowerCAmelCase ) -> str:
__lowerCamelCase : Union[str, Any] = ''
for i in sequence:
__lowerCamelCase : Tuple = ord(_lowerCAmelCase )
if 65 <= extract <= 90:
output += chr(155 - extract )
elif 97 <= extract <= 122:
output += chr(219 - extract )
else:
output += i
return output
def a_ ( _lowerCAmelCase ) -> str:
__lowerCamelCase : Optional[Any] = string.ascii_letters
__lowerCamelCase : str = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(_lowerCAmelCase )] if c in letters else c for c in sequence )
def a_ ( ) -> None:
from timeit import timeit
print('Running performance benchmarks...' )
__lowerCamelCase : Tuple = 'from string import printable ; from __main__ import atbash, atbash_slow'
print(F'> atbash_slow(): {timeit("atbash_slow(printable)" ,setup=_lowerCAmelCase )} seconds' )
print(F'> atbash(): {timeit("atbash(printable)" ,setup=_lowerCAmelCase )} seconds' )
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f'''{example} encrypted in atbash: {atbash(example)}''')
benchmark()
| 459 | 0 |
'''simple docstring'''
def UpperCamelCase__ ( _lowercase : list[int] , _lowercase : list[int] ) -> None:
__UpperCAmelCase: Dict = len(_lowercase )
print("""The following activities are selected:""" )
# The first activity is always selected
__UpperCAmelCase: Dict = 0
print(_lowercase , end=""",""" )
# Consider rest of the activities
for j in range(_lowercase ):
# If this activity has start time greater than
# or equal to the finish time of previously
# selected activity, then select it
if start[j] >= finish[i]:
print(_lowercase , end=""",""" )
__UpperCAmelCase: Optional[int] = j
if __name__ == "__main__":
import doctest
doctest.testmod()
SCREAMING_SNAKE_CASE_ = [1, 3, 0, 5, 8, 5]
SCREAMING_SNAKE_CASE_ = [2, 4, 6, 7, 9, 9]
print_max_activities(start, finish) | 466 | '''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
SCREAMING_SNAKE_CASE_ = {
'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RemBertConfig', 'RemBertOnnxConfig']
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ['RemBertTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ['RemBertTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'RemBertForCausalLM',
'RemBertForMaskedLM',
'RemBertForMultipleChoice',
'RemBertForQuestionAnswering',
'RemBertForSequenceClassification',
'RemBertForTokenClassification',
'RemBertLayer',
'RemBertModel',
'RemBertPreTrainedModel',
'load_tf_weights_in_rembert',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFRemBertForCausalLM',
'TFRemBertForMaskedLM',
'TFRemBertForMultipleChoice',
'TFRemBertForQuestionAnswering',
'TFRemBertForSequenceClassification',
'TFRemBertForTokenClassification',
'TFRemBertLayer',
'TFRemBertModel',
'TFRemBertPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert import RemBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert_fast import RemBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_rembert import (
REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RemBertForCausalLM,
RemBertForMaskedLM,
RemBertForMultipleChoice,
RemBertForQuestionAnswering,
RemBertForSequenceClassification,
RemBertForTokenClassification,
RemBertLayer,
RemBertModel,
RemBertPreTrainedModel,
load_tf_weights_in_rembert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_rembert import (
TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRemBertForCausalLM,
TFRemBertForMaskedLM,
TFRemBertForMultipleChoice,
TFRemBertForQuestionAnswering,
TFRemBertForSequenceClassification,
TFRemBertForTokenClassification,
TFRemBertLayer,
TFRemBertModel,
TFRemBertPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 466 | 1 |
import math
import os
import unittest
from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
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 (
MODEL_FOR_PRETRAINING_MAPPING,
MegatronBertForCausalLM,
MegatronBertForMaskedLM,
MegatronBertForMultipleChoice,
MegatronBertForNextSentencePrediction,
MegatronBertForPreTraining,
MegatronBertForQuestionAnswering,
MegatronBertForSequenceClassification,
MegatronBertForTokenClassification,
MegatronBertModel,
)
class __magic_name__ :
"""simple docstring"""
def __init__( self : List[str] , _lowercase : List[str] , _lowercase : List[Any]=13 , _lowercase : Optional[int]=7 , _lowercase : str=True , _lowercase : Tuple=True , _lowercase : Any=True , _lowercase : List[Any]=True , _lowercase : Tuple=99 , _lowercase : Optional[Any]=64 , _lowercase : Optional[Any]=32 , _lowercase : Dict=5 , _lowercase : Tuple=4 , _lowercase : Union[str, Any]=37 , _lowercase : Union[str, Any]="gelu" , _lowercase : Dict=0.1 , _lowercase : Optional[int]=0.1 , _lowercase : Optional[int]=512 , _lowercase : Tuple=16 , _lowercase : Tuple=2 , _lowercase : List[str]=0.02 , _lowercase : Optional[int]=3 , _lowercase : Tuple=4 , _lowercase : int=None , ):
"""simple docstring"""
_UpperCamelCase: Union[str, Any] = parent
_UpperCamelCase: Optional[Any] = batch_size
_UpperCamelCase: List[Any] = seq_length
_UpperCamelCase: Tuple = is_training
_UpperCamelCase: str = use_input_mask
_UpperCamelCase: List[str] = use_token_type_ids
_UpperCamelCase: Union[str, Any] = use_labels
_UpperCamelCase: Any = vocab_size
_UpperCamelCase: Tuple = hidden_size
_UpperCamelCase: Optional[Any] = embedding_size
_UpperCamelCase: List[Any] = num_hidden_layers
_UpperCamelCase: Optional[int] = num_attention_heads
_UpperCamelCase: Dict = intermediate_size
_UpperCamelCase: Optional[int] = hidden_act
_UpperCamelCase: Tuple = hidden_dropout_prob
_UpperCamelCase: Optional[Any] = attention_probs_dropout_prob
_UpperCamelCase: List[str] = max_position_embeddings
_UpperCamelCase: List[str] = type_vocab_size
_UpperCamelCase: List[str] = type_sequence_label_size
_UpperCamelCase: Any = initializer_range
_UpperCamelCase: Optional[int] = num_labels
_UpperCamelCase: str = num_choices
_UpperCamelCase: Optional[Any] = scope
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
_UpperCamelCase: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_UpperCamelCase: List[Any] = None
if self.use_input_mask:
_UpperCamelCase: Optional[int] = random_attention_mask([self.batch_size, self.seq_length] )
_UpperCamelCase: Any = None
if self.use_token_type_ids:
_UpperCamelCase: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_UpperCamelCase: List[Any] = None
_UpperCamelCase: List[str] = None
_UpperCamelCase: int = None
if self.use_labels:
_UpperCamelCase: List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCamelCase: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_UpperCamelCase: Dict = ids_tensor([self.batch_size] , self.num_choices )
_UpperCamelCase: Optional[Any] = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCAmelCase ( self : Optional[int] ):
"""simple docstring"""
return MegatronBertConfig(
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 , embedding_size=self.embedding_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=__lowerCAmelCase , initializer_range=self.initializer_range , )
def lowerCAmelCase ( self : Union[str, Any] , _lowercase : Union[str, Any] , _lowercase : Tuple , _lowercase : Tuple , _lowercase : Optional[int] , _lowercase : int , _lowercase : Optional[Any] , _lowercase : Any ):
"""simple docstring"""
_UpperCamelCase: Union[str, Any] = MegatronBertModel(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: str = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )
_UpperCamelCase: int = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )
_UpperCamelCase: Dict = model(__lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def lowerCAmelCase ( self : List[str] , _lowercase : str , _lowercase : Optional[Any] , _lowercase : Tuple , _lowercase : Optional[int] , _lowercase : Dict , _lowercase : Optional[int] , _lowercase : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: List[Any] = MegatronBertForMaskedLM(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: List[str] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase ( self : Tuple , _lowercase : Dict , _lowercase : Any , _lowercase : List[str] , _lowercase : str , _lowercase : Dict , _lowercase : str , _lowercase : str ):
"""simple docstring"""
_UpperCamelCase: int = MegatronBertForCausalLM(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase ( self : Tuple , _lowercase : Union[str, Any] , _lowercase : List[str] , _lowercase : Union[str, Any] , _lowercase : Union[str, Any] , _lowercase : Optional[Any] , _lowercase : Optional[Any] , _lowercase : List[Any] ):
"""simple docstring"""
_UpperCamelCase: Any = MegatronBertForNextSentencePrediction(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: List[Any] = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def lowerCAmelCase ( self : Tuple , _lowercase : Optional[Any] , _lowercase : List[str] , _lowercase : str , _lowercase : Optional[int] , _lowercase : Optional[int] , _lowercase : List[Any] , _lowercase : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: List[Any] = MegatronBertForPreTraining(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: int = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , next_sentence_label=__lowerCAmelCase , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def lowerCAmelCase ( self : int , _lowercase : Tuple , _lowercase : Tuple , _lowercase : int , _lowercase : List[Any] , _lowercase : Union[str, Any] , _lowercase : Any , _lowercase : Dict ):
"""simple docstring"""
_UpperCamelCase: Optional[int] = MegatronBertForQuestionAnswering(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: Optional[int] = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , )
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 lowerCAmelCase ( self : Optional[Any] , _lowercase : Any , _lowercase : Dict , _lowercase : Optional[Any] , _lowercase : Tuple , _lowercase : str , _lowercase : Optional[Any] , _lowercase : Union[str, Any] ):
"""simple docstring"""
_UpperCamelCase: List[Any] = self.num_labels
_UpperCamelCase: List[str] = MegatronBertForSequenceClassification(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: Optional[Any] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCAmelCase ( self : Optional[Any] , _lowercase : Optional[int] , _lowercase : List[Any] , _lowercase : Union[str, Any] , _lowercase : int , _lowercase : Union[str, Any] , _lowercase : int , _lowercase : Optional[Any] ):
"""simple docstring"""
_UpperCamelCase: Tuple = self.num_labels
_UpperCamelCase: Dict = MegatronBertForTokenClassification(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCAmelCase ( self : str , _lowercase : Any , _lowercase : Union[str, Any] , _lowercase : Union[str, Any] , _lowercase : Tuple , _lowercase : Any , _lowercase : int , _lowercase : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: Optional[Any] = self.num_choices
_UpperCamelCase: Optional[int] = MegatronBertForMultipleChoice(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase: List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase: Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase: Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase: Dict = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowerCAmelCase ( self : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: List[str] = self.prepare_config_and_inputs()
(
_UpperCamelCase
): Any = config_and_inputs
_UpperCamelCase: int = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class __magic_name__ ( _a , _a , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase : Tuple = (
(
MegatronBertModel,
MegatronBertForMaskedLM,
MegatronBertForCausalLM,
MegatronBertForMultipleChoice,
MegatronBertForNextSentencePrediction,
MegatronBertForPreTraining,
MegatronBertForQuestionAnswering,
MegatronBertForSequenceClassification,
MegatronBertForTokenClassification,
)
if is_torch_available()
else ()
)
lowerCAmelCase : Any = (
{
'''feature-extraction''': MegatronBertModel,
'''fill-mask''': MegatronBertForMaskedLM,
'''question-answering''': MegatronBertForQuestionAnswering,
'''text-classification''': MegatronBertForSequenceClassification,
'''text-generation''': MegatronBertForCausalLM,
'''token-classification''': MegatronBertForTokenClassification,
'''zero-shot''': MegatronBertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowerCAmelCase : int = True
# test_resize_embeddings = False
lowerCAmelCase : Dict = False
def lowerCAmelCase ( self : List[Any] , _lowercase : Optional[int] , _lowercase : Tuple , _lowercase : Optional[Any]=False ):
"""simple docstring"""
_UpperCamelCase: List[str] = super()._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase )
if return_labels:
if model_class in get_values(__lowerCAmelCase ):
_UpperCamelCase: Dict = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowerCAmelCase )
_UpperCamelCase: List[Any] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase )
return inputs_dict
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase: str = MegatronBertModelTester(self )
_UpperCamelCase: Dict = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=37 )
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase: Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_model(*__lowerCAmelCase )
def lowerCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
_UpperCamelCase: List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowerCAmelCase )
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase: Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowerCAmelCase )
def lowerCAmelCase ( self : List[Any] ):
"""simple docstring"""
_UpperCamelCase: Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowerCAmelCase )
def lowerCAmelCase ( self : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowerCAmelCase )
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase: Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowerCAmelCase )
def lowerCAmelCase ( self : int ):
"""simple docstring"""
_UpperCamelCase: int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowerCAmelCase )
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
_UpperCamelCase: List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowerCAmelCase )
def lowerCAmelCase_ ( lowercase: Any ) -> int:
'''simple docstring'''
return torch.tensor(
_lowerCamelCase , dtype=torch.long , device=_lowerCamelCase , )
UpperCAmelCase_ = 1E-4
@require_torch
@require_sentencepiece
@require_tokenizers
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
@slow
@unittest.skip('''Model is not available.''' )
def lowerCAmelCase ( self : str ):
"""simple docstring"""
_UpperCamelCase: Optional[int] = "nvidia/megatron-bert-uncased-345m"
if "MYDIR" in os.environ:
_UpperCamelCase: Optional[int] = os.path.join(os.environ['''MYDIR'''] , __lowerCAmelCase )
_UpperCamelCase: Optional[int] = MegatronBertModel.from_pretrained(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.half()
_UpperCamelCase: Optional[int] = _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]] )
with torch.no_grad():
_UpperCamelCase: Any = model(__lowerCAmelCase )[0]
_UpperCamelCase: List[str] = torch.Size((1, 9, 1_024) )
self.assertEqual(output.shape , __lowerCAmelCase )
_UpperCamelCase: Any = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728]
for ii in range(3 ):
for jj in range(3 ):
_UpperCamelCase: str = output[0, ii, jj]
_UpperCamelCase: Optional[int] = expected[3 * ii + jj]
_UpperCamelCase: Union[str, Any] = "ii={} jj={} a={} b={}".format(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
self.assertTrue(math.isclose(__lowerCAmelCase , __lowerCAmelCase , rel_tol=__lowerCAmelCase , abs_tol=__lowerCAmelCase ) , msg=__lowerCAmelCase ) | 271 |
"""simple docstring"""
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
_lowerCAmelCase : List[str] = 10
def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int:
'''simple docstring'''
for i in range(_lowerCamelCase , _lowerCamelCase ):
if array[i] == target:
return i
return -1
def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> int:
'''simple docstring'''
_lowerCamelCase : List[str] = 0
_lowerCamelCase : Any = len(_lowerCamelCase )
while left <= right:
if right - left < precision:
return lin_search(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
_lowerCamelCase : str = (left + right) // 3 + 1
_lowerCamelCase : List[str] = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
_lowerCamelCase : Union[str, Any] = one_third - 1
elif array[two_third] < target:
_lowerCamelCase : Any = two_third + 1
else:
_lowerCamelCase : List[str] = one_third + 1
_lowerCamelCase : int = two_third - 1
else:
return -1
def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int:
'''simple docstring'''
if left < right:
if right - left < precision:
return lin_search(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
_lowerCamelCase : Tuple = (left + right) // 3 + 1
_lowerCamelCase : Optional[Any] = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(_lowerCamelCase , one_third - 1 , _lowerCamelCase , _lowerCamelCase )
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , _lowerCamelCase , _lowerCamelCase )
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowerCAmelCase : Optional[Any] = input('''Enter numbers separated by comma:\n''').strip()
_lowerCAmelCase : Optional[Any] = [int(item.strip()) for item in user_input.split(''',''')]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
_lowerCAmelCase : Any = int(input('''Enter the number to be found in the list:\n''').strip())
_lowerCAmelCase : Union[str, Any] = ite_ternary_search(collection, target)
_lowerCAmelCase : str = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f'''Iterative search: {target} found at positions: {resulta}''')
print(f'''Recursive search: {target} found at positions: {resulta}''')
else:
print('''Not found''') | 46 | 0 |
"""simple docstring"""
from __future__ import annotations
def _snake_case ( UpperCAmelCase_ : list ):
if len(UpperCAmelCase_ ) == 0:
return []
A__ , A__ = min(UpperCAmelCase_ ), max(UpperCAmelCase_ )
A__ = int(max_value - min_value ) + 1
A__ = [[] for _ in range(UpperCAmelCase_ )]
for i in my_list:
buckets[int(i - min_value )].append(UpperCAmelCase_ )
return [v for bucket in buckets for v in sorted(UpperCAmelCase_ )]
if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
| 500 |
"""simple docstring"""
import unittest
from transformers import (
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TextaTextGenerationPipeline,
pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available
from .test_pipelines_common import ANY
if is_torch_available():
import torch
@is_pipeline_test
class a ( unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
UpperCAmelCase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def UpperCamelCase ( self: Dict , UpperCamelCase: str , UpperCamelCase: Optional[Any] , UpperCamelCase: Any ):
"""simple docstring"""
A__ = TextaTextGenerationPipeline(model=UpperCamelCase , tokenizer=UpperCamelCase )
return generator, ["Something to write", "Something else"]
def UpperCamelCase ( self: List[Any] , UpperCamelCase: Any , UpperCamelCase: Dict ):
"""simple docstring"""
A__ = generator("""Something there""" )
self.assertEqual(UpperCamelCase , [{"""generated_text""": ANY(UpperCamelCase )}] )
# These are encoder decoder, they don't just append to incoming string
self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) )
A__ = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=UpperCamelCase )
self.assertEqual(
UpperCamelCase , [
[{"""generated_text""": ANY(UpperCamelCase )}, {"""generated_text""": ANY(UpperCamelCase )}],
[{"""generated_text""": ANY(UpperCamelCase )}, {"""generated_text""": ANY(UpperCamelCase )}],
] , )
A__ = generator(
["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=UpperCamelCase )
self.assertEqual(
UpperCamelCase , [
[{"""generated_text""": ANY(UpperCamelCase )}, {"""generated_text""": ANY(UpperCamelCase )}],
[{"""generated_text""": ANY(UpperCamelCase )}, {"""generated_text""": ANY(UpperCamelCase )}],
] , )
with self.assertRaises(UpperCamelCase ):
generator(4 )
@require_torch
def UpperCamelCase ( self: Optional[Any] ):
"""simple docstring"""
A__ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""" )
# do_sample=False necessary for reproducibility
A__ = generator("""Something there""" , do_sample=UpperCamelCase )
self.assertEqual(UpperCamelCase , [{"""generated_text""": """"""}] )
A__ = 3
A__ = generator(
"""Something there""" , num_return_sequences=UpperCamelCase , num_beams=UpperCamelCase , )
A__ = [
{"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""},
{"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""},
{"""generated_text""": """"""},
]
self.assertEqual(UpperCamelCase , UpperCamelCase )
A__ = generator("""This is a test""" , do_sample=UpperCamelCase , num_return_sequences=2 , return_tensors=UpperCamelCase )
self.assertEqual(
UpperCamelCase , [
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
] , )
A__ = generator.model.config.eos_token_id
A__ = """<pad>"""
A__ = generator(
["""This is a test""", """This is a second test"""] , do_sample=UpperCamelCase , num_return_sequences=2 , batch_size=2 , return_tensors=UpperCamelCase , )
self.assertEqual(
UpperCamelCase , [
[
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
],
[
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
],
] , )
@require_tf
def UpperCamelCase ( self: Any ):
"""simple docstring"""
A__ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""" )
# do_sample=False necessary for reproducibility
A__ = generator("""Something there""" , do_sample=UpperCamelCase )
self.assertEqual(UpperCamelCase , [{"""generated_text""": """"""}] )
| 500 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
a_ = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = ['MBartTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = ['MBartTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
'MBART_PRETRAINED_MODEL_ARCHIVE_LIST',
'MBartForCausalLM',
'MBartForConditionalGeneration',
'MBartForQuestionAnswering',
'MBartForSequenceClassification',
'MBartModel',
'MBartPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
'TFMBartForConditionalGeneration',
'TFMBartModel',
'TFMBartPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
'FlaxMBartForConditionalGeneration',
'FlaxMBartForQuestionAnswering',
'FlaxMBartForSequenceClassification',
'FlaxMBartModel',
'FlaxMBartPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart import MBartTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart_fast import MBartTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mbart import (
MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
MBartForCausalLM,
MBartForConditionalGeneration,
MBartForQuestionAnswering,
MBartForSequenceClassification,
MBartModel,
MBartPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mbart import (
FlaxMBartForConditionalGeneration,
FlaxMBartForQuestionAnswering,
FlaxMBartForSequenceClassification,
FlaxMBartModel,
FlaxMBartPreTrainedModel,
)
else:
import sys
a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 417 | import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a_ = logging.get_logger(__name__)
a_ = '▁'
a_ = {'vocab_file': 'spiece.model'}
a_ = {
'vocab_file': {
'google/reformer-crime-and-punishment': (
'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'
)
}
}
a_ = {
'google/reformer-crime-and-punishment': 524_288,
}
class _lowercase ( snake_case_ ):
lowercase = VOCAB_FILES_NAMES
lowercase = PRETRAINED_VOCAB_FILES_MAP
lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase = ['input_ids', 'attention_mask']
def __init__( self : Any , snake_case : List[Any] , snake_case : Any="</s>" , snake_case : Optional[Any]="<unk>" , snake_case : str=[] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : str , ) -> None:
"""simple docstring"""
UpperCamelCase_ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=snake_case , unk_token=snake_case , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , )
UpperCamelCase_ : Dict = vocab_file
UpperCamelCase_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(snake_case )
@property
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Optional[Any]:
"""simple docstring"""
return self.sp_model.get_piece_size()
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Dict[str, int]:
"""simple docstring"""
UpperCamelCase_ : List[str] = {self.convert_ids_to_tokens(snake_case ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Tuple ) -> List[str]:
"""simple docstring"""
UpperCamelCase_ : Dict = self.__dict__.copy()
UpperCamelCase_ : Any = None
return state
def __setstate__( self : Optional[Any] , snake_case : Any ) -> Dict:
"""simple docstring"""
UpperCamelCase_ : Dict = d
# for backward compatibility
if not hasattr(self , 'sp_model_kwargs' ):
UpperCamelCase_ : Optional[int] = {}
UpperCamelCase_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : str ) -> List[str]:
"""simple docstring"""
return self.sp_model.encode(snake_case , out_type=snake_case )
def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Optional[int] ) -> int:
"""simple docstring"""
return self.sp_model.piece_to_id(snake_case )
def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Union[str, Any] ) -> str:
"""simple docstring"""
if index < self.sp_model.get_piece_size():
UpperCamelCase_ : Tuple = self.sp_model.IdToPiece(snake_case )
return token
def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : List[Any] ) -> List[Any]:
"""simple docstring"""
UpperCamelCase_ : Any = []
UpperCamelCase_ : Tuple = ''
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(snake_case ) + token
UpperCamelCase_ : int = []
else:
current_sub_tokens.append(snake_case )
out_string += self.sp_model.decode(snake_case )
return out_string.strip()
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : str , snake_case : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(snake_case ):
logger.error(f"Vocabulary path ({save_directory}) should be a directory" )
return
UpperCamelCase_ : Union[str, Any] = os.path.join(
snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , snake_case )
elif not os.path.isfile(self.vocab_file ):
with open(snake_case , 'wb' ) as fi:
UpperCamelCase_ : str = self.sp_model.serialized_model_proto()
fi.write(snake_case )
return (out_vocab_file,)
| 417 | 1 |
import gc
import threading
import time
import psutil
import torch
class lowercase_ :
def __init__( self: Optional[int]):
'''simple docstring'''
__lowerCAmelCase = psutil.Process()
__lowerCAmelCase = False
def _lowercase ( self: Dict):
'''simple docstring'''
__lowerCAmelCase = -1
while True:
__lowerCAmelCase = max(self.process.memory_info().rss, self.cpu_memory_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
if not self.peak_monitoring:
break
def _lowercase ( self: List[Any]):
'''simple docstring'''
__lowerCAmelCase = True
__lowerCAmelCase = threading.Thread(target=self.peak_monitor)
__lowerCAmelCase = True
self.thread.start()
def _lowercase ( self: str):
'''simple docstring'''
__lowerCAmelCase = False
self.thread.join()
return self.cpu_memory_peak
__A : int = PeakCPUMemory()
def UpperCAmelCase ( ) -> List[Any]:
'''simple docstring'''
__lowerCAmelCase = {"""time""": time.time()}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
__lowerCAmelCase = psutil.Process().memory_info().rss
cpu_peak_tracker.start()
# GPU mem
for i in range(torch.cuda.device_count() ):
__lowerCAmelCase = torch.cuda.memory_allocated(UpperCamelCase__ )
torch.cuda.reset_peak_memory_stats()
return measures
def UpperCAmelCase ( UpperCamelCase__ ) -> int:
'''simple docstring'''
__lowerCAmelCase = {"""time""": time.time() - start_measures["""time"""]}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
__lowerCAmelCase = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20
__lowerCAmelCase = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20
# GPU mem
for i in range(torch.cuda.device_count() ):
__lowerCAmelCase = (torch.cuda.memory_allocated(UpperCamelCase__ ) - start_measures[str(UpperCamelCase__ )]) / 2**20
__lowerCAmelCase = (torch.cuda.max_memory_allocated(UpperCamelCase__ ) - start_measures[str(UpperCamelCase__ )]) / 2**20
return measures
def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict:
'''simple docstring'''
print(F'''{description}:''' )
print(F'''- Time: {measures['time']:.2f}s''' )
for i in range(torch.cuda.device_count() ):
print(F'''- GPU {i} allocated: {measures[str(UpperCamelCase__ )]:.2f}MiB''' )
__lowerCAmelCase = measures[F'''{i}-peak''']
print(F'''- GPU {i} peak: {peak:.2f}MiB''' )
print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''' )
print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''' )
| 334 |
import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path
import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized
from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available
from ..wavaveca.test_feature_extraction_wavaveca import floats_list
if is_pyctcdecode_available():
from huggingface_hub import snapshot_download
from pyctcdecode import BeamSearchDecoderCTC
from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput
if is_torch_available():
from transformers import WavaVecaForCTC
@require_pyctcdecode
class lowercase_ ( unittest.TestCase ):
def _lowercase ( self: Union[str, Any]):
'''simple docstring'''
__lowerCAmelCase = """| <pad> <unk> <s> </s> a b c d e f g h i j k""".split()
__lowerCAmelCase = dict(zip(_lowercase, range(len(_lowercase))))
__lowerCAmelCase = {
"""unk_token""": """<unk>""",
"""bos_token""": """<s>""",
"""eos_token""": """</s>""",
}
__lowerCAmelCase = {
"""feature_size""": 1,
"""padding_value""": 0.0,
"""sampling_rate""": 16000,
"""return_attention_mask""": False,
"""do_normalize""": True,
}
__lowerCAmelCase = tempfile.mkdtemp()
__lowerCAmelCase = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""])
__lowerCAmelCase = os.path.join(self.tmpdirname, _lowercase)
with open(self.vocab_file, """w""", encoding="""utf-8""") as fp:
fp.write(json.dumps(_lowercase) + """\n""")
with open(self.feature_extraction_file, """w""", encoding="""utf-8""") as fp:
fp.write(json.dumps(_lowercase) + """\n""")
# load decoder from hub
__lowerCAmelCase = """hf-internal-testing/ngram-beam-search-decoder"""
def _lowercase ( self: Tuple, **_lowercase: str):
'''simple docstring'''
__lowerCAmelCase = self.add_kwargs_tokens_map.copy()
kwargs.update(_lowercase)
return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname, **_lowercase)
def _lowercase ( self: Tuple, **_lowercase: Dict):
'''simple docstring'''
return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname, **_lowercase)
def _lowercase ( self: str, **_lowercase: List[str]):
'''simple docstring'''
return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name, **_lowercase)
def _lowercase ( self: Union[str, Any]):
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def _lowercase ( self: List[Any]):
'''simple docstring'''
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
processor.save_pretrained(self.tmpdirname)
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname)
# tokenizer
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab())
self.assertIsInstance(processor.tokenizer, _lowercase)
# feature extractor
self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string())
self.assertIsInstance(processor.feature_extractor, _lowercase)
# decoder
self.assertEqual(processor.decoder._alphabet.labels, decoder._alphabet.labels)
self.assertEqual(
processor.decoder.model_container[decoder._model_key]._unigram_set, decoder.model_container[decoder._model_key]._unigram_set, )
self.assertIsInstance(processor.decoder, _lowercase)
def _lowercase ( self: List[str]):
'''simple docstring'''
__lowerCAmelCase = WavaVecaProcessorWithLM(
tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder())
processor.save_pretrained(self.tmpdirname)
# make sure that error is thrown when decoder alphabet doesn't match
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained(
self.tmpdirname, alpha=5.0, beta=3.0, score_boundary=-7.0, unk_score_offset=3)
# decoder
self.assertEqual(processor.language_model.alpha, 5.0)
self.assertEqual(processor.language_model.beta, 3.0)
self.assertEqual(processor.language_model.score_boundary, -7.0)
self.assertEqual(processor.language_model.unk_score_offset, 3)
def _lowercase ( self: Tuple):
'''simple docstring'''
__lowerCAmelCase = self.get_tokenizer()
# add token to trigger raise
tokenizer.add_tokens(["""xx"""])
with self.assertRaisesRegex(_lowercase, """include"""):
WavaVecaProcessorWithLM(
tokenizer=_lowercase, feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder())
def _lowercase ( self: Union[str, Any]):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = floats_list((3, 1000))
__lowerCAmelCase = feature_extractor(_lowercase, return_tensors="""np""")
__lowerCAmelCase = processor(_lowercase, 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: int):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = """This is a test string"""
__lowerCAmelCase = processor(text=_lowercase)
__lowerCAmelCase = tokenizer(_lowercase)
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key], encoded_processor[key])
def _lowercase ( self: List[Any], _lowercase: str=(2, 10, 16), _lowercase: str=77):
'''simple docstring'''
np.random.seed(_lowercase)
return np.random.rand(*_lowercase)
def _lowercase ( self: List[str]):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = self._get_dummy_logits(shape=(10, 16), seed=13)
__lowerCAmelCase = processor.decode(_lowercase)
__lowerCAmelCase = decoder.decode_beams(_lowercase)[0]
self.assertEqual(decoded_decoder[0], decoded_processor.text)
self.assertEqual("""</s> <s> </s>""", decoded_processor.text)
self.assertEqual(decoded_decoder[-2], decoded_processor.logit_score)
self.assertEqual(decoded_decoder[-1], decoded_processor.lm_score)
@parameterized.expand([[None], ["""fork"""], ["""spawn"""]])
def _lowercase ( self: List[Any], _lowercase: Optional[int]):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = self._get_dummy_logits()
# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
# otherwise, the LM won't be available to the pool's sub-processes.
# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
if pool_context is None:
__lowerCAmelCase = processor.batch_decode(_lowercase)
else:
with get_context(_lowercase).Pool() as pool:
__lowerCAmelCase = processor.batch_decode(_lowercase, _lowercase)
__lowerCAmelCase = list(_lowercase)
with get_context("""fork""").Pool() as p:
__lowerCAmelCase = decoder.decode_beams_batch(_lowercase, _lowercase)
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = [], [], []
for beams in decoded_beams:
texts_decoder.append(beams[0][0])
logit_scores_decoder.append(beams[0][-2])
lm_scores_decoder.append(beams[0][-1])
self.assertListEqual(_lowercase, decoded_processor.text)
self.assertListEqual(["""<s> <s> </s>""", """<s> <s> <s>"""], decoded_processor.text)
self.assertListEqual(_lowercase, decoded_processor.logit_score)
self.assertListEqual(_lowercase, decoded_processor.lm_score)
def _lowercase ( self: Dict):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = self._get_dummy_logits()
__lowerCAmelCase = 15
__lowerCAmelCase = -20.0
__lowerCAmelCase = -4.0
__lowerCAmelCase = processor.batch_decode(
_lowercase, beam_width=_lowercase, beam_prune_logp=_lowercase, token_min_logp=_lowercase, )
__lowerCAmelCase = decoded_processor_out.text
__lowerCAmelCase = list(_lowercase)
with get_context("""fork""").Pool() as pool:
__lowerCAmelCase = decoder.decode_beams_batch(
_lowercase, _lowercase, beam_width=_lowercase, beam_prune_logp=_lowercase, token_min_logp=_lowercase, )
__lowerCAmelCase = [d[0][0] for d in decoded_decoder_out]
__lowerCAmelCase = [d[0][2] for d in decoded_decoder_out]
__lowerCAmelCase = [d[0][3] for d in decoded_decoder_out]
self.assertListEqual(_lowercase, _lowercase)
self.assertListEqual(["""</s> <s> <s>""", """<s> <s> <s>"""], _lowercase)
self.assertTrue(np.array_equal(_lowercase, decoded_processor_out.logit_score))
self.assertTrue(np.allclose([-20.054, -18.447], _lowercase, atol=1e-3))
self.assertTrue(np.array_equal(_lowercase, decoded_processor_out.lm_score))
self.assertTrue(np.allclose([-15.554, -13.9_474], _lowercase, atol=1e-3))
def _lowercase ( self: Optional[int]):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
__lowerCAmelCase = self._get_dummy_logits()
__lowerCAmelCase = 2.0
__lowerCAmelCase = 5.0
__lowerCAmelCase = -20.0
__lowerCAmelCase = True
__lowerCAmelCase = processor.batch_decode(
_lowercase, alpha=_lowercase, beta=_lowercase, unk_score_offset=_lowercase, lm_score_boundary=_lowercase, )
__lowerCAmelCase = decoded_processor_out.text
__lowerCAmelCase = list(_lowercase)
decoder.reset_params(
alpha=_lowercase, beta=_lowercase, unk_score_offset=_lowercase, lm_score_boundary=_lowercase, )
with get_context("""fork""").Pool() as pool:
__lowerCAmelCase = decoder.decode_beams_batch(
_lowercase, _lowercase, )
__lowerCAmelCase = [d[0][0] for d in decoded_decoder_out]
self.assertListEqual(_lowercase, _lowercase)
self.assertListEqual(["""<s> </s> <s> </s> </s>""", """</s> </s> <s> </s> </s>"""], _lowercase)
__lowerCAmelCase = processor.decoder.model_container[processor.decoder._model_key]
self.assertEqual(lm_model.alpha, 2.0)
self.assertEqual(lm_model.beta, 5.0)
self.assertEqual(lm_model.unk_score_offset, -20.0)
self.assertEqual(lm_model.score_boundary, _lowercase)
def _lowercase ( self: Any):
'''simple docstring'''
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = processor.decoder.model_container[processor.decoder._model_key]
__lowerCAmelCase = Path(language_model._kenlm_model.path.decode("""utf-8""")).parent.parent.absolute()
__lowerCAmelCase = os.listdir(_lowercase)
__lowerCAmelCase = ["""alphabet.json""", """language_model"""]
downloaded_decoder_files.sort()
expected_decoder_files.sort()
# test that only decoder relevant files from
# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
# are downloaded and none of the rest (e.g. README.md, ...)
self.assertListEqual(_lowercase, _lowercase)
def _lowercase ( self: Any):
'''simple docstring'''
__lowerCAmelCase = snapshot_download("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained(_lowercase)
__lowerCAmelCase = processor.decoder.model_container[processor.decoder._model_key]
__lowerCAmelCase = Path(language_model._kenlm_model.path.decode("""utf-8""")).parent.parent.absolute()
__lowerCAmelCase = os.listdir(_lowercase)
__lowerCAmelCase = os.listdir(_lowercase)
local_decoder_files.sort()
expected_decoder_files.sort()
# test that both decoder form hub and local files in cache are the same
self.assertListEqual(_lowercase, _lowercase)
def _lowercase ( self: Any):
'''simple docstring'''
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = AutoProcessor.from_pretrained("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = floats_list((3, 1000))
__lowerCAmelCase = processor_wavaveca(_lowercase, return_tensors="""np""")
__lowerCAmelCase = processor_auto(_lowercase, return_tensors="""np""")
for key in input_wavaveca.keys():
self.assertAlmostEqual(input_wavaveca[key].sum(), input_auto[key].sum(), delta=1e-2)
__lowerCAmelCase = self._get_dummy_logits()
__lowerCAmelCase = processor_wavaveca.batch_decode(_lowercase)
__lowerCAmelCase = processor_auto.batch_decode(_lowercase)
self.assertListEqual(decoded_wavaveca.text, decoded_auto.text)
def _lowercase ( self: Union[str, Any]):
'''simple docstring'''
__lowerCAmelCase = self.get_feature_extractor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_decoder()
__lowerCAmelCase = WavaVecaProcessorWithLM(tokenizer=_lowercase, feature_extractor=_lowercase, decoder=_lowercase)
self.assertListEqual(
processor.model_input_names, feature_extractor.model_input_names, msg="""`processor` and `feature_extractor` model input names do not match""", )
@staticmethod
def _lowercase ( _lowercase: List[Any], _lowercase: str):
'''simple docstring'''
__lowerCAmelCase = [d[key] for d in offsets]
return retrieved_list
def _lowercase ( self: List[Any]):
'''simple docstring'''
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = self._get_dummy_logits()[0]
__lowerCAmelCase = processor.decode(_lowercase, output_word_offsets=_lowercase)
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys()), 4)
self.assertTrue("""text""" in outputs)
self.assertTrue("""word_offsets""" in outputs)
self.assertTrue(isinstance(_lowercase, _lowercase))
self.assertEqual(""" """.join(self.get_from_offsets(outputs["""word_offsets"""], """word""")), outputs.text)
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""], """word"""), ["""<s>""", """<s>""", """</s>"""])
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""], """start_offset"""), [0, 2, 4])
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""], """end_offset"""), [1, 3, 5])
def _lowercase ( self: Union[str, Any]):
'''simple docstring'''
__lowerCAmelCase = WavaVecaProcessorWithLM.from_pretrained("""hf-internal-testing/processor_with_lm""")
__lowerCAmelCase = self._get_dummy_logits()
__lowerCAmelCase = processor.batch_decode(_lowercase, output_word_offsets=_lowercase)
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys()), 4)
self.assertTrue("""text""" in outputs)
self.assertTrue("""word_offsets""" in outputs)
self.assertTrue(isinstance(_lowercase, _lowercase))
self.assertListEqual(
[""" """.join(self.get_from_offsets(_lowercase, """word""")) for o in outputs["""word_offsets"""]], outputs.text)
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0], """word"""), ["""<s>""", """<s>""", """</s>"""])
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0], """start_offset"""), [0, 2, 4])
self.assertListEqual(self.get_from_offsets(outputs["""word_offsets"""][0], """end_offset"""), [1, 3, 5])
@slow
@require_torch
@require_torchaudio
def _lowercase ( self: Optional[int]):
'''simple docstring'''
import torch
__lowerCAmelCase = load_dataset("""common_voice""", """en""", split="""train""", streaming=_lowercase)
__lowerCAmelCase = ds.cast_column("""audio""", datasets.Audio(sampling_rate=16000))
__lowerCAmelCase = iter(_lowercase)
__lowerCAmelCase = next(_lowercase)
__lowerCAmelCase = AutoProcessor.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""")
__lowerCAmelCase = WavaVecaForCTC.from_pretrained("""patrickvonplaten/wav2vec2-base-100h-with-lm""")
# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
__lowerCAmelCase = processor(sample["""audio"""]["""array"""], return_tensors="""pt""").input_values
with torch.no_grad():
__lowerCAmelCase = model(_lowercase).logits.cpu().numpy()
__lowerCAmelCase = processor.decode(logits[0], output_word_offsets=_lowercase)
__lowerCAmelCase = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
__lowerCAmelCase = [
{
"""start_time""": d["""start_offset"""] * time_offset,
"""end_time""": d["""end_offset"""] * time_offset,
"""word""": d["""word"""],
}
for d in output["""word_offsets"""]
]
__lowerCAmelCase = """WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL"""
# output words
self.assertEqual(""" """.join(self.get_from_offsets(_lowercase, """word""")), _lowercase)
self.assertEqual(""" """.join(self.get_from_offsets(_lowercase, """word""")), output.text)
# output times
__lowerCAmelCase = torch.tensor(self.get_from_offsets(_lowercase, """start_time"""))
__lowerCAmelCase = torch.tensor(self.get_from_offsets(_lowercase, """end_time"""))
# fmt: off
__lowerCAmelCase = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599])
__lowerCAmelCase = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94])
# fmt: on
self.assertTrue(torch.allclose(_lowercase, _lowercase, atol=0.01))
self.assertTrue(torch.allclose(_lowercase, _lowercase, atol=0.01))
| 334 | 1 |
'''simple docstring'''
def __lowerCamelCase ( _UpperCamelCase : int ):
'''simple docstring'''
UpperCAmelCase_ = [1]
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = 0, 0, 0
UpperCAmelCase_ = ugly_nums[ia] * 2
UpperCAmelCase_ = ugly_nums[ia] * 3
UpperCAmelCase_ = ugly_nums[ia] * 5
for _ in range(1 , _UpperCamelCase ):
UpperCAmelCase_ = min(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
ugly_nums.append(_UpperCamelCase )
if next_num == next_a:
ia += 1
UpperCAmelCase_ = ugly_nums[ia] * 2
if next_num == next_a:
ia += 1
UpperCAmelCase_ = ugly_nums[ia] * 3
if next_num == next_a:
ia += 1
UpperCAmelCase_ = ugly_nums[ia] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(F'''{ugly_numbers(200) = }''')
| 390 | '''simple docstring'''
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP
| 390 | 1 |
'''simple docstring'''
import math
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 0 ) -> list:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : str = end or len(SCREAMING_SNAKE_CASE__ )
for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
SCREAMING_SNAKE_CASE__ : Optional[int] = i
SCREAMING_SNAKE_CASE__ : str = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
SCREAMING_SNAKE_CASE__ : int = array[temp_index - 1]
temp_index -= 1
SCREAMING_SNAKE_CASE__ : str = temp_index_value
return array
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Max Heap
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Tuple = index
SCREAMING_SNAKE_CASE__ : List[str] = 2 * index + 1 # Left Node
SCREAMING_SNAKE_CASE__ : int = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
SCREAMING_SNAKE_CASE__ : Tuple = left_index
if right_index < heap_size and array[largest] < array[right_index]:
SCREAMING_SNAKE_CASE__ : str = right_index
if largest != index:
SCREAMING_SNAKE_CASE__ : Optional[Any] = array[largest], array[index]
heapify(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _a ( SCREAMING_SNAKE_CASE__ : list ) -> list:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = len(SCREAMING_SNAKE_CASE__ )
for i in range(n // 2 , -1 , -1 ):
heapify(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for i in range(n - 1 , 0 , -1 ):
SCREAMING_SNAKE_CASE__ : Optional[int] = array[0], array[i]
heapify(SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ )
return array
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int:
'''simple docstring'''
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Tuple = low
SCREAMING_SNAKE_CASE__ : Union[str, Any] = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
SCREAMING_SNAKE_CASE__ : int = array[j], array[i]
i += 1
def _a ( SCREAMING_SNAKE_CASE__ : list ) -> list:
'''simple docstring'''
if len(SCREAMING_SNAKE_CASE__ ) == 0:
return array
SCREAMING_SNAKE_CASE__ : str = 2 * math.ceil(math.loga(len(SCREAMING_SNAKE_CASE__ ) ) )
SCREAMING_SNAKE_CASE__ : List[str] = 16
return intro_sort(SCREAMING_SNAKE_CASE__ , 0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _a ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> list:
'''simple docstring'''
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(SCREAMING_SNAKE_CASE__ )
max_depth -= 1
SCREAMING_SNAKE_CASE__ : Dict = median_of_a(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , start + ((end - start) // 2) + 1 , end - 1 )
SCREAMING_SNAKE_CASE__ : Tuple = partition(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
intro_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : List[Any] = p
return insertion_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowerCamelCase : List[Any] = input('''Enter numbers separated by a comma : ''').strip()
_lowerCamelCase : Dict = [float(item) for item in user_input.split(''',''')]
print(sort(unsorted))
| 715 |
import pytest
from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
"split_dict" , [
SplitDict(),
SplitDict({"train": SplitInfo(name="train" , num_bytes=13_37 , num_examples=42 , dataset_name="my_dataset" )} ),
SplitDict({"train": SplitInfo(name="train" , num_bytes=13_37 , num_examples=42 )} ),
SplitDict({"train": SplitInfo()} ),
] , )
def _a ( SCREAMING_SNAKE_CASE__ : SplitDict ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : str = split_dict._to_yaml_list()
assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = SplitDict._from_yaml_list(SCREAMING_SNAKE_CASE__ )
for split_name, split_info in split_dict.items():
# dataset_name field is deprecated, and is therefore not part of the YAML dump
SCREAMING_SNAKE_CASE__ : Dict = None
# the split name of split_dict takes over the name of the split info object
SCREAMING_SNAKE_CASE__ : List[str] = split_name
assert split_dict == reloaded
@pytest.mark.parametrize(
"split_info" , [SplitInfo(), SplitInfo(dataset_name=SCREAMING_SNAKE_CASE__ ), SplitInfo(dataset_name="my_dataset" )] )
def _a ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Dict = asdict(SplitDict({"train": split_info} ) )
assert "dataset_name" in split_dict_asdict["train"]
assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
| 157 | 0 |
'''simple docstring'''
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
SCREAMING_SNAKE_CASE = get_tests_dir("""fixtures""")
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = mock.Mock()
UpperCAmelCase__ : str = 5_00
UpperCAmelCase__ : Dict = {}
UpperCAmelCase__ : Optional[Any] = HTTPError
UpperCAmelCase__ : Union[str, Any] = {}
# Download this model to make sure it's in the cache.
UpperCAmelCase__ : List[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=snake_case__ ) as mock_head:
UpperCAmelCase__ : Tuple = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" )
# This check we did call the fake head request
mock_head.assert_called()
def UpperCamelCase ( self : int ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = 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 UpperCamelCase ( cls : List[str] ):
'''simple docstring'''
UpperCAmelCase__ : Dict = TOKEN
HfFolder.save_token(snake_case__ )
@classmethod
def UpperCamelCase ( cls : List[str] ):
'''simple docstring'''
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 UpperCamelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase__ : str = WavaVecaFeatureExtractor.from_pretrained(snake_case__ )
feature_extractor.push_to_hub("test-feature-extractor" , use_auth_token=self._token )
UpperCAmelCase__ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" )
for k, v in feature_extractor.__dict__.items():
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
# 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(
snake_case__ , repo_id="test-feature-extractor" , push_to_hub=snake_case__ , use_auth_token=self._token )
UpperCAmelCase__ : int = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" )
for k, v in feature_extractor.__dict__.items():
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
def UpperCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : int = WavaVecaFeatureExtractor.from_pretrained(snake_case__ )
feature_extractor.push_to_hub("valid_org/test-feature-extractor" , use_auth_token=self._token )
UpperCAmelCase__ : Optional[int] = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor" )
for k, v in feature_extractor.__dict__.items():
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
# 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(
snake_case__ , repo_id="valid_org/test-feature-extractor-org" , push_to_hub=snake_case__ , use_auth_token=self._token )
UpperCAmelCase__ : str = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org" )
for k, v in feature_extractor.__dict__.items():
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
def UpperCamelCase ( self : List[Any] ):
'''simple docstring'''
CustomFeatureExtractor.register_for_auto_class()
UpperCAmelCase__ : Optional[int] = CustomFeatureExtractor.from_pretrained(snake_case__ )
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"} , )
UpperCAmelCase__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained(
F"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=snake_case__ )
# 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" )
| 199 | from __future__ import annotations
import math
import numpy as np
from numpy.linalg import norm
def lowerCamelCase ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray ) -> float:
return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(UpperCamelCase , UpperCamelCase ) ) )
def lowerCamelCase ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray ) -> list[list[list[float] | float]]:
if dataset.ndim != value_array.ndim:
_lowerCamelCase = (
'Wrong input data\'s dimensions... '
F"""dataset : {dataset.ndim}, value_array : {value_array.ndim}"""
)
raise ValueError(UpperCamelCase )
try:
if dataset.shape[1] != value_array.shape[1]:
_lowerCamelCase = (
'Wrong input data\'s shape... '
F"""dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}"""
)
raise ValueError(UpperCamelCase )
except IndexError:
if dataset.ndim != value_array.ndim:
raise TypeError('Wrong shape' )
if dataset.dtype != value_array.dtype:
_lowerCamelCase = (
'Input data have different datatype... '
F"""dataset : {dataset.dtype}, value_array : {value_array.dtype}"""
)
raise TypeError(UpperCamelCase )
_lowerCamelCase = []
for value in value_array:
_lowerCamelCase = euclidean(UpperCamelCase , dataset[0] )
_lowerCamelCase = dataset[0].tolist()
for dataset_value in dataset[1:]:
_lowerCamelCase = euclidean(UpperCamelCase , UpperCamelCase )
if dist > temp_dist:
_lowerCamelCase = temp_dist
_lowerCamelCase = dataset_value.tolist()
answer.append([vector, dist] )
return answer
def lowerCamelCase ( UpperCamelCase : np.ndarray , UpperCamelCase : np.ndarray ) -> float:
return np.dot(UpperCamelCase , UpperCamelCase ) / (norm(UpperCamelCase ) * norm(UpperCamelCase ))
if __name__ == "__main__":
import doctest
doctest.testmod() | 544 | 0 |
"""simple docstring"""
def lowerCamelCase_ ( UpperCAmelCase_ ) ->list:
"""simple docstring"""
if len(UpperCAmelCase_ ) < 2:
return collection
def circle_sort_util(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) -> bool:
__UpperCAmelCase : Union[str, Any] = False
if low == high:
return swapped
__UpperCAmelCase : Dict = low
__UpperCAmelCase : Union[str, Any] = high
while left < right:
if collection[left] > collection[right]:
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = (
collection[right],
collection[left],
)
__UpperCAmelCase : List[Any] = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
__UpperCAmelCase , __UpperCAmelCase : List[str] = (
collection[right + 1],
collection[left],
)
__UpperCAmelCase : int = True
__UpperCAmelCase : Optional[Any] = low + int((high - low) / 2 )
__UpperCAmelCase : Optional[int] = circle_sort_util(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
__UpperCAmelCase : Any = circle_sort_util(UpperCAmelCase_ , mid + 1 , UpperCAmelCase_ )
return swapped or left_swap or right_swap
__UpperCAmelCase : Union[str, Any] = True
while is_not_sorted is True:
__UpperCAmelCase : int = circle_sort_util(UpperCAmelCase_ , 0 , len(UpperCAmelCase_ ) - 1 )
return collection
if __name__ == "__main__":
lowercase__ :List[str] = input('Enter numbers separated by a comma:\n').strip()
lowercase__ :Union[str, Any] = [int(item) for item in user_input.split(',')]
print(circle_sort(unsorted)) | 374 |
"""simple docstring"""
import gc
import unittest
from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class snake_case ( unittest.TestCase ):
'''simple docstring'''
def A_ ( self : str ):
'''simple docstring'''
super().tearDown()
gc.collect()
def A_ ( self : List[Any] ):
'''simple docstring'''
__UpperCAmelCase , __UpperCAmelCase : List[Any] = FlaxStableDiffusionPipeline.from_pretrained(
'''stabilityai/stable-diffusion-2''' , revision='''bf16''' , dtype=jnp.bfloataa , )
__UpperCAmelCase : Dict = '''A painting of a squirrel eating a burger'''
__UpperCAmelCase : Any = jax.device_count()
__UpperCAmelCase : Optional[int] = num_samples * [prompt]
__UpperCAmelCase : Tuple = sd_pipe.prepare_inputs(__lowercase )
__UpperCAmelCase : List[Any] = replicate(__lowercase )
__UpperCAmelCase : Optional[Any] = shard(__lowercase )
__UpperCAmelCase : str = jax.random.PRNGKey(0 )
__UpperCAmelCase : Dict = jax.random.split(__lowercase , jax.device_count() )
__UpperCAmelCase : Tuple = sd_pipe(__lowercase , __lowercase , __lowercase , num_inference_steps=25 , jit=__lowercase )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
__UpperCAmelCase : Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__UpperCAmelCase : Union[str, Any] = images[0, 253:256, 253:256, -1]
__UpperCAmelCase : str = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__UpperCAmelCase : List[Any] = jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] )
print(f'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
def A_ ( self : Union[str, Any] ):
'''simple docstring'''
__UpperCAmelCase : Optional[int] = '''stabilityai/stable-diffusion-2'''
__UpperCAmelCase , __UpperCAmelCase : Any = FlaxDPMSolverMultistepScheduler.from_pretrained(__lowercase , subfolder='''scheduler''' )
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = FlaxStableDiffusionPipeline.from_pretrained(
__lowercase , scheduler=__lowercase , revision='''bf16''' , dtype=jnp.bfloataa , )
__UpperCAmelCase : Dict = scheduler_params
__UpperCAmelCase : int = '''A painting of a squirrel eating a burger'''
__UpperCAmelCase : List[Any] = jax.device_count()
__UpperCAmelCase : Optional[int] = num_samples * [prompt]
__UpperCAmelCase : Tuple = sd_pipe.prepare_inputs(__lowercase )
__UpperCAmelCase : Optional[int] = replicate(__lowercase )
__UpperCAmelCase : List[Any] = shard(__lowercase )
__UpperCAmelCase : Union[str, Any] = jax.random.PRNGKey(0 )
__UpperCAmelCase : List[Any] = jax.random.split(__lowercase , jax.device_count() )
__UpperCAmelCase : List[Any] = sd_pipe(__lowercase , __lowercase , __lowercase , num_inference_steps=25 , jit=__lowercase )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
__UpperCAmelCase : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__UpperCAmelCase : Any = images[0, 253:256, 253:256, -1]
__UpperCAmelCase : List[str] = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__UpperCAmelCase : Any = jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] )
print(f'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 | 374 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
a = logging.get_logger(__name__)
a = {
"""microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""",
}
class UpperCAmelCase_ (snake_case__ , snake_case__ ):
"""simple docstring"""
lowerCamelCase : Dict = 'resnet'
lowerCamelCase : int = ['basic', 'bottleneck']
def __init__( self: int , _UpperCAmelCase: Union[str, Any]=3 , _UpperCAmelCase: Optional[Any]=64 , _UpperCAmelCase: Optional[int]=[256, 512, 1024, 2048] , _UpperCAmelCase: Union[str, Any]=[3, 4, 6, 3] , _UpperCAmelCase: Optional[int]="bottleneck" , _UpperCAmelCase: str="relu" , _UpperCAmelCase: Dict=False , _UpperCAmelCase: List[str]=None , _UpperCAmelCase: str=None , **_UpperCAmelCase: Optional[Any] , ):
super().__init__(**_UpperCAmelCase )
if layer_type not in self.layer_types:
raise ValueError(f"""layer_type={layer_type} is not one of {",".join(self.layer_types )}""" )
_lowerCAmelCase :Tuple = num_channels
_lowerCAmelCase :Union[str, Any] = embedding_size
_lowerCAmelCase :Any = hidden_sizes
_lowerCAmelCase :List[str] = depths
_lowerCAmelCase :Dict = layer_type
_lowerCAmelCase :int = hidden_act
_lowerCAmelCase :Optional[Any] = downsample_in_first_stage
_lowerCAmelCase :List[str] = ['stem'] + [f"""stage{idx}""" for idx in range(1 , len(_UpperCAmelCase ) + 1 )]
_lowerCAmelCase , _lowerCAmelCase :Any = get_aligned_output_features_output_indices(
out_features=_UpperCAmelCase , out_indices=_UpperCAmelCase , stage_names=self.stage_names )
class UpperCAmelCase_ (snake_case__ ):
"""simple docstring"""
lowerCamelCase : Dict = version.parse('1.11' )
@property
def SCREAMING_SNAKE_CASE__ ( self: str ):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def SCREAMING_SNAKE_CASE__ ( self: Optional[Any] ):
return 1e-3 | 687 |
import unittest
import numpy as np
import torch
from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad
class UpperCAmelCase_ (unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE__ ( self: int ):
_lowerCAmelCase :Optional[int] = 10
def SCREAMING_SNAKE_CASE__ ( self: Optional[Any] ):
_lowerCAmelCase :str = [1, 2, 3, 4]
_lowerCAmelCase :Union[str, Any] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
self.assertEqual(truncate_or_pad(_UpperCAmelCase , self.block_size , 0 ) , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE__ ( self: int ):
_lowerCAmelCase :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_lowerCAmelCase :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(_UpperCAmelCase , self.block_size , 0 ) , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE__ ( self: Optional[int] ):
_lowerCAmelCase :Dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
_lowerCAmelCase :Optional[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(_UpperCAmelCase , self.block_size , 0 ) , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE__ ( self: List[str] ):
_lowerCAmelCase :List[str] = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.'
_lowerCAmelCase , _lowerCAmelCase :Optional[Any] = process_story(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , [] )
def SCREAMING_SNAKE_CASE__ ( self: Any ):
_lowerCAmelCase :Optional[int] = ''
_lowerCAmelCase , _lowerCAmelCase :str = process_story(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , [] )
self.assertEqual(_UpperCAmelCase , [] )
def SCREAMING_SNAKE_CASE__ ( self: str ):
_lowerCAmelCase :Optional[Any] = (
'It was the year of Our Lord one thousand seven hundred and '
'seventy-five\n\nSpiritual revelations were conceded to England '
'at that favoured period, as at this.\n@highlight\n\nIt was the best of times'
)
_lowerCAmelCase , _lowerCAmelCase :Optional[int] = process_story(_UpperCAmelCase )
_lowerCAmelCase :Optional[Any] = [
'It was the year of Our Lord one thousand seven hundred and seventy-five.',
'Spiritual revelations were conceded to England at that favoured period, as at this.',
]
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
_lowerCAmelCase :Optional[int] = ['It was the best of times.']
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE__ ( self: Tuple ):
_lowerCAmelCase :Union[str, Any] = torch.tensor([1, 2, 3, 4] )
_lowerCAmelCase :List[Any] = torch.tensor([1, 1, 1, 1] )
np.testing.assert_array_equal(build_mask(_UpperCAmelCase , 0 ).numpy() , expected.numpy() )
def SCREAMING_SNAKE_CASE__ ( self: Optional[int] ):
_lowerCAmelCase :List[Any] = torch.tensor([1, 2, 3, 4, 23, 23, 23] )
_lowerCAmelCase :Optional[int] = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(_UpperCAmelCase , 23 ).numpy() , expected.numpy() )
def SCREAMING_SNAKE_CASE__ ( self: Optional[Any] ):
_lowerCAmelCase :Tuple = torch.tensor([8, 2, 3, 4, 1, 1, 1] )
_lowerCAmelCase :List[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(_UpperCAmelCase , 1 ).numpy() , expected.numpy() )
def SCREAMING_SNAKE_CASE__ ( self: str ):
_lowerCAmelCase :List[str] = 101
_lowerCAmelCase :Dict = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] )
_lowerCAmelCase :int = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] )
_lowerCAmelCase :List[str] = compute_token_type_ids(_UpperCAmelCase , _UpperCAmelCase )
np.testing.assert_array_equal(_UpperCAmelCase , _UpperCAmelCase ) | 687 | 1 |
"""simple docstring"""
import math
def lowerCamelCase__ ( _lowerCamelCase : int ) -> bool:
return math.sqrt(_lowerCamelCase ) * math.sqrt(_lowerCamelCase ) == num
def lowerCamelCase__ ( _lowerCamelCase : int ) -> bool:
lowerCamelCase_ = 0
lowerCamelCase_ = n
while left <= right:
lowerCamelCase_ = (left + right) // 2
if mid**2 == n:
return True
elif mid**2 > n:
lowerCamelCase_ = mid - 1
else:
lowerCamelCase_ = mid + 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 720 |
"""simple docstring"""
import math
import os
import re
import sys
import unittest
from pathlib import Path
from typing import Tuple
from unittest.mock import patch
from parameterized import parameterized
from transformers.testing_utils import (
CaptureStderr,
ExtendSysPath,
TestCasePlus,
execute_subprocess_async,
get_gpu_count,
get_torch_dist_unique_port,
require_apex,
require_bitsandbytes,
require_fairscale,
require_torch,
require_torch_gpu,
require_torch_multi_gpu,
require_torch_non_multi_gpu,
slow,
)
from transformers.trainer_callback import TrainerState
from transformers.trainer_utils import set_seed
_SCREAMING_SNAKE_CASE : List[Any] = os.path.abspath(os.path.dirname(__file__))
with ExtendSysPath(F'''{bindir}/../../examples/pytorch/translation'''):
from run_translation import main # noqa
set_seed(42)
_SCREAMING_SNAKE_CASE : List[str] = '''sshleifer/student_marian_en_ro_6_1'''
_SCREAMING_SNAKE_CASE : List[Any] = '''sshleifer/tiny-mbart'''
@require_torch
class a ( __snake_case ):
def UpperCamelCase ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : str=True , ) -> int:
lowerCamelCase_ = self.run_trainer(
eval_steps=1 , max_len=12 , model_name=__SCREAMING_SNAKE_CASE , num_train_epochs=1 , distributed=__SCREAMING_SNAKE_CASE , extra_args_str=__SCREAMING_SNAKE_CASE , predict_with_generate=__SCREAMING_SNAKE_CASE , do_train=__SCREAMING_SNAKE_CASE , do_eval=__SCREAMING_SNAKE_CASE , do_predict=__SCREAMING_SNAKE_CASE , )
lowerCamelCase_ = TrainerState.load_from_json(os.path.join(__SCREAMING_SNAKE_CASE , 'trainer_state.json' ) ).log_history
if not do_eval:
return
lowerCamelCase_ = [log for log in logs if 'eval_loss' in log.keys()]
lowerCamelCase_ = eval_metrics[0]
if predict_with_generate:
assert "eval_bleu" in first_step_stats
lowerCamelCase_ = eval_metrics[-1]
assert isinstance(last_step_stats['eval_bleu'] , __SCREAMING_SNAKE_CASE )
assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`"
@require_torch_non_multi_gpu
def UpperCamelCase ( self : Dict ) -> Any:
self.run_seqaseq_quick()
@require_torch_multi_gpu
def UpperCamelCase ( self : str ) -> List[Any]:
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE )
@require_torch_multi_gpu
def UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]:
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE )
@unittest.skip('Requires an update of the env running those tests' )
@require_torch_multi_gpu
@require_fairscale
def UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]:
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--sharded_ddp simple' )
@unittest.skip('Requires an update of the env running those tests' )
@require_torch_multi_gpu
@require_fairscale
def UpperCamelCase ( self : str ) -> List[Any]:
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--sharded_ddp simple --fp16' )
@unittest.skip('Requires an update of the env running those tests' )
@require_torch_multi_gpu
@require_fairscale
def UpperCamelCase ( self : Any ) -> int:
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--sharded_ddp zero_dp_2' , predict_with_generate=__SCREAMING_SNAKE_CASE )
@unittest.skip('Requires an update of the env running those tests' )
@require_torch_multi_gpu
@require_fairscale
def UpperCamelCase ( self : List[Any] ) -> Optional[Any]:
self.run_seqaseq_quick(
distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--sharded_ddp zero_dp_2 --fp16' , predict_with_generate=__SCREAMING_SNAKE_CASE )
@require_apex
@require_torch_gpu
def UpperCamelCase ( self : List[Any] ) -> List[str]:
# XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same
# program and it breaks other tests that run from the same pytest worker, therefore until this is
# sorted out it must be run only in an external program, that is distributed=True in this
# test and only under one or more gpus - if we want cpu will need to make a special test
#
# specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via
# 2nd main() call it botches the future eval.
#
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--fp16 --fp16_backend=apex' )
# test 2nd time - was getting eval_loss': nan'
# to reproduce the problem set distributed=False
self.run_seqaseq_quick(distributed=__SCREAMING_SNAKE_CASE , extra_args_str='--fp16 --fp16_backend=apex' )
@parameterized.expand(['base', 'low', 'high', 'mixed'] )
@require_torch_multi_gpu
def UpperCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple:
# as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout
lowerCamelCase_ = {
# test with the default log_level - should be info and thus log info once
'base': {'extra_args_str': '', 'n_matches': 1},
# test with low log_level and log_level_replica - should be noisy on all processes
# now the info string should appear twice on 2 processes
'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2},
# test with high log_level and low log_level_replica
# now the info string should appear once only on the replica
'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1},
# test with high log_level and log_level_replica - should be quiet on all processes
'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0},
}
lowerCamelCase_ = experiments[experiment_id]
lowerCamelCase_ = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False}
lowerCamelCase_ = 'Running training'
with CaptureStderr() as cl:
self.run_seqaseq_quick(**__SCREAMING_SNAKE_CASE , extra_args_str=data['extra_args_str'] )
lowerCamelCase_ = len(re.findall(__SCREAMING_SNAKE_CASE , cl.err ) )
self.assertEqual(__SCREAMING_SNAKE_CASE , data['n_matches'] )
@slow
def UpperCamelCase ( self : int ) -> str:
lowerCamelCase_ = self.run_trainer(
eval_steps=2 , max_len=128 , model_name=__SCREAMING_SNAKE_CASE , learning_rate=3e-4 , num_train_epochs=10 , distributed=__SCREAMING_SNAKE_CASE , )
# Check metrics
lowerCamelCase_ = TrainerState.load_from_json(os.path.join(__SCREAMING_SNAKE_CASE , 'trainer_state.json' ) ).log_history
lowerCamelCase_ = [log for log in logs if 'eval_loss' in log.keys()]
lowerCamelCase_ = eval_metrics[0]
lowerCamelCase_ = eval_metrics[-1]
assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing"
assert isinstance(last_step_stats['eval_bleu'] , __SCREAMING_SNAKE_CASE )
# test if do_predict saves generations and metrics
lowerCamelCase_ = os.listdir(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = {os.path.basename(__SCREAMING_SNAKE_CASE ) for p in contents}
assert "generated_predictions.txt" in contents
assert "predict_results.json" in contents
@slow
@require_bitsandbytes
def UpperCamelCase ( self : Union[str, Any] ) -> Optional[Any]:
from transformers.training_args import OptimizerNames
def train_and_return_metrics(__SCREAMING_SNAKE_CASE : str ) -> Tuple[int, float]:
lowerCamelCase_ = '--skip_memory_metrics 0'
lowerCamelCase_ = self.run_trainer(
max_len=128 , model_name=__SCREAMING_SNAKE_CASE , learning_rate=3e-4 , num_train_epochs=1 , optim=__SCREAMING_SNAKE_CASE , distributed=__SCREAMING_SNAKE_CASE , extra_args_str=__SCREAMING_SNAKE_CASE , do_eval=__SCREAMING_SNAKE_CASE , do_predict=__SCREAMING_SNAKE_CASE , n_gpus_to_use=1 , )
# Check metrics
lowerCamelCase_ = TrainerState.load_from_json(Path(__SCREAMING_SNAKE_CASE , 'trainer_state.json' ) ).log_history
lowerCamelCase_ = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 )
lowerCamelCase_ = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 )
lowerCamelCase_ = logs[0]['train_loss']
return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value )
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value )
lowerCamelCase_ = gpu_alloc_mem_orig - gpu_alloc_mem_bnb
lowerCamelCase_ = gpu_peak_mem_orig + gpu_alloc_mem_orig
lowerCamelCase_ = gpu_peak_mem_bnb + gpu_alloc_mem_bnb
lowerCamelCase_ = gpu_total_mem_orig - gpu_total_mem_bnb
# sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which
# doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized
# in 2 bytes and the diff in optim memory usage is derived as so:
#
# - normal 25*8=~200MB (8 bytes per param)
# - bnb 25*2= ~50MB (2 bytes per param)
#
# Thus we should expect ~150MB total memory saved.
#
# Peak memory should be the same - the total should be different by about that same margin
#
# After leaving a small margin to accommodate for differences between gpus let's check
# that we have at least 120MB in savings
lowerCamelCase_ = 120
# uncomment the following if this test starts failing - requires py38 for a new print feature
# gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb
# print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB")
# print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB")
# print(f"{gpu_alloc_mem_diff=}MB")
# print(f"{gpu_peak_mem_diff=}MB")
# print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB")
# print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB")
self.assertGreater(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got'
F''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and'''
F''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , )
self.assertGreater(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got'
F''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and'''
F''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , )
self.assertEqual(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , F'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' )
def UpperCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : float = 3e-3 , __SCREAMING_SNAKE_CASE : str = "adafactor" , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : str = None , __SCREAMING_SNAKE_CASE : int = 0 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : int = None , ) -> Optional[int]:
lowerCamelCase_ = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro'
lowerCamelCase_ = self.get_auto_remove_tmp_dir()
lowerCamelCase_ = F'''
--model_name_or_path {model_name}
--train_file {data_dir}/train.json
--validation_file {data_dir}/val.json
--test_file {data_dir}/test.json
--output_dir {output_dir}
--overwrite_output_dir
--max_train_samples 8
--max_source_length {max_len}
--max_target_length {max_len}
--do_train
--num_train_epochs {str(__SCREAMING_SNAKE_CASE )}
--per_device_train_batch_size 4
--learning_rate {learning_rate}
--warmup_steps 8
--logging_steps 0
--logging_strategy no
--save_steps {str(__SCREAMING_SNAKE_CASE )}
--group_by_length
--label_smoothing_factor 0.1
--target_lang ro_RO
--source_lang en_XX
'''.split()
lowerCamelCase_ = F'''
--do_eval
--per_device_eval_batch_size 4
--max_eval_samples 8
--val_max_target_length {max_len}
--evaluation_strategy steps
--eval_steps {str(__SCREAMING_SNAKE_CASE )}
'''.split()
lowerCamelCase_ = '\n --do_predict\n '.split()
lowerCamelCase_ = []
if do_train:
args += args_train
if do_eval:
args += args_eval
if do_predict:
args += args_predict
if predict_with_generate:
args += "--predict_with_generate".split()
if do_train:
if optim == "adafactor":
args += "--adafactor".split()
else:
args += F'''--optim {optim}'''.split()
if extra_args_str is not None:
args += extra_args_str.split()
if distributed:
if n_gpus_to_use is None:
lowerCamelCase_ = get_gpu_count()
lowerCamelCase_ = get_torch_dist_unique_port()
lowerCamelCase_ = F'''
-m torch.distributed.run
--nproc_per_node={n_gpus_to_use}
--master_port={master_port}
{self.examples_dir_str}/pytorch/translation/run_translation.py
'''.split()
lowerCamelCase_ = [sys.executable] + distributed_args + args
# keep for quick debug
# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=self.get_env() )
else:
lowerCamelCase_ = ['run_translation.py'] + args
with patch.object(__SCREAMING_SNAKE_CASE , 'argv' , __SCREAMING_SNAKE_CASE ):
main()
return output_dir
| 137 | 0 |
"""simple docstring"""
import math
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(__snake_case ) + 1 ), 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def lowerCamelCase__ ( __snake_case = 1_00_01 ) -> int:
"""simple docstring"""
try:
_UpperCamelCase = int(__snake_case )
except (TypeError, ValueError):
raise TypeError('''Parameter nth must be int or castable to int.''' ) from None
if nth <= 0:
raise ValueError('''Parameter nth must be greater than or equal to one.''' )
_UpperCamelCase = []
_UpperCamelCase = 2
while len(__snake_case ) < nth:
if is_prime(__snake_case ):
primes.append(__snake_case )
num += 1
else:
num += 1
return primes[len(__snake_case ) - 1]
if __name__ == "__main__":
print(F"""{solution() = }""")
| 19 |
"""simple docstring"""
from datasets.utils.patching import _PatchedModuleObj, patch_submodule
from . import _test_patching
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
import os as original_os
from os import path as original_path
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
_UpperCamelCase = '''__test_patch_submodule_mock__'''
with patch_submodule(_test_patching, '''os.path.join''', __snake_case ):
# Every way to access os.path.join must be patched, and the rest must stay untouched
# check os.path.join
assert isinstance(_test_patching.os, _PatchedModuleObj )
assert isinstance(_test_patching.os.path, _PatchedModuleObj )
assert _test_patching.os.path.join is mock
# check path.join
assert isinstance(_test_patching.path, _PatchedModuleObj )
assert _test_patching.path.join is mock
# check join
assert _test_patching.join is mock
# check that the other attributes are untouched
assert _test_patching.os.rename is original_rename
assert _test_patching.path.dirname is original_dirname
assert _test_patching.os.path.dirname is original_dirname
# Even renamed modules or objects must be patched
# check renamed_os.path.join
assert isinstance(_test_patching.renamed_os, _PatchedModuleObj )
assert isinstance(_test_patching.renamed_os.path, _PatchedModuleObj )
assert _test_patching.renamed_os.path.join is mock
# check renamed_path.join
assert isinstance(_test_patching.renamed_path, _PatchedModuleObj )
assert _test_patching.renamed_path.join is mock
# check renamed_join
assert _test_patching.renamed_join is mock
# check that the other attributes are untouched
assert _test_patching.renamed_os.rename is original_rename
assert _test_patching.renamed_path.dirname is original_dirname
assert _test_patching.renamed_os.path.dirname is original_dirname
# check that everthing is back to normal when the patch is over
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
assert _test_patching.open is open
_UpperCamelCase = '''__test_patch_submodule_builtin_mock__'''
# _test_patching has "open" in its globals
assert _test_patching.open is open
with patch_submodule(_test_patching, '''open''', __snake_case ):
assert _test_patching.open is mock
# check that everthing is back to normal when the patch is over
assert _test_patching.open is open
def lowerCamelCase__ ( ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = '''__test_patch_submodule_missing_mock__'''
with patch_submodule(_test_patching, '''pandas.read_csv''', __snake_case ):
pass
def lowerCamelCase__ ( ) -> Dict:
"""simple docstring"""
_UpperCamelCase = '''__test_patch_submodule_missing_builtin_mock__'''
# _test_patching doesn't have "len" in its globals
assert getattr(_test_patching, '''len''', __snake_case ) is None
with patch_submodule(_test_patching, '''len''', __snake_case ):
assert _test_patching.len is mock
assert _test_patching.len is len
def lowerCamelCase__ ( ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = '''__test_patch_submodule_start_and_stop_mock__'''
_UpperCamelCase = patch_submodule(_test_patching, '''open''', __snake_case )
assert _test_patching.open is open
patch.start()
assert _test_patching.open is mock
patch.stop()
assert _test_patching.open is open
def lowerCamelCase__ ( ) -> Optional[int]:
"""simple docstring"""
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
_UpperCamelCase = '''__test_patch_submodule_successive_join__'''
_UpperCamelCase = '''__test_patch_submodule_successive_dirname__'''
_UpperCamelCase = '''__test_patch_submodule_successive_rename__'''
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
with patch_submodule(_test_patching, '''os.path.join''', __snake_case ):
with patch_submodule(_test_patching, '''os.rename''', __snake_case ):
with patch_submodule(_test_patching, '''os.path.dirname''', __snake_case ):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
# try another order
with patch_submodule(_test_patching, '''os.rename''', __snake_case ):
with patch_submodule(_test_patching, '''os.path.join''', __snake_case ):
with patch_submodule(_test_patching, '''os.path.dirname''', __snake_case ):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
def lowerCamelCase__ ( ) -> str:
"""simple docstring"""
_UpperCamelCase = '''__test_patch_submodule_doesnt_exist_mock__'''
with patch_submodule(_test_patching, '''__module_that_doesn_exist__.__attribute_that_doesn_exist__''', __snake_case ):
pass
with patch_submodule(_test_patching, '''os.__attribute_that_doesn_exist__''', __snake_case ):
pass
| 19 | 1 |
"""simple docstring"""
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
# python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
import re
import subprocess
import sys
_A = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
_A = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode("utf-8").split()
_A = "|".join(sys.argv[1:])
_A = re.compile(rf"""^({joined_dirs}).*?\.py$""")
_A = [x for x in modified_files if regex.match(x)]
print(" ".join(relevant_modified_files), end="") | 228 |
"""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 __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def A ( self : int )-> Union[str, Any]:
__UpperCamelCase = tempfile.mkdtemp()
# fmt: off
__UpperCamelCase = ["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 = dict(zip(A_ , range(len(A_ ) ) ) )
__UpperCamelCase = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
__UpperCamelCase = {"unk_token": "<unk>"}
__UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__UpperCamelCase = 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(A_ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(A_ ) )
__UpperCamelCase = {
"do_resize": True,
"size": 20,
"do_center_crop": True,
"crop_size": 18,
"do_normalize": True,
"image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073],
"image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711],
}
__UpperCamelCase = os.path.join(self.tmpdirname , A_ )
with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp:
json.dump(A_ , A_ )
def A ( self : Dict , **A_ : List[str] )-> List[Any]:
return CLIPTokenizer.from_pretrained(self.tmpdirname , **A_ )
def A ( self : Optional[int] , **A_ : Any )-> Tuple:
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **A_ )
def A ( self : Any , **A_ : List[Any] )-> Optional[int]:
return ViTImageProcessor.from_pretrained(self.tmpdirname , **A_ )
def A ( self : Tuple )-> Union[str, Any]:
shutil.rmtree(self.tmpdirname )
def A ( self : int )-> str:
__UpperCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
__UpperCamelCase = [Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def A ( self : List[Any] )-> Optional[Any]:
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = self.get_rust_tokenizer()
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
processor_slow.save_pretrained(self.tmpdirname )
__UpperCamelCase = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=A_ )
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
processor_fast.save_pretrained(self.tmpdirname )
__UpperCamelCase = 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 , A_ )
self.assertIsInstance(processor_fast.tokenizer , A_ )
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 , A_ )
self.assertIsInstance(processor_fast.image_processor , A_ )
def A ( self : Dict )-> Dict:
__UpperCamelCase = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__UpperCamelCase = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
__UpperCamelCase = self.get_image_processor(do_normalize=A_ , padding_value=1.0 )
__UpperCamelCase = CLIPSegProcessor.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 , A_ )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , A_ )
def A ( self : int )-> Any:
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
__UpperCamelCase = self.prepare_image_inputs()
__UpperCamelCase = image_processor(A_ , return_tensors="np" )
__UpperCamelCase = 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 A ( self : int )-> Union[str, Any]:
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
__UpperCamelCase = "lower newer"
__UpperCamelCase = processor(text=A_ )
__UpperCamelCase = tokenizer(A_ )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def A ( self : List[Any] )-> List[Any]:
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
__UpperCamelCase = "lower newer"
__UpperCamelCase = self.prepare_image_inputs()
__UpperCamelCase = processor(text=A_ , images=A_ )
self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] )
# test if it raises when no input is passed
with pytest.raises(A_ ):
processor()
def A ( self : Union[str, Any] )-> Union[str, Any]:
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
__UpperCamelCase = self.prepare_image_inputs()
__UpperCamelCase = self.prepare_image_inputs()
__UpperCamelCase = processor(images=A_ , visual_prompt=A_ )
self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] )
# test if it raises when no input is passed
with pytest.raises(A_ ):
processor()
def A ( self : Optional[int] )-> int:
__UpperCamelCase = self.get_image_processor()
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = CLIPSegProcessor(tokenizer=A_ , image_processor=A_ )
__UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__UpperCamelCase = processor.batch_decode(A_ )
__UpperCamelCase = tokenizer.batch_decode(A_ )
self.assertListEqual(A_ , A_ ) | 228 | 1 |
"""simple docstring"""
import unittest
from transformers import is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow
if is_flax_available():
import optax
from flax.training.common_utils import onehot
from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration
from transformers.models.ta.modeling_flax_ta import shift_tokens_right
@require_torch
@require_sentencepiece
@require_tokenizers
@require_flax
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''')
_UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''')
_UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''np''').input_ids
_UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''np''').input_ids
_UpperCamelCase = shift_tokens_right(__a , model.config.pad_token_id , model.config.decoder_start_token_id)
_UpperCamelCase = model(__a , decoder_input_ids=__a).logits
_UpperCamelCase = optax.softmax_cross_entropy(__a , onehot(__a , logits.shape[-1])).mean()
_UpperCamelCase = -(labels.shape[-1] * loss.item())
_UpperCamelCase = -84.9127
self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
| 19 |
"""simple docstring"""
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'ViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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 , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = 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)
def __call__( self , __a=None , __a=None , __a=None , __a=None , **__a) -> Tuple:
'''simple docstring'''
if text is None and visual_prompt is None and images is None:
raise ValueError('''You have to specify either text, visual prompt or images.''')
if text is not None and visual_prompt is not None:
raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''')
if text is not None:
_UpperCamelCase = self.tokenizer(__a , return_tensors=__a , **__a)
if visual_prompt is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if visual_prompt is not None and images is not None:
_UpperCamelCase = {
'''pixel_values''': image_features.pixel_values,
'''conditional_pixel_values''': prompt_features.pixel_values,
}
return encoding
elif text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None:
return encoding
elif visual_prompt is not None:
_UpperCamelCase = {
'''conditional_pixel_values''': prompt_features.pixel_values,
}
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> Any:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> List[str]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
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 UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 19 | 1 |
import argparse
import os
import re
snake_case_ : Optional[Any] = "src/transformers/models/auto"
# re pattern that matches mapping introductions:
# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
snake_case_ : Optional[int] = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict")
# re pattern that matches identifiers in mappings
snake_case_ : Tuple = re.compile(r"\s*\(\s*\"(\S[^\"]+)\"")
def A (__A : Optional[int] , __A : bool = False ) -> str:
"""simple docstring"""
with open(__A , '''r''' , encoding='''utf-8''' ) as f:
UpperCAmelCase_ = f.read()
UpperCAmelCase_ = content.split('''\n''' )
UpperCAmelCase_ = []
UpperCAmelCase_ = 0
while line_idx < len(__A ):
if _re_intro_mapping.search(lines[line_idx] ) is not None:
UpperCAmelCase_ = len(re.search(R'''^(\s*)\S''' , lines[line_idx] ).groups()[0] ) + 8
# Start of a new mapping!
while not lines[line_idx].startswith(''' ''' * indent + '''(''' ):
new_lines.append(lines[line_idx] )
line_idx += 1
UpperCAmelCase_ = []
while lines[line_idx].strip() != "]":
# Blocks either fit in one line or not
if lines[line_idx].strip() == "(":
UpperCAmelCase_ = line_idx
while not lines[line_idx].startswith(''' ''' * indent + ''')''' ):
line_idx += 1
blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) )
else:
blocks.append(lines[line_idx] )
line_idx += 1
# Sort blocks by their identifiers
UpperCAmelCase_ = sorted(__A , key=lambda __A : _re_identifier.search(__A ).groups()[0] )
new_lines += blocks
else:
new_lines.append(lines[line_idx] )
line_idx += 1
if overwrite:
with open(__A , '''w''' , encoding='''utf-8''' ) as f:
f.write('''\n'''.join(__A ) )
elif "\n".join(__A ) != content:
return True
def A (__A : bool = False ) -> Tuple:
"""simple docstring"""
UpperCAmelCase_ = [os.path.join(__A , __A ) for f in os.listdir(__A ) if f.endswith('''.py''' )]
UpperCAmelCase_ = [sort_auto_mapping(__A , overwrite=__A ) for fname in fnames]
if not overwrite and any(__A ):
UpperCAmelCase_ = [f for f, d in zip(__A , __A ) if d]
raise ValueError(
F"""The following files have auto mappings that need sorting: {", ".join(__A )}. Run `make style` to fix"""
''' this.''' )
if __name__ == "__main__":
snake_case_ : List[str] = argparse.ArgumentParser()
parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
snake_case_ : int = parser.parse_args()
sort_all_auto_mappings(not args.check_only)
| 706 |
from __future__ import annotations
def A (__A : list[int] ) -> list[int]: # This function is recursive
"""simple docstring"""
UpperCAmelCase_ = len(__A )
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
UpperCAmelCase_ = array[0]
UpperCAmelCase_ = False
UpperCAmelCase_ = 1
UpperCAmelCase_ = []
while not is_found and i < array_length:
if array[i] < pivot:
UpperCAmelCase_ = True
UpperCAmelCase_ = [element for element in array[i:] if element >= array[i]]
UpperCAmelCase_ = longest_subsequence(__A )
if len(__A ) > len(__A ):
UpperCAmelCase_ = temp_array
else:
i += 1
UpperCAmelCase_ = [element for element in array[1:] if element >= pivot]
UpperCAmelCase_ = [pivot, *longest_subsequence(__A )]
if len(__A ) > len(__A ):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| 169 | 0 |
def SCREAMING_SNAKE_CASE ( lowercase_ = 100 ) -> int:
"""simple docstring"""
A__ = (n * (n + 1) // 2) ** 2
A__ = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(F'''{solution() = }''')
| 87 |
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be trained.'} )
lowerCamelCase : Optional[str] = field(
default='./' , metadata={'help': 'Save dir where model repo is cloned and models updates are saved to.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path of training dataset.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} )
lowerCamelCase : Optional[int] = field(default=2 , metadata={'help': 'Batch size for training.'} )
lowerCamelCase : Optional[int] = field(default=2 , metadata={'help': 'Batch size for evaluation.'} )
lowerCamelCase : Optional[float] = field(default=0.1 , metadata={'help': 'Value of weight decay.'} )
lowerCamelCase : Optional[int] = field(
default=1_00_00 , metadata={'help': 'Size of buffer used to shuffle streaming dataset.'} )
lowerCamelCase : Optional[float] = field(default=2e-4 , metadata={'help': 'Learning rate fo training.'} )
lowerCamelCase : Optional[str] = field(default='cosine' , metadata={'help': 'Learning rate.'} )
lowerCamelCase : Optional[int] = field(
default=7_50 , metadata={'help': 'Number of warmup steps in the learning rate schedule.'} )
lowerCamelCase : Optional[int] = field(
default=16 , metadata={'help': 'Number of gradient accumulation steps.'} )
lowerCamelCase : Optional[bool] = field(
default=snake_case__ , metadata={'help': 'Use gradient checkpointing to reduce memory footprint.'} )
lowerCamelCase : Optional[int] = field(default=5_00_00 , metadata={'help': 'Maximum number of training steps.'} )
lowerCamelCase : Optional[int] = field(
default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} )
lowerCamelCase : Optional[int] = field(default=10_24 , metadata={'help': 'Sequence lengths used for training.'} )
lowerCamelCase : Optional[int] = field(default=1 , metadata={'help': 'Training seed.'} )
lowerCamelCase : Optional[int] = field(
default=10_24 , metadata={'help': 'Interval to save checkpoints. Measured as number of forward passes not training steps.'} , )
lowerCamelCase : Optional[str] = field(
default=snake_case__ , metadata={'help': 'States path if the training should continue from a checkpoint folder.'} )
lowerCamelCase : Optional[bool] = field(default=snake_case__ , metadata={'help': 'If True the data is pretokenized.'} )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} )
lowerCamelCase : Optional[int] = field(default=2 , metadata={'help': 'Batch size used for evaluation.'} )
lowerCamelCase : Optional[int] = field(
default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} )
lowerCamelCase : Optional[int] = field(default=10_24 , metadata={'help': 'Length of sequences to be evaluated.'} )
lowerCamelCase : Optional[int] = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} )
lowerCamelCase : Optional[int] = field(default=snake_case__ , metadata={'help': 'Number of workers used for code evaluation.'} )
lowerCamelCase : Optional[int] = field(
default=snake_case__ , metadata={'help': 'The number of human-eval tasks to run. If not included all tasks are evaluated.'} , )
lowerCamelCase : Optional[bool] = field(
default=snake_case__ , metadata={'help': 'Sample from the language model\'s output distribution.'} )
lowerCamelCase : Optional[float] = field(default=0.2 , metadata={'help': 'Sampling temperature used for generation.'} )
lowerCamelCase : Optional[int] = field(default=2_56 , metadata={'help': 'Maximum number of newly generated tokens.'} )
lowerCamelCase : Optional[int] = field(default=0 , metadata={'help': 'Top-k parameter used for generation.'} )
lowerCamelCase : Optional[float] = field(default=0.95 , metadata={'help': 'Top-p parameter used for nucleus sampling.'} )
lowerCamelCase : Optional[int] = field(default=10 , metadata={'help': 'Number of generations to run in parallel.'} )
lowerCamelCase : Optional[int] = field(
default=2_00 , metadata={'help': 'Number of completions to generate for each sample.'} )
lowerCamelCase : Optional[int] = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} )
lowerCamelCase : Optional[str] = field(
default='eval_results.json' , metadata={'help': 'Random seed used for evaluation.'} )
lowerCamelCase : Optional[str] = field(
default='0' , metadata={'help': 'Allow `code_eval` to execute Python code on machine'} )
lowerCamelCase : Optional[int] = field(
default=-1 , metadata={
'help': (
'Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive'
' number corresponds to which GPU device id to run on.'
)
} , )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[int] = field(
default=snake_case__ , metadata={
'help': 'The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.'
} , )
lowerCamelCase : Optional[str] = field(
default='transformersbook/codeparrot' , metadata={'help': 'Folder or name of dataset to process.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot-clean' , metadata={'help': 'Folder to save processed processed dataset.'} )
lowerCamelCase : Optional[int] = field(
default=10_00_00 , metadata={'help': 'Number of files to save per JSON output file.'} )
lowerCamelCase : Optional[str] = field(default='content' , metadata={'help': 'Column containing text data to process.'} )
lowerCamelCase : Optional[float] = field(
default=10_00 , metadata={'help': 'Maximum line length in file, otherwise file is filtered.'} )
lowerCamelCase : Optional[float] = field(
default=1_00 , metadata={'help': 'Maximum mean line length in file, otherwise file is filtered.'} )
lowerCamelCase : Optional[float] = field(
default=0.25 , metadata={'help': 'Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'} )
lowerCamelCase : Optional[float] = field(
default=1.5 , metadata={'help': 'Minimum character token ratio for the file, otherwise file is filtered.'} )
lowerCamelCase : Optional[float] = field(
default=0.7 , metadata={'help': 'Probability for filtering config, test and uncommon files.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} , )
lowerCamelCase : Optional[bool] = field(
default=snake_case__ , metadata={'help': 'If True, near-duplicate samples are removed.'} )
lowerCamelCase : Optional[float] = field(
default=0.85 , metadata={'help': 'Jaccard threshold for near-duplicate samples.'} )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='gpt2' , metadata={'help': 'Base tokenizer to build new tokenizer from.'} )
lowerCamelCase : Optional[str] = field(
default='transformersbook/codeparrot-train' , metadata={'help': 'Dataset to train tokenizer on.'} )
lowerCamelCase : Optional[str] = field(default='content' , metadata={'help': 'Column containing text data to process.'} )
lowerCamelCase : Optional[int] = field(default=20_00_00 , metadata={'help': 'Number of examples to train tokenizer on.'} )
lowerCamelCase : Optional[int] = field(
default=3_27_68 , metadata={'help': 'Number of examples to train the tokenizer on.'} )
lowerCamelCase : Optional[str] = field(default='codeparrot' , metadata={'help': 'Name of new tokenizer.'} )
lowerCamelCase : Optional[bool] = field(default=snake_case__ , metadata={'help': 'Push saved tokenizer to the hub.'} )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path to the dataset to pretokenize.'} )
lowerCamelCase : Optional[str] = field(
default='tokenized-codeparrot-train' , metadata={'help': 'Repo name of the pretokenized data.'} )
lowerCamelCase : Optional[int] = field(default=snake_case__ , metadata={'help': 'Number of workers used for code evaluation.'} )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Optional[str] = field(
default='gpt2-large' , metadata={'help': 'Configuration to use for model initialization.'} )
lowerCamelCase : Optional[str] = field(
default='codeparrot/codeparrot' , metadata={'help': 'Tokenizer attached to model.'} )
lowerCamelCase : Optional[str] = field(default='codeparrot' , metadata={'help': 'Name of the created model.'} )
lowerCamelCase : Optional[bool] = field(default=snake_case__ , metadata={'help': 'Push saved tokenizer to the hub.'} ) | 687 | 0 |
'''simple docstring'''
# Author: OMKAR PATHAK, Nwachukwu Chidiebere
# Use a Python dictionary to construct the graph.
from __future__ import annotations
from pprint import pformat
from typing import Generic, TypeVar
A =TypeVar('T')
class _a ( Generic[T] ):
def __init__( self : List[Any] , lowercase : bool = True ):
'''simple docstring'''
UpperCAmelCase = {} # dictionary of lists
UpperCAmelCase = directed
def A ( self : int , lowercase : T , lowercase : T ):
'''simple docstring'''
if not self.directed: # For undirected graphs
# if both source vertex and destination vertex are both present in the
# adjacency list, add destination vertex to source vertex list of adjacent
# vertices and add source vertex to destination vertex list of adjacent
# vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(lowercase )
self.adj_list[destination_vertex].append(lowercase )
# if only source vertex is present in adjacency list, add destination vertex
# to source vertex list of adjacent vertices, then create a new vertex with
# destination vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(lowercase )
UpperCAmelCase = [source_vertex]
# if only destination vertex is present in adjacency list, add source vertex
# to destination vertex list of adjacent vertices, then create a new vertex
# with source vertex as key and assign a list containing the source vertex
# as it's first adjacent vertex.
elif destination_vertex in self.adj_list:
self.adj_list[destination_vertex].append(lowercase )
UpperCAmelCase = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and assign a list
# containing the destination vertex as it's first adjacent vertex also
# create a new vertex with destination vertex as key and assign a list
# containing the source vertex as it's first adjacent vertex.
else:
UpperCAmelCase = [destination_vertex]
UpperCAmelCase = [source_vertex]
else: # For directed graphs
# if both source vertex and destination vertex are present in adjacency
# list, add destination vertex to source vertex list of adjacent vertices.
if source_vertex in self.adj_list and destination_vertex in self.adj_list:
self.adj_list[source_vertex].append(lowercase )
# if only source vertex is present in adjacency list, add destination
# vertex to source vertex list of adjacent vertices and create a new vertex
# with destination vertex as key, which has no adjacent vertex
elif source_vertex in self.adj_list:
self.adj_list[source_vertex].append(lowercase )
UpperCAmelCase = []
# if only destination vertex is present in adjacency list, create a new
# vertex with source vertex as key and assign a list containing destination
# vertex as first adjacent vertex
elif destination_vertex in self.adj_list:
UpperCAmelCase = [destination_vertex]
# if both source vertex and destination vertex are not present in adjacency
# list, create a new vertex with source vertex as key and a list containing
# destination vertex as it's first adjacent vertex. Then create a new vertex
# with destination vertex as key, which has no adjacent vertex
else:
UpperCAmelCase = [destination_vertex]
UpperCAmelCase = []
return self
def __repr__( self : List[Any] ):
'''simple docstring'''
return pformat(self.adj_list )
| 358 |
'''simple docstring'''
import unittest
from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
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 (
MODEL_FOR_PRETRAINING_MAPPING,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
MobileBertModel,
)
class _a :
def __init__( self : List[str] , lowercase : Dict , lowercase : List[Any]=13 , lowercase : Optional[Any]=7 , lowercase : Any=True , lowercase : str=True , lowercase : List[Any]=True , lowercase : str=True , lowercase : List[str]=99 , lowercase : int=64 , lowercase : List[Any]=32 , lowercase : str=5 , lowercase : Optional[int]=4 , lowercase : int=37 , lowercase : str="gelu" , lowercase : Any=0.1 , lowercase : Optional[Any]=0.1 , lowercase : Optional[int]=512 , lowercase : Union[str, Any]=16 , lowercase : List[str]=2 , lowercase : Tuple=0.02 , lowercase : List[Any]=3 , lowercase : int=4 , lowercase : Optional[Any]=None , ):
'''simple docstring'''
UpperCAmelCase = parent
UpperCAmelCase = batch_size
UpperCAmelCase = seq_length
UpperCAmelCase = is_training
UpperCAmelCase = use_input_mask
UpperCAmelCase = use_token_type_ids
UpperCAmelCase = use_labels
UpperCAmelCase = vocab_size
UpperCAmelCase = hidden_size
UpperCAmelCase = embedding_size
UpperCAmelCase = num_hidden_layers
UpperCAmelCase = num_attention_heads
UpperCAmelCase = intermediate_size
UpperCAmelCase = hidden_act
UpperCAmelCase = hidden_dropout_prob
UpperCAmelCase = attention_probs_dropout_prob
UpperCAmelCase = max_position_embeddings
UpperCAmelCase = type_vocab_size
UpperCAmelCase = type_sequence_label_size
UpperCAmelCase = initializer_range
UpperCAmelCase = num_labels
UpperCAmelCase = num_choices
UpperCAmelCase = scope
def A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCAmelCase = None
if self.use_input_mask:
UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase = None
if self.use_token_type_ids:
UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
UpperCAmelCase = None
UpperCAmelCase = None
UpperCAmelCase = None
if self.use_labels:
UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices )
UpperCAmelCase = 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 MobileBertConfig(
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 , embedding_size=self.embedding_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=lowercase , initializer_range=self.initializer_range , )
def A ( self : Tuple , lowercase : Optional[Any] , lowercase : List[Any] , lowercase : Optional[int] , lowercase : Union[str, Any] , lowercase : List[Any] , lowercase : str , lowercase : Dict ):
'''simple docstring'''
UpperCAmelCase = MobileBertModel(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase )
UpperCAmelCase = model(lowercase , token_type_ids=lowercase )
UpperCAmelCase = model(lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def A ( self : Dict , lowercase : Union[str, Any] , lowercase : List[str] , lowercase : List[str] , lowercase : Dict , lowercase : List[str] , lowercase : Optional[int] , lowercase : List[str] ):
'''simple docstring'''
UpperCAmelCase = MobileBertForMaskedLM(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : Dict , lowercase : Any , lowercase : Dict , lowercase : Optional[Any] , lowercase : Optional[Any] , lowercase : List[Any] , lowercase : List[Any] , lowercase : List[str] ):
'''simple docstring'''
UpperCAmelCase = MobileBertForNextSentencePrediction(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(
lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def A ( self : Optional[int] , lowercase : Tuple , lowercase : Optional[Any] , lowercase : int , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Union[str, Any] , lowercase : Tuple ):
'''simple docstring'''
UpperCAmelCase = MobileBertForPreTraining(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(
lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , next_sentence_label=lowercase , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def A ( self : Optional[int] , lowercase : Any , lowercase : Dict , lowercase : str , lowercase : Optional[Any] , lowercase : List[str] , lowercase : int , lowercase : Any ):
'''simple docstring'''
UpperCAmelCase = MobileBertForQuestionAnswering(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(
lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , )
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 : Optional[Any] , lowercase : Tuple , lowercase : Union[str, Any] , lowercase : List[Any] , lowercase : List[str] , lowercase : List[str] , lowercase : str , lowercase : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.num_labels
UpperCAmelCase = MobileBertForSequenceClassification(lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : List[Any] , lowercase : int , lowercase : List[Any] , lowercase : Tuple , lowercase : Optional[int] , lowercase : List[Any] , lowercase : List[str] , lowercase : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.num_labels
UpperCAmelCase = MobileBertForTokenClassification(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : int , lowercase : Optional[int] , lowercase : Tuple , lowercase : List[Any] , lowercase : Tuple , lowercase : str , lowercase : Tuple , lowercase : Dict ):
'''simple docstring'''
UpperCAmelCase = self.num_choices
UpperCAmelCase = MobileBertForMultipleChoice(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCAmelCase = model(
lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : int ):
'''simple docstring'''
UpperCAmelCase = self.prepare_config_and_inputs()
(
(
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) ,
) = config_and_inputs
UpperCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _a ( __a , __a , unittest.TestCase ):
__a : Dict = (
(
MobileBertModel,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
)
if is_torch_available()
else ()
)
__a : List[str] = (
{
"""feature-extraction""": MobileBertModel,
"""fill-mask""": MobileBertForMaskedLM,
"""question-answering""": MobileBertForQuestionAnswering,
"""text-classification""": MobileBertForSequenceClassification,
"""token-classification""": MobileBertForTokenClassification,
"""zero-shot""": MobileBertForSequenceClassification,
}
if is_torch_available()
else {}
)
__a : Any = True
def A ( self : List[Any] , lowercase : int , lowercase : Any , lowercase : Optional[Any]=False ):
'''simple docstring'''
UpperCAmelCase = super()._prepare_for_class(lowercase , lowercase , return_labels=lowercase )
if return_labels:
if model_class in get_values(lowercase ):
UpperCAmelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowercase )
UpperCAmelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowercase )
return inputs_dict
def A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = MobileBertModelTester(self )
UpperCAmelCase = ConfigTester(self , config_class=lowercase , hidden_size=37 )
def A ( self : Dict ):
'''simple docstring'''
self.config_tester.run_common_tests()
def A ( self : Any ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*lowercase )
def A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*lowercase )
def A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*lowercase )
def A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*lowercase )
def A ( self : int ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*lowercase )
def A ( self : Optional[int] ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*lowercase )
def A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*lowercase )
def A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*lowercase )
def snake_case_ (_a : List[Any] ):
return torch.tensor(
_a , dtype=torch.long , device=_a , )
A =1E-3
@require_torch
@require_sentencepiece
@require_tokenizers
class _a ( unittest.TestCase ):
@slow
def A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase = MobileBertModel.from_pretrained('''google/mobilebert-uncased''' ).to(lowercase )
UpperCAmelCase = _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]] )
with torch.no_grad():
UpperCAmelCase = model(lowercase )[0]
UpperCAmelCase = torch.Size((1, 9, 512) )
self.assertEqual(output.shape , lowercase )
UpperCAmelCase = torch.tensor(
[
[
[-2.4_736_526E07, 8.2_691_656E04, 1.6_521_838E05],
[-5.7_541_704E-01, 3.9_056_022E00, 4.4_011_507E00],
[2.6_047_359E00, 1.5_677_652E00, -1.7_324_188E-01],
]
] , device=lowercase , )
# MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
# ~1 difference, it's therefore not a good idea to measure using addition.
# Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
# result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
UpperCAmelCase = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE )
UpperCAmelCase = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE )
self.assertTrue(lower_bound and upper_bound )
| 358 | 1 |
from __future__ import annotations
class lowerCamelCase:
'''simple docstring'''
def __init__( self , snake_case_=None ):
_A = data
_A = None
def __repr__( self ):
_A = []
_A = self
while temp:
string_rep.append(F"{temp.data}" )
_A = temp.next
return "->".join(snake_case_ )
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
if not elements_list:
raise Exception('The Elements List is empty' )
_A = _A = Node(elements_list[0] )
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ):
_A = Node(elements_list[i] )
_A = current.next
return head
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> None:
"""simple docstring"""
if head_node is not None and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
print_reverse(head_node.next )
print(head_node.data )
def __lowerCAmelCase( ) -> Any:
"""simple docstring"""
from doctest import testmod
testmod()
_A = make_linked_list([14, 52, 14, 12, 43] )
print('Linked List:' )
print(_SCREAMING_SNAKE_CASE )
print('Elements in Reverse:' )
print_reverse(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 27 | '''simple docstring'''
import absl # noqa: F401 # Here to have a nice missing dependency error message early on
import nltk # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy # noqa: F401 # Here to have a nice missing dependency error message early on
import six # noqa: F401 # Here to have a nice missing dependency error message early on
from rouge_score import rouge_scorer, scoring
import datasets
UpperCamelCase_ = '''\
@inproceedings{lin-2004-rouge,
title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",
author = "Lin, Chin-Yew",
booktitle = "Text Summarization Branches Out",
month = jul,
year = "2004",
address = "Barcelona, Spain",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/W04-1013",
pages = "74--81",
}
'''
UpperCamelCase_ = '''\
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
evaluating automatic summarization and machine translation software in natural language processing.
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.
Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.
This metrics is a wrapper around Google Research reimplementation of ROUGE:
https://github.com/google-research/google-research/tree/master/rouge
'''
UpperCamelCase_ = '''
Calculates average rouge scores for a list of hypotheses and 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.
rouge_types: A list of rouge types to calculate.
Valid names:
`"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,
`"rougeL"`: Longest common subsequence based scoring.
`"rougeLSum"`: rougeLsum splits text using `"\n"`.
See details in https://github.com/huggingface/datasets/issues/617
use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
use_aggregator: Return aggregates if this is set to True
Returns:
rouge1: rouge_1 (precision, recall, f1),
rouge2: rouge_2 (precision, recall, f1),
rougeL: rouge_l (precision, recall, f1),
rougeLsum: rouge_lsum (precision, recall, f1)
Examples:
>>> rouge = datasets.load_metric(\'rouge\')
>>> predictions = ["hello there", "general kenobi"]
>>> references = ["hello there", "general kenobi"]
>>> results = rouge.compute(predictions=predictions, references=references)
>>> print(list(results.keys()))
[\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']
>>> print(results["rouge1"])
AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))
>>> print(results["rouge1"].mid.fmeasure)
1.0
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _SCREAMING_SNAKE_CASE( datasets.Metric ):
def __lowerCamelCase ( self : Any ) -> Union[str, Any]:
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/google-research/google-research/tree/master/rouge'] , reference_urls=[
'https://en.wikipedia.org/wiki/ROUGE_(metric)',
'https://github.com/google-research/google-research/tree/master/rouge',
] , )
def __lowerCamelCase ( self : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Tuple=True , UpperCamelCase_ : str=False ) -> Optional[Any]:
if rouge_types is None:
SCREAMING_SNAKE_CASE__ :Optional[int] = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
SCREAMING_SNAKE_CASE__ :Union[str, Any] = rouge_scorer.RougeScorer(rouge_types=UpperCamelCase_ , use_stemmer=UpperCamelCase_ )
if use_aggregator:
SCREAMING_SNAKE_CASE__ :Tuple = scoring.BootstrapAggregator()
else:
SCREAMING_SNAKE_CASE__ :Any = []
for ref, pred in zip(UpperCamelCase_ , UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :Tuple = scorer.score(UpperCamelCase_ , UpperCamelCase_ )
if use_aggregator:
aggregator.add_scores(UpperCamelCase_ )
else:
scores.append(UpperCamelCase_ )
if use_aggregator:
SCREAMING_SNAKE_CASE__ :Tuple = aggregator.aggregate()
else:
SCREAMING_SNAKE_CASE__ :List[str] = {}
for key in scores[0]:
SCREAMING_SNAKE_CASE__ :int = [score[key] for score in scores]
return result
| 209 | 0 |
"""simple docstring"""
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class _lowerCAmelCase ( unittest.TestCase ):
def _lowerCAmelCase ( self : List[str] ) -> List[Any]:
"""simple docstring"""
lowercase : str = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
lowercase : List[Any] = get_activation('''gelu''' )
self.assertTrue(torch.allclose(gelu_python(a ) , torch_builtin(a ) ) )
self.assertFalse(torch.allclose(gelu_python(a ) , gelu_new(a ) ) )
def _lowerCAmelCase ( self : List[str] ) -> Optional[Any]:
"""simple docstring"""
lowercase : Dict = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
lowercase : Optional[Any] = get_activation('''gelu''' )
lowercase : Union[str, Any] = get_activation('''gelu_10''' )
lowercase : List[str] = torch_builtin(a )
lowercase : Optional[int] = geluaa(a )
lowercase : Any = torch.where(y_gelu_aa < 10.0 , 1 , 0 )
self.assertTrue(torch.max(a ).item() == 10.0 )
self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) )
def _lowerCAmelCase ( self : Any ) -> Optional[int]:
"""simple docstring"""
get_activation('''gelu''' )
get_activation('''gelu_10''' )
get_activation('''gelu_fast''' )
get_activation('''gelu_new''' )
get_activation('''gelu_python''' )
get_activation('''gelu_pytorch_tanh''' )
get_activation('''linear''' )
get_activation('''mish''' )
get_activation('''quick_gelu''' )
get_activation('''relu''' )
get_activation('''sigmoid''' )
get_activation('''silu''' )
get_activation('''swish''' )
get_activation('''tanh''' )
with self.assertRaises(a ):
get_activation('''bogus''' )
with self.assertRaises(a ):
get_activation(a )
def _lowerCAmelCase ( self : Dict ) -> Dict:
"""simple docstring"""
lowercase : List[Any] = get_activation('''gelu''' )
lowercase : Optional[int] = 1
lowercase : Optional[int] = get_activation('''gelu''' )
self.assertEqual(acta.a , 1 )
with self.assertRaises(a ):
lowercase : Tuple = acta.a | 709 |
"""simple docstring"""
def A_ ( __UpperCamelCase : str , __UpperCamelCase : str ):
lowercase = len(__UpperCamelCase )
lowercase = []
for i in range(len(__UpperCamelCase ) - pat_len + 1 ):
lowercase = True
for j in range(__UpperCamelCase ):
if s[i + j] != pattern[j]:
lowercase = False
break
if match_found:
position.append(__UpperCamelCase )
return position
if __name__ == "__main__":
assert naive_pattern_search('''ABCDEFG''', '''DE''') == [3]
print(naive_pattern_search('''ABAAABCDBBABCDDEBCABC''', '''ABC''')) | 396 | 0 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
__SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE = {
'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json',
}
class lowerCAmelCase__ ( snake_case_ ):
"""simple docstring"""
__UpperCamelCase = "instructblip_vision_model"
def __init__( self : str , A__ : Union[str, Any]=1_4_0_8 , A__ : Tuple=6_1_4_4 , A__ : Dict=3_9 , A__ : str=1_6 , A__ : List[Any]=2_2_4 , A__ : int=1_4 , A__ : Dict="gelu" , A__ : str=1E-6 , A__ : Dict=0.0 , A__ : Dict=1E-10 , A__ : List[str]=True , **A__ : Optional[Any] , ) -> List[str]:
'''simple docstring'''
super().__init__(**A__ )
a__ : List[str] = hidden_size
a__ : Dict = intermediate_size
a__ : str = num_hidden_layers
a__ : Optional[int] = num_attention_heads
a__ : Optional[int] = patch_size
a__ : Union[str, Any] = image_size
a__ : Dict = initializer_range
a__ : Any = attention_dropout
a__ : Union[str, Any] = layer_norm_eps
a__ : List[Any] = hidden_act
a__ : Any = qkv_bias
@classmethod
def __lowerCAmelCase ( cls : Any , A__ : List[Any] , **A__ : int ) -> "PretrainedConfig":
'''simple docstring'''
cls._set_token_in_kwargs(A__ )
a__ , a__ : Dict = cls.get_config_dict(A__ , **A__ )
# get the vision config dict if we are loading from InstructBlipConfig
if config_dict.get('''model_type''' ) == "instructblip":
a__ : Dict = config_dict['''vision_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(A__ , **A__ )
class lowerCAmelCase__ ( snake_case_ ):
"""simple docstring"""
__UpperCamelCase = "instructblip_qformer"
def __init__( self : int , A__ : Optional[Any]=3_0_5_2_2 , A__ : List[str]=7_6_8 , A__ : Tuple=1_2 , A__ : List[Any]=1_2 , A__ : Any=3_0_7_2 , A__ : Optional[Any]="gelu" , A__ : Union[str, Any]=0.1 , A__ : Optional[int]=0.1 , A__ : Any=5_1_2 , A__ : str=0.02 , A__ : str=1E-12 , A__ : Any=0 , A__ : Optional[Any]="absolute" , A__ : Optional[int]=2 , A__ : str=1_4_0_8 , **A__ : Tuple , ) -> str:
'''simple docstring'''
super().__init__(pad_token_id=A__ , **A__ )
a__ : Dict = vocab_size
a__ : List[Any] = hidden_size
a__ : Dict = num_hidden_layers
a__ : Optional[Any] = num_attention_heads
a__ : str = hidden_act
a__ : List[str] = intermediate_size
a__ : List[Any] = hidden_dropout_prob
a__ : Tuple = attention_probs_dropout_prob
a__ : Optional[int] = max_position_embeddings
a__ : Optional[int] = initializer_range
a__ : Dict = layer_norm_eps
a__ : Optional[Any] = position_embedding_type
a__ : Dict = cross_attention_frequency
a__ : int = encoder_hidden_size
@classmethod
def __lowerCAmelCase ( cls : Optional[Any] , A__ : int , **A__ : int ) -> "PretrainedConfig":
'''simple docstring'''
cls._set_token_in_kwargs(A__ )
a__ , a__ : List[Any] = cls.get_config_dict(A__ , **A__ )
# get the qformer config dict if we are loading from InstructBlipConfig
if config_dict.get('''model_type''' ) == "instructblip":
a__ : Union[str, Any] = config_dict['''qformer_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(A__ , **A__ )
class lowerCAmelCase__ ( snake_case_ ):
"""simple docstring"""
__UpperCamelCase = "instructblip"
__UpperCamelCase = True
def __init__( self : str , A__ : int=None , A__ : int=None , A__ : List[Any]=None , A__ : int=3_2 , **A__ : Tuple ) -> Optional[int]:
'''simple docstring'''
super().__init__(**A__ )
if vision_config is None:
a__ : Dict = {}
logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''' )
if qformer_config is None:
a__ : List[Any] = {}
logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''' )
if text_config is None:
a__ : str = {}
logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' )
a__ : Tuple = InstructBlipVisionConfig(**A__ )
a__ : Tuple = InstructBlipQFormerConfig(**A__ )
a__ : Optional[Any] = text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
a__ : Optional[Any] = CONFIG_MAPPING[text_model_type](**A__ )
a__ : Dict = self.text_config.tie_word_embeddings
a__ : Any = self.text_config.is_encoder_decoder
a__ : Optional[int] = num_query_tokens
a__ : int = self.vision_config.hidden_size
a__ : int = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
a__ : Any = 1.0
a__ : int = 0.02
@classmethod
def __lowerCAmelCase ( cls : Tuple , A__ : List[Any] , A__ : Union[str, Any] , A__ : Optional[Any] , **A__ : Union[str, Any] , ) -> Dict:
'''simple docstring'''
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A__ , )
def __lowerCAmelCase ( self : List[str] ) -> Optional[int]:
'''simple docstring'''
a__ : Optional[int] = copy.deepcopy(self.__dict__ )
a__ : Any = self.vision_config.to_dict()
a__ : Tuple = self.qformer_config.to_dict()
a__ : Optional[Any] = self.text_config.to_dict()
a__ : Union[str, Any] = self.__class__.model_type
return output
| 688 |
import math
def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ):
if 0 not in (x, y):
# We use the relation x^y = y*log10(x), where 10 is the base.
return y * math.logaa(lowerCamelCase__ )
else:
if x == 0: # 0 raised to any number is 0
return 0
elif y == 0:
return 1 # any number raised to 0 is 1
raise AssertionError("This should never happen" )
if __name__ == "__main__": # Main function
# Read two numbers from input and typecast them to int using map function.
# Here x is the base and y is the power.
__A ='''Enter the base and the power separated by a comma: '''
__A, __A =map(int, input(prompt).split(''','''))
__A, __A =map(int, input(prompt).split(''','''))
# We find the log of each number, using the function res(), which takes two
# arguments.
__A =res(xa, ya)
__A =res(xa, ya)
# We check for the largest number
if resa > resa:
print('''Largest number is''', xa, '''^''', ya)
elif resa > resa:
print('''Largest number is''', xa, '''^''', ya)
else:
print('''Both are equal''')
| 463 | 0 |
'''simple docstring'''
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece
from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging
lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__)
lowerCAmelCase_ : Any = '▁'
lowerCAmelCase_ : int = {
'vocab_file': 'vocab.json',
'spm_file': 'sentencepiece.bpe.model',
'tokenizer_config_file': 'tokenizer_config.json',
}
lowerCAmelCase_ : List[Any] = {
'vocab_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json',
},
'spm_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model',
},
'tokenizer_config_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json',
},
}
lowerCAmelCase_ : Optional[int] = {
'facebook/m2m100_418M': 10_24,
}
# fmt: off
lowerCAmelCase_ : Optional[int] = {
'm2m100': ['af', 'am', 'ar', 'ast', 'az', 'ba', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'ceb', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gu', 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'lb', 'lg', 'ln', 'lo', 'lt', 'lv', 'mg', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'ne', 'nl', 'no', 'ns', 'oc', 'or', 'pa', 'pl', 'ps', 'pt', 'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'so', 'sq', 'sr', 'ss', 'su', 'sv', 'sw', 'ta', 'th', 'tl', 'tn', 'tr', 'uk', 'ur', 'uz', 'vi', 'wo', 'xh', 'yi', 'yo', 'zh', 'zu'],
'wmt21': ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de']
}
class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ):
"""simple docstring"""
__a =VOCAB_FILES_NAMES
__a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a =PRETRAINED_VOCAB_FILES_MAP
__a =['input_ids', 'attention_mask']
__a =[]
__a =[]
def __init__( self : List[Any] , __a : List[str] , __a : Union[str, Any] , __a : Optional[Any]=None , __a : List[Any]=None , __a : Dict="<s>" , __a : Optional[Any]="</s>" , __a : Any="</s>" , __a : int="<pad>" , __a : str="<unk>" , __a : int="m2m100" , __a : Optional[Dict[str, Any]] = None , __a : int=8 , **__a : List[Any] , ):
_a = {} if sp_model_kwargs is None else sp_model_kwargs
_a = language_codes
_a = FAIRSEQ_LANGUAGE_CODES[language_codes]
_a = {lang_code: f'__{lang_code}__' for lang_code in fairseq_language_code}
_a = kwargs.get("additional_special_tokens" , [] )
kwargs["additional_special_tokens"] += [
self.get_lang_token(__a )
for lang_code in fairseq_language_code
if self.get_lang_token(__a ) not in kwargs["additional_special_tokens"]
]
super().__init__(
src_lang=__a , tgt_lang=__a , bos_token=__a , eos_token=__a , sep_token=__a , unk_token=__a , pad_token=__a , language_codes=__a , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__a , **__a , )
_a = vocab_file
_a = load_json(__a )
_a = {v: k for k, v in self.encoder.items()}
_a = spm_file
_a = load_spm(__a , self.sp_model_kwargs )
_a = len(self.encoder )
_a = {
self.get_lang_token(__a ): self.encoder_size + i for i, lang_code in enumerate(__a )
}
_a = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__a )}
_a = {v: k for k, v in self.lang_token_to_id.items()}
_a = src_lang if src_lang is not None else "en"
_a = tgt_lang
_a = self.get_lang_id(self._src_lang )
self.set_src_lang_special_tokens(self._src_lang )
_a = num_madeup_words
@property
def UpperCamelCase__ ( self : int ):
return len(self.encoder ) + len(self.lang_token_to_id )
@property
def UpperCamelCase__ ( self : str ):
return self._src_lang
@src_lang.setter
def UpperCamelCase__ ( self : Tuple , __a : str ):
_a = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def UpperCamelCase__ ( self : Any , __a : str ):
return self.sp_model.encode(__a , out_type=__a )
def UpperCamelCase__ ( self : Dict , __a : Dict ):
if token in self.lang_token_to_id:
return self.lang_token_to_id[token]
return self.encoder.get(__a , self.encoder[self.unk_token] )
def UpperCamelCase__ ( self : Union[str, Any] , __a : int ):
if index in self.id_to_lang_token:
return self.id_to_lang_token[index]
return self.decoder.get(__a , self.unk_token )
def UpperCamelCase__ ( self : List[Any] , __a : Dict ):
_a = []
_a = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(__a ) + token
_a = []
else:
current_sub_tokens.append(__a )
out_string += self.sp_model.decode(__a )
return out_string.strip()
def UpperCamelCase__ ( self : Optional[Any] , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a )
_a = [1] * len(self.prefix_tokens )
_a = [1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(__a )) + suffix_ones
return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones
def UpperCamelCase__ ( self : Dict , __a : List[int] , __a : Optional[List[int]] = None ):
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def UpperCamelCase__ ( self : Optional[int] ):
_a = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : int ):
_a = self.__dict__.copy()
_a = None
return state
def __setstate__( self : int , __a : Dict ):
_a = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
_a = {}
_a = load_spm(self.spm_file , self.sp_model_kwargs )
def UpperCamelCase__ ( self : Any , __a : str , __a : Optional[str] = None ):
_a = Path(__a )
if not save_dir.is_dir():
raise OSError(f'{save_directory} should be a directory' )
_a = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
)
_a = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
)
save_json(self.encoder , __a )
if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ):
copyfile(self.spm_file , __a )
elif not os.path.isfile(self.spm_file ):
with open(__a , "wb" ) as fi:
_a = self.sp_model.serialized_model_proto()
fi.write(__a )
return (str(__a ), str(__a ))
def UpperCamelCase__ ( self : Tuple , __a : List[str] , __a : str = "en" , __a : Optional[List[str]] = None , __a : str = "ro" , **__a : Union[str, Any] , ):
_a = src_lang
_a = tgt_lang
self.set_src_lang_special_tokens(self.src_lang )
return super().prepare_seqaseq_batch(__a , __a , **__a )
def UpperCamelCase__ ( self : Tuple , __a : int , __a : Optional[str] , __a : Optional[str] , **__a : int ):
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
_a = src_lang
_a = self(__a , add_special_tokens=__a , **__a )
_a = self.get_lang_id(__a )
_a = tgt_lang_id
return inputs
def UpperCamelCase__ ( self : Any ):
self.set_src_lang_special_tokens(self.src_lang )
def UpperCamelCase__ ( self : Optional[Any] ):
self.set_tgt_lang_special_tokens(self.tgt_lang )
def UpperCamelCase__ ( self : Optional[Any] , __a : str ):
_a = self.get_lang_token(__a )
_a = self.lang_token_to_id[lang_token]
_a = [self.cur_lang_id]
_a = [self.eos_token_id]
def UpperCamelCase__ ( self : Optional[int] , __a : str ):
_a = self.get_lang_token(__a )
_a = self.lang_token_to_id[lang_token]
_a = [self.cur_lang_id]
_a = [self.eos_token_id]
def UpperCamelCase__ ( self : List[Any] , __a : str ):
return self.lang_code_to_token[lang]
def UpperCamelCase__ ( self : Optional[Any] , __a : str ):
_a = self.get_lang_token(__a )
return self.lang_token_to_id[lang_token]
def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor:
_a = sentencepiece.SentencePieceProcessor(**lowercase )
spm.Load(str(lowercase ) )
return spm
def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]:
with open(lowercase , "r" ) as f:
return json.load(lowercase )
def _lowerCamelCase ( lowercase : int , lowercase : str ) -> None:
with open(lowercase , "w" ) as f:
json.dump(lowercase , lowercase , indent=2 )
| 521 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import _LazyModule
lowerCAmelCase_ : List[Any] = {'tokenization_byt5': ['ByT5Tokenizer']}
if TYPE_CHECKING:
from .tokenization_byta import ByTaTokenizer
else:
import sys
lowerCAmelCase_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 521 | 1 |
"""simple docstring"""
import gc
import threading
import time
import psutil
import torch
class __a :
def __init__( self ):
_lowerCamelCase = psutil.Process()
_lowerCamelCase = False
def snake_case_ ( self ):
_lowerCamelCase = -1
while True:
_lowerCamelCase = max(self.process.memory_info().rss , self.cpu_memory_peak )
# can't sleep or will not catch the peak right (this comment is here on purpose)
if not self.peak_monitoring:
break
def snake_case_ ( self ):
_lowerCamelCase = True
_lowerCamelCase = threading.Thread(target=self.peak_monitor )
_lowerCamelCase = True
self.thread.start()
def snake_case_ ( self ):
_lowerCamelCase = False
self.thread.join()
return self.cpu_memory_peak
A_ : Optional[Any] =PeakCPUMemory()
def SCREAMING_SNAKE_CASE_ ( )-> str:
# Time
_lowerCamelCase = {'time': time.time()}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
_lowerCamelCase = psutil.Process().memory_info().rss
cpu_peak_tracker.start()
# GPU mem
for i in range(torch.cuda.device_count() ):
_lowerCamelCase = torch.cuda.memory_allocated(snake_case )
torch.cuda.reset_peak_memory_stats()
return measures
def SCREAMING_SNAKE_CASE_ ( snake_case : List[Any] )-> Any:
# Time
_lowerCamelCase = {'time': time.time() - start_measures['time']}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
_lowerCamelCase = (psutil.Process().memory_info().rss - start_measures['cpu']) / 2**20
_lowerCamelCase = (cpu_peak_tracker.stop() - start_measures['cpu']) / 2**20
# GPU mem
for i in range(torch.cuda.device_count() ):
_lowerCamelCase = (torch.cuda.memory_allocated(snake_case ) - start_measures[str(snake_case )]) / 2**20
_lowerCamelCase = (torch.cuda.max_memory_allocated(snake_case ) - start_measures[str(snake_case )]) / 2**20
return measures
def SCREAMING_SNAKE_CASE_ ( snake_case : Any , snake_case : Any )-> Dict:
print(f'{description}:' )
print(f'- Time: {measures["time"]:.2f}s' )
for i in range(torch.cuda.device_count() ):
print(f'- GPU {i} allocated: {measures[str(snake_case )]:.2f}MiB' )
_lowerCamelCase = measures[f'{i}-peak']
print(f'- GPU {i} peak: {peak:.2f}MiB' )
print(f'- CPU RAM allocated: {measures["cpu"]:.2f}MiB' )
print(f'- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB' )
| 650 |
"""simple docstring"""
# Imports
import numpy as np
class __a :
def __init__( self , a__=None , a__=None , a__=None , a__=None , a__=None ):
self.set_matricies(red=a__ , green=a__ , blue=a__ , red_edge=a__ , nir=a__ )
def snake_case_ ( self , a__=None , a__=None , a__=None , a__=None , a__=None ):
if red is not None:
_lowerCamelCase = red
if green is not None:
_lowerCamelCase = green
if blue is not None:
_lowerCamelCase = blue
if red_edge is not None:
_lowerCamelCase = red_edge
if nir is not None:
_lowerCamelCase = nir
return True
def snake_case_ ( self , a__="" , a__=None , a__=None , a__=None , a__=None , a__=None ):
self.set_matricies(red=a__ , green=a__ , blue=a__ , red_edge=a__ , nir=a__ )
_lowerCamelCase = {
'ARVI2': self.arvaa,
'CCCI': self.ccci,
'CVI': self.cvi,
'GLI': self.gli,
'NDVI': self.ndvi,
'BNDVI': self.bndvi,
'redEdgeNDVI': self.red_edge_ndvi,
'GNDVI': self.gndvi,
'GBNDVI': self.gbndvi,
'GRNDVI': self.grndvi,
'RBNDVI': self.rbndvi,
'PNDVI': self.pndvi,
'ATSAVI': self.atsavi,
'BWDRVI': self.bwdrvi,
'CIgreen': self.ci_green,
'CIrededge': self.ci_rededge,
'CI': self.ci,
'CTVI': self.ctvi,
'GDVI': self.gdvi,
'EVI': self.evi,
'GEMI': self.gemi,
'GOSAVI': self.gosavi,
'GSAVI': self.gsavi,
'Hue': self.hue,
'IVI': self.ivi,
'IPVI': self.ipvi,
'I': self.i,
'RVI': self.rvi,
'MRVI': self.mrvi,
'MSAVI': self.m_savi,
'NormG': self.norm_g,
'NormNIR': self.norm_nir,
'NormR': self.norm_r,
'NGRDI': self.ngrdi,
'RI': self.ri,
'S': self.s,
'IF': self._if,
'DVI': self.dvi,
'TVI': self.tvi,
'NDRE': self.ndre,
}
try:
return funcs[index]()
except KeyError:
print('Index not in the list!' )
return False
def snake_case_ ( self ):
return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red)))
def snake_case_ ( self ):
return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
(self.nir - self.red) / (self.nir + self.red)
)
def snake_case_ ( self ):
return self.nir * (self.red / (self.green**2))
def snake_case_ ( self ):
return (2 * self.green - self.red - self.blue) / (
2 * self.green + self.red + self.blue
)
def snake_case_ ( self ):
return (self.nir - self.red) / (self.nir + self.red)
def snake_case_ ( self ):
return (self.nir - self.blue) / (self.nir + self.blue)
def snake_case_ ( self ):
return (self.redEdge - self.red) / (self.redEdge + self.red)
def snake_case_ ( self ):
return (self.nir - self.green) / (self.nir + self.green)
def snake_case_ ( self ):
return (self.nir - (self.green + self.blue)) / (
self.nir + (self.green + self.blue)
)
def snake_case_ ( self ):
return (self.nir - (self.green + self.red)) / (
self.nir + (self.green + self.red)
)
def snake_case_ ( self ):
return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))
def snake_case_ ( self ):
return (self.nir - (self.green + self.red + self.blue)) / (
self.nir + (self.green + self.red + self.blue)
)
def snake_case_ ( self , a__=0.08 , a__=1.22 , a__=0.03 ):
return a * (
(self.nir - a * self.red - b)
/ (a * self.nir + self.red - a * b + x * (1 + a**2))
)
def snake_case_ ( self ):
return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)
def snake_case_ ( self ):
return (self.nir / self.green) - 1
def snake_case_ ( self ):
return (self.nir / self.redEdge) - 1
def snake_case_ ( self ):
return (self.red - self.blue) / self.red
def snake_case_ ( self ):
_lowerCamelCase = self.ndvi()
return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2))
def snake_case_ ( self ):
return self.nir - self.green
def snake_case_ ( self ):
return 2.5 * (
(self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
)
def snake_case_ ( self ):
_lowerCamelCase = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
self.nir + self.red + 0.5
)
return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red)
def snake_case_ ( self , a__=0.16 ):
return (self.nir - self.green) / (self.nir + self.green + y)
def snake_case_ ( self , a__=0.5 ):
return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n)
def snake_case_ ( self ):
return np.arctan(
((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) )
def snake_case_ ( self , a__=None , a__=None ):
return (self.nir - b) / (a * self.red)
def snake_case_ ( self ):
return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1)
def snake_case_ ( self ):
return (self.red + self.green + self.blue) / 30.5
def snake_case_ ( self ):
return self.nir / self.red
def snake_case_ ( self ):
return (self.rvi() - 1) / (self.rvi() + 1)
def snake_case_ ( self ):
return (
(2 * self.nir + 1)
- ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2)
) / 2
def snake_case_ ( self ):
return self.green / (self.nir + self.red + self.green)
def snake_case_ ( self ):
return self.nir / (self.nir + self.red + self.green)
def snake_case_ ( self ):
return self.red / (self.nir + self.red + self.green)
def snake_case_ ( self ):
return (self.green - self.red) / (self.green + self.red)
def snake_case_ ( self ):
return (self.red - self.green) / (self.red + self.green)
def snake_case_ ( self ):
_lowerCamelCase = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] )
_lowerCamelCase = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] )
return (max_value - min_value) / max_value
def snake_case_ ( self ):
return (2 * self.red - self.green - self.blue) / (self.green - self.blue)
def snake_case_ ( self ):
return self.nir / self.red
def snake_case_ ( self ):
return (self.ndvi() + 0.5) ** (1 / 2)
def snake_case_ ( self ):
return (self.nir - self.redEdge) / (self.nir + self.redEdge)
| 650 | 1 |
'''simple docstring'''
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__)
UpperCAmelCase_ : Any = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase_ : str = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class UpperCAmelCase__ :
lowerCAmelCase_ = field(
default=A , metadata={'help': 'Model type selected in the list: ' + ', '.join(A )} )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
lowerCAmelCase_ = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
lowerCAmelCase_ = field(
default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , )
lowerCAmelCase_ = field(
default=64 , metadata={
'help': (
'The maximum number of tokens for the question. Questions longer than this will '
'be truncated to this length.'
)
} , )
lowerCAmelCase_ = field(
default=30 , metadata={
'help': (
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
)
} , )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
lowerCAmelCase_ = field(
default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCAmelCase_ = field(
default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCAmelCase_ = field(
default=0 , metadata={
'help': (
'language id of input for language-specific xlm models (see'
' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
)
} , )
lowerCAmelCase_ = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} )
class UpperCAmelCase__ ( A ):
lowerCAmelCase_ = 'train'
lowerCAmelCase_ = 'dev'
class UpperCAmelCase__ ( A ):
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
def __init__( self : Optional[int],__A : SquadDataTrainingArguments,__A : PreTrainedTokenizer,__A : Optional[int] = None,__A : Union[str, Split] = Split.train,__A : Optional[bool] = False,__A : Optional[str] = None,__A : Optional[str] = "pt",):
_lowerCamelCase : Tuple = args
_lowerCamelCase : List[str] = is_language_sensitive
_lowerCamelCase : Dict = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(__A,__A ):
try:
_lowerCamelCase : Union[str, Any] = Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name" )
_lowerCamelCase : str = mode
# Load data features from cache or dataset file
_lowerCamelCase : str = "v2" if args.version_2_with_negative else "v1"
_lowerCamelCase : Optional[Any] = os.path.join(
cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',)
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
_lowerCamelCase : Tuple = cached_features_file + ".lock"
with FileLock(__A ):
if os.path.exists(__A ) and not args.overwrite_cache:
_lowerCamelCase : int = time.time()
_lowerCamelCase : int = torch.load(__A )
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
_lowerCamelCase : Union[str, Any] = self.old_features["features"]
_lowerCamelCase : List[Any] = self.old_features.get("dataset",__A )
_lowerCamelCase : List[Any] = self.old_features.get("examples",__A )
logger.info(
f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start )
if self.dataset is None or self.examples is None:
logger.warning(
f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
" future run" )
else:
if mode == Split.dev:
_lowerCamelCase : Dict = self.processor.get_dev_examples(args.data_dir )
else:
_lowerCamelCase : Dict = self.processor.get_train_examples(args.data_dir )
_lowerCamelCase , _lowerCamelCase : Dict = squad_convert_examples_to_features(
examples=self.examples,tokenizer=__A,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__A,)
_lowerCamelCase : List[Any] = time.time()
torch.save(
{"features": self.features, "dataset": self.dataset, "examples": self.examples},__A,)
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' )
def __len__( self : Optional[Any] ):
return len(self.features )
def __getitem__( self : Tuple,__A : str ):
# Convert to Tensors and build dataset
_lowerCamelCase : List[str] = self.features[i]
_lowerCamelCase : List[str] = torch.tensor(feature.input_ids,dtype=torch.long )
_lowerCamelCase : Optional[int] = torch.tensor(feature.attention_mask,dtype=torch.long )
_lowerCamelCase : Union[str, Any] = torch.tensor(feature.token_type_ids,dtype=torch.long )
_lowerCamelCase : str = torch.tensor(feature.cls_index,dtype=torch.long )
_lowerCamelCase : str = torch.tensor(feature.p_mask,dtype=torch.float )
_lowerCamelCase : Tuple = torch.tensor(feature.is_impossible,dtype=torch.float )
_lowerCamelCase : Optional[Any] = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({"cls_index": cls_index, "p_mask": p_mask} )
if self.args.version_2_with_negative:
inputs.update({"is_impossible": is_impossible} )
if self.is_language_sensitive:
inputs.update({"langs": (torch.ones(input_ids.shape,dtype=torch.intaa ) * self.args.lang_id)} )
if self.mode == Split.train:
_lowerCamelCase : List[str] = torch.tensor(feature.start_position,dtype=torch.long )
_lowerCamelCase : Any = torch.tensor(feature.end_position,dtype=torch.long )
inputs.update({"start_positions": start_positions, "end_positions": end_positions} )
return inputs | 11 |
'''simple docstring'''
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__)
UpperCAmelCase_ : Any = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase_ : str = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class UpperCAmelCase__ :
lowerCAmelCase_ = field(
default=A , metadata={'help': 'Model type selected in the list: ' + ', '.join(A )} )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
lowerCAmelCase_ = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
lowerCAmelCase_ = field(
default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , )
lowerCAmelCase_ = field(
default=64 , metadata={
'help': (
'The maximum number of tokens for the question. Questions longer than this will '
'be truncated to this length.'
)
} , )
lowerCAmelCase_ = field(
default=30 , metadata={
'help': (
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
)
} , )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
lowerCAmelCase_ = field(
default=A , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
lowerCAmelCase_ = field(
default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCAmelCase_ = field(
default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCAmelCase_ = field(
default=0 , metadata={
'help': (
'language id of input for language-specific xlm models (see'
' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
)
} , )
lowerCAmelCase_ = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} )
class UpperCAmelCase__ ( A ):
lowerCAmelCase_ = 'train'
lowerCAmelCase_ = 'dev'
class UpperCAmelCase__ ( A ):
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
def __init__( self : Optional[int],__A : SquadDataTrainingArguments,__A : PreTrainedTokenizer,__A : Optional[int] = None,__A : Union[str, Split] = Split.train,__A : Optional[bool] = False,__A : Optional[str] = None,__A : Optional[str] = "pt",):
_lowerCamelCase : Tuple = args
_lowerCamelCase : List[str] = is_language_sensitive
_lowerCamelCase : Dict = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(__A,__A ):
try:
_lowerCamelCase : Union[str, Any] = Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name" )
_lowerCamelCase : str = mode
# Load data features from cache or dataset file
_lowerCamelCase : str = "v2" if args.version_2_with_negative else "v1"
_lowerCamelCase : Optional[Any] = os.path.join(
cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',)
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
_lowerCamelCase : Tuple = cached_features_file + ".lock"
with FileLock(__A ):
if os.path.exists(__A ) and not args.overwrite_cache:
_lowerCamelCase : int = time.time()
_lowerCamelCase : int = torch.load(__A )
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
_lowerCamelCase : Union[str, Any] = self.old_features["features"]
_lowerCamelCase : List[Any] = self.old_features.get("dataset",__A )
_lowerCamelCase : List[Any] = self.old_features.get("examples",__A )
logger.info(
f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start )
if self.dataset is None or self.examples is None:
logger.warning(
f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
" future run" )
else:
if mode == Split.dev:
_lowerCamelCase : Dict = self.processor.get_dev_examples(args.data_dir )
else:
_lowerCamelCase : Dict = self.processor.get_train_examples(args.data_dir )
_lowerCamelCase , _lowerCamelCase : Dict = squad_convert_examples_to_features(
examples=self.examples,tokenizer=__A,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__A,)
_lowerCamelCase : List[Any] = time.time()
torch.save(
{"features": self.features, "dataset": self.dataset, "examples": self.examples},__A,)
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' )
def __len__( self : Optional[Any] ):
return len(self.features )
def __getitem__( self : Tuple,__A : str ):
# Convert to Tensors and build dataset
_lowerCamelCase : List[str] = self.features[i]
_lowerCamelCase : List[str] = torch.tensor(feature.input_ids,dtype=torch.long )
_lowerCamelCase : Optional[int] = torch.tensor(feature.attention_mask,dtype=torch.long )
_lowerCamelCase : Union[str, Any] = torch.tensor(feature.token_type_ids,dtype=torch.long )
_lowerCamelCase : str = torch.tensor(feature.cls_index,dtype=torch.long )
_lowerCamelCase : str = torch.tensor(feature.p_mask,dtype=torch.float )
_lowerCamelCase : Tuple = torch.tensor(feature.is_impossible,dtype=torch.float )
_lowerCamelCase : Optional[Any] = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({"cls_index": cls_index, "p_mask": p_mask} )
if self.args.version_2_with_negative:
inputs.update({"is_impossible": is_impossible} )
if self.is_language_sensitive:
inputs.update({"langs": (torch.ones(input_ids.shape,dtype=torch.intaa ) * self.args.lang_id)} )
if self.mode == Split.train:
_lowerCamelCase : List[str] = torch.tensor(feature.start_position,dtype=torch.long )
_lowerCamelCase : Any = torch.tensor(feature.end_position,dtype=torch.long )
inputs.update({"start_positions": start_positions, "end_positions": end_positions} )
return inputs | 11 | 1 |
"""simple docstring"""
import itertools
import json
import os
import unittest
from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast
from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCamelCase__ ( _lowerCAmelCase , unittest.TestCase ):
"""simple docstring"""
A__ : List[str] = LongformerTokenizer
A__ : Optional[int] = True
A__ : Optional[Any] = LongformerTokenizerFast
A__ : Tuple = True
def snake_case__ ( self ) -> Any:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
A__ = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
A__ = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) )
A__ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
A__ = {"unk_token": "<unk>"}
A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
A__ = 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(SCREAMING_SNAKE_CASE__ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) )
def snake_case__ ( self , **SCREAMING_SNAKE_CASE__ ) -> int:
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self , **SCREAMING_SNAKE_CASE__ ) -> int:
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ ) -> Dict:
A__ = "lower newer"
A__ = "lower newer"
return input_text, output_text
def snake_case__ ( self ) -> Optional[int]:
A__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map )
A__ = "lower newer"
A__ = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
A__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # , add_prefix_space=True)
self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = tokens + [tokenizer.unk_token]
A__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self ) -> Tuple:
A__ = self.get_tokenizer()
self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , [0, 31414, 232, 328, 2] )
self.assertListEqual(
tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] , )
@slow
def snake_case__ ( self ) -> Dict:
A__ = self.tokenizer_class.from_pretrained("allenai/longformer-base-4096" )
A__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.encode(
"sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.encode(
"sequence builders" , "multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
def snake_case__ ( self ) -> List[Any]:
A__ = self.get_tokenizer()
A__ = "Encode this sequence."
A__ = tokenizer.byte_encoder[" ".encode("utf-8" )[0]]
# Testing encoder arguments
A__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
tokenizer.add_special_tokens({"bos_token": "<s>"} )
A__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0]
self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# Testing spaces after special tokens
A__ = "<mask>"
tokenizer.add_special_tokens(
{"mask_token": AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ )} ) # mask token has a left space
A__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
A__ = "Encode <mask> sequence"
A__ = "Encode <mask>sequence"
A__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ )
A__ = encoded.index(SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.encode(SCREAMING_SNAKE_CASE__ )
A__ = encoded.index(SCREAMING_SNAKE_CASE__ )
A__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self ) -> Any:
pass
def snake_case__ ( self ) -> Optional[int]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
A__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
A__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
A__ = "A, <mask> AllenNLP sentence."
A__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ )
# 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"] ) , )
A__ = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] )
A__ = 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, 50264, 3823, 487, 21992, 3645, 4, 2] )
self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] )
self.assertSequenceEqual(
SCREAMING_SNAKE_CASE__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
self.assertSequenceEqual(
SCREAMING_SNAKE_CASE__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
def snake_case__ ( self ) -> List[str]:
for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ):
A__ = self.rust_tokenizer_class.from_pretrained(
self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() )
A__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() )
self.assertEqual(pre_tokenizer_state["add_prefix_space"] , SCREAMING_SNAKE_CASE__ )
self.assertEqual(post_processor_state["add_prefix_space"] , SCREAMING_SNAKE_CASE__ )
self.assertEqual(post_processor_state["trim_offsets"] , SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self ) -> Optional[Any]:
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
# `trim_offsets`
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
A__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name`
A__ = f"""{text_of_1_token} {text_of_1_token}"""
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE__ ) + 1, len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE__ ) + 1, len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE__ ), len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE__ ), len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = f""" {text}"""
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
# )
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
# self.assertEqual(
# encoding.offset_mapping[1],
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
# )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE__ ) + 1, 1 + len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE__ ), 1 + len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
A__ = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ )
A__ = tokenizer_r(SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE__ ), 1 + len(SCREAMING_SNAKE_CASE__ ) + 1 + len(SCREAMING_SNAKE_CASE__ )) , )
| 104 |
'''simple docstring'''
import unittest
from knapsack import knapsack as k
class a_ ( unittest.TestCase ):
def UpperCamelCase ( self : str ) -> List[Any]:
snake_case: Optional[Any] =0
snake_case: List[str] =[0]
snake_case: List[str] =[0]
snake_case: Union[str, Any] =len(a_ )
self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 0 )
snake_case: Union[str, Any] =[6_0]
snake_case: str =[1_0]
snake_case: List[str] =len(a_ )
self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 0 )
def UpperCamelCase ( self : int ) -> Optional[Any]:
snake_case: Optional[int] =3
snake_case: Dict =[1, 2, 3]
snake_case: List[Any] =[3, 2, 1]
snake_case: Tuple =len(a_ )
self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 5 )
def UpperCamelCase ( self : List[str] ) -> str:
snake_case: Any =5_0
snake_case: str =[6_0, 1_0_0, 1_2_0]
snake_case: Any =[1_0, 2_0, 3_0]
snake_case: Tuple =len(a_ )
self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 2_2_0 )
if __name__ == "__main__":
unittest.main()
| 350 | 0 |
import math
def lowerCamelCase_(lowerCamelCase_ ) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def lowerCamelCase_(lowerCamelCase_ = 10_001 ) -> int:
try:
UpperCAmelCase = int(lowerCamelCase_ )
except (TypeError, ValueError):
raise TypeError("Parameter nth must be int or castable to int." ) from None
if nth <= 0:
raise ValueError("Parameter nth must be greater than or equal to one." )
UpperCAmelCase = []
UpperCAmelCase = 2
while len(lowerCamelCase_ ) < nth:
if is_prime(lowerCamelCase_ ):
primes.append(lowerCamelCase_ )
num += 1
else:
num += 1
return primes[len(lowerCamelCase_ ) - 1]
if __name__ == "__main__":
print(F'''{solution() = }''')
| 457 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__lowerCamelCase : Any = {
"configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Optional[int] = [
"MEGA_PRETRAINED_MODEL_ARCHIVE_LIST",
"MegaForCausalLM",
"MegaForMaskedLM",
"MegaForMultipleChoice",
"MegaForQuestionAnswering",
"MegaForSequenceClassification",
"MegaForTokenClassification",
"MegaModel",
"MegaPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__lowerCamelCase : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 457 | 1 |
import importlib
import torch
import yaml
from omegaconf import OmegaConf
from taming.models.vqgan import VQModel
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase=False ):
__magic_name__ : Optional[int] =OmegaConf.load(lowerCamelCase )
if display:
print(yaml.dump(OmegaConf.to_container(lowerCamelCase ) ) )
return config
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None ):
if conf_path is None:
__magic_name__ : List[str] ="""./model_checkpoints/vqgan_only.yaml"""
__magic_name__ : Dict =load_config(lowerCamelCase , display=lowerCamelCase )
__magic_name__ : Tuple =VQModel(**config.model.params )
if ckpt_path is None:
__magic_name__ : Optional[Any] ="""./model_checkpoints/vqgan_only.pt"""
__magic_name__ : Tuple =torch.load(lowerCamelCase , map_location=lowerCamelCase )
if ".ckpt" in ckpt_path:
__magic_name__ : Any =sd["""state_dict"""]
model.load_state_dict(lowerCamelCase , strict=lowerCamelCase )
model.to(lowerCamelCase )
del sd
return model
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase ):
__magic_name__ , __magic_name__ , __magic_name__ : Optional[Any] =model.encode(lowerCamelCase )
print(F"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" )
__magic_name__ : List[Any] =model.decode(lowerCamelCase )
return xrec
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase=False ):
__magic_name__ , __magic_name__ : Optional[int] =string.rsplit(""".""" , 1 )
if reload:
__magic_name__ : Optional[int] =importlib.import_module(lowerCamelCase )
importlib.reload(lowerCamelCase )
return getattr(importlib.import_module(lowerCamelCase , package=lowerCamelCase ) , cls )
def lowerCAmelCase_ ( lowerCamelCase ):
if "target" not in config:
raise KeyError("""Expected key `target` to instantiate.""" )
return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) )
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=True , lowerCamelCase=True ):
__magic_name__ : str =instantiate_from_config(lowerCamelCase )
if sd is not None:
model.load_state_dict(lowerCamelCase )
if gpu:
model.cuda()
if eval_mode:
model.eval()
return {"model": model}
def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
# load the specified checkpoint
if ckpt:
__magic_name__ : str =torch.load(lowerCamelCase , map_location="""cpu""" )
__magic_name__ : Any =pl_sd["""global_step"""]
print(F"loaded model from global step {global_step}." )
else:
__magic_name__ : List[Any] ={"""state_dict""": None}
__magic_name__ : Optional[Any] =None
__magic_name__ : Tuple =load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=lowerCamelCase , eval_mode=lowerCamelCase )["""model"""]
return model, global_step
| 21 |
"""simple docstring"""
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
A_ : int =logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[int] , snake_case : Tuple , snake_case : Union[str, Any] )-> Optional[Any]:
_lowerCamelCase = WavaVecaForSequenceClassification.from_pretrained(snake_case , config=snake_case )
_lowerCamelCase = downstream_dict['projector.weight']
_lowerCamelCase = downstream_dict['projector.bias']
_lowerCamelCase = downstream_dict['model.post_net.linear.weight']
_lowerCamelCase = downstream_dict['model.post_net.linear.bias']
return model
def SCREAMING_SNAKE_CASE_ ( snake_case : Union[str, Any] , snake_case : Dict , snake_case : Optional[int] )-> List[str]:
_lowerCamelCase = WavaVecaForAudioFrameClassification.from_pretrained(snake_case , config=snake_case )
_lowerCamelCase = downstream_dict['model.linear.weight']
_lowerCamelCase = downstream_dict['model.linear.bias']
return model
def SCREAMING_SNAKE_CASE_ ( snake_case : str , snake_case : List[str] , snake_case : Any )-> Tuple:
_lowerCamelCase = WavaVecaForXVector.from_pretrained(snake_case , config=snake_case )
_lowerCamelCase = downstream_dict['connector.weight']
_lowerCamelCase = downstream_dict['connector.bias']
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
_lowerCamelCase = downstream_dict[
f'model.framelevel_feature_extractor.module.{i}.kernel.weight'
]
_lowerCamelCase = downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias']
_lowerCamelCase = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight']
_lowerCamelCase = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias']
_lowerCamelCase = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight']
_lowerCamelCase = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias']
_lowerCamelCase = downstream_dict['objective.W']
return model
@torch.no_grad()
def SCREAMING_SNAKE_CASE_ ( snake_case : List[str] , snake_case : Optional[Any] , snake_case : int , snake_case : Dict )-> str:
_lowerCamelCase = torch.load(snake_case , map_location='cpu' )
_lowerCamelCase = checkpoint['Downstream']
_lowerCamelCase = WavaVecaConfig.from_pretrained(snake_case )
_lowerCamelCase = WavaVecaFeatureExtractor.from_pretrained(
snake_case , return_attention_mask=snake_case , do_normalize=snake_case )
_lowerCamelCase = hf_config.architectures[0]
if arch.endswith('ForSequenceClassification' ):
_lowerCamelCase = convert_classification(snake_case , snake_case , snake_case )
elif arch.endswith('ForAudioFrameClassification' ):
_lowerCamelCase = convert_diarization(snake_case , snake_case , snake_case )
elif arch.endswith('ForXVector' ):
_lowerCamelCase = convert_xvector(snake_case , snake_case , snake_case )
else:
raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' )
if hf_config.use_weighted_layer_sum:
_lowerCamelCase = checkpoint['Featurizer']['weights']
hf_feature_extractor.save_pretrained(snake_case )
hf_model.save_pretrained(snake_case )
if __name__ == "__main__":
A_ : Optional[int] =argparse.ArgumentParser()
parser.add_argument(
"""--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model."""
)
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""")
parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""")
A_ : List[Any] =parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 650 | 0 |
"""simple docstring"""
from typing import Any, Dict, Optional
import torch
import torch.nn.functional as F
from torch import nn
from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings
@maybe_allow_in_graph
class lowercase ( nn.Module):
def __init__( self : List[Any] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : str = "geglu" , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = True , _lowerCamelCase : str = "layer_norm" , _lowerCamelCase : bool = False , ):
"""simple docstring"""
super().__init__()
A_ : Optional[Any] = only_cross_attention
A_ : int = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero'''
A_ : str = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm'''
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
raise ValueError(
F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"""
F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" )
# Define 3 blocks. Each block has its own normalization layer.
# 1. Self-Attn
if self.use_ada_layer_norm:
A_ : Tuple = AdaLayerNorm(_lowerCamelCase , _lowerCamelCase )
elif self.use_ada_layer_norm_zero:
A_ : Dict = AdaLayerNormZero(_lowerCamelCase , _lowerCamelCase )
else:
A_ : List[str] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase )
A_ : str = Attention(
query_dim=_lowerCamelCase , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_lowerCamelCase , )
# 2. Cross-Attn
if cross_attention_dim is not None or double_self_attention:
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
# the second cross attention block.
A_ : List[str] = (
AdaLayerNorm(_lowerCamelCase , _lowerCamelCase )
if self.use_ada_layer_norm
else nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase )
)
A_ : Dict = Attention(
query_dim=_lowerCamelCase , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , upcast_attention=_lowerCamelCase , ) # is self-attn if encoder_hidden_states is none
else:
A_ : str = None
A_ : List[str] = None
# 3. Feed-forward
A_ : Tuple = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase )
A_ : int = FeedForward(_lowerCamelCase , dropout=_lowerCamelCase , activation_fn=_lowerCamelCase , final_dropout=_lowerCamelCase )
# let chunk size default to None
A_ : List[str] = None
A_ : str = 0
def a_ ( self : List[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : int ):
"""simple docstring"""
A_ : Optional[int] = chunk_size
A_ : Tuple = dim
def a_ ( self : Optional[Any] , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : Optional[torch.FloatTensor] = None , _lowerCamelCase : Optional[torch.FloatTensor] = None , _lowerCamelCase : Optional[torch.FloatTensor] = None , _lowerCamelCase : Optional[torch.LongTensor] = None , _lowerCamelCase : Dict[str, Any] = None , _lowerCamelCase : Optional[torch.LongTensor] = None , ):
"""simple docstring"""
if self.use_ada_layer_norm:
A_ : List[str] = self.norma(_lowerCamelCase , _lowerCamelCase )
elif self.use_ada_layer_norm_zero:
A_ , A_ , A_ , A_ , A_ : Dict = self.norma(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , hidden_dtype=hidden_states.dtype )
else:
A_ : int = self.norma(_lowerCamelCase )
A_ : Union[str, Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {}
A_ : int = self.attna(
_lowerCamelCase , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_lowerCamelCase , **_lowerCamelCase , )
if self.use_ada_layer_norm_zero:
A_ : Tuple = gate_msa.unsqueeze(1 ) * attn_output
A_ : str = attn_output + hidden_states
# 2. Cross-Attention
if self.attna is not None:
A_ : Dict = (
self.norma(_lowerCamelCase , _lowerCamelCase ) if self.use_ada_layer_norm else self.norma(_lowerCamelCase )
)
A_ : int = self.attna(
_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , attention_mask=_lowerCamelCase , **_lowerCamelCase , )
A_ : List[str] = attn_output + hidden_states
# 3. Feed-forward
A_ : str = self.norma(_lowerCamelCase )
if self.use_ada_layer_norm_zero:
A_ : str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
if self._chunk_size is not None:
# "feed_forward_chunk_size" can be used to save memory
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
raise ValueError(
F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" )
A_ : Dict = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
A_ : List[str] = torch.cat(
[self.ff(_lowerCamelCase ) for hid_slice in norm_hidden_states.chunk(_lowerCamelCase , dim=self._chunk_dim )] , dim=self._chunk_dim , )
else:
A_ : str = self.ff(_lowerCamelCase )
if self.use_ada_layer_norm_zero:
A_ : Optional[int] = gate_mlp.unsqueeze(1 ) * ff_output
A_ : Dict = ff_output + hidden_states
return hidden_states
class lowercase ( nn.Module):
def __init__( self : List[str] , _lowerCamelCase : int , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 4 , _lowerCamelCase : float = 0.0 , _lowerCamelCase : str = "geglu" , _lowerCamelCase : bool = False , ):
"""simple docstring"""
super().__init__()
A_ : List[Any] = int(dim * mult )
A_ : int = dim_out if dim_out is not None else dim
if activation_fn == "gelu":
A_ : List[Any] = GELU(_lowerCamelCase , _lowerCamelCase )
if activation_fn == "gelu-approximate":
A_ : Union[str, Any] = GELU(_lowerCamelCase , _lowerCamelCase , approximate='''tanh''' )
elif activation_fn == "geglu":
A_ : Union[str, Any] = GEGLU(_lowerCamelCase , _lowerCamelCase )
elif activation_fn == "geglu-approximate":
A_ : Dict = ApproximateGELU(_lowerCamelCase , _lowerCamelCase )
A_ : List[str] = nn.ModuleList([] )
# project in
self.net.append(_lowerCamelCase )
# project dropout
self.net.append(nn.Dropout(_lowerCamelCase ) )
# project out
self.net.append(nn.Linear(_lowerCamelCase , _lowerCamelCase ) )
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
if final_dropout:
self.net.append(nn.Dropout(_lowerCamelCase ) )
def a_ ( self : Any , _lowerCamelCase : Optional[Any] ):
"""simple docstring"""
for module in self.net:
A_ : Any = module(_lowerCamelCase )
return hidden_states
class lowercase ( nn.Module):
def __init__( self : Optional[Any] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : str = "none" ):
"""simple docstring"""
super().__init__()
A_ : Tuple = nn.Linear(_lowerCamelCase , _lowerCamelCase )
A_ : Optional[int] = approximate
def a_ ( self : List[str] , _lowerCamelCase : Dict ):
"""simple docstring"""
if gate.device.type != "mps":
return F.gelu(_lowerCamelCase , approximate=self.approximate )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype )
def a_ ( self : Any , _lowerCamelCase : int ):
"""simple docstring"""
A_ : str = self.proj(_lowerCamelCase )
A_ : List[Any] = self.gelu(_lowerCamelCase )
return hidden_states
class lowercase ( nn.Module):
def __init__( self : Optional[int] , _lowerCamelCase : int , _lowerCamelCase : int ):
"""simple docstring"""
super().__init__()
A_ : Union[str, Any] = nn.Linear(_lowerCamelCase , dim_out * 2 )
def a_ ( self : List[Any] , _lowerCamelCase : str ):
"""simple docstring"""
if gate.device.type != "mps":
return F.gelu(_lowerCamelCase )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype )
def a_ ( self : str , _lowerCamelCase : str ):
"""simple docstring"""
A_ , A_ : Union[str, Any] = self.proj(_lowerCamelCase ).chunk(2 , dim=-1 )
return hidden_states * self.gelu(_lowerCamelCase )
class lowercase ( nn.Module):
def __init__( self : Dict , _lowerCamelCase : int , _lowerCamelCase : int ):
"""simple docstring"""
super().__init__()
A_ : Optional[Any] = nn.Linear(_lowerCamelCase , _lowerCamelCase )
def a_ ( self : int , _lowerCamelCase : List[Any] ):
"""simple docstring"""
A_ : str = self.proj(_lowerCamelCase )
return x * torch.sigmoid(1.702 * x )
class lowercase ( nn.Module):
def __init__( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] ):
"""simple docstring"""
super().__init__()
A_ : List[str] = nn.Embedding(_lowerCamelCase , _lowerCamelCase )
A_ : str = nn.SiLU()
A_ : List[str] = nn.Linear(_lowerCamelCase , embedding_dim * 2 )
A_ : str = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase )
def a_ ( self : Tuple , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any ):
"""simple docstring"""
A_ : Union[str, Any] = self.linear(self.silu(self.emb(_lowerCamelCase ) ) )
A_ , A_ : List[str] = torch.chunk(_lowerCamelCase , 2 )
A_ : str = self.norm(_lowerCamelCase ) * (1 + scale) + shift
return x
class lowercase ( nn.Module):
def __init__( self : List[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[int] ):
"""simple docstring"""
super().__init__()
A_ : Optional[int] = CombinedTimestepLabelEmbeddings(_lowerCamelCase , _lowerCamelCase )
A_ : str = nn.SiLU()
A_ : List[Any] = nn.Linear(_lowerCamelCase , 6 * embedding_dim , bias=_lowerCamelCase )
A_ : Union[str, Any] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase , eps=1E-6 )
def a_ ( self : Tuple , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[Any]=None ):
"""simple docstring"""
A_ : Any = self.linear(self.silu(self.emb(_lowerCamelCase , _lowerCamelCase , hidden_dtype=_lowerCamelCase ) ) )
A_ , A_ , A_ , A_ , A_ , A_ : Any = emb.chunk(6 , dim=1 )
A_ : str = self.norm(_lowerCamelCase ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class lowercase ( nn.Module):
def __init__( self : Dict , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : float = 1E-5 ):
"""simple docstring"""
super().__init__()
A_ : int = num_groups
A_ : str = eps
if act_fn is None:
A_ : Optional[Any] = None
else:
A_ : str = get_activation(_lowerCamelCase )
A_ : Union[str, Any] = nn.Linear(_lowerCamelCase , out_dim * 2 )
def a_ ( self : Union[str, Any] , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int] ):
"""simple docstring"""
if self.act:
A_ : Optional[Any] = self.act(_lowerCamelCase )
A_ : List[str] = self.linear(_lowerCamelCase )
A_ : str = emb[:, :, None, None]
A_ , A_ : Any = emb.chunk(2 , dim=1 )
A_ : List[str] = F.group_norm(_lowerCamelCase , self.num_groups , eps=self.eps )
A_ : str = x * (1 + scale) + shift
return x
| 361 |
"""simple docstring"""
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : int = len(_UpperCAmelCase )
for i in range(length - 1 ):
A_ : str = i
for k in range(i + 1 , _UpperCAmelCase ):
if collection[k] < collection[least]:
A_ : Tuple = k
if least != i:
A_ , A_ : Optional[int] = (collection[i], collection[least])
return collection
if __name__ == "__main__":
_lowerCamelCase : Optional[int] = input('Enter numbers separated by a comma:\n').strip()
_lowerCamelCase : List[str] = [int(item) for item in user_input.split(',')]
print(selection_sort(unsorted))
| 361 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
snake_case_ = {
'''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''],
'''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ = ['''MaskFormerFeatureExtractor''']
snake_case_ = ['''MaskFormerImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ = [
'''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''MaskFormerForInstanceSegmentation''',
'''MaskFormerModel''',
'''MaskFormerPreTrainedModel''',
]
snake_case_ = [
'''MaskFormerSwinBackbone''',
'''MaskFormerSwinModel''',
'''MaskFormerSwinPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
from .configuration_maskformer_swin import MaskFormerSwinConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_maskformer import MaskFormerFeatureExtractor
from .image_processing_maskformer import MaskFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskformer import (
MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskFormerForInstanceSegmentation,
MaskFormerModel,
MaskFormerPreTrainedModel,
)
from .modeling_maskformer_swin import (
MaskFormerSwinBackbone,
MaskFormerSwinModel,
MaskFormerSwinPreTrainedModel,
)
else:
import sys
snake_case_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 164 |
"""simple docstring"""
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.generation import DisjunctiveConstraint
@require_torch
class a_ ( unittest.TestCase ):
def _snake_case ( self : Union[str, Any] ) ->Any:
'''simple docstring'''
_UpperCAmelCase = [[1, 2, 4], [1, 2, 3, 4]]
_UpperCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
self.assertTrue(isinstance(dc.token_ids , __UpperCamelCase ) )
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def _snake_case ( self : Optional[int] ) ->Dict:
'''simple docstring'''
_UpperCAmelCase = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint(__UpperCamelCase ) # fails here
def _snake_case ( self : Optional[int] ) ->Dict:
'''simple docstring'''
_UpperCAmelCase = [[1, 2, 3], [1, 2, 4]]
_UpperCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(1 )
_UpperCAmelCase = stepped is True and completed is False and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(2 )
_UpperCAmelCase = stepped is True and completed is False and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(3 )
_UpperCAmelCase = stepped is True and completed is True and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def _snake_case ( self : List[Any] ) ->Any:
'''simple docstring'''
_UpperCAmelCase = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
_UpperCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] ) | 555 | 0 |
def a_ ( lowerCAmelCase_ : Union[str, Any] ):
__lowerCAmelCase = 0
while num > 0:
digit_sum += num % 10
num //= 10
return digit_sum
def a_ ( lowerCAmelCase_ : Optional[Any] = 100 ):
__lowerCAmelCase = 1
__lowerCAmelCase = 2
for i in range(2, max_n + 1 ):
__lowerCAmelCase = pre_numerator
__lowerCAmelCase = 2 * i // 3 if i % 3 == 0 else 1
__lowerCAmelCase = cur_numerator
__lowerCAmelCase = e_cont * pre_numerator + temp
return sum_digits(lowerCAmelCase_ )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 718 |
import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
_snake_case : List[Any] = get_tests_dir('fixtures/dummy-config.json')
class _UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def lowercase ( self : List[str] ) -> List[str]:
__lowerCAmelCase = 0
def lowercase ( self : Dict ) -> Optional[Any]:
self.assertIsNotNone(transformers.models.auto.__spec__ )
self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto' ) )
def lowercase ( self : Dict ) -> List[str]:
__lowerCAmelCase = AutoConfig.from_pretrained('bert-base-uncased' )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def lowercase ( self : Optional[Any] ) -> List[str]:
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def lowercase ( self : Optional[int] ) -> List[Any]:
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def lowercase ( self : Union[str, Any] ) -> int:
__lowerCAmelCase = AutoConfig.for_model('roberta' )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def lowercase ( self : List[Any] ) -> int:
with tempfile.TemporaryDirectory() as tmp_dir:
# This model name contains bert and roberta, but roberta ends up being picked.
__lowerCAmelCase = os.path.join(lowerCAmelCase_ , 'fake-roberta' )
os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ )
with open(os.path.join(lowerCAmelCase_ , 'config.json' ) , 'w' ) as f:
f.write(json.dumps({} ) )
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ )
self.assertEqual(type(lowerCAmelCase_ ) , lowerCAmelCase_ )
def lowercase ( self : Union[str, Any] ) -> List[Any]:
try:
AutoConfig.register('custom' , lowerCAmelCase_ )
# Wrong model type will raise an error
with self.assertRaises(lowerCAmelCase_ ):
AutoConfig.register('model' , lowerCAmelCase_ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(lowerCAmelCase_ ):
AutoConfig.register('bert' , lowerCAmelCase_ )
# Now that the config is registered, it can be used as any other config with the auto-API
__lowerCAmelCase = CustomConfig()
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(lowerCAmelCase_ )
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
def lowercase ( self : Optional[int] ) -> Dict:
with self.assertRaisesRegex(
lowerCAmelCase_ , 'bert-base is not a local folder and is not a valid model identifier' ):
__lowerCAmelCase = AutoConfig.from_pretrained('bert-base' )
def lowercase ( self : List[Any] ) -> Dict:
with self.assertRaisesRegex(
lowerCAmelCase_ , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ):
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ , revision='aaaaaa' )
def lowercase ( self : Union[str, Any] ) -> Optional[Any]:
with self.assertRaisesRegex(
lowerCAmelCase_ , 'hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.' , ):
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/no-config-test-repo' )
def lowercase ( self : str ) -> str:
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(lowerCAmelCase_ ):
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(lowerCAmelCase_ ):
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' , trust_remote_code=lowerCAmelCase_ )
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(config.__class__.__name__ , 'NewModelConfig' )
# Test config can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(lowerCAmelCase_ )
__lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase_ , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(reloaded_config.__class__.__name__ , 'NewModelConfig' )
def lowercase ( self : List[Any] ) -> List[str]:
class _UpperCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
a_ = """new-model"""
try:
AutoConfig.register('new-model' , lowerCAmelCase_ )
# If remote code is not set, the default is to use local
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' )
self.assertEqual(config.__class__.__name__ , 'NewModelConfigLocal' )
# If remote code is disabled, we load the local one.
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(config.__class__.__name__ , 'NewModelConfigLocal' )
# If remote is enabled, we load from the Hub
__lowerCAmelCase = AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(config.__class__.__name__ , 'NewModelConfig' )
finally:
if "new-model" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["new-model"]
| 421 | 0 |
def _lowercase ( __lowerCamelCase : int ,__lowerCamelCase : float ,__lowerCamelCase : float ) -> float:
'''simple docstring'''
return round(float(moles / volume ) * nfactor )
def _lowercase ( __lowerCamelCase : float ,__lowerCamelCase : float ,__lowerCamelCase : float ) -> float:
'''simple docstring'''
return round(float((moles * 0.0_8_2_1 * temperature) / (volume) ) )
def _lowercase ( __lowerCamelCase : float ,__lowerCamelCase : float ,__lowerCamelCase : float ) -> float:
'''simple docstring'''
return round(float((moles * 0.0_8_2_1 * temperature) / (pressure) ) )
def _lowercase ( __lowerCamelCase : float ,__lowerCamelCase : float ,__lowerCamelCase : float ) -> float:
'''simple docstring'''
return round(float((pressure * volume) / (0.0_8_2_1 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 344 |
import inspect
import os
import unittest
from dataclasses import dataclass
import torch
from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs
from accelerate.state import AcceleratorState
from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu
from accelerate.utils import KwargsHandler
@dataclass
class UpperCamelCase__ ( __lowerCamelCase ):
a__ : int = 0
a__ : bool = False
a__ : float = 3.0
class UpperCamelCase__ ( unittest.TestCase ):
def __lowercase( self : str ) -> int:
# If no defaults are changed, `to_kwargs` returns an empty dict.
self.assertDictEqual(MockClass().to_kwargs(), {} )
self.assertDictEqual(MockClass(a=2 ).to_kwargs(), {'''a''': 2} )
self.assertDictEqual(MockClass(a=2, b=__lowerCamelCase ).to_kwargs(), {'''a''': 2, '''b''': True} )
self.assertDictEqual(MockClass(a=2, c=2.25 ).to_kwargs(), {'''a''': 2, '''c''': 2.25} )
@require_cuda
def __lowercase( self : Tuple ) -> List[str]:
# If no defaults are changed, `to_kwargs` returns an empty dict.
UpperCamelCase__ : Union[str, Any] = GradScalerKwargs(init_scale=10_24, growth_factor=2 )
AcceleratorState._reset_state()
UpperCamelCase__ : str = Accelerator(mixed_precision='''fp16''', kwargs_handlers=[scaler_handler] )
print(accelerator.use_fpaa )
UpperCamelCase__ : Union[str, Any] = accelerator.scaler
# Check the kwargs have been applied
self.assertEqual(scaler._init_scale, 1024.0 )
self.assertEqual(scaler._growth_factor, 2.0 )
# Check the other values are at the default
self.assertEqual(scaler._backoff_factor, 0.5 )
self.assertEqual(scaler._growth_interval, 20_00 )
self.assertEqual(scaler._enabled, __lowerCamelCase )
@require_multi_gpu
def __lowercase( self : Optional[int] ) -> Optional[int]:
UpperCamelCase__ : Optional[Any] = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )]
execute_subprocess_async(__lowerCamelCase, env=os.environ.copy() )
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE : Tuple = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True)
_SCREAMING_SNAKE_CASE : List[Any] = Accelerator(kwargs_handlers=[ddp_scaler])
_SCREAMING_SNAKE_CASE : Optional[Any] = torch.nn.Linear(100, 200)
_SCREAMING_SNAKE_CASE : int = accelerator.prepare(model)
# Check the values changed in kwargs
_SCREAMING_SNAKE_CASE : List[Any] = """"""
_SCREAMING_SNAKE_CASE : List[Any] = model.bucket_bytes_cap // (1024 * 1024)
if observed_bucket_cap_map != 15:
error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n"
if model.find_unused_parameters is not True:
error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n"
# Check the values of the defaults
if model.dim != 0:
error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n"
if model.broadcast_buffers is not True:
error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n"
if model.gradient_as_bucket_view is not False:
error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n"
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 344 | 1 |
"""simple docstring"""
from collections import defaultdict
from pathlib import Path
import pandas as pd
from rouge_cli import calculate_rouge_path
from utils import calculate_rouge
A = [
'''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the'''
''' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe'''
''' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.''',
'''The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal'''
''' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s'''
''' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the'''
''' body.''',
'''Amnesty International releases its annual report on the death penalty. The report catalogs the use of'''
''' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the'''
''' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital'''
''' punishment.''',
]
A = [
'''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .'''
''' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz'''
''' had informed his Lufthansa training school of an episode of severe depression, airline says .''',
'''Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .'''
''' Israel and the United States opposed the move, which could open the door to war crimes investigations against'''
''' Israelis .''',
'''Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to'''
''' death . Organization claims that governments around the world are using the threat of terrorism to advance'''
''' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death'''
''' sentences up by 28% .''',
]
def __A ( ) -> Union[str, Any]:
__a : str = calculate_rouge(a_ , a_ , bootstrap_aggregation=a_ , rouge_keys=['''rouge2''', '''rougeL'''])
assert isinstance(a_ , a_)
__a : Any = calculate_rouge(a_ , a_ , bootstrap_aggregation=a_ , rouge_keys=['''rouge2'''])
assert (
pd.DataFrame(no_aggregation['''rouge2''']).fmeasure.mean()
== pd.DataFrame(no_aggregation_just_ra['''rouge2''']).fmeasure.mean()
)
def __A ( ) -> str:
__a : str = '''rougeLsum'''
__a : int = calculate_rouge(a_ , a_ , newline_sep=a_ , rouge_keys=[k])[k]
__a : List[Any] = calculate_rouge(a_ , a_ , newline_sep=a_ , rouge_keys=[k])[k]
assert score > score_no_sep
def __A ( ) -> List[str]:
__a : Optional[Any] = ['''rouge1''', '''rouge2''', '''rougeL''']
__a : Any = calculate_rouge(a_ , a_ , newline_sep=a_ , rouge_keys=a_)
__a : List[Any] = calculate_rouge(a_ , a_ , newline_sep=a_ , rouge_keys=a_)
assert score_sep == score_no_sep
def __A ( ) -> Any:
__a : Union[str, Any] = [
'''Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.''',
'''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''',
]
__a : Tuple = [
'''Margot Frank, died in 1945, a month earlier than previously thought.''',
'''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of'''
''' the final seconds on board Flight 9525.''',
]
assert calculate_rouge(a_ , a_ , newline_sep=a_) == calculate_rouge(a_ , a_ , newline_sep=a_)
def __A ( ) -> List[Any]:
__a : Dict = [
'''" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" '''
]
__a : List[str] = [
''' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .'''
]
__a : List[Any] = calculate_rouge(a_ , a_ , rouge_keys=['''rougeLsum'''] , newline_sep=a_)['''rougeLsum''']
__a : Optional[int] = calculate_rouge(a_ , a_ , rouge_keys=['''rougeLsum'''])['''rougeLsum''']
assert new_score > prev_score
def __A ( ) -> Tuple:
__a : Dict = Path('''examples/seq2seq/test_data/wmt_en_ro''')
__a : Dict = calculate_rouge_path(data_dir.joinpath('''test.source''') , data_dir.joinpath('''test.target'''))
assert isinstance(a_ , a_)
__a : Any = calculate_rouge_path(
data_dir.joinpath('''test.source''') , data_dir.joinpath('''test.target''') , bootstrap_aggregation=a_)
assert isinstance(a_ , a_) | 101 |
"""simple docstring"""
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
A = ['''bert-base-uncased''', '''bert-base-cased''']
A = '''hf-internal-testing/tiny-bert-tf-only'''
if is_tf_available():
class __lowercase ( tf.keras.Model ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase ):
super().__init__()
__a : Any = tokenizer
__a : Optional[Any] = AutoConfig.from_pretrained(_UpperCAmelCase )
__a : str = TFAutoModel.from_config(_UpperCAmelCase )
def _lowerCamelCase ( self , _UpperCAmelCase ):
__a : Any = self.tokenizer(_UpperCAmelCase )
__a : int = self.bert(**_UpperCAmelCase )
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class __lowercase ( unittest.TestCase ):
'''simple docstring'''
def _lowerCamelCase ( self ):
super().setUp()
__a : Any = [
BertTokenizer.from_pretrained(_UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
__a : Union[str, Any] = [TFBertTokenizer.from_pretrained(_UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(_UpperCAmelCase , use_fast_bert_tokenizer=_UpperCAmelCase )
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
__a : Tuple = [
'''This is a straightforward English test sentence.''',
'''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''',
'''Now we\'re going to add some Chinese: 一 二 三 一二三''',
'''And some much more rare Chinese: 齉 堃 齉堃''',
'''Je vais aussi écrire en français pour tester les accents''',
'''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
]
__a : Any = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def _lowerCamelCase ( self ):
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in (self.test_sentences, self.paired_sentences):
__a : List[Any] = tokenizer(_UpperCAmelCase , return_tensors='''tf''' , padding='''longest''' )
__a : List[str] = tf_tokenizer(_UpperCAmelCase )
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) )
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) )
@slow
def _lowerCamelCase ( self ):
for tf_tokenizer in self.tf_tokenizers:
__a : Dict = tf_tokenizer(self.paired_sentences )
__a : str = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) )
@slow
def _lowerCamelCase ( self ):
for tf_tokenizer in self.tf_tokenizers:
__a : Tuple = tf.function(_UpperCAmelCase )
for test_inputs in (self.test_sentences, self.paired_sentences):
__a : List[str] = tf.constant(_UpperCAmelCase )
__a : Tuple = compiled_tokenizer(_UpperCAmelCase )
__a : Union[str, Any] = tf_tokenizer(_UpperCAmelCase )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def _lowerCamelCase ( self ):
for tf_tokenizer in self.tf_tokenizers:
__a : Dict = ModelToSave(tokenizer=_UpperCAmelCase )
__a : Tuple = tf.convert_to_tensor(self.test_sentences )
__a : List[str] = model(_UpperCAmelCase ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
__a : Tuple = Path(_UpperCAmelCase ) / '''saved.model'''
model.save(_UpperCAmelCase )
__a : Tuple = tf.keras.models.load_model(_UpperCAmelCase )
__a : int = loaded_model(_UpperCAmelCase )
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 ) | 101 | 1 |
"""simple docstring"""
def __lowercase ( _a ):
if isinstance(_a , _a ):
raise TypeError('''\'float\' object cannot be interpreted as an integer''' )
if isinstance(_a , _a ):
raise TypeError('''\'str\' object cannot be interpreted as an integer''' )
if num == 0:
return "0b0"
snake_case_ : str = False
if num < 0:
snake_case_ : Optional[int] = True
snake_case_ : Any = -num
snake_case_ : list[int] = []
while num > 0:
binary.insert(0 , num % 2 )
num >>= 1
if negative:
return "-0b" + "".join(str(_a ) for e in binary )
return "0b" + "".join(str(_a ) for e in binary )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 123 |
"""simple docstring"""
import random
import unittest
import numpy as np
import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax
if is_flax_available():
import os
import jax.numpy as jnp
from jax import jit
from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
lowercase__ : List[str] = '''0.12''' # assumed parallelism: 8
if is_torch_available():
import torch
def __lowercase ( _a , _a , _a=None ):
if rng is None:
snake_case_ : Tuple = random.Random()
snake_case_ : Optional[Any] = 1
for dim in shape:
total_dims *= dim
snake_case_ : Union[str, Any] = []
for _ in range(_a ):
values.append(rng.randint(0 , vocab_size - 1 ) )
snake_case_ : Tuple = np.array(_a , dtype=jnp.intaa ).reshape(_a )
return output
def __lowercase ( _a , _a=None ):
snake_case_ : int = ids_tensor(_a , vocab_size=2 , rng=_a )
# make sure that at least one token is attended to for each batch
snake_case_ : int = 1
return attn_mask
@require_flax
class _UpperCAmelCase :
_lowerCAmelCase : int = None
_lowerCAmelCase : str = ()
def _snake_case ( self : int ):
snake_case_, snake_case_ : int = self.model_tester.prepare_config_and_inputs_for_common()
# cut to half length & take max batch_size 3
snake_case_ : str = 2
snake_case_ : Optional[Any] = inputs['''input_ids'''].shape[-1] // 2
snake_case_ : List[str] = inputs['''input_ids'''][:max_batch_size, :sequence_length]
snake_case_ : Optional[Any] = jnp.ones_like(lowercase_ )
snake_case_ : List[Any] = attention_mask[:max_batch_size, :sequence_length]
# generate max 5 tokens
snake_case_ : Optional[Any] = input_ids.shape[-1] + 5
if config.eos_token_id is not None and config.pad_token_id is None:
# hack to allow generate for models such as GPT2 as is done in `generate()`
snake_case_ : Optional[int] = config.eos_token_id
return config, input_ids, attention_mask, max_length
@is_pt_flax_cross_test
def _snake_case ( self : Any ):
snake_case_, snake_case_, snake_case_, snake_case_ : Dict = self._get_input_ids_and_config()
snake_case_ : Optional[int] = False
snake_case_ : List[Any] = max_length
snake_case_ : Optional[Any] = 0
for model_class in self.all_generative_model_classes:
snake_case_ : Any = model_class(lowercase_ )
snake_case_ : str = model_class.__name__[4:] # Skip the "Flax" at the beginning
snake_case_ : Optional[int] = getattr(lowercase_ , lowercase_ )
snake_case_ : Union[str, Any] = pt_model_class(lowercase_ ).eval()
snake_case_ : Union[str, Any] = load_flax_weights_in_pytorch_model(lowercase_ , flax_model.params )
snake_case_ : Optional[Any] = flax_model.generate(lowercase_ ).sequences
snake_case_ : Union[str, Any] = pt_model.generate(torch.tensor(lowercase_ , dtype=torch.long ) )
if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
snake_case_ : Optional[Any] = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]
self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() )
def _snake_case ( self : List[Any] ):
snake_case_, snake_case_, snake_case_, snake_case_ : Optional[int] = self._get_input_ids_and_config()
snake_case_ : Optional[Any] = False
snake_case_ : Optional[int] = max_length
for model_class in self.all_generative_model_classes:
snake_case_ : List[str] = model_class(lowercase_ )
snake_case_ : int = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : List[Any] = jit(model.generate )
snake_case_ : int = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : Union[str, Any] ):
snake_case_, snake_case_, snake_case_, snake_case_ : Dict = self._get_input_ids_and_config()
snake_case_ : List[Any] = True
snake_case_ : Any = max_length
for model_class in self.all_generative_model_classes:
snake_case_ : List[str] = model_class(lowercase_ )
snake_case_ : Union[str, Any] = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Union[str, Any] = jit(model.generate )
snake_case_ : Any = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : int ):
snake_case_, snake_case_, snake_case_, snake_case_ : Union[str, Any] = self._get_input_ids_and_config()
snake_case_ : Optional[Any] = False
snake_case_ : Tuple = max_length
snake_case_ : int = 2
for model_class in self.all_generative_model_classes:
snake_case_ : Optional[Any] = model_class(lowercase_ )
snake_case_ : Optional[Any] = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Tuple = jit(model.generate )
snake_case_ : List[str] = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : int ):
snake_case_, snake_case_, snake_case_, snake_case_ : str = self._get_input_ids_and_config()
snake_case_ : Tuple = False
snake_case_ : Union[str, Any] = max_length
snake_case_ : str = 2
snake_case_ : List[str] = 2
for model_class in self.all_generative_model_classes:
snake_case_ : Tuple = model_class(lowercase_ )
snake_case_ : Dict = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences )
def _snake_case ( self : Dict ):
snake_case_, snake_case_, snake_case_, snake_case_ : Union[str, Any] = self._get_input_ids_and_config()
snake_case_ : List[str] = True
snake_case_ : Optional[int] = max_length
snake_case_ : Any = 0.8
snake_case_ : str = 10
snake_case_ : Union[str, Any] = 0.3
snake_case_ : Optional[int] = 1
snake_case_ : str = 8
snake_case_ : Tuple = 9
for model_class in self.all_generative_model_classes:
snake_case_ : int = model_class(lowercase_ )
snake_case_ : Any = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Dict = jit(model.generate )
snake_case_ : List[Any] = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : Optional[Any] ):
snake_case_, snake_case_, snake_case_, snake_case_ : Dict = self._get_input_ids_and_config()
snake_case_ : Any = max_length
snake_case_ : str = 1
snake_case_ : List[str] = 8
snake_case_ : str = 9
for model_class in self.all_generative_model_classes:
snake_case_ : List[str] = model_class(lowercase_ )
snake_case_ : List[Any] = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Any = jit(model.generate )
snake_case_ : int = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : Dict ):
snake_case_, snake_case_, snake_case_, snake_case_ : Optional[Any] = self._get_input_ids_and_config()
snake_case_ : Dict = max_length
snake_case_ : Optional[int] = 2
snake_case_ : Tuple = 1
snake_case_ : int = 8
snake_case_ : Any = 9
for model_class in self.all_generative_model_classes:
snake_case_ : List[str] = model_class(lowercase_ )
snake_case_ : Tuple = model.generate(lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Any = jit(model.generate )
snake_case_ : List[str] = jit_generate(lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : Tuple ):
snake_case_, snake_case_, snake_case_, snake_case_ : int = self._get_input_ids_and_config()
# pad attention mask on the left
snake_case_ : Optional[int] = attention_mask.at[(0, 0)].set(0 )
snake_case_ : Union[str, Any] = False
snake_case_ : Union[str, Any] = max_length
for model_class in self.all_generative_model_classes:
snake_case_ : Any = model_class(lowercase_ )
snake_case_ : Tuple = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Union[str, Any] = jit(model.generate )
snake_case_ : str = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : int ):
snake_case_, snake_case_, snake_case_, snake_case_ : Tuple = self._get_input_ids_and_config()
# pad attention mask on the left
snake_case_ : Union[str, Any] = attention_mask.at[(0, 0)].set(0 )
snake_case_ : Optional[Any] = True
snake_case_ : Optional[int] = max_length
for model_class in self.all_generative_model_classes:
snake_case_ : int = model_class(lowercase_ )
snake_case_ : Optional[int] = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : List[str] = jit(model.generate )
snake_case_ : Union[str, Any] = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def _snake_case ( self : Union[str, Any] ):
snake_case_, snake_case_, snake_case_, snake_case_ : List[str] = self._get_input_ids_and_config()
# pad attention mask on the left
snake_case_ : Optional[int] = attention_mask.at[(0, 0)].set(0 )
snake_case_ : str = 2
snake_case_ : List[str] = max_length
for model_class in self.all_generative_model_classes:
snake_case_ : List[Any] = model_class(lowercase_ )
snake_case_ : List[Any] = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowercase_ )
snake_case_ : Any = jit(model.generate )
snake_case_ : Union[str, Any] = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
@require_flax
class _UpperCAmelCase ( unittest.TestCase):
def _snake_case ( self : Dict ):
snake_case_ : Any = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert''' )
snake_case_ : Tuple = FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' )
snake_case_ : Optional[Any] = '''Hello world'''
snake_case_ : Any = tokenizer(lowercase_ , return_tensors='''np''' ).input_ids
# typos are quickly detected (the correct argument is `do_sample`)
with self.assertRaisesRegex(lowercase_ , '''do_samples''' ):
model.generate(lowercase_ , do_samples=lowercase_ )
# arbitrary arguments that will not be used anywhere are also not accepted
with self.assertRaisesRegex(lowercase_ , '''foo''' ):
snake_case_ : Union[str, Any] = {'''foo''': '''bar'''}
model.generate(lowercase_ , **lowercase_ )
| 123 | 1 |
"""simple docstring"""
import os
from typing import List, Optional, Union
from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer
class __a (a__):
'''simple docstring'''
_SCREAMING_SNAKE_CASE :int = ["""image_processor""", """tokenizer"""]
_SCREAMING_SNAKE_CASE :Tuple = """BlipImageProcessor"""
_SCREAMING_SNAKE_CASE :int = """AutoTokenizer"""
def __init__( self , _a , _a , _a ) -> List[str]:
"""simple docstring"""
super().__init__(_A , _A )
# add QFormer tokenizer
SCREAMING_SNAKE_CASE__ : str = qformer_tokenizer
def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> int:
"""simple docstring"""
if images is None and text is None:
raise ValueError("""You have to specify at least images or text.""" )
SCREAMING_SNAKE_CASE__ : List[str] = BatchFeature()
if text is not None:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
encoding.update(_A )
SCREAMING_SNAKE_CASE__ : Any = self.qformer_tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
SCREAMING_SNAKE_CASE__ : List[str] = qformer_text_encoding.pop("""input_ids""" )
SCREAMING_SNAKE_CASE__ : Optional[int] = qformer_text_encoding.pop("""attention_mask""" )
if images is not None:
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor(_A , return_tensors=_A )
encoding.update(_A )
return encoding
def _a ( self , *_a , **_a ) -> Dict:
"""simple docstring"""
return self.tokenizer.batch_decode(*_A , **_A )
def _a ( self , *_a , **_a ) -> Dict:
"""simple docstring"""
return self.tokenizer.decode(*_A , **_A )
@property
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
def _a ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE__ : str = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
def _a ( self , _a , **_a ) -> Dict:
"""simple docstring"""
if os.path.isfile(_A ):
raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' )
os.makedirs(_A , exist_ok=_A )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(_A , """qformer_tokenizer""" )
self.qformer_tokenizer.save_pretrained(_A )
return super().save_pretrained(_A , **_A )
@classmethod
def _a ( cls , _a , **_a ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained(_A , subfolder="""qformer_tokenizer""" )
SCREAMING_SNAKE_CASE__ : Dict = cls._get_arguments_from_pretrained(_A , **_A )
args.append(_A )
return cls(*_A )
| 715 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from tokenizers import processors
from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_nllb import NllbTokenizer
else:
a :Optional[int] = None
a :Optional[Any] = logging.get_logger(__name__)
a :Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
a :Union[str, Any] = {
"vocab_file": {
"facebook/nllb-200-distilled-600M": (
"https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model"
),
},
"tokenizer_file": {
"facebook/nllb-200-distilled-600M": (
"https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json"
),
},
}
a :Any = {
"facebook/nllb-large-en-ro": 1_024,
"facebook/nllb-200-distilled-600M": 1_024,
}
# fmt: off
a :Tuple = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"]
class __a (UpperCamelCase_):
'''simple docstring'''
_SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES
_SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_SCREAMING_SNAKE_CASE :str = PRETRAINED_VOCAB_FILES_MAP
_SCREAMING_SNAKE_CASE :int = ["""input_ids""", """attention_mask"""]
_SCREAMING_SNAKE_CASE :Tuple = NllbTokenizer
_SCREAMING_SNAKE_CASE :List[int] = []
_SCREAMING_SNAKE_CASE :List[int] = []
def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , _a=False , **_a , ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token
SCREAMING_SNAKE_CASE__ : Optional[int] = legacy_behaviour
super().__init__(
vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , legacy_behaviour=_a , **_a , )
SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file
SCREAMING_SNAKE_CASE__ : str = False if not self.vocab_file else True
SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES.copy()
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
_additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in _additional_special_tokens] )
self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} )
SCREAMING_SNAKE_CASE__ : List[str] = {
lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES
}
SCREAMING_SNAKE_CASE__ : Dict = src_lang if src_lang is not None else """eng_Latn"""
SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(self._src_lang )
SCREAMING_SNAKE_CASE__ : Dict = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
@property
def _a ( self ) -> str:
"""simple docstring"""
return self._src_lang
@src_lang.setter
def _a ( self , _a ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def _a ( self , _a , _a = None ) -> List[int]:
"""simple docstring"""
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def _a ( self , _a , _a = None ) -> List[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id]
SCREAMING_SNAKE_CASE__ : 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]
def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple:
"""simple docstring"""
if src_lang is None or tgt_lang is None:
raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" )
SCREAMING_SNAKE_CASE__ : Dict = src_lang
SCREAMING_SNAKE_CASE__ : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_tokens_to_ids(_a )
SCREAMING_SNAKE_CASE__ : List[Any] = tgt_lang_id
return inputs
def _a ( self , _a , _a = "eng_Latn" , _a = None , _a = "fra_Latn" , **_a , ) -> BatchEncoding:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = src_lang
SCREAMING_SNAKE_CASE__ : Dict = tgt_lang
return super().prepare_seqaseq_batch(_a , _a , **_a )
def _a ( self ) -> Optional[Any]:
"""simple docstring"""
return self.set_src_lang_special_tokens(self.src_lang )
def _a ( self ) -> str:
"""simple docstring"""
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def _a ( self , _a ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[Any] = self.convert_tokens_to_ids(_a )
if self.legacy_behaviour:
SCREAMING_SNAKE_CASE__ : str = []
SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id, self.cur_lang_code]
else:
SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code]
SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id]
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_ids_to_tokens(self.prefix_tokens )
SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(self.suffix_tokens )
SCREAMING_SNAKE_CASE__ : int = processors.TemplateProcessing(
single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def _a ( self , _a ) -> None:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a )
if self.legacy_behaviour:
SCREAMING_SNAKE_CASE__ : List[Any] = []
SCREAMING_SNAKE_CASE__ : Optional[int] = [self.eos_token_id, self.cur_lang_code]
else:
SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_code]
SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id]
SCREAMING_SNAKE_CASE__ : Any = self.convert_ids_to_tokens(self.prefix_tokens )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(self.suffix_tokens )
SCREAMING_SNAKE_CASE__ : Tuple = processors.TemplateProcessing(
single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def _a ( self , _a , _a = 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(_a ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' )
return
SCREAMING_SNAKE_CASE__ : Dict = 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 ):
copyfile(self.vocab_file , _a )
return (out_vocab_file,)
| 12 | 0 |
import math
import random
def UpperCAmelCase_ ( snake_case__ , snake_case__ = False ) -> float:
"""simple docstring"""
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
_lowerCAmelCase : Union[str, Any] = 0.0_2
def UpperCAmelCase_ ( snake_case__ , snake_case__ ) -> float:
"""simple docstring"""
lowerCAmelCase__ = float(2 * (random.randint(1 , 100 )) - 1 )
for _ in range(snake_case__ ):
# Forward propagation
lowerCAmelCase__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
lowerCAmelCase__ = (expected / 100) - layer_a
# Error delta
lowerCAmelCase__ = layer_1_error * sigmoid_function(snake_case__ , snake_case__ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowerCAmelCase : List[str] = int(input("Expected value: "))
_lowerCAmelCase : Any = int(input("Number of propagations: "))
print(forward_propagation(expected, number_propagations))
| 193 |
from bisect import bisect
from itertools import accumulate
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase__ = sorted(zip(snake_case__ , snake_case__ ) , key=lambda snake_case__ : x[0] / x[1] , reverse=snake_case__ )
lowerCAmelCase__ , lowerCAmelCase__ = [i[0] for i in r], [i[1] for i in r]
lowerCAmelCase__ = list(accumulate(snake_case__ ) )
lowerCAmelCase__ = bisect(snake_case__ , snake_case__ )
return (
0
if k == 0
else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
if k != n
else sum(vl[:k] )
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 193 | 1 |
"""simple docstring"""
import cva
import numpy as np
class UpperCAmelCase :
def __init__( self : Union[str, Any] , __lowerCamelCase : float , __lowerCamelCase : int ):
"""simple docstring"""
if k in (0.0_4, 0.0_6):
_snake_case = k
_snake_case = window_size
else:
raise ValueError('''invalid k value''' )
def __str__( self : List[str] ):
"""simple docstring"""
return str(self.k )
def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : str ):
"""simple docstring"""
_snake_case = cva.imread(__lowerCamelCase , 0 )
_snake_case , _snake_case = img.shape
_snake_case = []
_snake_case = img.copy()
_snake_case = cva.cvtColor(__lowerCamelCase , cva.COLOR_GRAY2RGB )
_snake_case , _snake_case = np.gradient(__lowerCamelCase )
_snake_case = dx**2
_snake_case = dy**2
_snake_case = dx * dy
_snake_case = 0.0_4
_snake_case = self.window_size // 2
for y in range(__lowerCamelCase , h - offset ):
for x in range(__lowerCamelCase , w - offset ):
_snake_case = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
_snake_case = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
_snake_case = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
_snake_case = (wxx * wyy) - (wxy**2)
_snake_case = wxx + wyy
_snake_case = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r] )
color_img.itemset((y, x, 0) , 0 )
color_img.itemset((y, x, 1) , 0 )
color_img.itemset((y, x, 2) , 2_5_5 )
return color_img, corner_list
if __name__ == "__main__":
snake_case = HarrisCorner(0.0_4, 3)
snake_case , snake_case = edge_detect.detect('''path_to_image''')
cva.imwrite('''detect.png''', color_img)
| 404 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_big_bird import BigBirdTokenizer
else:
snake_case = None
snake_case = logging.get_logger(__name__)
snake_case = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''}
snake_case = {
'''vocab_file''': {
'''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''',
'''google/bigbird-roberta-large''': (
'''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model'''
),
'''google/bigbird-base-trivia-itc''': (
'''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model'''
),
},
'''tokenizer_file''': {
'''google/bigbird-roberta-base''': (
'''https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json'''
),
'''google/bigbird-roberta-large''': (
'''https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json'''
),
'''google/bigbird-base-trivia-itc''': (
'''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json'''
),
},
}
snake_case = {
'''google/bigbird-roberta-base''': 4_0_9_6,
'''google/bigbird-roberta-large''': 4_0_9_6,
'''google/bigbird-base-trivia-itc''': 4_0_9_6,
}
snake_case = '''▁'''
class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ):
A__ : Dict = VOCAB_FILES_NAMES
A__ : Any = PRETRAINED_VOCAB_FILES_MAP
A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A__ : List[Any] = BigBirdTokenizer
A__ : Dict = ['''input_ids''', '''attention_mask''']
A__ : List[int] = []
def __init__( self : Union[str, Any] , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Dict=None , __lowerCamelCase : int="<unk>" , __lowerCamelCase : Optional[int]="<s>" , __lowerCamelCase : Tuple="</s>" , __lowerCamelCase : Any="<pad>" , __lowerCamelCase : List[str]="[SEP]" , __lowerCamelCase : str="[MASK]" , __lowerCamelCase : str="[CLS]" , **__lowerCamelCase : Any , ):
"""simple docstring"""
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token
# Mask token behave like a normal word, i.e. include the space before it
_snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token
super().__init__(
__lowerCamelCase , tokenizer_file=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , **__lowerCamelCase , )
_snake_case = vocab_file
_snake_case = False if not self.vocab_file else True
def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ):
"""simple docstring"""
_snake_case = [self.sep_token_id]
_snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'''You should not supply a second sequence if the provided sequence of '''
'''ids is already formatted with special tokens for the model.''' )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is None:
return [1] + ([0] * len(__lowerCamelCase )) + [1]
return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1]
def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ):
"""simple docstring"""
_snake_case = [self.sep_token_id]
_snake_case = [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 __UpperCAmelCase ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ):
"""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(__lowerCamelCase ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
_snake_case = os.path.join(
__lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ):
copyfile(self.vocab_file , __lowerCamelCase )
return (out_vocab_file,)
| 404 | 1 |
"""simple docstring"""
import colorsys
from PIL import Image # type: ignore
def lowercase__( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[int] ):
lowercase_ : Tuple = x
lowercase_ : Optional[Any] = y
for step in range(__SCREAMING_SNAKE_CASE ): # noqa: B007
lowercase_ : Dict = a * a - b * b + x
lowercase_ : Union[str, Any] = 2 * a * b + y
lowercase_ : Union[str, Any] = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def lowercase__( __SCREAMING_SNAKE_CASE : Dict ):
if distance == 1:
return (0, 0, 0)
else:
return (2_55, 2_55, 2_55)
def lowercase__( __SCREAMING_SNAKE_CASE : Optional[Any] ):
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__SCREAMING_SNAKE_CASE , 1 , 1 ) )
def lowercase__( __SCREAMING_SNAKE_CASE : Any = 8_00 , __SCREAMING_SNAKE_CASE : Optional[int] = 6_00 , __SCREAMING_SNAKE_CASE : Tuple = -0.6 , __SCREAMING_SNAKE_CASE : List[str] = 0 , __SCREAMING_SNAKE_CASE : Dict = 3.2 , __SCREAMING_SNAKE_CASE : Optional[int] = 50 , __SCREAMING_SNAKE_CASE : Optional[int] = True , ):
lowercase_ : str = Image.new('RGB' , (image_width, image_height) )
lowercase_ : List[str] = img.load()
# loop through the image-coordinates
for image_x in range(__SCREAMING_SNAKE_CASE ):
for image_y in range(__SCREAMING_SNAKE_CASE ):
# determine the figure-coordinates based on the image-coordinates
lowercase_ : Any = figure_width / image_width * image_height
lowercase_ : Tuple = figure_center_x + (image_x / image_width - 0.5) * figure_width
lowercase_ : str = figure_center_y + (image_y / image_height - 0.5) * figure_height
lowercase_ : List[Any] = get_distance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
lowercase_ : Any = get_color_coded_rgb(__SCREAMING_SNAKE_CASE )
else:
lowercase_ : str = get_black_and_white_rgb(__SCREAMING_SNAKE_CASE )
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
__SCREAMING_SNAKE_CASE =get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| 425 |
'''simple docstring'''
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def UpperCamelCase ( a , a ) -> Tuple:
'''simple docstring'''
assert isinstance(a , a )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('''keep_in_memory''' , [False, True] )
def UpperCamelCase ( a , a , a ) -> str:
'''simple docstring'''
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader(a , cache_dir=a , keep_in_memory=a ).read()
_check_text_dataset(a , a )
@pytest.mark.parametrize(
'''features''' , [
None,
{'''text''': '''string'''},
{'''text''': '''int32'''},
{'''text''': '''float32'''},
] , )
def UpperCamelCase ( a , a , a ) -> Union[str, Any]:
'''simple docstring'''
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(a ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader(a , features=a , cache_dir=a ).read()
_check_text_dataset(a , a )
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def UpperCamelCase ( a , a , a ) -> Optional[int]:
'''simple docstring'''
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
__magic_name__ = TextDatasetReader(a , cache_dir=a , split=a ).read()
_check_text_dataset(a , a )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize('''path_type''' , [str, list] )
def UpperCamelCase ( a , a , a ) -> int:
'''simple docstring'''
if issubclass(a , a ):
__magic_name__ = text_path
elif issubclass(a , a ):
__magic_name__ = [text_path]
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
__magic_name__ = TextDatasetReader(a , cache_dir=a ).read()
_check_text_dataset(a , a )
def UpperCamelCase ( a , a , a=("train",) ) -> List[Any]:
'''simple docstring'''
assert isinstance(a , a )
for split in splits:
__magic_name__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('''keep_in_memory''' , [False, True] )
def UpperCamelCase ( a , a , a ) -> Tuple:
'''simple docstring'''
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader({'''train''': text_path} , cache_dir=a , keep_in_memory=a ).read()
_check_text_datasetdict(a , a )
@pytest.mark.parametrize(
'''features''' , [
None,
{'''text''': '''string'''},
{'''text''': '''int32'''},
{'''text''': '''float32'''},
] , )
def UpperCamelCase ( a , a , a ) -> Optional[Any]:
'''simple docstring'''
__magic_name__ = tmp_path / '''cache'''
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
__magic_name__ = {'''text''': '''string'''}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(a ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader({'''train''': text_path} , features=a , cache_dir=a ).read()
_check_text_datasetdict(a , a )
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def UpperCamelCase ( a , a , a ) -> List[str]:
'''simple docstring'''
if split:
__magic_name__ = {split: text_path}
else:
__magic_name__ = '''train'''
__magic_name__ = {'''train''': text_path, '''test''': text_path}
__magic_name__ = tmp_path / '''cache'''
__magic_name__ = {'''text''': '''string'''}
__magic_name__ = TextDatasetReader(a , cache_dir=a ).read()
_check_text_datasetdict(a , a , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 432 | 0 |
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
if not isinstance(__A , __A ):
raise TypeError('''only integers accepted as input''' )
else:
UpperCAmelCase_ : List[str] = str(abs(__A ) )
UpperCAmelCase_ : List[Any] = [list(__A ) for char in range(len(__A ) )]
for index in range(len(__A ) ):
num_transpositions[index].pop(__A )
return max(
int(''''''.join(list(__A ) ) ) for transposition in num_transpositions )
if __name__ == "__main__":
__import__('doctest').testmod() | 701 |
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(
'\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n'
)
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__a = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__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 = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__a = (
'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.'
)
__a = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__a = (
'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.'
)
__a = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__a = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.'
__a = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n'
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n'
__a = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.'
__a = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n'
__a = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.'
__a = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n'
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__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 = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n'
__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 lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
assert ReadMe.from_string(_lowercase , _lowercase ).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 lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
with pytest.raises(_lowercase , match=re.escape(expected_error.format(path='''root''' ) ) ):
UpperCAmelCase_ : Union[str, Any] = ReadMe.from_string(_lowercase , _lowercase )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
] , )
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
with pytest.raises(_lowercase , match=re.escape(expected_error.format(path='''root''' ) ) ):
ReadMe.from_string(_lowercase , _lowercase )
@pytest.mark.parametrize(
'''readme_md,''' , [
(README_MULTIPLE_SAME_HEADING_1),
] , )
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
ReadMe.from_string(_lowercase , _lowercase , suppress_parsing_errors=_lowercase )
@pytest.mark.parametrize(
'''readme_md, expected_dict''' , [
(README_CORRECT, CORRECT_DICT),
(README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
] , )
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : Dict = Path(_lowercase ) / '''README.md'''
with open(_lowercase , '''w+''' ) as readme_file:
readme_file.write(_lowercase )
UpperCAmelCase_ : Optional[int] = ReadMe.from_readme(_lowercase , _lowercase ).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 lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : Optional[int] = Path(_lowercase ) / '''README.md'''
with open(_lowercase , '''w+''' ) as readme_file:
readme_file.write(_lowercase )
UpperCAmelCase_ : List[Any] = expected_error.format(path=_lowercase )
with pytest.raises(_lowercase , match=re.escape(_lowercase ) ):
UpperCAmelCase_ : Any = ReadMe.from_readme(_lowercase , _lowercase )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
] , )
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : List[Any] = Path(_lowercase ) / '''README.md'''
with open(_lowercase , '''w+''' ) as readme_file:
readme_file.write(_lowercase )
UpperCAmelCase_ : List[str] = expected_error.format(path=_lowercase )
with pytest.raises(_lowercase , match=re.escape(_lowercase ) ):
ReadMe.from_readme(_lowercase , _lowercase )
@pytest.mark.parametrize(
'''readme_md,''' , [
(README_MULTIPLE_SAME_HEADING_1),
] , )
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : Dict = Path(_lowercase ) / '''README.md'''
with open(_lowercase , '''w+''' ) as readme_file:
readme_file.write(_lowercase )
ReadMe.from_readme(_lowercase , _lowercase , suppress_parsing_errors=_lowercase ) | 300 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case = 1_00_00_00 ) -> int:
"""simple docstring"""
_UpperCamelCase = [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, __snake_case ):
phi[j] -= phi[j] // i
return sum(phi[2 : limit + 1] )
if __name__ == "__main__":
print(solution())
| 19 |
import unittest
import numpy as np
import torch
from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class _snake_case ( _A , unittest.TestCase ):
_A = DDIMPipeline
_A = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
_A = PipelineTesterMixin.required_optional_params - {
'num_images_per_prompt',
'latents',
'callback',
'callback_steps',
}
_A = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
_A = False
def lowerCAmelCase_ ( self ) -> Any:
torch.manual_seed(0 )
snake_case__ :List[str] = UNetaDModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("DownBlock2D", "AttnDownBlock2D") ,up_block_types=("AttnUpBlock2D", "UpBlock2D") ,)
snake_case__ :int = DDIMScheduler()
snake_case__ :List[Any] = {"unet": unet, "scheduler": scheduler}
return components
def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase=0 ) -> Optional[Any]:
if str(UpperCamelCase ).startswith("mps" ):
snake_case__ :Dict = torch.manual_seed(UpperCamelCase )
else:
snake_case__ :Union[str, Any] = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase )
snake_case__ :List[str] = {
"batch_size": 1,
"generator": generator,
"num_inference_steps": 2,
"output_type": "numpy",
}
return inputs
def lowerCAmelCase_ ( self ) -> int:
snake_case__ :Tuple = "cpu"
snake_case__ :int = self.get_dummy_components()
snake_case__ :str = self.pipeline_class(**UpperCamelCase )
pipe.to(UpperCamelCase )
pipe.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :Optional[Any] = self.get_dummy_inputs(UpperCamelCase )
snake_case__ :Dict = pipe(**UpperCamelCase ).images
snake_case__ :Optional[int] = image[0, -3:, -3:, -1]
self.assertEqual(image.shape ,(1, 32, 32, 3) )
snake_case__ :Tuple = np.array(
[1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] )
snake_case__ :Dict = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(UpperCamelCase ,1E-3 )
def lowerCAmelCase_ ( self ) -> Any:
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> List[Any]:
super().test_save_load_local(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> Tuple:
super().test_save_load_optional_components(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> Dict:
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
@slow
@require_torch_gpu
class _snake_case ( unittest.TestCase ):
def lowerCAmelCase_ ( self ) -> str:
snake_case__ :Optional[int] = "google/ddpm-cifar10-32"
snake_case__ :int = UNetaDModel.from_pretrained(UpperCamelCase )
snake_case__ :List[str] = DDIMScheduler()
snake_case__ :Any = DDIMPipeline(unet=UpperCamelCase ,scheduler=UpperCamelCase )
ddim.to(UpperCamelCase )
ddim.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :Dict = torch.manual_seed(0 )
snake_case__ :Optional[Any] = ddim(generator=UpperCamelCase ,eta=0.0 ,output_type="numpy" ).images
snake_case__ :int = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
snake_case__ :str = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def lowerCAmelCase_ ( self ) -> Any:
snake_case__ :int = "google/ddpm-ema-bedroom-256"
snake_case__ :Tuple = UNetaDModel.from_pretrained(UpperCamelCase )
snake_case__ :int = DDIMScheduler.from_pretrained(UpperCamelCase )
snake_case__ :Union[str, Any] = DDIMPipeline(unet=UpperCamelCase ,scheduler=UpperCamelCase )
ddpm.to(UpperCamelCase )
ddpm.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :int = torch.manual_seed(0 )
snake_case__ :Optional[int] = ddpm(generator=UpperCamelCase ,output_type="numpy" ).images
snake_case__ :Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
snake_case__ :Optional[int] = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 | 241 | 0 |
'''simple docstring'''
from typing import Optional, Tuple, Union
import tensorflow as tf
from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
TFBaseModelOutputWithNoAttention,
TFBaseModelOutputWithPoolingAndNoAttention,
TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig
__a = logging.get_logger(__name__)
# General docstring
__a = "RegNetConfig"
# Base docstring
__a = "facebook/regnet-y-040"
__a = [1, 1088, 7, 7]
# Image classification docstring
__a = "facebook/regnet-y-040"
__a = "tabby, tabby cat"
__a = [
"facebook/regnet-y-040",
# See all regnet models at https://huggingface.co/models?filter=regnet
]
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : str , snake_case_ : str , snake_case_ : str = 3 , snake_case_ : str = 1 , snake_case_ : Union[str, Any] = 1 , snake_case_ : Optional[int] = "relu" , **snake_case_ : Dict , ):
super().__init__(**A_ )
# The padding and conv has been verified in
# https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
snake_case__ : Optional[int] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 )
snake_case__ : Union[str, Any] = tf.keras.layers.ConvaD(
filters=A_ , kernel_size=A_ , strides=A_ , padding="""VALID""" , groups=A_ , use_bias=A_ , name="""convolution""" , )
snake_case__ : Any = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="""normalization""" )
snake_case__ : str = ACTaFN[activation] if activation is not None else tf.identity
def lowerCamelCase ( self : List[str] , snake_case_ : Optional[int] ):
snake_case__ : Optional[Any] = self.convolution(self.padding(A_ ) )
snake_case__ : int = self.normalization(A_ )
snake_case__ : int = self.activation(A_ )
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Any , snake_case_ : int , **snake_case_ : List[str] ):
super().__init__(**A_ )
snake_case__ : Optional[Any] = config.num_channels
snake_case__ : Optional[int] = TFRegNetConvLayer(
out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="""embedder""" , )
def lowerCamelCase ( self : str , snake_case_ : int ):
snake_case__ : List[str] = shape_list(A_ )[1]
if tf.executing_eagerly() and num_channels != self.num_channels:
raise ValueError(
"""Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" )
# When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
# So change the input format from `NCHW` to `NHWC`.
# shape = (batch_size, in_height, in_width, in_channels=num_channels)
snake_case__ : List[Any] = tf.transpose(A_ , perm=(0, 2, 3, 1) )
snake_case__ : str = self.embedder(A_ )
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Optional[int] , snake_case_ : Union[str, Any] , snake_case_ : Tuple = 2 , **snake_case_ : Union[str, Any] ):
super().__init__(**A_ )
snake_case__ : str = tf.keras.layers.ConvaD(
filters=A_ , kernel_size=1 , strides=A_ , use_bias=A_ , name="""convolution""" )
snake_case__ : List[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="""normalization""" )
def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Union[str, Any] , snake_case_ : List[str] = False ):
return self.normalization(self.convolution(A_ ) , training=A_ )
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : str , snake_case_ : Dict , snake_case_ : str , **snake_case_ : Any ):
super().__init__(**A_ )
snake_case__ : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_ , name="""pooler""" )
snake_case__ : int = [
tf.keras.layers.ConvaD(filters=A_ , kernel_size=1 , activation="""relu""" , name="""attention.0""" ),
tf.keras.layers.ConvaD(filters=A_ , kernel_size=1 , activation="""sigmoid""" , name="""attention.2""" ),
]
def lowerCamelCase ( self : int , snake_case_ : Any ):
snake_case__ : Dict = self.pooler(A_ )
for layer_module in self.attention:
snake_case__ : Optional[int] = layer_module(A_ )
snake_case__ : int = hidden_state * pooled
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : List[str] , snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] , snake_case_ : Any , snake_case_ : List[str] = 1 , **snake_case_ : Union[str, Any] ):
super().__init__(**A_ )
snake_case__ : Optional[Any] = in_channels != out_channels or stride != 1
snake_case__ : Tuple = max(1 , out_channels // config.groups_width )
snake_case__ : Tuple = (
TFRegNetShortCut(A_ , stride=A_ , name="""shortcut""" )
if should_apply_shortcut
else tf.keras.layers.Activation("""linear""" , name="""shortcut""" )
)
# `self.layers` instead of `self.layer` because that is a reserved argument.
snake_case__ : Dict = [
TFRegNetConvLayer(A_ , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ),
TFRegNetConvLayer(
A_ , stride=A_ , groups=A_ , activation=config.hidden_act , name="""layer.1""" ),
TFRegNetConvLayer(A_ , kernel_size=1 , activation=A_ , name="""layer.2""" ),
]
snake_case__ : Any = ACTaFN[config.hidden_act]
def lowerCamelCase ( self : List[Any] , snake_case_ : Optional[int] ):
snake_case__ : Dict = hidden_state
for layer_module in self.layers:
snake_case__ : Union[str, Any] = layer_module(A_ )
snake_case__ : Optional[int] = self.shortcut(A_ )
hidden_state += residual
snake_case__ : List[str] = self.activation(A_ )
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : str , snake_case_ : Union[str, Any] , snake_case_ : int , snake_case_ : List[Any] , snake_case_ : Optional[int] = 1 , **snake_case_ : List[str] ):
super().__init__(**A_ )
snake_case__ : Optional[Any] = in_channels != out_channels or stride != 1
snake_case__ : List[str] = max(1 , out_channels // config.groups_width )
snake_case__ : Optional[int] = (
TFRegNetShortCut(A_ , stride=A_ , name="""shortcut""" )
if should_apply_shortcut
else tf.keras.layers.Activation("""linear""" , name="""shortcut""" )
)
snake_case__ : List[str] = [
TFRegNetConvLayer(A_ , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ),
TFRegNetConvLayer(
A_ , stride=A_ , groups=A_ , activation=config.hidden_act , name="""layer.1""" ),
TFRegNetSELayer(A_ , reduced_channels=int(round(in_channels / 4 ) ) , name="""layer.2""" ),
TFRegNetConvLayer(A_ , kernel_size=1 , activation=A_ , name="""layer.3""" ),
]
snake_case__ : Optional[int] = ACTaFN[config.hidden_act]
def lowerCamelCase ( self : Optional[Any] , snake_case_ : Tuple ):
snake_case__ : Dict = hidden_state
for layer_module in self.layers:
snake_case__ : Tuple = layer_module(A_ )
snake_case__ : List[Any] = self.shortcut(A_ )
hidden_state += residual
snake_case__ : List[Any] = self.activation(A_ )
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Optional[int] , snake_case_ : Tuple , snake_case_ : List[Any] , snake_case_ : str , snake_case_ : Dict = 2 , snake_case_ : Tuple = 2 , **snake_case_ : Tuple ):
super().__init__(**A_ )
snake_case__ : str = TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
snake_case__ : Any = [
# downsampling is done in the first layer with stride of 2
layer(A_ , A_ , A_ , stride=A_ , name="""layers.0""" ),
*[layer(A_ , A_ , A_ , name=f"layers.{i+1}" ) for i in range(depth - 1 )],
]
def lowerCamelCase ( self : Any , snake_case_ : int ):
for layer_module in self.layers:
snake_case__ : Dict = layer_module(A_ )
return hidden_state
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : List[str] , snake_case_ : Union[str, Any] , **snake_case_ : int ):
super().__init__(**A_ )
snake_case__ : List[str] = []
# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
self.stages.append(
TFRegNetStage(
A_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="""stages.0""" , ) )
snake_case__ : Optional[int] = zip(config.hidden_sizes , config.hidden_sizes[1:] )
for i, ((in_channels, out_channels), depth) in enumerate(zip(A_ , config.depths[1:] ) ):
self.stages.append(TFRegNetStage(A_ , A_ , A_ , depth=A_ , name=f"stages.{i+1}" ) )
def lowerCamelCase ( self : Tuple , snake_case_ : Optional[int] , snake_case_ : int = False , snake_case_ : List[Any] = True ):
snake_case__ : Union[str, Any] = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
snake_case__ : Tuple = hidden_states + (hidden_state,)
snake_case__ : Any = stage_module(A_ )
if output_hidden_states:
snake_case__ : Union[str, Any] = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None )
return TFBaseModelOutputWithNoAttention(last_hidden_state=A_ , hidden_states=A_ )
@keras_serializable
class UpperCAmelCase_ ( tf.keras.layers.Layer ):
"""simple docstring"""
lowercase = RegNetConfig
def __init__( self : List[Any] , snake_case_ : int , **snake_case_ : Optional[int] ):
super().__init__(**A_ )
snake_case__ : Tuple = config
snake_case__ : Any = TFRegNetEmbeddings(A_ , name="""embedder""" )
snake_case__ : str = TFRegNetEncoder(A_ , name="""encoder""" )
snake_case__ : Optional[Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_ , name="""pooler""" )
@unpack_inputs
def lowerCamelCase ( self : Tuple , snake_case_ : Optional[Any] , snake_case_ : Dict = None , snake_case_ : Optional[int] = None , snake_case_ : Union[str, Any] = False , ):
snake_case__ : Dict = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
snake_case__ : Tuple = return_dict if return_dict is not None else self.config.use_return_dict
snake_case__ : int = self.embedder(A_ , training=A_ )
snake_case__ : int = self.encoder(
A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ )
snake_case__ : Optional[int] = encoder_outputs[0]
snake_case__ : Union[str, Any] = self.pooler(A_ )
# Change to NCHW output format have uniformity in the modules
snake_case__ : int = tf.transpose(A_ , perm=(0, 3, 1, 2) )
snake_case__ : List[str] = tf.transpose(A_ , perm=(0, 3, 1, 2) )
# Change the other hidden state outputs to NCHW as well
if output_hidden_states:
snake_case__ : str = tuple([tf.transpose(A_ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] )
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=A_ , pooler_output=A_ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , )
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
lowercase = RegNetConfig
lowercase = "regnet"
lowercase = "pixel_values"
@property
def lowerCamelCase ( self : int ):
return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )}
__a = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n"
__a = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
"The bare RegNet model outputting raw features without any specific head on top." , _SCREAMING_SNAKE_CASE , )
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
def __init__( self : Optional[Any] , snake_case_ : int , *snake_case_ : Union[str, Any] , **snake_case_ : Dict ):
super().__init__(A_ , *A_ , **A_ )
snake_case__ : List[Any] = TFRegNetMainLayer(A_ , name="""regnet""" )
@unpack_inputs
@add_start_docstrings_to_model_forward(A_ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=A_ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def lowerCamelCase ( self : Union[str, Any] , snake_case_ : List[str] , snake_case_ : List[str] = None , snake_case_ : Optional[int] = None , snake_case_ : str=False , ):
snake_case__ : Dict = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
snake_case__ : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict
snake_case__ : str = self.regnet(
pixel_values=A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ , )
if not return_dict:
return (outputs[0],) + outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , )
@add_start_docstrings(
"\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , _SCREAMING_SNAKE_CASE , )
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
def __init__( self : int , snake_case_ : str , *snake_case_ : int , **snake_case_ : Tuple ):
super().__init__(A_ , *A_ , **A_ )
snake_case__ : str = config.num_labels
snake_case__ : Union[str, Any] = TFRegNetMainLayer(A_ , name="""regnet""" )
# classification head
snake_case__ : Dict = [
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(config.num_labels , name="""classifier.1""" ) if config.num_labels > 0 else tf.identity,
]
@unpack_inputs
@add_start_docstrings_to_model_forward(A_ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def lowerCamelCase ( self : Optional[Any] , snake_case_ : List[str] = None , snake_case_ : Union[str, Any] = None , snake_case_ : Optional[int] = None , snake_case_ : Dict = None , snake_case_ : Union[str, Any]=False , ):
snake_case__ : Tuple = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
snake_case__ : int = return_dict if return_dict is not None else self.config.use_return_dict
snake_case__ : Any = self.regnet(
A_ , output_hidden_states=A_ , return_dict=A_ , training=A_ )
snake_case__ : Tuple = outputs.pooler_output if return_dict else outputs[1]
snake_case__ : List[str] = self.classifier[0](A_ )
snake_case__ : Any = self.classifier[1](A_ )
snake_case__ : str = None if labels is None else self.hf_compute_loss(labels=A_ , logits=A_ )
if not return_dict:
snake_case__ : Optional[int] = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFSequenceClassifierOutput(loss=A_ , logits=A_ , hidden_states=outputs.hidden_states )
| 703 |
'''simple docstring'''
def __snake_case( _lowerCAmelCase ) -> bool:
snake_case__ : Tuple = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def __snake_case( _lowerCAmelCase = 5_000 ) -> int:
snake_case__ : Any = [(i * (3 * i - 1)) // 2 for i in range(1 , _lowerCAmelCase )]
for i, pentagonal_i in enumerate(_lowerCAmelCase ):
for j in range(_lowerCAmelCase , len(_lowerCAmelCase ) ):
snake_case__ : Any = pentagonal_nums[j]
snake_case__ : Any = pentagonal_i + pentagonal_j
snake_case__ : Union[str, Any] = pentagonal_j - pentagonal_i
if is_pentagonal(_lowerCAmelCase ) and is_pentagonal(_lowerCAmelCase ):
return b
return -1
if __name__ == "__main__":
print(F"{solution() = }")
| 301 | 0 |
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ,lowerCAmelCase__ ):
return x if y == 0 else greatest_common_divisor(lowerCAmelCase__ ,x % y )
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ,lowerCAmelCase__ ):
return (x * y) // greatest_common_divisor(lowerCAmelCase__ ,lowerCAmelCase__ )
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ = 20 ):
lowerCamelCase_ : Optional[int] = 1
for i in range(1 ,n + 1 ):
lowerCamelCase_ : List[str] = lcm(lowerCAmelCase__ ,lowerCAmelCase__ )
return g
if __name__ == "__main__":
print(F'''{solution() = }''')
| 364 |
_lowercase : Optional[Any] ="""
# Transformers installation
! pip install transformers datasets
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/transformers.git
"""
_lowercase : Union[str, Any] =[{"""type""": """code""", """content""": INSTALL_CONTENT}]
_lowercase : List[Any] ={
"""{processor_class}""": """FakeProcessorClass""",
"""{model_class}""": """FakeModelClass""",
"""{object_class}""": """FakeObjectClass""",
}
| 364 | 1 |
import unittest
from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import 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 lowerCamelCase_ :
'''simple docstring'''
@staticmethod
def A ( *snake_case_ , **snake_case_ ) -> Tuple:
'''simple docstring'''
pass
@is_pipeline_test
@require_torch
@require_vision
class lowerCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
__UpperCAmelCase = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING
def A ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]:
'''simple docstring'''
__lowercase = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' )
__lowercase = [
{
'''image''': Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ),
'''question''': '''How many cats are there?''',
},
{
'''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
'''question''': '''How many cats are there?''',
},
]
return vqa_pipeline, examples
def A ( self , snake_case_ , snake_case_ ) -> int:
'''simple docstring'''
__lowercase = vqa_pipeline(snake_case_ , top_k=1 )
self.assertEqual(
snake_case_ , [
[{'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}],
[{'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}],
] , )
@require_torch
def A ( self ) -> List[Any]:
'''simple docstring'''
__lowercase = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' )
__lowercase = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
__lowercase = '''How many cats are there?'''
__lowercase = vqa_pipeline(image=snake_case_ , question='''How many cats are there?''' , top_k=2 )
self.assertEqual(
snake_case_ , [{'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}, {'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}] )
__lowercase = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(
snake_case_ , [{'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}, {'''score''': ANY(snake_case_ ), '''answer''': ANY(snake_case_ )}] )
@slow
@require_torch
def A ( self ) -> int:
'''simple docstring'''
__lowercase = pipeline('''visual-question-answering''' , model='''dandelin/vilt-b32-finetuned-vqa''' )
__lowercase = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
__lowercase = '''How many cats are there?'''
__lowercase = vqa_pipeline(image=snake_case_ , question=snake_case_ , top_k=2 )
self.assertEqual(
nested_simplify(snake_case_ , decimals=4 ) , [{'''score''': 0.8_7_9_9, '''answer''': '''2'''}, {'''score''': 0.2_9_6, '''answer''': '''1'''}] )
__lowercase = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(snake_case_ , decimals=4 ) , [{'''score''': 0.8_7_9_9, '''answer''': '''2'''}, {'''score''': 0.2_9_6, '''answer''': '''1'''}] )
__lowercase = vqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 )
self.assertEqual(
nested_simplify(snake_case_ , decimals=4 ) , [[{'''score''': 0.8_7_9_9, '''answer''': '''2'''}, {'''score''': 0.2_9_6, '''answer''': '''1'''}]] * 2 , )
@require_tf
@unittest.skip('''Visual question answering not implemented in TF''' )
def A ( self ) -> List[Any]:
'''simple docstring'''
pass
| 719 |
def lowercase_ ( _UpperCamelCase ):
'''simple docstring'''
__lowercase = []
__lowercase = []
__lowercase = {
'''^''': 3,
'''*''': 2,
'''/''': 2,
'''%''': 2,
'''+''': 1,
'''-''': 1,
} # Priority of each operator
__lowercase = len(_UpperCamelCase ) if (len(_UpperCamelCase ) > 7) else 7
# Print table header for output
print(
'''Symbol'''.center(8 ) , '''Stack'''.center(_UpperCamelCase ) , '''Postfix'''.center(_UpperCamelCase ) , sep=''' | ''' , )
print('''-''' * (print_width * 3 + 7) )
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(_UpperCamelCase ) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(_UpperCamelCase ) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while stack[-1] != "(":
post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(_UpperCamelCase ) == 0:
stack.append(_UpperCamelCase ) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while len(_UpperCamelCase ) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop() ) # pop stack & add to Postfix
stack.append(_UpperCamelCase ) # push x to stack
print(
x.center(8 ) , (''''''.join(_UpperCamelCase )).ljust(_UpperCamelCase ) , (''''''.join(_UpperCamelCase )).ljust(_UpperCamelCase ) , sep=''' | ''' , ) # Output in tabular format
while len(_UpperCamelCase ) > 0: # while stack is not empty
post_fix.append(stack.pop() ) # pop stack & add to Postfix
print(
''' '''.center(8 ) , (''''''.join(_UpperCamelCase )).ljust(_UpperCamelCase ) , (''''''.join(_UpperCamelCase )).ljust(_UpperCamelCase ) , sep=''' | ''' , ) # Output in tabular format
return "".join(_UpperCamelCase ) # return Postfix as str
def lowercase_ ( _UpperCamelCase ):
'''simple docstring'''
__lowercase = list(infix[::-1] ) # reverse the infix equation
for i in range(len(_UpperCamelCase ) ):
if infix[i] == "(":
__lowercase = ''')''' # change "(" to ")"
elif infix[i] == ")":
__lowercase = '''(''' # change ")" to "("
return (infix_2_postfix(''''''.join(_UpperCamelCase ) ))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
a : Union[str, Any] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation
a : Optional[Any] = ''''''.join(Infix.split()) # Remove spaces from the input
print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
| 527 | 0 |
"""simple docstring"""
import argparse
import os
import jax as jnp
import numpy as onp
import torch
import torch.nn as nn
from music_spectrogram_diffusion import inference
from tax import checkpoints
from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
lowercase__ : Tuple = "base_with_context"
def __lowercase ( _a , _a ):
snake_case_ : Dict = nn.Parameter(torch.FloatTensor(weights['''token_embedder''']['''embedding'''] ) )
snake_case_ : Union[str, Any] = nn.Parameter(
torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=__A )
for lyr_num, lyr in enumerate(model.encoders ):
snake_case_ : str = weights[f"layers_{lyr_num}"]
snake_case_ : int = nn.Parameter(
torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) )
snake_case_ : Optional[int] = ly_weight['''attention''']
snake_case_ : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) )
snake_case_ : str = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) )
snake_case_ : int = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) )
snake_case_ : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) )
snake_case_ : int = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) )
snake_case_ : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) )
snake_case_ : List[str] = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) )
return model
def __lowercase ( _a , _a ):
snake_case_ : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights['''input_proj''']['''kernel'''].T ) )
snake_case_ : Union[str, Any] = nn.Parameter(
torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=__A )
for lyr_num, lyr in enumerate(model.encoders ):
snake_case_ : Optional[int] = weights[f"layers_{lyr_num}"]
snake_case_ : Optional[int] = ly_weight['''attention''']
snake_case_ : Any = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) )
snake_case_ : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) )
snake_case_ : Any = nn.Parameter(
torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) )
snake_case_ : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) )
snake_case_ : List[str] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) )
snake_case_ : int = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) )
snake_case_ : List[Any] = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) )
return model
def __lowercase ( _a , _a ):
snake_case_ : int = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense0''']['''kernel'''].T ) )
snake_case_ : List[Any] = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense1''']['''kernel'''].T ) )
snake_case_ : Dict = nn.Parameter(
torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=__A )
snake_case_ : Optional[Any] = nn.Parameter(
torch.FloatTensor(weights['''continuous_inputs_projection''']['''kernel'''].T ) )
for lyr_num, lyr in enumerate(model.decoders ):
snake_case_ : Any = weights[f"layers_{lyr_num}"]
snake_case_ : Optional[int] = nn.Parameter(
torch.FloatTensor(ly_weight['''pre_self_attention_layer_norm''']['''scale'''] ) )
snake_case_ : List[str] = nn.Parameter(
torch.FloatTensor(ly_weight['''FiLMLayer_0''']['''DenseGeneral_0''']['''kernel'''].T ) )
snake_case_ : Optional[Any] = ly_weight['''self_attention''']
snake_case_ : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) )
snake_case_ : int = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) )
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) )
snake_case_ : List[str] = ly_weight['''MultiHeadDotProductAttention_0''']
snake_case_ : Tuple = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) )
snake_case_ : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) )
snake_case_ : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) )
snake_case_ : str = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) )
snake_case_ : Any = nn.Parameter(
torch.FloatTensor(ly_weight['''pre_cross_attention_layer_norm''']['''scale'''] ) )
snake_case_ : Dict = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) )
snake_case_ : List[Any] = nn.Parameter(
torch.FloatTensor(ly_weight['''FiLMLayer_1''']['''DenseGeneral_0''']['''kernel'''].T ) )
snake_case_ : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) )
snake_case_ : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) )
snake_case_ : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) )
snake_case_ : Optional[int] = nn.Parameter(torch.FloatTensor(weights['''decoder_norm''']['''scale'''] ) )
snake_case_ : Dict = nn.Parameter(torch.FloatTensor(weights['''spec_out_dense''']['''kernel'''].T ) )
return model
def __lowercase ( _a ):
snake_case_ : Tuple = checkpoints.load_tax_checkpoint(args.checkpoint_path )
snake_case_ : Optional[Any] = jnp.tree_util.tree_map(onp.array , __A )
snake_case_ : List[str] = [
'''from __gin__ import dynamic_registration''',
'''from music_spectrogram_diffusion.models.diffusion import diffusion_utils''',
'''diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0''',
'''diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()''',
]
snake_case_ : Optional[int] = os.path.join(args.checkpoint_path , '''..''' , '''config.gin''' )
snake_case_ : Optional[Any] = inference.parse_training_gin_file(__A , __A )
snake_case_ : int = inference.InferenceModel(args.checkpoint_path , __A )
snake_case_ : Any = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' , variance_type='''fixed_large''' )
snake_case_ : str = SpectrogramNotesEncoder(
max_length=synth_model.sequence_length['''inputs'''] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , )
snake_case_ : List[Any] = SpectrogramContEncoder(
input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length['''targets_context'''] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , )
snake_case_ : Dict = TaFilmDecoder(
input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length['''targets_context'''] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , )
snake_case_ : Tuple = load_notes_encoder(ta_checkpoint['''target''']['''token_encoder'''] , __A )
snake_case_ : Union[str, Any] = load_continuous_encoder(ta_checkpoint['''target''']['''continuous_encoder'''] , __A )
snake_case_ : Union[str, Any] = load_decoder(ta_checkpoint['''target''']['''decoder'''] , __A )
snake_case_ : Any = OnnxRuntimeModel.from_pretrained('''kashif/soundstream_mel_decoder''' )
snake_case_ : Tuple = SpectrogramDiffusionPipeline(
notes_encoder=__A , continuous_encoder=__A , decoder=__A , scheduler=__A , melgan=__A , )
if args.save:
pipe.save_pretrained(args.output_path )
if __name__ == "__main__":
lowercase__ : Optional[Any] = argparse.ArgumentParser()
parser.add_argument('''--output_path''', default=None, type=str, required=True, help='''Path to the converted model.''')
parser.add_argument(
'''--save''', default=True, type=bool, required=False, help='''Whether to save the converted model or not.'''
)
parser.add_argument(
'''--checkpoint_path''',
default=f'{MODEL}/checkpoint_500000',
type=str,
required=False,
help='''Path to the original jax model checkpoint.''',
)
lowercase__ : str = parser.parse_args()
main(args)
| 123 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
lowercase : Any = {
"configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase : Optional[Any] = [
"ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
"ErnieForCausalLM",
"ErnieForMaskedLM",
"ErnieForMultipleChoice",
"ErnieForNextSentencePrediction",
"ErnieForPreTraining",
"ErnieForQuestionAnswering",
"ErnieForSequenceClassification",
"ErnieForTokenClassification",
"ErnieModel",
"ErniePreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
lowercase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 495 | 0 |
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
FEATURE_EXTRACTOR_MAPPING,
AutoConfig,
AutoFeatureExtractor,
WavaVecaConfig,
WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402
SCREAMING_SNAKE_CASE__ : Tuple =get_tests_dir('fixtures')
SCREAMING_SNAKE_CASE__ : List[Any] =get_tests_dir('fixtures/dummy_feature_extractor_config.json')
SCREAMING_SNAKE_CASE__ : str =get_tests_dir('fixtures/dummy-config.json')
class _UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def a__ ( self ) -> Optional[Any]:
_lowerCamelCase : Optional[int] = 0
def a__ ( self ) -> Any:
_lowerCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''' )
self.assertIsInstance(__A , __A )
def a__ ( self ) -> Optional[int]:
_lowerCamelCase : Any = AutoFeatureExtractor.from_pretrained(__A )
self.assertIsInstance(__A , __A )
def a__ ( self ) -> List[Any]:
with tempfile.TemporaryDirectory() as tmpdirname:
_lowerCamelCase : Dict = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
_lowerCamelCase : int = AutoFeatureExtractor.from_pretrained(__A ).to_dict()
config_dict.pop('''feature_extractor_type''' )
_lowerCamelCase : Tuple = WavaVecaFeatureExtractor(**__A )
# save in new folder
model_config.save_pretrained(__A )
config.save_pretrained(__A )
_lowerCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(__A )
# make sure private variable is not incorrectly saved
_lowerCamelCase : int = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(__A , __A )
def a__ ( self ) -> Optional[int]:
_lowerCamelCase : Dict = AutoFeatureExtractor.from_pretrained(__A )
self.assertIsInstance(__A , __A )
def a__ ( self ) -> Union[str, Any]:
with self.assertRaisesRegex(
__A , '''bert-base is not a local folder and is not a valid model identifier''' ):
_lowerCamelCase : Optional[Any] = AutoFeatureExtractor.from_pretrained('''bert-base''' )
def a__ ( self ) -> List[Any]:
with self.assertRaisesRegex(
__A , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
_lowerCamelCase : Optional[Any] = AutoFeatureExtractor.from_pretrained(__A , revision='''aaaaaa''' )
def a__ ( self ) -> Optional[Any]:
with self.assertRaisesRegex(
__A , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
_lowerCamelCase : Any = AutoFeatureExtractor.from_pretrained('''hf-internal-testing/config-no-model''' )
def a__ ( self ) -> List[str]:
with self.assertRaises(__A ):
_lowerCamelCase : Optional[int] = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(__A ):
_lowerCamelCase : str = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=__A )
_lowerCamelCase : Any = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=__A )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
# Test feature extractor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(__A )
_lowerCamelCase : int = AutoFeatureExtractor.from_pretrained(__A , trust_remote_code=__A )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
def a__ ( self ) -> str:
try:
AutoConfig.register('''custom''' , __A )
AutoFeatureExtractor.register(__A , __A )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(__A ):
AutoFeatureExtractor.register(__A , __A )
# Now that the config is registered, it can be used as any other config with the auto-API
_lowerCamelCase : Tuple = CustomFeatureExtractor.from_pretrained(__A )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(__A )
_lowerCamelCase : Optional[Any] = AutoFeatureExtractor.from_pretrained(__A )
self.assertIsInstance(__A , __A )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
def a__ ( self ) -> Optional[int]:
class _UpperCAmelCase ( UpperCamelCase__ ):
"""simple docstring"""
__snake_case = True
try:
AutoConfig.register('''custom''' , __A )
AutoFeatureExtractor.register(__A , __A )
# If remote code is not set, the default is to use local
_lowerCamelCase : Optional[int] = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(feature_extractor.is_local )
# If remote code is disabled, we load the local one.
_lowerCamelCase : Any = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=__A )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(feature_extractor.is_local )
# If remote is enabled, we load from the Hub
_lowerCamelCase : Optional[int] = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=__A )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(not hasattr(__A , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
| 715 | """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 _UpperCAmelCase ( a_ , unittest.TestCase ):
"""simple docstring"""
__snake_case = CLIPTokenizer
__snake_case = CLIPTokenizerFast
__snake_case = True
__snake_case = {}
__snake_case = False
def a__ ( self ) -> Tuple:
super().setUp()
# fmt: off
_lowerCamelCase : List[str] = ['''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
_lowerCamelCase : Any = dict(zip(_lowercase , range(len(_lowercase ) ) ) )
_lowerCamelCase : Union[str, Any] = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''']
_lowerCamelCase : List[Any] = {'''unk_token''': '''<unk>'''}
_lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_lowerCamelCase : int = 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(_lowercase ) + '''\n''' )
with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write('''\n'''.join(_lowercase ) )
def a__ ( self , **_lowercase ) -> List[str]:
kwargs.update(self.special_tokens_map )
return CLIPTokenizer.from_pretrained(self.tmpdirname , **_lowercase )
def a__ ( self , **_lowercase ) -> Dict:
kwargs.update(self.special_tokens_map )
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_lowercase )
def a__ ( self , _lowercase ) -> Any:
_lowerCamelCase : Any = '''lower newer'''
_lowerCamelCase : Any = '''lower newer'''
return input_text, output_text
def a__ ( self ) -> Tuple:
_lowerCamelCase : Dict = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_lowerCamelCase : Union[str, Any] = '''lower newer'''
_lowerCamelCase : Optional[int] = ['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>''']
_lowerCamelCase : str = tokenizer.tokenize(_lowercase )
self.assertListEqual(_lowercase , _lowercase )
_lowerCamelCase : Any = tokens + [tokenizer.unk_token]
_lowerCamelCase : Union[str, Any] = [10, 2, 16, 9, 3, 2, 16, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase ) , _lowercase )
@require_ftfy
def a__ ( self ) -> Optional[Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase )
_lowerCamelCase : Tuple = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase )
_lowerCamelCase : Any = '''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.'''
_lowerCamelCase : Tuple = tokenizer_s.tokenize(_lowercase )
_lowerCamelCase : Union[str, Any] = tokenizer_r.tokenize(_lowercase )
self.assertListEqual(_lowercase , _lowercase )
# Test that the tokenization is identical on an example containing a character (Latin Small Letter A
# with Tilde) encoded in 2 different ways
_lowerCamelCase : Any = '''xa\u0303y''' + ''' ''' + '''x\xe3y'''
_lowerCamelCase : Tuple = tokenizer_s.tokenize(_lowercase )
_lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(_lowercase )
self.assertListEqual(_lowercase , _lowercase )
# Test that the tokenization is identical on unicode of space type
_lowerCamelCase : Optional[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:
_lowerCamelCase : Optional[int] = tokenizer_s.tokenize(_lowercase )
_lowerCamelCase : Any = tokenizer_r.tokenize(_lowercase )
self.assertListEqual(_lowercase , _lowercase )
# Test that the tokenization is identical on unicode of line break type
_lowerCamelCase : 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:
_lowerCamelCase : Dict = tokenizer_s.tokenize(_lowercase )
_lowerCamelCase : str = tokenizer_r.tokenize(_lowercase )
self.assertListEqual(_lowercase , _lowercase )
def a__ ( self ) -> str:
# 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})''' ):
_lowerCamelCase : int = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name`
_lowerCamelCase : List[Any] = F'''{text_of_1_token} {text_of_1_token}'''
_lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(
_lowercase , use_fast=_lowercase , )
_lowerCamelCase : List[str] = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowercase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(_lowercase ) + 1, len(_lowercase ) + 1 + len(_lowercase )) , )
_lowerCamelCase : str = F''' {text}'''
_lowerCamelCase : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(
_lowercase , use_fast=_lowercase , )
_lowerCamelCase : List[Any] = tokenizer_r(_lowercase , return_offsets_mapping=_lowercase , add_special_tokens=_lowercase )
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_lowercase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(_lowercase ) + 1, 1 + len(_lowercase ) + 1 + len(_lowercase )) , )
def a__ ( self ) -> Optional[Any]:
# 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(_lowercase ) 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 ) -> Tuple:
super().test_tokenization_python_rust_equals()
def a__ ( self ) -> Tuple:
# CLIP always lower cases letters
pass
| 558 | 0 |
'''simple docstring'''
from math import isqrt
def UpperCamelCase_ ( _UpperCAmelCase : int ) -> bool:
"""simple docstring"""
return all(number % divisor != 0 for divisor in range(2 , isqrt(_UpperCAmelCase ) + 1 ) )
def UpperCamelCase_ ( _UpperCAmelCase : int = 10**6 ) -> int:
"""simple docstring"""
_UpperCAmelCase : Optional[int] = 0
_UpperCAmelCase : Union[str, Any] = 1
_UpperCAmelCase : str = 7
while prime_candidate < max_prime:
primes_count += is_prime(_UpperCAmelCase )
cube_index += 1
prime_candidate += 6 * cube_index
return primes_count
if __name__ == "__main__":
print(F'{solution() = }')
| 244 | '''simple docstring'''
import datasets
from .evaluate import evaluate
__SCREAMING_SNAKE_CASE : Optional[Any] = """\
@inproceedings{Rajpurkar2016SQuAD10,
title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
booktitle={EMNLP},
year={2016}
}
"""
__SCREAMING_SNAKE_CASE : Any = """
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).
Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
"""
__SCREAMING_SNAKE_CASE : str = """
Computes SQuAD scores (F1 and EM).
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': the text of the answer
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 SQuAD 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
Examples:
>>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]
>>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
>>> squad_metric = datasets.load_metric(\"squad\")
>>> results = squad_metric.compute(predictions=predictions, references=references)
>>> print(results)
{'exact_match': 100.0, 'f1': 100.0}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowerCamelCase_ (datasets.Metric ):
'''simple docstring'''
def _A ( self : str ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": {"id": datasets.Value("string" ), "prediction_text": datasets.Value("string" )},
"references": {
"id": datasets.Value("string" ),
"answers": datasets.features.Sequence(
{
"text": datasets.Value("string" ),
"answer_start": datasets.Value("int32" ),
} ),
},
} ) , codebase_urls=["https://rajpurkar.github.io/SQuAD-explorer/"] , reference_urls=["https://rajpurkar.github.io/SQuAD-explorer/"] , )
def _A ( self : List[str] , A : Dict , A : Optional[Any] ):
_UpperCAmelCase : Tuple = {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
_UpperCAmelCase : List[str] = [
{
"paragraphs": [
{
"qas": [
{
"answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
"id": ref["id"],
}
for ref in references
]
}
]
}
]
_UpperCAmelCase : Optional[int] = evaluate(dataset=A , predictions=A )
return score
| 244 | 1 |
'''simple docstring'''
import fire
from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : str , **_UpperCAmelCase : List[Any] ) -> str:
__snake_case = AutoConfig.from_pretrained(_A , **_A )
__snake_case = AutoModelForSeqaSeqLM.from_config(_A )
model.save_pretrained(_A )
AutoTokenizer.from_pretrained(_A ).save_pretrained(_A )
return model
if __name__ == "__main__":
fire.Fire(save_randomly_initialized_version)
| 719 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
a : Union[str, Any] = logging.get_logger(__name__)
a : List[Any] = {
'''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """data2vec-text"""
def __init__( self : List[str] , a_ : str=30_522 , a_ : Optional[int]=768 , a_ : Dict=12 , a_ : int=12 , a_ : Dict=3_072 , a_ : Dict="gelu" , a_ : Optional[Any]=0.1 , a_ : List[str]=0.1 , a_ : int=512 , a_ : Any=2 , a_ : int=0.02 , a_ : Dict=1e-12 , a_ : Dict=1 , a_ : Any=0 , a_ : Dict=2 , a_ : Optional[int]="absolute" , a_ : List[Any]=True , a_ : Dict=None , **a_ : List[str] , ):
"""simple docstring"""
super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ )
__snake_case = vocab_size
__snake_case = hidden_size
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = hidden_act
__snake_case = intermediate_size
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = initializer_range
__snake_case = layer_norm_eps
__snake_case = position_embedding_type
__snake_case = use_cache
__snake_case = classifier_dropout
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
@property
def A ( self : Any ):
"""simple docstring"""
if self.task == "multiple-choice":
__snake_case = {0: "batch", 1: "choice", 2: "sequence"}
else:
__snake_case = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 680 | 0 |
'''simple docstring'''
from __future__ import annotations
import numpy as np
def _snake_case ( _SCREAMING_SNAKE_CASE : np.ndarray ) -> tuple[np.ndarray, np.ndarray]:
"""simple docstring"""
lowerCAmelCase, lowerCAmelCase = np.shape(_SCREAMING_SNAKE_CASE )
if rows != columns:
lowerCAmelCase = (
"""'table' has to be of square shaped array but got a """
f'{rows}x{columns} array:\n{table}'
)
raise ValueError(_SCREAMING_SNAKE_CASE )
lowerCAmelCase = np.zeros((rows, columns) )
lowerCAmelCase = np.zeros((rows, columns) )
for i in range(_SCREAMING_SNAKE_CASE ):
for j in range(_SCREAMING_SNAKE_CASE ):
lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(_SCREAMING_SNAKE_CASE ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
lowerCAmelCase = (table[i][j] - total) / upper[j][j]
lowerCAmelCase = 1
for j in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(_SCREAMING_SNAKE_CASE ) )
lowerCAmelCase = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod() | 433 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = {
'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json',
}
class __snake_case( _lowerCAmelCase ):
'''simple docstring'''
UpperCAmelCase : int = "mgp-str"
def __init__( self , A_=[32, 128] , A_=4 , A_=3 , A_=27 , A_=38 , A_=5_0257 , A_=3_0522 , A_=768 , A_=12 , A_=12 , A_=4.0 , A_=True , A_=False , A_=1e-5 , A_=0.0 , A_=0.0 , A_=0.0 , A_=False , A_=0.0_2 , **A_ , ) -> List[str]:
super().__init__(**A_ )
lowerCAmelCase = image_size
lowerCAmelCase = patch_size
lowerCAmelCase = num_channels
lowerCAmelCase = max_token_length
lowerCAmelCase = num_character_labels
lowerCAmelCase = num_bpe_labels
lowerCAmelCase = num_wordpiece_labels
lowerCAmelCase = hidden_size
lowerCAmelCase = num_hidden_layers
lowerCAmelCase = num_attention_heads
lowerCAmelCase = mlp_ratio
lowerCAmelCase = distilled
lowerCAmelCase = layer_norm_eps
lowerCAmelCase = drop_rate
lowerCAmelCase = qkv_bias
lowerCAmelCase = attn_drop_rate
lowerCAmelCase = drop_path_rate
lowerCAmelCase = output_aa_attentions
lowerCAmelCase = initializer_range | 433 | 1 |
from __future__ import annotations
from scipy.special import comb # type: ignore
class _A :
def __init__( self , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = list_of_points
# Degree determines the flexibility of the curve.
# Degree = 1 will produce a straight line.
_UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) - 1
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
assert 0 <= t <= 1, "Time t must be between 0 and 1."
_UpperCAmelCase = []
for i in range(len(self.list_of_points ) ):
# basis function for each i
output_values.append(
comb(self.degree , _SCREAMING_SNAKE_CASE ) * ((1 - t) ** (self.degree - i)) * (t**i) )
# the basis must sum up to 1 for it to produce a valid Bezier curve.
assert round(sum(_SCREAMING_SNAKE_CASE ) , 5 ) == 1
return output_values
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
assert 0 <= t <= 1, "Time t must be between 0 and 1."
_UpperCAmelCase = self.basis_function(_SCREAMING_SNAKE_CASE )
_UpperCAmelCase = 0.0
_UpperCAmelCase = 0.0
for i in range(len(self.list_of_points ) ):
# For all points, sum up the product of i-th basis function and i-th point.
x += basis_function[i] * self.list_of_points[i][0]
y += basis_function[i] * self.list_of_points[i][1]
return (x, y)
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE = 0.01 ):
from matplotlib import pyplot as plt # type: ignore
_UpperCAmelCase = [] # x coordinates of points to plot
_UpperCAmelCase = [] # y coordinates of points to plot
_UpperCAmelCase = 0.0
while t <= 1:
_UpperCAmelCase = self.bezier_curve_function(_SCREAMING_SNAKE_CASE )
to_plot_x.append(value[0] )
to_plot_y.append(value[1] )
t += step_size
_UpperCAmelCase = [i[0] for i in self.list_of_points]
_UpperCAmelCase = [i[1] for i in self.list_of_points]
plt.plot(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , color="""blue""" , label="""Curve of Degree """ + str(self.degree ) , )
plt.scatter(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , color="""red""" , label="""Control Points""" )
plt.legend()
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1
BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2
BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3 | 175 |
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> bool:
_UpperCAmelCase = len(snake_case ) + 1
_UpperCAmelCase = len(snake_case ) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
_UpperCAmelCase = [[0 for i in range(snake_case )] for j in range(snake_case )]
# since string of zero length match pattern of zero length
_UpperCAmelCase = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1 , snake_case ):
_UpperCAmelCase = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1 , snake_case ):
_UpperCAmelCase = dp[0][j - 2] if pattern[j - 1] == """*""" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1 , snake_case ):
for j in range(1 , snake_case ):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
_UpperCAmelCase = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
_UpperCAmelCase = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
_UpperCAmelCase = dp[i - 1][j]
else:
_UpperCAmelCase = 0
else:
_UpperCAmelCase = 0
return bool(dp[-1][-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
a = "aab"
a = "c*a*b"
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(F'{input_string} matches the given pattern {pattern}')
else:
print(F'{input_string} does not match with the given pattern {pattern}') | 175 | 1 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
import PIL.Image
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
PILImageResampling,
get_image_size,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__SCREAMING_SNAKE_CASE : str =logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( __lowercase ):
"""simple docstring"""
A__ : List[Any] = ["pixel_values"]
def __init__( self , A = True , A = 32 , A=PILImageResampling.BILINEAR , A = True , **A , ) -> None:
A: Optional[int] = do_resize
A: Union[str, Any] = do_rescale
A: Any = size_divisor
A: Dict = resample
super().__init__(**SCREAMING_SNAKE_CASE_ )
def a__ ( self , A , A , A , A = None , **A ) -> np.ndarray:
A , A: str = get_image_size(SCREAMING_SNAKE_CASE_ )
# Rounds the height and width down to the closest multiple of size_divisor
A: List[str] = height // size_divisor * size_divisor
A: Any = width // size_divisor * size_divisor
A: Any = resize(SCREAMING_SNAKE_CASE_ , (new_h, new_w) , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
return image
def a__ ( self , A , A , A = None , **A ) -> np.ndarray:
return rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def a__ ( self , A , A = None , A = None , A=None , A = None , A = None , A = ChannelDimension.FIRST , **A , ) -> BatchFeature:
A: List[str] = do_resize if do_resize is not None else self.do_resize
A: Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale
A: Optional[Any] = size_divisor if size_divisor is not None else self.size_divisor
A: Optional[int] = resample if resample is not None else self.resample
if do_resize and size_divisor is None:
raise ValueError("""size_divisor is required for resizing""" )
A: str = make_list_of_images(SCREAMING_SNAKE_CASE_ )
if not valid_images(SCREAMING_SNAKE_CASE_ ):
raise ValueError("""Invalid image(s)""" )
# All transformations expect numpy arrays.
A: List[Any] = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for img in images]
if do_resize:
A: str = [self.resize(SCREAMING_SNAKE_CASE_ , size_divisor=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images]
if do_rescale:
A: Optional[int] = [self.rescale(SCREAMING_SNAKE_CASE_ , scale=1 / 2_55 ) for image in images]
A: Optional[Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images]
A: List[str] = {"""pixel_values""": images}
return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
| 135 |
'''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 : int = get_tests_dir("fixtures/test_sentencepiece.model")
_a : Dict = {"target_lang": "fi", "source_lang": "en"}
_a : Optional[int] = ">>zh<<"
_a : List[str] = "Helsinki-NLP/"
if is_torch_available():
_a : List[str] = "pt"
elif is_tf_available():
_a : Dict = "tf"
else:
_a : Union[str, Any] = "jax"
@require_sentencepiece
class _lowercase ( __lowercase , unittest.TestCase ):
_SCREAMING_SNAKE_CASE : int = MarianTokenizer
_SCREAMING_SNAKE_CASE : str = False
_SCREAMING_SNAKE_CASE : Union[str, Any] = True
def a ( self : int ) -> int:
super().setUp()
__snake_case = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>']
__snake_case = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) )
__snake_case = Path(self.tmpdirname )
save_json(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['vocab'] )
save_json(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['tokenizer_config_file'] )
if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists():
copyfile(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['source_spm'] )
copyfile(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['target_spm'] )
__snake_case = MarianTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def a ( self : int , **SCREAMING_SNAKE_CASE_ : Optional[int] ) -> MarianTokenizer:
return MarianTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ )
def a ( self : str , SCREAMING_SNAKE_CASE_ : List[str] ) -> List[Any]:
return (
"This is a test",
"This is a test",
)
def a ( self : int ) -> Optional[Any]:
__snake_case = '</s>'
__snake_case = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
def a ( self : Dict ) -> List[str]:
__snake_case = 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(SCREAMING_SNAKE_CASE_ ) , 9 )
def a ( self : List[Any] ) -> str:
self.assertEqual(self.get_tokenizer().vocab_size , 9 )
def a ( self : Any ) -> Optional[int]:
__snake_case = MarianTokenizer.from_pretrained(f'{ORG_NAME}opus-mt-en-de' )
__snake_case = en_de_tokenizer(['I am a small frog'] , return_tensors=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__snake_case = [38, 121, 14, 697, 3_8848, 0]
self.assertListEqual(SCREAMING_SNAKE_CASE_ , batch.input_ids[0] )
__snake_case = tempfile.mkdtemp()
en_de_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
__snake_case = [x.name for x in Path(SCREAMING_SNAKE_CASE_ ).glob('*' )]
self.assertIn('source.spm' , SCREAMING_SNAKE_CASE_ )
MarianTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
def a ( self : Optional[int] ) -> Any:
__snake_case = self.get_tokenizer()
__snake_case = tok(
['I am a small frog' * 1000, 'I am a small frog'] , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(batch.input_ids.shape , (2, 512) )
def a ( self : Tuple ) -> Dict:
__snake_case = self.get_tokenizer()
__snake_case = tok(['I am a tiny frog', 'I am a small frog'] , padding=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(batch_smaller.input_ids.shape , (2, 10) )
@slow
def a ( self : int ) -> int:
# fmt: off
__snake_case = {'input_ids': [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], '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=SCREAMING_SNAKE_CASE_ , model_name='Helsinki-NLP/opus-mt-en-de' , revision='1a8c2263da11e68e50938f97e10cd57820bd504c' , decode_kwargs={'use_source_tokenizer': True} , )
def a ( self : Dict ) -> str:
__snake_case = MarianTokenizer.from_pretrained('hf-internal-testing/test-marian-two-vocabs' )
__snake_case = 'Tämä on testi'
__snake_case = 'This is a test'
__snake_case = [76, 7, 2047, 2]
__snake_case = [69, 12, 11, 940, 2]
__snake_case = tokenizer(SCREAMING_SNAKE_CASE_ ).input_ids
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__snake_case = tokenizer(text_target=SCREAMING_SNAKE_CASE_ ).input_ids
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__snake_case = tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
| 56 | 0 |
'''simple docstring'''
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
)
from transformers.utils import is_sentencepiece_available
if is_sentencepiece_available():
from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json
from ...test_tokenization_common import TokenizerTesterMixin
if is_sentencepiece_available():
__UpperCAmelCase = get_tests_dir('''fixtures/test_sentencepiece.model''')
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__UpperCAmelCase = 128_022
__UpperCAmelCase = 128_028
@require_sentencepiece
class a__ ( lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
lowercase__ : Dict = MaMaaaTokenizer
lowercase__ : List[str] = False
lowercase__ : int = False
lowercase__ : List[Any] = True
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
super().setUp()
lowerCAmelCase__ = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>''']
lowerCAmelCase__ = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) )
lowerCAmelCase__ = Path(self.tmpdirname )
save_json(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['''spm_file'''] )
lowerCAmelCase__ = MaMaaaTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def __SCREAMING_SNAKE_CASE ( self , **lowerCamelCase_ ) -> Any:
return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> str:
return (
"This is a test",
"This is a test",
)
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
lowerCAmelCase__ = '''</s>'''
lowerCAmelCase__ = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> int:
lowerCAmelCase__ = self.get_tokenizer()
lowerCAmelCase__ = list(tokenizer.get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''</s>''' )
self.assertEqual(vocab_keys[1] , '''<unk>''' )
self.assertEqual(vocab_keys[-1] , '''<s>''' )
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) )
@unittest.skip('''Skip this test while all models are still to be uploaded.''' )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
pass
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
lowerCAmelCase__ = self.get_tokenizer()
lowerCAmelCase__ = tokenizer.tokenize('''This is a test''' )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [2, 3, 4, 5, 6] , )
lowerCAmelCase__ = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] )
lowerCAmelCase__ = tokenizer.convert_tokens_to_string(_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , '''This is a test''' )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
# fmt: off
lowerCAmelCase__ = {'''input_ids''': [[12_80_22, 11_01_08, 3_97, 11, 3_82_72, 22_47, 12_48_11, 2_85, 1_81_05, 15_86, 2_07, 7, 3_95_34, 44_28, 3_97, 10_19, 1_81_05, 15_86, 2_07, 7, 4_13_37, 1_67_86, 2_41, 7, 2_02_14, 17, 12_56_90, 1_03_98, 7, 4_43_78, 5_80_69, 6_83_42, 77_98, 73_43, 11, 2_99, 3_33_10, 4, 1_58, 3_73_50, 9_40_77, 45_69, 2_99, 3_33_10, 90, 4, 5_28_40, 2_90, 4, 3_12_70, 1_12, 2_99, 6_82, 4, 5_28_40, 3_99_53, 1_40_79, 1_93, 5_25_19, 9_08_94, 1_78_94, 12_06_97, 11, 4_04_45, 5_51, 17, 10_19, 5_25_19, 9_08_94, 1_77_56, 9_63, 11, 4_04_45, 4_80, 17, 97_92, 11_20, 51_73, 13_93, 62_40, 1_67_86, 2_41, 12_09_96, 28, 12_45, 13_93, 11_82_40, 1_11_23, 10_19, 9_36_12, 26_91, 1_06_18, 9_80_58, 12_04_09, 19_28, 2_79, 4, 4_06_83, 3_67, 1_78, 2_07, 10_19, 1_03, 10_31_21, 5_06, 6_52_96, 5, 2], [12_80_22, 2_12_17, 3_67, 1_17, 12_54_50, 1_28, 7_19, 7, 73_08, 40, 9_36_12, 1_26_69, 11_16, 1_67_04, 71, 1_77_85, 36_99, 1_55_92, 35, 1_44, 95_84, 2_41, 1_19_43, 7_13, 9_50, 7_99, 22_47, 8_84_27, 1_50, 1_49, 11_88_13, 12_07_06, 10_19, 10_69_06, 8_15_18, 28, 12_24, 2_27_99, 3_97, 5, 2, 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], [12_80_22, 16_58, 12_33_11, 51_55, 55_78, 47_22, 2_79, 1_49_47, 23_66, 11_20, 11_97, 14, 13_48, 92_32, 5, 2, 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]], '''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, 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], [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, 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=_SCREAMING_SNAKE_CASE , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , )
@require_torch
@require_sentencepiece
@require_tokenizers
class a__ ( unittest.TestCase ):
'''simple docstring'''
lowercase__ : Union[str, Any] = "facebook/m2m100_418M"
lowercase__ : Optional[Any] = [
"In my opinion, there are two levels of response from the French government.",
"NSA Affair Emphasizes Complete Lack of Debate on Intelligence",
]
lowercase__ : Optional[int] = [
"Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.",
"L'affaire NSA souligne l'absence totale de débat sur le renseignement",
]
# fmt: off
lowercase__ : Union[str, Any] = [EN_CODE, 5_9_3, 1_9_4_9, 1_1_5_7_8_1, 4, 7_1_5_8_6, 4_2_3_4, 6_0_6_3_3, 1_2_6_2_3_3, 4_3_2, 1_2_3_8_0_8, 1_5_5_9_2, 1_1_9_7, 1_1_7_1_3_2, 1_2_0_6_1_8, 5, 2]
@classmethod
def __SCREAMING_SNAKE_CASE ( cls ) -> Union[str, Any]:
lowerCAmelCase__ = MaMaaaTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' )
lowerCAmelCase__ = 1
return cls
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 12_80_06 )
self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 12_80_22 )
self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 12_80_76 )
self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 12_80_63 )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
lowerCAmelCase__ = self.tokenizer.get_vocab()
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.tokenizer.vocab_size )
self.assertEqual(vocab['''<unk>'''] , 3 )
self.assertIn(self.tokenizer.get_lang_token('''en''' ) , _SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
lowerCAmelCase__ = '''en'''
lowerCAmelCase__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , _SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
self.assertIn(_SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids )
# fmt: off
lowerCAmelCase__ = [FR_CODE, 53_64, 82, 86_42, 4, 2_94, 47, 8, 1_40_28, 1_36, 32_86, 97_06, 6, 9_07_97, 6, 14_40_12, 1_62, 8_81_28, 3_00_61, 5, 2]
# fmt: on
lowerCAmelCase__ = self.tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
self.assertNotIn(self.tokenizer.eos_token , _SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> int:
lowerCAmelCase__ = tempfile.mkdtemp()
lowerCAmelCase__ = self.tokenizer.lang_token_to_id
self.tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ = MaMaaaTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE )
self.assertDictEqual(new_tok.lang_token_to_id , _SCREAMING_SNAKE_CASE )
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
lowerCAmelCase__ = '''en'''
lowerCAmelCase__ = '''fr'''
lowerCAmelCase__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_SCREAMING_SNAKE_CASE , return_tensors='''pt''' )
lowerCAmelCase__ = shift_tokens_right(
batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id )
for k in batch:
lowerCAmelCase__ = batch[k].tolist()
# batch = {k: v.tolist() for k,v in batch.items()}
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
# batch.decoder_inputs_ids[0][0] ==
assert batch.input_ids[1][0] == EN_CODE
assert batch.input_ids[1][-1] == 2
assert batch.labels[1][0] == FR_CODE
assert batch.labels[1][-1] == 2
assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
lowerCAmelCase__ = '''mr'''
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
lowerCAmelCase__ = '''zh'''
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
lowerCAmelCase__ = '''mr'''
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
lowerCAmelCase__ = '''zh'''
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
lowerCAmelCase__ = self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' )
self.assertEqual(
nested_simplify(_SCREAMING_SNAKE_CASE ) , {
# en_XX, A, test, EOS
'''input_ids''': [[12_80_22, 58, 41_83, 2]],
'''attention_mask''': [[1, 1, 1, 1]],
# ar_AR
'''forced_bos_token_id''': 12_80_06,
} , ) | 709 |
'''simple docstring'''
import doctest
from collections import deque
import numpy as np
class a__ :
'''simple docstring'''
def __init__( self ) -> None:
lowerCAmelCase__ = [2, 1, 2, -1]
lowerCAmelCase__ = [1, 2, 3, 4]
def __SCREAMING_SNAKE_CASE ( self ) -> list[float]:
lowerCAmelCase__ = len(self.first_signal )
lowerCAmelCase__ = len(self.second_signal )
lowerCAmelCase__ = max(lowerCamelCase_ , lowerCamelCase_ )
# create a zero matrix of max_length x max_length
lowerCAmelCase__ = [[0] * max_length for i in range(lowerCamelCase_ )]
# fills the smaller signal with zeros to make both signals of same length
if length_first_signal < length_second_signal:
self.first_signal += [0] * (max_length - length_first_signal)
elif length_first_signal > length_second_signal:
self.second_signal += [0] * (max_length - length_second_signal)
for i in range(lowerCamelCase_ ):
lowerCAmelCase__ = deque(self.second_signal )
rotated_signal.rotate(lowerCamelCase_ )
for j, item in enumerate(lowerCamelCase_ ):
matrix[i][j] += item
# multiply the matrix with the first signal
lowerCAmelCase__ = np.matmul(np.transpose(lowerCamelCase_ ) , np.transpose(self.first_signal ) )
# rounding-off to two decimal places
return [round(lowerCamelCase_ , 2 ) for i in final_signal]
if __name__ == "__main__":
doctest.testmod() | 98 | 0 |
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ConditionalDetrImageProcessor
class lowercase_ (unittest.TestCase ):
def __init__( self , lowercase_ , lowercase_=7 , lowercase_=3 , lowercase_=30 , lowercase_=400 , lowercase_=True , lowercase_=None , lowercase_=True , lowercase_=[0.5, 0.5, 0.5] , lowercase_=[0.5, 0.5, 0.5] , lowercase_=True , lowercase_=1 / 255 , lowercase_=True , ) -> List[Any]:
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
a__ =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
a__ =parent
a__ =batch_size
a__ =num_channels
a__ =min_resolution
a__ =max_resolution
a__ =do_resize
a__ =size
a__ =do_normalize
a__ =image_mean
a__ =image_std
a__ =do_rescale
a__ =rescale_factor
a__ =do_pad
def __UpperCamelCase ( self) -> Dict:
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def __UpperCamelCase ( self , lowercase_ , lowercase_=False) -> Any:
if not batched:
a__ =image_inputs[0]
if isinstance(lowercase_ , Image.Image):
a__ , a__ =image.size
else:
a__ , a__ =image.shape[1], image.shape[2]
if w < h:
a__ =int(self.size['shortest_edge'] * h / w)
a__ =self.size['shortest_edge']
elif w > h:
a__ =self.size['shortest_edge']
a__ =int(self.size['shortest_edge'] * w / h)
else:
a__ =self.size['shortest_edge']
a__ =self.size['shortest_edge']
else:
a__ =[]
for image in image_inputs:
a__ , a__ =self.get_expected_values([image])
expected_values.append((expected_height, expected_width))
a__ =max(lowercase_ , key=lambda lowercase_: item[0])[0]
a__ =max(lowercase_ , key=lambda lowercase_: item[1])[1]
return expected_height, expected_width
@require_torch
@require_vision
class lowercase_ (lowercase__ , unittest.TestCase ):
snake_case =ConditionalDetrImageProcessor if is_vision_available() else None
def __UpperCamelCase ( self) -> Tuple:
a__ =ConditionalDetrImageProcessingTester(self)
@property
def __UpperCamelCase ( self) -> Dict:
return self.image_processor_tester.prepare_image_processor_dict()
def __UpperCamelCase ( self) -> Any:
a__ =self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(lowercase_ , 'image_mean'))
self.assertTrue(hasattr(lowercase_ , 'image_std'))
self.assertTrue(hasattr(lowercase_ , 'do_normalize'))
self.assertTrue(hasattr(lowercase_ , 'do_resize'))
self.assertTrue(hasattr(lowercase_ , 'size'))
def __UpperCamelCase ( self) -> Union[str, Any]:
a__ =self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333})
self.assertEqual(image_processor.do_pad , lowercase_)
a__ =self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowercase_)
self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84})
self.assertEqual(image_processor.do_pad , lowercase_)
def __UpperCamelCase ( self) -> Optional[Any]:
pass
def __UpperCamelCase ( self) -> Optional[Any]:
# Initialize image_processing
a__ =self.image_processing_class(**self.image_processor_dict)
# create random PIL images
a__ =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_)
for image in image_inputs:
self.assertIsInstance(lowercase_ , Image.Image)
# Test not batched input
a__ =image_processing(image_inputs[0] , return_tensors='pt').pixel_values
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_ , batched=lowercase_)
a__ =image_processing(lowercase_ , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __UpperCamelCase ( self) -> Optional[int]:
# Initialize image_processing
a__ =self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
a__ =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , numpify=lowercase_)
for image in image_inputs:
self.assertIsInstance(lowercase_ , np.ndarray)
# Test not batched input
a__ =image_processing(image_inputs[0] , return_tensors='pt').pixel_values
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a__ =image_processing(lowercase_ , return_tensors='pt').pixel_values
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_ , batched=lowercase_)
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __UpperCamelCase ( self) -> Optional[Any]:
# Initialize image_processing
a__ =self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
a__ =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , torchify=lowercase_)
for image in image_inputs:
self.assertIsInstance(lowercase_ , torch.Tensor)
# Test not batched input
a__ =image_processing(image_inputs[0] , return_tensors='pt').pixel_values
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a__ =image_processing(lowercase_ , return_tensors='pt').pixel_values
a__ , a__ =self.image_processor_tester.get_expected_values(lowercase_ , batched=lowercase_)
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def __UpperCamelCase ( self) -> List[Any]:
# prepare image and target
a__ =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f:
a__ =json.loads(f.read())
a__ ={'image_id': 39769, 'annotations': target}
# encode them
a__ =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50')
a__ =image_processing(images=lowercase_ , annotations=lowercase_ , return_tensors='pt')
# verify pixel values
a__ =torch.Size([1, 3, 800, 1066])
self.assertEqual(encoding['pixel_values'].shape , lowercase_)
a__ =torch.tensor([0.27_96, 0.31_38, 0.34_81])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase_ , atol=1e-4))
# verify area
a__ =torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase_))
# verify boxes
a__ =torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase_)
a__ =torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase_ , atol=1e-3))
# verify image_id
a__ =torch.tensor([39769])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase_))
# verify is_crowd
a__ =torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase_))
# verify class_labels
a__ =torch.tensor([75, 75, 63, 65, 17, 17])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase_))
# verify orig_size
a__ =torch.tensor([480, 640])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase_))
# verify size
a__ =torch.tensor([800, 1066])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase_))
@slow
def __UpperCamelCase ( self) -> Dict:
# prepare image, target and masks_path
a__ =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f:
a__ =json.loads(f.read())
a__ ={'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target}
a__ =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic')
# encode them
a__ =ConditionalDetrImageProcessor(format='coco_panoptic')
a__ =image_processing(images=lowercase_ , annotations=lowercase_ , masks_path=lowercase_ , return_tensors='pt')
# verify pixel values
a__ =torch.Size([1, 3, 800, 1066])
self.assertEqual(encoding['pixel_values'].shape , lowercase_)
a__ =torch.tensor([0.27_96, 0.31_38, 0.34_81])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase_ , atol=1e-4))
# verify area
a__ =torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase_))
# verify boxes
a__ =torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase_)
a__ =torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase_ , atol=1e-3))
# verify image_id
a__ =torch.tensor([39769])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase_))
# verify is_crowd
a__ =torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase_))
# verify class_labels
a__ =torch.tensor([17, 17, 63, 75, 75, 93])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase_))
# verify masks
a__ =822873
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , lowercase_)
# verify orig_size
a__ =torch.tensor([480, 640])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase_))
# verify size
a__ =torch.tensor([800, 1066])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase_))
| 20 |
'''simple docstring'''
import os
from datetime import datetime as dt
from github import Github
__A =[
'good first issue',
'feature request',
'wip',
]
def _UpperCamelCase ( ):
UpperCAmelCase__ : List[str] = Github(os.environ["""GITHUB_TOKEN"""] )
UpperCAmelCase__ : Dict = g.get_repo("""huggingface/accelerate""" )
UpperCAmelCase__ : Any = repo.get_issues(state="""open""" )
for issue in open_issues:
UpperCAmelCase__ : Tuple = sorted([comment for comment in issue.get_comments()] , key=lambda UpperCamelCase__ : i.created_at , reverse=UpperCamelCase__ )
UpperCAmelCase__ : Any = comments[0] if len(UpperCamelCase__ ) > 0 else None
UpperCAmelCase__ : Optional[Any] = dt.utcnow()
UpperCAmelCase__ : Optional[int] = (current_time - issue.updated_at).days
UpperCAmelCase__ : int = (current_time - issue.created_at).days
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and days_since_updated > 7
and days_since_creation >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Close issue since it has been 7 days of inactivity since bot mention.
issue.edit(state="""closed""" )
elif (
days_since_updated > 2_3
and days_since_creation >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Add stale comment
issue.create_comment(
"""This issue has been automatically marked as stale because it has not had """
"""recent activity. If you think this still needs to be addressed """
"""please comment on this thread.\n\nPlease note that issues that do not follow the """
"""[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) """
"""are likely to be ignored.""" )
if __name__ == "__main__":
main() | 407 | 0 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
from transformers import BatchEncoding, CanineTokenizer
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.tokenization_utils import AddedToken
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
'''simple docstring'''
__UpperCamelCase = CanineTokenizer
__UpperCamelCase = False
def _UpperCamelCase ( self ):
'''simple docstring'''
super().setUp()
snake_case: List[Any] = CanineTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def _UpperCamelCase ( self ):
'''simple docstring'''
return CanineTokenizer.from_pretrained('google/canine-s' )
def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: List[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ )
snake_case: Any = 10_24
return tokenizer
@require_torch
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Union[str, Any] = self.canine_tokenizer
snake_case: Union[str, Any] = ['Life is like a box of chocolates.', 'You never know what you\'re gonna get.']
# fmt: off
snake_case: Any = [5_73_44, 76, 1_05, 1_02, 1_01, 32, 1_05, 1_15, 32, 1_08, 1_05, 1_07, 1_01, 32, 97, 32, 98, 1_11, 1_20, 32, 1_11, 1_02, 32, 99, 1_04, 1_11, 99, 1_11, 1_08, 97, 1_16, 1_01, 1_15, 46, 5_73_45, 0, 0, 0, 0]
# fmt: on
snake_case: List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
snake_case: Optional[int] = list(batch.input_ids.numpy()[0] )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
self.assertEqual((2, 39) , batch.input_ids.shape )
self.assertEqual((2, 39) , batch.attention_mask.shape )
@require_torch
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Any = self.canine_tokenizer
snake_case: Optional[Any] = ['Once there was a man.', 'He wrote a test in HuggingFace Tranformers.']
snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )
# check if input_ids, attention_mask and token_type_ids are returned
self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ )
self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ )
self.assertIn('token_type_ids' , SCREAMING_SNAKE_CASE__ )
@require_torch
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Any = self.canine_tokenizer
snake_case: List[str] = [
'What\'s the weater?',
'It\'s about 25 degrees.',
]
snake_case: int = tokenizer(
text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )
self.assertEqual(32 , targets['input_ids'].shape[1] )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: List[Any] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
self.assertNotEqual(tokenizer.model_max_length , 42 )
# Now let's start the test
snake_case: str = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
# Isolate this from the other tests because we save additional tokens/etc
snake_case: List[str] = tempfile.mkdtemp()
snake_case: Union[str, Any] = ' He is very happy, UNwant\u00E9d,running'
snake_case: Dict = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ )
snake_case: str = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ )
snake_case: Dict = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
shutil.rmtree(SCREAMING_SNAKE_CASE__ )
snake_case: Any = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
# Isolate this from the other tests because we save additional tokens/etc
snake_case: int = tempfile.mkdtemp()
snake_case: Tuple = ' He is very happy, UNwant\u00E9d,running'
snake_case: str = tokenizer.additional_special_tokens
# We can add a new special token for Canine as follows:
snake_case: Optional[int] = chr(0xe_007 )
additional_special_tokens.append(SCREAMING_SNAKE_CASE__ )
tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} )
snake_case: Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ )
snake_case: Optional[Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ )
snake_case: Optional[int] = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
self.assertIn(SCREAMING_SNAKE_CASE__ , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 42 )
snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 )
self.assertEqual(tokenizer.model_max_length , 43 )
shutil.rmtree(SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: List[Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
snake_case , snake_case: Any = self.get_clean_sequence(SCREAMING_SNAKE_CASE__ )
# a special token for Canine can be defined as follows:
snake_case: Optional[int] = 0xe_005
snake_case: List[str] = chr(SCREAMING_SNAKE_CASE__ )
tokenizer.add_special_tokens({'cls_token': special_token} )
snake_case: Dict = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 )
snake_case: List[Any] = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ )
snake_case: str = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
snake_case: Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertEqual(SCREAMING_SNAKE_CASE__ , input_encoded + special_token_id )
snake_case: Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
self.assertTrue(special_token not in decoded )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Union[str, Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
snake_case: Union[str, Any] = chr(0xe_005 )
snake_case: Optional[int] = chr(0xe_006 )
# `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py)
tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=SCREAMING_SNAKE_CASE__ )
# `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`,
# which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py)
tokenizer.add_special_tokens({'additional_special_tokens': [SPECIAL_TOKEN_2]} )
snake_case: Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ )
snake_case: str = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ )
self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 )
self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 )
self.assertEqual(token_a[0] , SCREAMING_SNAKE_CASE__ )
self.assertEqual(token_a[0] , SCREAMING_SNAKE_CASE__ )
@require_tokenizers
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Any = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
# a special token for Canine can be defined as follows:
snake_case: Union[str, Any] = 0xe_006
snake_case: Tuple = chr(SCREAMING_SNAKE_CASE__ )
snake_case: List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ )
tokenizer.add_special_tokens({'additional_special_tokens': [new_token]} )
with tempfile.TemporaryDirectory() as tmp_dir_name:
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ )
tokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: int = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ )
with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file:
snake_case: int = json.load(SCREAMING_SNAKE_CASE__ )
with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file:
snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ )
# a special token for Canine can be defined as follows:
snake_case: Union[str, Any] = 0xe_006
snake_case: int = chr(SCREAMING_SNAKE_CASE__ )
snake_case: Dict = [new_token_a]
snake_case: Dict = [new_token_a]
with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile:
json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile:
json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
snake_case: Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , extra_ids=0 )
self.assertIn(SCREAMING_SNAKE_CASE__ , tokenizer_without_change_in_init.additional_special_tokens )
# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
[new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , )
snake_case: Optional[Any] = 0xe_007
snake_case: Dict = chr(SCREAMING_SNAKE_CASE__ )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
snake_case: int = [AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ )]
snake_case: str = tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , extra_ids=0 )
self.assertIn(SCREAMING_SNAKE_CASE__ , tokenizer.additional_special_tokens )
# self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
[new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) )
@require_tokenizers
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Optional[Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
snake_case: List[Any] = 'hello world'
if self.space_between_special_tokens:
snake_case: List[str] = '[CLS] hello world [SEP]'
else:
snake_case: Dict = input
snake_case: Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ )
snake_case: Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ , spaces_between_special_tokens=self.space_between_special_tokens )
self.assertIn(SCREAMING_SNAKE_CASE__ , [output, output.lower()] )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: List[str] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
snake_case: str = [
'bos_token',
'eos_token',
'unk_token',
'sep_token',
'pad_token',
'cls_token',
'mask_token',
]
snake_case: Optional[Any] = 'a'
snake_case: List[str] = ord(SCREAMING_SNAKE_CASE__ )
for attr in attributes_list:
setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ )
setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ )
setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] )
snake_case: List[Any] = 0xe_006
snake_case: List[Any] = chr(SCREAMING_SNAKE_CASE__ )
setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [additional_special_token_id] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [additional_special_token] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [additional_special_token_id] )
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
pass | 692 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = "▁"
__UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"}
__UpperCAmelCase = {
"vocab_file": {
"facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
}
}
__UpperCAmelCase = {
"facebook/xglm-564M": 2_048,
}
class SCREAMING_SNAKE_CASE ( snake_case ):
'''simple docstring'''
__UpperCamelCase = VOCAB_FILES_NAMES
__UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP
__UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__UpperCamelCase = ["input_ids", "attention_mask"]
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ):
'''simple docstring'''
snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
# Compatibility with the original tokenizer
snake_case: Optional[Any] = 7
snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )]
snake_case: str = kwargs.get('additional_special_tokens' , [] )
kwargs["additional_special_tokens"] += [
word for word in madeup_words if word not in kwargs["additional_special_tokens"]
]
super().__init__(
bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , )
snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) )
snake_case: int = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
snake_case: Tuple = 1
# Mimic fairseq token-to-id alignment for the first 4 token
snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}
snake_case: Union[str, Any] = len(self.sp_model )
snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )}
self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ )
snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def __getstate__( self ):
'''simple docstring'''
snake_case: List[Any] = self.__dict__.copy()
snake_case: Union[str, Any] = None
snake_case: Union[str, Any] = self.sp_model.serialized_model_proto()
return state
def __setstate__( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Optional[int] = d
# for backward compatibility
if not hasattr(self , 'sp_model_kwargs' ):
snake_case: Union[str, Any] = {}
snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ):
'''simple docstring'''
if token_ids_a is None:
return [self.sep_token_id] + token_ids_a
snake_case: Optional[Any] = [self.sep_token_id]
return sep + token_ids_a + sep + sep + token_ids_a
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ )
if token_ids_a is None:
return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ ))
return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ ))
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ):
'''simple docstring'''
snake_case: int = [self.sep_token_id]
if token_ids_a is None:
return len(sep + token_ids_a ) * [0]
return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0]
@property
def _UpperCamelCase ( self ):
'''simple docstring'''
return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
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 _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip()
return out_string
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ):
'''simple docstring'''
if not os.path.isdir(SCREAMING_SNAKE_CASE__ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
snake_case: List[str] = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ )
elif not os.path.isfile(self.vocab_file ):
with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi:
snake_case: int = self.sp_model.serialized_model_proto()
fi.write(SCREAMING_SNAKE_CASE__ )
return (out_vocab_file,) | 692 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
lowerCamelCase_ : Any = {
"""configuration_distilbert""": [
"""DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""DistilBertConfig""",
"""DistilBertOnnxConfig""",
],
"""tokenization_distilbert""": ["""DistilBertTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase_ : Optional[int] = ["""DistilBertTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase_ : int = [
"""DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DistilBertForMaskedLM""",
"""DistilBertForMultipleChoice""",
"""DistilBertForQuestionAnswering""",
"""DistilBertForSequenceClassification""",
"""DistilBertForTokenClassification""",
"""DistilBertModel""",
"""DistilBertPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase_ : Any = [
"""TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFDistilBertForMaskedLM""",
"""TFDistilBertForMultipleChoice""",
"""TFDistilBertForQuestionAnswering""",
"""TFDistilBertForSequenceClassification""",
"""TFDistilBertForTokenClassification""",
"""TFDistilBertMainLayer""",
"""TFDistilBertModel""",
"""TFDistilBertPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase_ : List[Any] = [
"""FlaxDistilBertForMaskedLM""",
"""FlaxDistilBertForMultipleChoice""",
"""FlaxDistilBertForQuestionAnswering""",
"""FlaxDistilBertForSequenceClassification""",
"""FlaxDistilBertForTokenClassification""",
"""FlaxDistilBertModel""",
"""FlaxDistilBertPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_distilbert import (
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
DistilBertConfig,
DistilBertOnnxConfig,
)
from .tokenization_distilbert import DistilBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_distilbert_fast import DistilBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_distilbert import (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
DistilBertModel,
DistilBertPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_distilbert import (
TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDistilBertForMaskedLM,
TFDistilBertForMultipleChoice,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertMainLayer,
TFDistilBertModel,
TFDistilBertPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_distilbert import (
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertModel,
FlaxDistilBertPreTrainedModel,
)
else:
import sys
lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 559 | import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
lowerCamelCase_ : List[Any] = pd.read_csv("""sample_data.csv""", header=None)
lowerCamelCase_ : Optional[Any] = df.shape[:1][0]
# If you're using some other dataset input the target column
lowerCamelCase_ : Union[str, Any] = df.iloc[:, 1:2]
lowerCamelCase_ : str = actual_data.values.reshape(len_data, 1)
lowerCamelCase_ : List[Any] = MinMaxScaler().fit_transform(actual_data)
lowerCamelCase_ : List[str] = 10
lowerCamelCase_ : Tuple = 5
lowerCamelCase_ : Optional[Any] = 20
lowerCamelCase_ : List[Any] = len_data - periods * look_back
lowerCamelCase_ : Union[str, Any] = actual_data[:division]
lowerCamelCase_ : Dict = actual_data[division - look_back :]
lowerCamelCase_ , lowerCamelCase_ : int = [], []
lowerCamelCase_ , lowerCamelCase_ : List[Any] = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
lowerCamelCase_ : Dict = np.array(train_x)
lowerCamelCase_ : Union[str, Any] = np.array(test_x)
lowerCamelCase_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y])
lowerCamelCase_ : Any = np.array([list(i.ravel()) for i in test_y])
lowerCamelCase_ : int = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss="""mean_squared_error""", optimizer="""adam""")
lowerCamelCase_ : Optional[int] = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
lowerCamelCase_ : int = model.predict(x_test)
| 559 | 1 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool
class A__ ( _a ):
UpperCAmelCase = "facebook/bart-large-mnli"
UpperCAmelCase = (
"This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which "
"should be the text to classify, and `labels`, which should be the list of labels to use for classification. "
"It returns the most likely label in the list of provided `labels` for the input text."
)
UpperCAmelCase = "text_classifier"
UpperCAmelCase = AutoTokenizer
UpperCAmelCase = AutoModelForSequenceClassification
UpperCAmelCase = ["text", ["text"]]
UpperCAmelCase = ["text"]
def __UpperCamelCase ( self : Union[str, Any] ) -> Dict:
"""simple docstring"""
super().setup()
_SCREAMING_SNAKE_CASE =self.model.config
_SCREAMING_SNAKE_CASE =-1
for idx, label in config.idalabel.items():
if label.lower().startswith('''entail''' ):
_SCREAMING_SNAKE_CASE =int(_A )
if self.entailment_id == -1:
raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' )
def __UpperCamelCase ( self : Dict , _a : Optional[Any] , _a : Dict ) -> List[str]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =labels
return self.pre_processor(
[text] * len(_A ) , [f"This example is {label}" for label in labels] , return_tensors='''pt''' , padding='''max_length''' , )
def __UpperCamelCase ( self : str , _a : Any ) -> Tuple:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =outputs.logits
_SCREAMING_SNAKE_CASE =torch.argmax(logits[:, 2] ).item()
return self._labels[label_id] | 714 |
snake_case_ : dict[tuple[int, int, int], int] = {}
def lowerCamelCase( a__ ,a__ ,a__):
# if we are absent twice, or late 3 consecutive days,
# no further prize strings are possible
if late == 3 or absent == 2:
return 0
# if we have no days left, and have not failed any other rules,
# we have a prize string
if days == 0:
return 1
# No easy solution, so now we need to do the recursive calculation
# First, check if the combination is already in the cache, and
# if yes, return the stored value from there since we already
# know the number of possible prize strings from this point on
_SCREAMING_SNAKE_CASE =(days, absent, late)
if key in cache:
return cache[key]
# now we calculate the three possible ways that can unfold from
# this point on, depending on our attendance today
# 1) if we are late (but not absent), the "absent" counter stays as
# it is, but the "late" counter increases by one
_SCREAMING_SNAKE_CASE =_calculate(days - 1 ,a__ ,late + 1)
# 2) if we are absent, the "absent" counter increases by 1, and the
# "late" counter resets to 0
_SCREAMING_SNAKE_CASE =_calculate(days - 1 ,absent + 1 ,0)
# 3) if we are on time, this resets the "late" counter and keeps the
# absent counter
_SCREAMING_SNAKE_CASE =_calculate(days - 1 ,a__ ,0)
_SCREAMING_SNAKE_CASE =state_late + state_absent + state_ontime
_SCREAMING_SNAKE_CASE =prizestrings
return prizestrings
def lowerCamelCase( a__ = 30):
return _calculate(a__ ,absent=0 ,late=0)
if __name__ == "__main__":
print(solution()) | 191 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_lowercase = {
"""configuration_rembert""": ["""REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RemBertConfig""", """RemBertOnnxConfig"""]
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ["""RemBertTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ["""RemBertTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
"""REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""RemBertForCausalLM""",
"""RemBertForMaskedLM""",
"""RemBertForMultipleChoice""",
"""RemBertForQuestionAnswering""",
"""RemBertForSequenceClassification""",
"""RemBertForTokenClassification""",
"""RemBertLayer""",
"""RemBertModel""",
"""RemBertPreTrainedModel""",
"""load_tf_weights_in_rembert""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
"""TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFRemBertForCausalLM""",
"""TFRemBertForMaskedLM""",
"""TFRemBertForMultipleChoice""",
"""TFRemBertForQuestionAnswering""",
"""TFRemBertForSequenceClassification""",
"""TFRemBertForTokenClassification""",
"""TFRemBertLayer""",
"""TFRemBertModel""",
"""TFRemBertPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert import RemBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert_fast import RemBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_rembert import (
REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RemBertForCausalLM,
RemBertForMaskedLM,
RemBertForMultipleChoice,
RemBertForQuestionAnswering,
RemBertForSequenceClassification,
RemBertForTokenClassification,
RemBertLayer,
RemBertModel,
RemBertPreTrainedModel,
load_tf_weights_in_rembert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_rembert import (
TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRemBertForCausalLM,
TFRemBertForMaskedLM,
TFRemBertForMultipleChoice,
TFRemBertForQuestionAnswering,
TFRemBertForSequenceClassification,
TFRemBertForTokenClassification,
TFRemBertLayer,
TFRemBertModel,
TFRemBertPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 443 | import unittest
from transformers import (
MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TextGenerationPipeline,
logging,
pipeline,
)
from transformers.testing_utils import (
CaptureLogger,
is_pipeline_test,
require_accelerate,
require_tf,
require_torch,
require_torch_gpu,
require_torch_or_tf,
)
from .test_pipelines_common import ANY
@is_pipeline_test
@require_torch_or_tf
class lowerCAmelCase_ ( unittest.TestCase ):
UpperCAmelCase = MODEL_FOR_CAUSAL_LM_MAPPING
UpperCAmelCase = TF_MODEL_FOR_CAUSAL_LM_MAPPING
@require_torch
def UpperCamelCase_ ( self : str ):
_UpperCamelCase = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' )
# Using `do_sample=False` to force deterministic output
_UpperCamelCase = text_generator('''This is a test''' , do_sample=_A )
self.assertEqual(
_A , [
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
] , )
_UpperCamelCase = text_generator(['''This is a test''', '''This is a second test'''] )
self.assertEqual(
_A , [
[
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy'''
''' oscope. oscope. FiliFili@@'''
)
}
],
] , )
_UpperCamelCase = text_generator('''This is a test''' , do_sample=_A , num_return_sequences=2 , return_tensors=_A )
self.assertEqual(
_A , [
{'''generated_token_ids''': ANY(_A )},
{'''generated_token_ids''': ANY(_A )},
] , )
_UpperCamelCase = text_generator.model.config.eos_token_id
_UpperCamelCase = '''<pad>'''
_UpperCamelCase = text_generator(
['''This is a test''', '''This is a second test'''] , do_sample=_A , num_return_sequences=2 , batch_size=2 , return_tensors=_A , )
self.assertEqual(
_A , [
[
{'''generated_token_ids''': ANY(_A )},
{'''generated_token_ids''': ANY(_A )},
],
[
{'''generated_token_ids''': ANY(_A )},
{'''generated_token_ids''': ANY(_A )},
],
] , )
@require_tf
def UpperCamelCase_ ( self : Dict ):
_UpperCamelCase = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' )
# Using `do_sample=False` to force deterministic output
_UpperCamelCase = text_generator('''This is a test''' , do_sample=_A )
self.assertEqual(
_A , [
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
] , )
_UpperCamelCase = text_generator(['''This is a test''', '''This is a second test'''] , do_sample=_A )
self.assertEqual(
_A , [
[
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes'''
''' Cannes 閲閲Cannes Cannes Cannes 攵 please,'''
)
}
],
] , )
def UpperCamelCase_ ( self : int , _A : str , _A : Union[str, Any] , _A : Any ):
_UpperCamelCase = TextGenerationPipeline(model=_A , tokenizer=_A )
return text_generator, ["This is a test", "Another test"]
def UpperCamelCase_ ( self : Union[str, Any] ):
_UpperCamelCase = '''Hello I believe in'''
_UpperCamelCase = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
_UpperCamelCase = text_generator(_A )
self.assertEqual(
_A , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , )
_UpperCamelCase = text_generator(_A , stop_sequence=''' fe''' )
self.assertEqual(_A , [{'''generated_text''': '''Hello I believe in fe'''}] )
def UpperCamelCase_ ( self : Any , _A : List[Any] , _A : Union[str, Any] ):
_UpperCamelCase = text_generator.model
_UpperCamelCase = text_generator.tokenizer
_UpperCamelCase = text_generator('''This is a test''' )
self.assertEqual(_A , [{'''generated_text''': ANY(_A )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
_UpperCamelCase = text_generator('''This is a test''' , return_full_text=_A )
self.assertEqual(_A , [{'''generated_text''': ANY(_A )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
_UpperCamelCase = pipeline(task='''text-generation''' , model=_A , tokenizer=_A , return_full_text=_A )
_UpperCamelCase = text_generator('''This is a test''' )
self.assertEqual(_A , [{'''generated_text''': ANY(_A )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
_UpperCamelCase = text_generator('''This is a test''' , return_full_text=_A )
self.assertEqual(_A , [{'''generated_text''': ANY(_A )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
_UpperCamelCase = text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=_A )
self.assertEqual(
_A , [
[{'''generated_text''': ANY(_A )}, {'''generated_text''': ANY(_A )}],
[{'''generated_text''': ANY(_A )}, {'''generated_text''': ANY(_A )}],
] , )
if text_generator.tokenizer.pad_token is not None:
_UpperCamelCase = text_generator(
['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=_A )
self.assertEqual(
_A , [
[{'''generated_text''': ANY(_A )}, {'''generated_text''': ANY(_A )}],
[{'''generated_text''': ANY(_A )}, {'''generated_text''': ANY(_A )}],
] , )
with self.assertRaises(_A ):
_UpperCamelCase = text_generator('''test''' , return_full_text=_A , return_text=_A )
with self.assertRaises(_A ):
_UpperCamelCase = text_generator('''test''' , return_full_text=_A , return_tensors=_A )
with self.assertRaises(_A ):
_UpperCamelCase = text_generator('''test''' , return_text=_A , return_tensors=_A )
# Empty prompt is slighly special
# it requires BOS token to exist.
# Special case for Pegasus which will always append EOS so will
# work even without BOS.
if (
text_generator.tokenizer.bos_token_id is not None
or "Pegasus" in tokenizer.__class__.__name__
or "Git" in model.__class__.__name__
):
_UpperCamelCase = text_generator('''''' )
self.assertEqual(_A , [{'''generated_text''': ANY(_A )}] )
else:
with self.assertRaises((ValueError, AssertionError) ):
_UpperCamelCase = text_generator('''''' )
if text_generator.framework == "tf":
# TF generation does not support max_new_tokens, and it's impossible
# to control long generation with only max_length without
# fancy calculation, dismissing tests for now.
return
# We don't care about infinite range models.
# They already work.
# Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
_UpperCamelCase = ['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM''']
if (
tokenizer.model_max_length < 1_0000
and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
):
# Handling of large generations
with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ):
text_generator('''This is a test''' * 500 , max_new_tokens=20 )
_UpperCamelCase = text_generator('''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=20 )
# Hole strategy cannot work
with self.assertRaises(_A ):
text_generator(
'''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 10 , )
@require_torch
@require_accelerate
@require_torch_gpu
def UpperCamelCase_ ( self : Optional[int] ):
import torch
# Classic `model_kwargs`
_UpperCamelCase = pipeline(
model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
_UpperCamelCase = pipe('''This is a test''' )
self.assertEqual(
_A , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
_UpperCamelCase = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
_UpperCamelCase = pipe('''This is a test''' )
self.assertEqual(
_A , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
_UpperCamelCase = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa )
_UpperCamelCase = pipe('''This is a test''' )
self.assertEqual(
_A , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
@require_torch
@require_torch_gpu
def UpperCamelCase_ ( self : Union[str, Any] ):
import torch
_UpperCamelCase = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa )
pipe('''This is a test''' )
@require_torch
@require_accelerate
@require_torch_gpu
def UpperCamelCase_ ( self : Optional[int] ):
import torch
_UpperCamelCase = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa )
pipe('''This is a test''' , do_sample=_A , top_p=0.5 )
def UpperCamelCase_ ( self : Tuple ):
_UpperCamelCase = '''Hello world'''
_UpperCamelCase = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
if text_generator.model.framework == "tf":
_UpperCamelCase = logging.get_logger('''transformers.generation.tf_utils''' )
else:
_UpperCamelCase = logging.get_logger('''transformers.generation.utils''' )
_UpperCamelCase = '''Both `max_new_tokens`''' # The beggining of the message to be checked in this test
# Both are set by the user -> log warning
with CaptureLogger(_A ) as cl:
_UpperCamelCase = text_generator(_A , max_length=10 , max_new_tokens=1 )
self.assertIn(_A , cl.out )
# The user only sets one -> no warning
with CaptureLogger(_A ) as cl:
_UpperCamelCase = text_generator(_A , max_new_tokens=1 )
self.assertNotIn(_A , cl.out )
with CaptureLogger(_A ) as cl:
_UpperCamelCase = text_generator(_A , max_length=10 )
self.assertNotIn(_A , cl.out )
| 10 | 0 |
'''simple docstring'''
import re
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
class lowercase__ ( snake_case_ ):
'''simple docstring'''
_snake_case = ['''image_processor''', '''tokenizer''']
_snake_case = '''AutoImageProcessor'''
_snake_case = '''AutoTokenizer'''
def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , **lowerCamelCase__ ):
'''simple docstring'''
UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , lowerCamelCase__ , )
UpperCamelCase = kwargs.pop('''feature_extractor''' )
UpperCamelCase = 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__(lowerCamelCase__ , lowerCamelCase__ )
UpperCamelCase = self.image_processor
UpperCamelCase = False
def __call__( self , *lowerCamelCase__ , **lowerCamelCase__ ):
'''simple docstring'''
if self._in_target_context_manager:
return self.current_processor(*lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = kwargs.pop('''images''' , lowerCamelCase__ )
UpperCamelCase = kwargs.pop('''text''' , lowerCamelCase__ )
if len(lowerCamelCase__ ) > 0:
UpperCamelCase = args[0]
UpperCamelCase = args[1:]
if images is None and text is None:
raise ValueError('''You need to specify either an `images` or `text` input to process.''' )
if images is not None:
UpperCamelCase = self.image_processor(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ )
if text is not None:
UpperCamelCase = self.tokenizer(lowerCamelCase__ , **lowerCamelCase__ )
if text is None:
return inputs
elif images is None:
return encodings
else:
UpperCamelCase = encodings['''input_ids''']
return inputs
def UpperCAmelCase ( self , *lowerCamelCase__ , **lowerCamelCase__ ):
'''simple docstring'''
return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ )
def UpperCAmelCase ( self , *lowerCamelCase__ , **lowerCamelCase__ ):
'''simple docstring'''
return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ )
@contextmanager
def UpperCAmelCase ( self ):
'''simple docstring'''
warnings.warn(
'''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
'''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
'''your images inputs, or in a separate call.''' )
UpperCamelCase = True
UpperCamelCase = self.tokenizer
yield
UpperCamelCase = self.image_processor
UpperCamelCase = False
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=False , lowerCamelCase__=None ):
'''simple docstring'''
if added_vocab is None:
UpperCamelCase = self.tokenizer.get_added_vocab()
UpperCamelCase = {}
while tokens:
UpperCamelCase = re.search(R'''<s_(.*?)>''' , lowerCamelCase__ , re.IGNORECASE )
if start_token is None:
break
UpperCamelCase = start_token.group(1 )
UpperCamelCase = re.search(Rf'</s_{key}>' , lowerCamelCase__ , re.IGNORECASE )
UpperCamelCase = start_token.group()
if end_token is None:
UpperCamelCase = tokens.replace(lowerCamelCase__ , '''''' )
else:
UpperCamelCase = end_token.group()
UpperCamelCase = re.escape(lowerCamelCase__ )
UpperCamelCase = re.escape(lowerCamelCase__ )
UpperCamelCase = re.search(f'{start_token_escaped}(.*?){end_token_escaped}' , lowerCamelCase__ , re.IGNORECASE )
if content is not None:
UpperCamelCase = content.group(1 ).strip()
if r"<s_" in content and r"</s_" in content: # non-leaf node
UpperCamelCase = self.tokenajson(lowerCamelCase__ , is_inner_value=lowerCamelCase__ , added_vocab=lowerCamelCase__ )
if value:
if len(lowerCamelCase__ ) == 1:
UpperCamelCase = value[0]
UpperCamelCase = value
else: # leaf nodes
UpperCamelCase = []
for leaf in content.split(R'''<sep/>''' ):
UpperCamelCase = leaf.strip()
if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
UpperCamelCase = leaf[1:-2] # for categorical special tokens
output[key].append(lowerCamelCase__ )
if len(output[key] ) == 1:
UpperCamelCase = output[key][0]
UpperCamelCase = tokens[tokens.find(lowerCamelCase__ ) + len(lowerCamelCase__ ) :].strip()
if tokens[:6] == r"<sep/>": # non-leaf nodes
return [output] + self.tokenajson(tokens[6:] , is_inner_value=lowerCamelCase__ , added_vocab=lowerCamelCase__ )
if len(lowerCamelCase__ ):
return [output] if is_inner_value else output
else:
return [] if is_inner_value else {"text_sequence": tokens}
@property
def UpperCAmelCase ( self ):
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowerCamelCase__ , )
return self.image_processor_class
@property
def UpperCAmelCase ( self ):
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowerCamelCase__ , )
return self.image_processor
| 720 |
'''simple docstring'''
import os
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_pegasus import PegasusTokenizer
else:
snake_case_ : Dict = None
snake_case_ : int = logging.get_logger(__name__)
snake_case_ : int = '▁'
snake_case_ : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}
snake_case_ : List[Any] = {
'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'},
'tokenizer_file': {
'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json'
},
}
snake_case_ : Tuple = {
'google/pegasus-xsum': 512,
}
class lowercase__ ( snake_case_ ):
'''simple docstring'''
_snake_case = VOCAB_FILES_NAMES
_snake_case = PRETRAINED_VOCAB_FILES_MAP
_snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_snake_case = PegasusTokenizer
_snake_case = ['''input_ids''', '''attention_mask''']
def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__="<pad>" , lowerCamelCase__="</s>" , lowerCamelCase__="<unk>" , lowerCamelCase__="<mask_2>" , lowerCamelCase__="<mask_1>" , lowerCamelCase__=None , lowerCamelCase__=1_0_3 , **lowerCamelCase__ , ):
'''simple docstring'''
UpperCamelCase = offset
if additional_special_tokens is not None:
if not isinstance(lowerCamelCase__ , lowerCamelCase__ ):
raise TypeError(
f'additional_special_tokens should be of type {type(lowerCamelCase__ )}, but is'
f' {type(lowerCamelCase__ )}' )
UpperCamelCase = (
([mask_token_sent] + additional_special_tokens)
if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
else additional_special_tokens
)
# fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
additional_special_tokens_extended += [
f'<unk_{i}>' for i in range(len(lowerCamelCase__ ) , self.offset - 1 )
]
if len(set(lowerCamelCase__ ) ) != len(lowerCamelCase__ ):
raise ValueError(
'''Please make sure that the provided additional_special_tokens do not contain an incorrectly'''
f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' )
UpperCamelCase = additional_special_tokens_extended
else:
UpperCamelCase = [mask_token_sent] if mask_token_sent is not None else []
additional_special_tokens += [f'<unk_{i}>' for i in range(2 , self.offset )]
super().__init__(
lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , pad_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , mask_token_sent=lowerCamelCase__ , offset=lowerCamelCase__ , additional_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , )
UpperCamelCase = vocab_file
UpperCamelCase = False if not self.vocab_file else True
def UpperCAmelCase ( self , lowerCamelCase__ ):
'''simple docstring'''
UpperCamelCase = set(self.all_special_ids ) # call it once instead of inside list comp
all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special
if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ):
raise ValueError(
'''There should be 3 special tokens: mask_token, pad_token, and eos_token +'''
f' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}' )
return [1 if x in all_special_ids else 0 for x in seq]
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False ):
'''simple docstring'''
if already_has_special_tokens:
return self._special_token_mask(lowerCamelCase__ )
elif token_ids_a is None:
return self._special_token_mask(lowerCamelCase__ ) + [1]
else:
return self._special_token_mask(token_ids_a + token_ids_a ) + [1]
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=None ):
'''simple docstring'''
if token_ids_a is None:
return token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return token_ids_a + token_ids_a + [self.eos_token_id]
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None ):
'''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(lowerCamelCase__ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
UpperCamelCase = os.path.join(
lowerCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase__ ):
copyfile(self.vocab_file , lowerCamelCase__ )
return (out_vocab_file,)
| 350 | 0 |
"""simple docstring"""
from typing import List, Optional, Union
import torch
from transformers import (
XLMRobertaTokenizer,
)
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
from .text_encoder import MultilingualCLIP
SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) # pylint: disable=invalid-name
SCREAMING_SNAKE_CASE : Tuple = '''
Examples:
```py
>>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline
>>> import torch
>>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")
>>> pipe_prior.to("cuda")
>>> prompt = "red cat, 4k photo"
>>> out = pipe_prior(prompt)
>>> image_emb = out.image_embeds
>>> negative_image_emb = out.negative_image_embeds
>>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")
>>> pipe.to("cuda")
>>> image = pipe(
... prompt,
... image_embeds=image_emb,
... negative_image_embeds=negative_image_emb,
... height=768,
... width=768,
... num_inference_steps=100,
... ).images
>>> image[0].save("cat.png")
```
'''
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=8 ):
A__ = h // scale_factor**2
if h % scale_factor**2 != 0:
new_h += 1
A__ = w // scale_factor**2
if w % scale_factor**2 != 0:
new_w += 1
return new_h * scale_factor, new_w * scale_factor
class snake_case_ ( _lowerCamelCase ):
"""simple docstring"""
def __init__( self , __a , __a , __a , __a , __a , ):
"""simple docstring"""
super().__init__()
self.register_modules(
text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , movq=__a , )
A__ = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def _UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a ):
"""simple docstring"""
if latents is None:
A__ = randn_tensor(__a , generator=__a , device=__a , dtype=__a )
else:
if latents.shape != shape:
raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' )
A__ = latents.to(__a )
A__ = latents * scheduler.init_noise_sigma
return latents
def _UpperCAmelCase ( self , __a , __a , __a , __a , __a=None , ):
"""simple docstring"""
A__ = len(__a ) if isinstance(__a , __a ) else 1
# get prompt text embeddings
A__ = self.tokenizer(
__a , padding='max_length' , truncation=__a , max_length=77 , return_attention_mask=__a , add_special_tokens=__a , return_tensors='pt' , )
A__ = text_inputs.input_ids
A__ = self.tokenizer(__a , padding='longest' , return_tensors='pt' ).input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__a , __a ):
A__ = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] )
logger.warning(
'The following part of your input was truncated because CLIP can only handle sequences up to'
f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
A__ = text_input_ids.to(__a )
A__ = text_inputs.attention_mask.to(__a )
A__ , A__ = self.text_encoder(
input_ids=__a , attention_mask=__a )
A__ = prompt_embeds.repeat_interleave(__a , dim=0 )
A__ = text_encoder_hidden_states.repeat_interleave(__a , dim=0 )
A__ = text_mask.repeat_interleave(__a , dim=0 )
if do_classifier_free_guidance:
A__ = 42
if negative_prompt is None:
A__ = [''] * batch_size
elif type(__a ) is not type(__a ):
raise TypeError(
f'''`negative_prompt` should be the same type to `prompt`, but got {type(__a )} !='''
f''' {type(__a )}.''' )
elif isinstance(__a , __a ):
A__ = [negative_prompt]
elif batch_size != len(__a ):
raise ValueError(
f'''`negative_prompt`: {negative_prompt} has batch size {len(__a )}, but `prompt`:'''
f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
' the batch size of `prompt`.' )
else:
A__ = negative_prompt
A__ = self.tokenizer(
__a , padding='max_length' , max_length=77 , truncation=__a , return_attention_mask=__a , add_special_tokens=__a , return_tensors='pt' , )
A__ = uncond_input.input_ids.to(__a )
A__ = uncond_input.attention_mask.to(__a )
A__ , A__ = self.text_encoder(
input_ids=__a , attention_mask=__a )
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
A__ = negative_prompt_embeds.shape[1]
A__ = negative_prompt_embeds.repeat(1 , __a )
A__ = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __a )
A__ = uncond_text_encoder_hidden_states.shape[1]
A__ = uncond_text_encoder_hidden_states.repeat(1 , __a , 1 )
A__ = uncond_text_encoder_hidden_states.view(
batch_size * num_images_per_prompt , __a , -1 )
A__ = uncond_text_mask.repeat_interleave(__a , dim=0 )
# done duplicates
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
A__ = torch.cat([negative_prompt_embeds, prompt_embeds] )
A__ = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] )
A__ = torch.cat([uncond_text_mask, text_mask] )
return prompt_embeds, text_encoder_hidden_states, text_mask
def _UpperCAmelCase ( self , __a=0 ):
"""simple docstring"""
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError('Please install accelerate via `pip install accelerate`' )
A__ = torch.device(f'''cuda:{gpu_id}''' )
A__ = [
self.unet,
self.text_encoder,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(__a , __a )
def _UpperCAmelCase ( self , __a=0 ):
"""simple docstring"""
if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ):
from accelerate import cpu_offload_with_hook
else:
raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' )
A__ = torch.device(f'''cuda:{gpu_id}''' )
if self.device.type != "cpu":
self.to('cpu' , silence_dtype_warnings=__a )
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
A__ = None
for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
A__ , A__ = cpu_offload_with_hook(__a , __a , prev_module_hook=__a )
if self.safety_checker is not None:
A__ , A__ = cpu_offload_with_hook(self.safety_checker , __a , prev_module_hook=__a )
# We'll offload the last model manually.
A__ = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def _UpperCAmelCase ( self ):
"""simple docstring"""
if not hasattr(self.unet , '_hf_hook' ):
return self.device
for module in self.unet.modules():
if (
hasattr(__a , '_hf_hook' )
and hasattr(module._hf_hook , 'execution_device' )
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device )
return self.device
@torch.no_grad()
@replace_example_docstring(__a )
def __call__( self , __a , __a , __a , __a = None , __a = 512 , __a = 512 , __a = 100 , __a = 4.0 , __a = 1 , __a = None , __a = None , __a = "pil" , __a = True , ):
"""simple docstring"""
if isinstance(__a , __a ):
A__ = 1
elif isinstance(__a , __a ):
A__ = len(__a )
else:
raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(__a )}''' )
A__ = self._execution_device
A__ = batch_size * num_images_per_prompt
A__ = guidance_scale > 1.0
A__ , A__ , A__ = self._encode_prompt(
__a , __a , __a , __a , __a )
if isinstance(__a , __a ):
A__ = torch.cat(__a , dim=0 )
if isinstance(__a , __a ):
A__ = torch.cat(__a , dim=0 )
if do_classifier_free_guidance:
A__ = image_embeds.repeat_interleave(__a , dim=0 )
A__ = negative_image_embeds.repeat_interleave(__a , dim=0 )
A__ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(
dtype=prompt_embeds.dtype , device=__a )
self.scheduler.set_timesteps(__a , device=__a )
A__ = self.scheduler.timesteps
A__ = self.unet.config.in_channels
A__ , A__ = get_new_h_w(__a , __a , self.movq_scale_factor )
# create initial latent
A__ = self.prepare_latents(
(batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , __a , __a , __a , self.scheduler , )
for i, t in enumerate(self.progress_bar(__a ) ):
# expand the latents if we are doing classifier free guidance
A__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
A__ = {'text_embeds': prompt_embeds, 'image_embeds': image_embeds}
A__ = self.unet(
sample=__a , timestep=__a , encoder_hidden_states=__a , added_cond_kwargs=__a , return_dict=__a , )[0]
if do_classifier_free_guidance:
A__ , A__ = noise_pred.split(latents.shape[1] , dim=1 )
A__ , A__ = noise_pred.chunk(2 )
A__ , A__ = variance_pred.chunk(2 )
A__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
A__ = torch.cat([noise_pred, variance_pred_text] , dim=1 )
if not (
hasattr(self.scheduler.config , 'variance_type' )
and self.scheduler.config.variance_type in ["learned", "learned_range"]
):
A__ , A__ = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
A__ = self.scheduler.step(
__a , __a , __a , generator=__a , ).prev_sample
# post-processing
A__ = self.movq.decode(__a , force_not_quantize=__a )['sample']
if output_type not in ["pt", "np", "pil"]:
raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' )
if output_type in ["np", "pil"]:
A__ = image * 0.5 + 0.5
A__ = image.clamp(0 , 1 )
A__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
A__ = self.numpy_to_pil(__a )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=__a )
| 260 |
"""simple docstring"""
def __lowerCamelCase ( lowerCAmelCase__ ):
A__ = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
A__ = set()
return any(
node not in visited and depth_first_search(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
for node in graph )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ):
visited.add(lowerCAmelCase__ )
rec_stk.add(lowerCAmelCase__ )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(lowerCAmelCase__ )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 260 | 1 |
import unittest
from huggingface_hub import hf_hub_download
from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_decord,
require_tf,
require_torch,
require_torch_or_tf,
require_vision,
)
from .test_pipelines_common import ANY
@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class _UpperCAmelCase ( unittest.TestCase ):
a = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
def _lowerCamelCase ( self , a__ , a__ , a__ ):
A_ : Union[str, Any] = hf_hub_download(
repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" )
A_ : List[str] = VideoClassificationPipeline(model=a__ , image_processor=a__ , top_k=2 )
A_ : int = [
example_video_filepath,
"""https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""",
]
return video_classifier, examples
def _lowerCamelCase ( self , a__ , a__ ):
for example in examples:
A_ : Optional[int] = video_classifier(a__ )
self.assertEqual(
a__ , [
{"""score""": ANY(a__ ), """label""": ANY(a__ )},
{"""score""": ANY(a__ ), """label""": ANY(a__ )},
] , )
@require_torch
def _lowerCamelCase ( self ):
A_ : Tuple = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification"""
A_ : Optional[Any] = VideoMAEFeatureExtractor(
size={"""shortest_edge""": 10} , crop_size={"""height""": 10, """width""": 10} )
A_ : int = pipeline(
"""video-classification""" , model=a__ , feature_extractor=a__ , frame_sampling_rate=4 )
A_ : str = hf_hub_download(repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" )
A_ : int = video_classifier(a__ , top_k=2 )
self.assertEqual(
nested_simplify(a__ , decimals=4 ) , [{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}] , )
A_ : Union[str, Any] = video_classifier(
[
video_file_path,
video_file_path,
] , top_k=2 , )
self.assertEqual(
nested_simplify(a__ , decimals=4 ) , [
[{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}],
[{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}],
] , )
@require_tf
def _lowerCamelCase ( self ):
pass
| 710 |
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()
_lowerCAmelCase = logging.get_logger(__name__)
_lowerCAmelCase = {
"""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""",
}
_lowerCAmelCase = [
"""ctc_proj""",
"""quantizer.weight_proj""",
"""quantizer.codevectors""",
"""project_q""",
"""project_hid""",
]
def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
'''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
A_ : Tuple = """lm_head"""
A_ : int = getattr(_lowerCAmelCase ,_lowerCAmelCase )
if weight_type is not None:
A_ : List[str] = getattr(_lowerCAmelCase ,_lowerCAmelCase ).shape
else:
A_ : Optional[Any] = 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_ : Union[str, Any] = value
elif weight_type == "weight_g":
A_ : Any = value
elif weight_type == "weight_v":
A_ : Tuple = value
elif weight_type == "bias":
A_ : List[Any] = value
else:
A_ : int = value
logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" )
def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
'''simple docstring'''
A_ : Dict = []
A_ : List[Any] = fairseq_model.state_dict()
A_ : Any = hf_model.unispeech.feature_extractor
for name, value in fairseq_dict.items():
A_ : Any = False
if "conv_layers" in name:
load_conv_layer(
_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,hf_model.config.feat_extract_norm == """group""" ,)
A_ : int = True
else:
for key, mapped_key in MAPPING.items():
A_ : 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]:
A_ : Dict = True
if "*" in mapped_key:
A_ : Any = name.split(_lowerCAmelCase )[0].split(""".""" )[-2]
A_ : Optional[int] = mapped_key.replace("""*""" ,_lowerCAmelCase )
if "weight_g" in name:
A_ : Tuple = """weight_g"""
elif "weight_v" in name:
A_ : Optional[int] = """weight_v"""
elif "bias" in name:
A_ : List[Any] = """bias"""
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
A_ : Optional[int] = """weight"""
else:
A_ : Dict = 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 _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
'''simple docstring'''
A_ : Union[str, Any] = full_name.split("""conv_layers.""" )[-1]
A_ : Union[str, Any] = name.split(""".""" )
A_ : List[str] = int(items[0] )
A_ : Optional[Any] = 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_ : List[Any] = 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_ : 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."
)
A_ : List[str] = 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_ : Tuple = 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 _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase=None ,_lowerCAmelCase=None ,_lowerCAmelCase=True ):
'''simple docstring'''
if config_path is not None:
A_ : Optional[int] = UniSpeechConfig.from_pretrained(_lowerCAmelCase )
else:
A_ : List[str] = UniSpeechConfig()
if is_finetuned:
if dict_path:
A_ : str = Dictionary.load_from_json(_lowerCAmelCase )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
A_ : List[Any] = target_dict.pad_index
A_ : str = target_dict.bos_index
A_ : Optional[Any] = target_dict.eos_index
A_ : Optional[int] = len(target_dict.symbols )
A_ : str = 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 )
A_ : Optional[int] = target_dict.indices
# fairseq has the <pad> and <s> switched
A_ : Dict = 4_2
A_ : Optional[Any] = 4_3
with open(_lowerCAmelCase ,"""w""" ,encoding="""utf-8""" ) as vocab_handle:
json.dump(_lowerCAmelCase ,_lowerCAmelCase )
A_ : Tuple = 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 ,)
A_ : Any = True if config.feat_extract_norm == """layer""" else False
A_ : List[str] = WavaVecaFeatureExtractor(
feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=_lowerCAmelCase ,return_attention_mask=_lowerCAmelCase ,)
A_ : Optional[int] = WavaVecaProcessor(feature_extractor=_lowerCAmelCase ,tokenizer=_lowerCAmelCase )
processor.save_pretrained(_lowerCAmelCase )
A_ : int = UniSpeechForCTC(_lowerCAmelCase )
else:
A_ : str = UniSpeechForPreTraining(_lowerCAmelCase )
if is_finetuned:
A_ , A_ , A_ : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} )
else:
A_ , A_ , A_ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
A_ : List[str] = model[0].eval()
recursively_load_weights(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase )
hf_unispeech.save_pretrained(_lowerCAmelCase )
if __name__ == "__main__":
_lowerCAmelCase = 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"""
)
_lowerCAmelCase = parser.parse_args()
convert_unispeech_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 481 | 0 |
from collections.abc import Iterable
from typing import Any
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self : int , lowerCamelCase : int | None = None ) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase = value
_UpperCAmelCase = None # Added in order to delete a node easier
_UpperCAmelCase = None
_UpperCAmelCase = None
def __repr__( self : Any ) -> str:
"""simple docstring"""
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value )
return pformat({f"""{self.value}""": (self.left, self.right)} , indent=1 )
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self : List[Any] , lowerCamelCase : Node | None = None ) -> Dict:
"""simple docstring"""
_UpperCAmelCase = root
def __str__( self : Union[str, Any] ) -> str:
"""simple docstring"""
return str(self.root )
def lowerCamelCase ( self : Any , lowerCamelCase : Node , lowerCamelCase : Node | None ) -> None:
"""simple docstring"""
if new_children is not None: # reset its kids
_UpperCAmelCase = node.parent
if node.parent is not None: # reset its parent
if self.is_right(lowerCamelCase ): # If it is the right children
_UpperCAmelCase = new_children
else:
_UpperCAmelCase = new_children
else:
_UpperCAmelCase = new_children
def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Node ) -> bool:
"""simple docstring"""
if node.parent and node.parent.right:
return node == node.parent.right
return False
def lowerCamelCase ( self : int ) -> bool:
"""simple docstring"""
return self.root is None
def lowerCamelCase ( self : List[str] , lowerCamelCase : int ) -> None:
"""simple docstring"""
_UpperCAmelCase = Node(lowerCamelCase ) # create a new Node
if self.empty(): # if Tree is empty
_UpperCAmelCase = new_node # set its root
else: # Tree is not empty
_UpperCAmelCase = self.root # from root
if parent_node is None:
return
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
_UpperCAmelCase = new_node # We insert the new node in a leaf
break
else:
_UpperCAmelCase = parent_node.left
else:
if parent_node.right is None:
_UpperCAmelCase = new_node
break
else:
_UpperCAmelCase = parent_node.right
_UpperCAmelCase = parent_node
def lowerCamelCase ( self : int , *lowerCamelCase : List[str] ) -> None:
"""simple docstring"""
for value in values:
self.__insert(lowerCamelCase )
def lowerCamelCase ( self : List[str] , lowerCamelCase : Optional[Any] ) -> Node | None:
"""simple docstring"""
if self.empty():
raise IndexError("""Warning: Tree is empty! please use another.""" )
else:
_UpperCAmelCase = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
_UpperCAmelCase = node.left if value < node.value else node.right
return node
def lowerCamelCase ( self : str , lowerCamelCase : Node | None = None ) -> Node | None:
"""simple docstring"""
if node is None:
if self.root is None:
return None
_UpperCAmelCase = self.root
if not self.empty():
while node.right is not None:
_UpperCAmelCase = node.right
return node
def lowerCamelCase ( self : Any , lowerCamelCase : Node | None = None ) -> Node | None:
"""simple docstring"""
if node is None:
_UpperCAmelCase = self.root
if self.root is None:
return None
if not self.empty():
_UpperCAmelCase = self.root
while node.left is not None:
_UpperCAmelCase = node.left
return node
def lowerCamelCase ( self : Any , lowerCamelCase : int ) -> None:
"""simple docstring"""
_UpperCAmelCase = self.search(lowerCamelCase ) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(lowerCamelCase , lowerCamelCase )
elif node.left is None: # Has only right children
self.__reassign_nodes(lowerCamelCase , node.right )
elif node.right is None: # Has only left children
self.__reassign_nodes(lowerCamelCase , node.left )
else:
_UpperCAmelCase = self.get_max(
node.left ) # Gets the max value of the left branch
self.remove(tmp_node.value ) # type: ignore
_UpperCAmelCase = (
tmp_node.value # type: ignore
) # Assigns the value to the node to delete and keep tree structure
def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Node | None ) -> Iterable:
"""simple docstring"""
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left )
yield from self.preorder_traverse(node.right )
def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Any=None ) -> Any:
"""simple docstring"""
if traversal_function is None:
return self.preorder_traverse(self.root )
else:
return traversal_function(self.root )
def lowerCamelCase ( self : Any , lowerCamelCase : list , lowerCamelCase : Node | None ) -> None:
"""simple docstring"""
if node:
self.inorder(lowerCamelCase , node.left )
arr.append(node.value )
self.inorder(lowerCamelCase , node.right )
def lowerCamelCase ( self : List[str] , lowerCamelCase : int , lowerCamelCase : Node ) -> int:
"""simple docstring"""
_UpperCAmelCase = []
self.inorder(lowerCamelCase , lowerCamelCase ) # append all values to list using inorder traversal
return arr[k - 1]
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> list[Node]:
_UpperCAmelCase = []
if curr_node is not None:
_UpperCAmelCase = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node]
return node_list
def _SCREAMING_SNAKE_CASE ( ) -> None:
_UpperCAmelCase = (8, 3, 6, 1, 1_0, 1_4, 1_3, 4, 7)
_UpperCAmelCase = BinarySearchTree()
for i in testlist:
t.insert(__snake_case )
# Prints all the elements of the list in order traversal
print(__snake_case )
if t.search(6 ) is not None:
print("""The value 6 exists""" )
else:
print("""The value 6 doesn't exist""" )
if t.search(-1 ) is not None:
print("""The value -1 exists""" )
else:
print("""The value -1 doesn't exist""" )
if not t.empty():
print("""Max Value: """ , t.get_max().value ) # type: ignore
print("""Min Value: """ , t.get_min().value ) # type: ignore
for i in testlist:
t.remove(__snake_case )
print(__snake_case )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) | 108 |
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel
from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class __A ( unittest.TestCase ):
@property
def lowercase__ ( self : List[str] ):
torch.manual_seed(0 )
lowerCAmelCase : Optional[Any] = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , )
return model
@property
def lowercase__ ( self : Tuple ):
torch.manual_seed(0 )
lowerCAmelCase : int = VQModel(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , )
return model
@property
def lowercase__ ( self : int ):
torch.manual_seed(0 )
lowerCAmelCase : Tuple = 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=1000 , )
return CLIPTextModel(UpperCAmelCase_ )
def lowercase__ ( self : Any ):
lowerCAmelCase : List[Any] = self.dummy_uncond_unet
lowerCAmelCase : List[Any] = DDIMScheduler()
lowerCAmelCase : Optional[int] = self.dummy_vq_model
lowerCAmelCase : Optional[int] = LDMPipeline(unet=UpperCAmelCase_ , vqvae=UpperCAmelCase_ , scheduler=UpperCAmelCase_ )
ldm.to(UpperCAmelCase_ )
ldm.set_progress_bar_config(disable=UpperCAmelCase_ )
lowerCAmelCase : int = torch.manual_seed(0 )
lowerCAmelCase : Optional[Any] = ldm(generator=UpperCAmelCase_ , num_inference_steps=2 , output_type='numpy' ).images
lowerCAmelCase : Optional[Any] = torch.manual_seed(0 )
lowerCAmelCase : Optional[Any] = ldm(generator=UpperCAmelCase_ , num_inference_steps=2 , output_type='numpy' , return_dict=UpperCAmelCase_ )[0]
lowerCAmelCase : Optional[int] = image[0, -3:, -3:, -1]
lowerCAmelCase : Dict = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
lowerCAmelCase : int = np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72] )
lowerCAmelCase : str = 1E-2 if torch_device != 'mps' else 3E-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance
@slow
@require_torch
class __A ( unittest.TestCase ):
def lowercase__ ( self : int ):
lowerCAmelCase : Dict = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' )
ldm.to(UpperCAmelCase_ )
ldm.set_progress_bar_config(disable=UpperCAmelCase_ )
lowerCAmelCase : List[Any] = torch.manual_seed(0 )
lowerCAmelCase : Optional[Any] = ldm(generator=UpperCAmelCase_ , num_inference_steps=5 , output_type='numpy' ).images
lowerCAmelCase : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
lowerCAmelCase : Dict = np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47] )
lowerCAmelCase : Optional[int] = 1E-2 if torch_device != 'mps' else 3E-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
| 343 | 0 |
"""simple docstring"""
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_gpta import GPTaTokenizer
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
a : Union[str, Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
a : Optional[Any] = {
'''vocab_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''',
},
'''merges_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/tokenizer.json''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/tokenizer.json''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/tokenizer.json''',
},
}
a : Tuple = {
'''gpt2''': 1024,
'''gpt2-medium''': 1024,
'''gpt2-large''': 1024,
'''gpt2-xl''': 1024,
'''distilgpt2''': 1024,
}
class _UpperCamelCase ( __UpperCamelCase ):
'''simple docstring'''
__lowercase : Any = VOCAB_FILES_NAMES
__lowercase : int = PRETRAINED_VOCAB_FILES_MAP
__lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowercase : List[str] = ['input_ids', 'attention_mask']
__lowercase : Dict = GPTaTokenizer
def __init__( self , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase="<|endoftext|>" , __lowercase="<|endoftext|>" , __lowercase="<|endoftext|>" , __lowercase=False , **__lowercase , ):
super().__init__(
__lowercase , __lowercase , tokenizer_file=__lowercase , unk_token=__lowercase , bos_token=__lowercase , eos_token=__lowercase , add_prefix_space=__lowercase , **__lowercase , )
UpperCAmelCase__ = kwargs.pop("""add_bos_token""" , __lowercase )
UpperCAmelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("""add_prefix_space""" , __lowercase ) != add_prefix_space:
UpperCAmelCase__ = getattr(__lowercase , pre_tok_state.pop("""type""" ) )
UpperCAmelCase__ = add_prefix_space
UpperCAmelCase__ = pre_tok_class(**__lowercase )
UpperCAmelCase__ = add_prefix_space
def A__ ( self , *__lowercase , **__lowercase ):
UpperCAmelCase__ = kwargs.get("""is_split_into_words""" , __lowercase )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*__lowercase , **__lowercase )
def A__ ( self , *__lowercase , **__lowercase ):
UpperCAmelCase__ = kwargs.get("""is_split_into_words""" , __lowercase )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._encode_plus(*__lowercase , **__lowercase )
def A__ ( self , __lowercase , __lowercase = None ):
UpperCAmelCase__ = self._tokenizer.model.save(__lowercase , name=__lowercase )
return tuple(__lowercase )
def A__ ( self , __lowercase ):
UpperCAmelCase__ = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(__lowercase , add_special_tokens=__lowercase ) + [self.eos_token_id] )
if len(__lowercase ) > self.model_max_length:
UpperCAmelCase__ = input_ids[-self.model_max_length :]
return input_ids
| 422 |
"""simple docstring"""
from datetime import datetime as dt
import os
from github import Github
a : Optional[int] = [
'''good first issue''',
'''good second issue''',
'''good difficult issue''',
'''feature request''',
'''new model''',
'''wip''',
]
def snake_case__ ( ) ->Dict:
UpperCAmelCase__ = Github(os.environ["""GITHUB_TOKEN"""] )
UpperCAmelCase__ = g.get_repo("""huggingface/transformers""" )
UpperCAmelCase__ = repo.get_issues(state="""open""" )
for issue in open_issues:
UpperCAmelCase__ = sorted([comment for comment in issue.get_comments()] , key=lambda _SCREAMING_SNAKE_CASE : i.created_at , reverse=_SCREAMING_SNAKE_CASE )
UpperCAmelCase__ = comments[0] if len(_SCREAMING_SNAKE_CASE ) > 0 else None
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and (dt.utcnow() - issue.updated_at).days > 7
and (dt.utcnow() - issue.created_at).days >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
issue.edit(state="""closed""" )
elif (
(dt.utcnow() - issue.updated_at).days > 2_3
and (dt.utcnow() - issue.created_at).days >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# print(f"Would add stale comment to {issue.number}")
issue.create_comment(
"""This issue has been automatically marked as stale because it has not had """
"""recent activity. If you think this still needs to be addressed """
"""please comment on this thread.\n\nPlease note that issues that do not follow the """
"""[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) """
"""are likely to be ignored.""" )
if __name__ == "__main__":
main()
| 422 | 1 |
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_):
"""simple docstring"""
snake_case__ : Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase_)
snake_case__ : List[Any] = FlaxAutoModelForSeqaSeqLM.from_config(config=UpperCAmelCase_)
snake_case__ : str = checkpoints.load_tax_checkpoint(UpperCAmelCase_)
snake_case__ : List[Any] = """wi_0""" in tax_model["""target"""]["""encoder"""]["""layers_0"""]["""mlp"""]
if config.model_type == "t5":
snake_case__ : List[str] = """SelfAttention"""
if config.model_type == "longt5" and config.encoder_attention_type == "local":
snake_case__ : int = """LocalSelfAttention"""
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
snake_case__ : str = """TransientGlobalSelfAttention"""
else:
raise ValueError(
"""Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"""
""" attribute with a value from ['local', 'transient-global].""")
# Encoder
for layer_index in range(config.num_layers):
snake_case__ : List[Any] = F'layers_{str(UpperCAmelCase_)}'
# Self-Attention
snake_case__ : Union[str, Any] = tax_model["""target"""]["""encoder"""][layer_name]["""attention"""]["""key"""]["""kernel"""]
snake_case__ : Dict = tax_model["""target"""]["""encoder"""][layer_name]["""attention"""]["""out"""]["""kernel"""]
snake_case__ : List[Any] = tax_model["""target"""]["""encoder"""][layer_name]["""attention"""]["""query"""]["""kernel"""]
snake_case__ : Tuple = tax_model["""target"""]["""encoder"""][layer_name]["""attention"""]["""value"""]["""kernel"""]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
snake_case__ : Union[str, Any] = tax_model["""target"""]["""encoder"""][layer_name]["""attention"""]["""T5LayerNorm_0"""]["""scale"""]
# Layer Normalization
snake_case__ : Dict = tax_model["""target"""]["""encoder"""][layer_name]["""pre_attention_layer_norm"""]["""scale"""]
if split_mlp_wi:
snake_case__ : Union[str, Any] = tax_model["""target"""]["""encoder"""][layer_name]["""mlp"""]["""wi_0"""]["""kernel"""]
snake_case__ : Union[str, Any] = tax_model["""target"""]["""encoder"""][layer_name]["""mlp"""]["""wi_1"""]["""kernel"""]
else:
snake_case__ : Tuple = tax_model["""target"""]["""encoder"""][layer_name]["""mlp"""]["""wi"""]["""kernel"""]
snake_case__ : Optional[int] = tax_model["""target"""]["""encoder"""][layer_name]["""mlp"""]["""wo"""]["""kernel"""]
# Layer Normalization
snake_case__ : str = tax_model["""target"""]["""encoder"""][layer_name]["""pre_mlp_layer_norm"""]["""scale"""]
# Assigning
snake_case__ : Tuple = flax_model.params["""encoder"""]["""block"""][str(UpperCAmelCase_)]["""layer"""]
snake_case__ : str = tax_attention_key
snake_case__ : List[Any] = tax_attention_out
snake_case__ : Dict = tax_attention_query
snake_case__ : List[str] = tax_attention_value
snake_case__ : Union[str, Any] = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
snake_case__ : str = tax_global_layer_norm
if split_mlp_wi:
snake_case__ : Optional[Any] = tax_mlp_wi_a
snake_case__ : int = tax_mlp_wi_a
else:
snake_case__ : List[str] = tax_mlp_wi
snake_case__ : List[Any] = tax_mlp_wo
snake_case__ : Dict = tax_mlp_layer_norm
snake_case__ : str = flax_model_encoder_layer_block
# Only for layer 0:
snake_case__ : Any = tax_model["""target"""]["""encoder"""]["""relpos_bias"""]["""rel_embedding"""].T
snake_case__ : Optional[int] = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
snake_case__ : Union[str, Any] = tax_model["""target"""]["""encoder"""]["""side_relpos_bias"""]["""rel_embedding"""].T
snake_case__ : Optional[int] = tax_encoder_global_rel_embedding
# Assigning
snake_case__ : str = tax_model["""target"""]["""encoder"""]["""encoder_norm"""]["""scale"""]
snake_case__ : Any = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers):
snake_case__ : Any = F'layers_{str(UpperCAmelCase_)}'
# Self-Attention
snake_case__ : Any = tax_model["""target"""]["""decoder"""][layer_name]["""self_attention"""]["""key"""]["""kernel"""]
snake_case__ : str = tax_model["""target"""]["""decoder"""][layer_name]["""self_attention"""]["""out"""]["""kernel"""]
snake_case__ : Dict = tax_model["""target"""]["""decoder"""][layer_name]["""self_attention"""]["""query"""]["""kernel"""]
snake_case__ : Optional[int] = tax_model["""target"""]["""decoder"""][layer_name]["""self_attention"""]["""value"""]["""kernel"""]
# Layer Normalization
snake_case__ : str = tax_model["""target"""]["""decoder"""][layer_name]["""pre_self_attention_layer_norm"""][
"""scale"""
]
# Encoder-Decoder-Attention
snake_case__ : Optional[int] = tax_model["""target"""]["""decoder"""][layer_name]["""encoder_decoder_attention"""]
snake_case__ : int = tax_enc_dec_attention_module["""key"""]["""kernel"""]
snake_case__ : Union[str, Any] = tax_enc_dec_attention_module["""out"""]["""kernel"""]
snake_case__ : Union[str, Any] = tax_enc_dec_attention_module["""query"""]["""kernel"""]
snake_case__ : Union[str, Any] = tax_enc_dec_attention_module["""value"""]["""kernel"""]
# Layer Normalization
snake_case__ : Union[str, Any] = tax_model["""target"""]["""decoder"""][layer_name]["""pre_cross_attention_layer_norm"""]["""scale"""]
# MLP
if split_mlp_wi:
snake_case__ : Optional[int] = tax_model["""target"""]["""decoder"""][layer_name]["""mlp"""]["""wi_0"""]["""kernel"""]
snake_case__ : Union[str, Any] = tax_model["""target"""]["""decoder"""][layer_name]["""mlp"""]["""wi_1"""]["""kernel"""]
else:
snake_case__ : List[Any] = tax_model["""target"""]["""decoder"""][layer_name]["""mlp"""]["""wi"""]["""kernel"""]
snake_case__ : List[Any] = tax_model["""target"""]["""decoder"""][layer_name]["""mlp"""]["""wo"""]["""kernel"""]
# Layer Normalization
snake_case__ : Optional[Any] = tax_model["""target"""]["""decoder"""][layer_name]["""pre_mlp_layer_norm"""]["""scale"""]
# Assigning
snake_case__ : Dict = flax_model.params["""decoder"""]["""block"""][str(UpperCAmelCase_)]["""layer"""]
snake_case__ : Optional[Any] = tax_attention_key
snake_case__ : List[str] = tax_attention_out
snake_case__ : Optional[int] = tax_attention_query
snake_case__ : List[str] = tax_attention_value
snake_case__ : int = tax_pre_attention_layer_norm
snake_case__ : Dict = tax_enc_dec_attention_key
snake_case__ : Optional[Any] = tax_enc_dec_attention_out
snake_case__ : Optional[int] = tax_enc_dec_attention_query
snake_case__ : Union[str, Any] = tax_enc_dec_attention_value
snake_case__ : Tuple = tax_cross_layer_norm
if split_mlp_wi:
snake_case__ : Union[str, Any] = tax_mlp_wi_a
snake_case__ : Any = tax_mlp_wi_a
else:
snake_case__ : Tuple = tax_mlp_wi
snake_case__ : int = tax_mlp_wo
snake_case__ : Dict = txa_mlp_layer_norm
snake_case__ : int = flax_model_decoder_layer_block
# Decoder Normalization
snake_case__ : List[Any] = tax_model["""target"""]["""decoder"""]["""decoder_norm"""]["""scale"""]
snake_case__ : Dict = txa_decoder_norm
# Only for layer 0:
snake_case__ : Dict = tax_model["""target"""]["""decoder"""]["""relpos_bias"""]["""rel_embedding"""].T
snake_case__ : int = tax_decoder_rel_embedding
# Token Embeddings
snake_case__ : int = tax_model["""target"""]["""token_embedder"""]["""embedding"""]
snake_case__ : List[Any] = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
snake_case__ : Optional[Any] = tax_model["""target"""]["""decoder"""]["""logits_dense"""]["""kernel"""]
flax_model.save_pretrained(UpperCAmelCase_)
print("""T5X Model was sucessfully converted!""")
if __name__ == "__main__":
lowercase_: Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
lowercase_: Tuple = parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 648 |
import argparse
import hashlib
import os
import urllib
import warnings
import torch
from torch import nn
from tqdm import tqdm
from transformers import WhisperConfig, WhisperForConditionalGeneration
lowercase_: Tuple = {
'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt',
'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt',
'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt',
'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt',
'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt',
'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt',
'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt',
'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt',
'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt',
'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt',
}
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
snake_case__ : Any = ["""layers""", """blocks"""]
for k in ignore_keys:
state_dict.pop(UpperCAmelCase_ , UpperCAmelCase_)
lowercase_: Dict = {
'blocks': 'layers',
'mlp.0': 'fc1',
'mlp.2': 'fc2',
'mlp_ln': 'final_layer_norm',
'.attn.query': '.self_attn.q_proj',
'.attn.key': '.self_attn.k_proj',
'.attn.value': '.self_attn.v_proj',
'.attn_ln': '.self_attn_layer_norm',
'.attn.out': '.self_attn.out_proj',
'.cross_attn.query': '.encoder_attn.q_proj',
'.cross_attn.key': '.encoder_attn.k_proj',
'.cross_attn.value': '.encoder_attn.v_proj',
'.cross_attn_ln': '.encoder_attn_layer_norm',
'.cross_attn.out': '.encoder_attn.out_proj',
'decoder.ln.': 'decoder.layer_norm.',
'encoder.ln.': 'encoder.layer_norm.',
'token_embedding': 'embed_tokens',
'encoder.positional_embedding': 'encoder.embed_positions.weight',
'decoder.positional_embedding': 'decoder.embed_positions.weight',
'ln_post': 'layer_norm',
}
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
snake_case__ : Tuple = list(s_dict.keys())
for key in keys:
snake_case__ : str = key
for k, v in WHISPER_MAPPING.items():
if k in key:
snake_case__ : Union[str, Any] = new_key.replace(UpperCAmelCase_ , UpperCAmelCase_)
print(F'{key} -> {new_key}')
snake_case__ : Dict = s_dict.pop(UpperCAmelCase_)
return s_dict
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
snake_case__ , snake_case__ : Any = emb.weight.shape
snake_case__ : List[Any] = nn.Linear(UpperCAmelCase_ , UpperCAmelCase_ , bias=UpperCAmelCase_)
snake_case__ : int = emb.weight.data
return lin_layer
def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_):
"""simple docstring"""
os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_)
snake_case__ : Dict = os.path.basename(UpperCAmelCase_)
snake_case__ : Tuple = url.split("""/""")[-2]
snake_case__ : Optional[int] = os.path.join(UpperCAmelCase_ , UpperCAmelCase_)
if os.path.exists(UpperCAmelCase_) and not os.path.isfile(UpperCAmelCase_):
raise RuntimeError(F'{download_target} exists and is not a regular file')
if os.path.isfile(UpperCAmelCase_):
snake_case__ : Optional[int] = open(UpperCAmelCase_ , """rb""").read()
if hashlib.shaaaa(UpperCAmelCase_).hexdigest() == expected_shaaaa:
return model_bytes
else:
warnings.warn(F'{download_target} exists, but the SHA256 checksum does not match; re-downloading the file')
with urllib.request.urlopen(UpperCAmelCase_) as source, open(UpperCAmelCase_ , """wb""") as output:
with tqdm(
total=int(source.info().get("""Content-Length""")) , ncols=80 , unit="""iB""" , unit_scale=UpperCAmelCase_ , unit_divisor=1_024) as loop:
while True:
snake_case__ : Union[str, Any] = source.read(8_192)
if not buffer:
break
output.write(UpperCAmelCase_)
loop.update(len(UpperCAmelCase_))
snake_case__ : Optional[int] = open(UpperCAmelCase_ , """rb""").read()
if hashlib.shaaaa(UpperCAmelCase_).hexdigest() != expected_shaaaa:
raise RuntimeError(
"""Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""")
return model_bytes
def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_):
"""simple docstring"""
if ".pt" not in checkpoint_path:
snake_case__ : List[Any] = _download(_MODELS[checkpoint_path])
else:
snake_case__ : Union[str, Any] = torch.load(UpperCAmelCase_ , map_location="""cpu""")
snake_case__ : Union[str, Any] = original_checkpoint["""dims"""]
snake_case__ : Optional[int] = original_checkpoint["""model_state_dict"""]
snake_case__ : int = state_dict["""decoder.token_embedding.weight"""]
remove_ignore_keys_(UpperCAmelCase_)
rename_keys(UpperCAmelCase_)
snake_case__ : List[Any] = True
snake_case__ : Dict = state_dict["""decoder.layers.0.fc1.weight"""].shape[0]
snake_case__ : List[Any] = WhisperConfig(
vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=UpperCAmelCase_ , decoder_ffn_dim=UpperCAmelCase_ , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , )
snake_case__ : int = WhisperForConditionalGeneration(UpperCAmelCase_)
snake_case__ , snake_case__ : Tuple = model.model.load_state_dict(UpperCAmelCase_ , strict=UpperCAmelCase_)
if len(UpperCAmelCase_) > 0 and not set(UpperCAmelCase_) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"""Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"""
F' but all the following weights are missing {missing}')
if tie_embeds:
snake_case__ : Dict = make_linear_from_emb(model.model.decoder.embed_tokens)
else:
snake_case__ : Optional[int] = proj_out_weights
model.save_pretrained(UpperCAmelCase_)
if __name__ == "__main__":
lowercase_: int = argparse.ArgumentParser()
# # Required parameters
parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints')
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
lowercase_: int = parser.parse_args()
convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
| 648 | 1 |
def __lowerCamelCase (UpperCAmelCase__ : int = 1_0**9 ):
SCREAMING_SNAKE_CASE = 1
SCREAMING_SNAKE_CASE = 2
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 0
while perimeter <= max_perimeter:
perimeters_sum += perimeter
prev_value += 2 * value
value += prev_value
SCREAMING_SNAKE_CASE = 2 * value + 2 if i % 2 == 0 else 2 * value - 2
i += 1
return perimeters_sum
if __name__ == "__main__":
print(f"""{solution() = }""")
| 647 | from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_lowerCamelCase : Optional[int] = {
'''configuration_blenderbot''': [
'''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''BlenderbotConfig''',
'''BlenderbotOnnxConfig''',
],
'''tokenization_blenderbot''': ['''BlenderbotTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[Any] = ['''BlenderbotTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Tuple = [
'''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BlenderbotForCausalLM''',
'''BlenderbotForConditionalGeneration''',
'''BlenderbotModel''',
'''BlenderbotPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[str] = [
'''TFBlenderbotForConditionalGeneration''',
'''TFBlenderbotModel''',
'''TFBlenderbotPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Optional[int] = [
'''FlaxBlenderbotForConditionalGeneration''',
'''FlaxBlenderbotModel''',
'''FlaxBlenderbotPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 647 | 1 |
"""simple docstring"""
import os
import sys
import unittest
lowerCAmelCase__ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))
import check_dummies # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402
# Align TRANSFORMERS_PATH in check_dummies with the current path
lowerCAmelCase__ = os.path.join(git_repo_path, 'src', 'transformers')
lowerCAmelCase__ = '\n{0} = None\n'
lowerCAmelCase__ = '\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n'
lowerCAmelCase__ = '\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n'
class _lowerCAmelCase ( unittest.TestCase ):
def A ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE : int = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' )
self.assertIsNone(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = find_backend(' if not is_tokenizers_available():' )
self.assertEqual(lowerCAmelCase_ , 'tokenizers' )
_SCREAMING_SNAKE_CASE : Dict = find_backend(' if not is_tensorflow_text_available():' )
self.assertEqual(lowerCAmelCase_ , 'tensorflow_text' )
_SCREAMING_SNAKE_CASE : Optional[int] = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' )
self.assertEqual(lowerCAmelCase_ , 'sentencepiece_and_tokenizers' )
_SCREAMING_SNAKE_CASE : Optional[Any] = find_backend(
' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' )
self.assertEqual(lowerCAmelCase_ , 'sentencepiece_and_tensorflow_text' )
_SCREAMING_SNAKE_CASE : Union[str, Any] = find_backend(
' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' )
self.assertEqual(lowerCAmelCase_ , 'sentencepiece_and_tokenizers_and_vision' )
def A ( self ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE : Tuple = read_init()
# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
self.assertIn('torch' , lowerCAmelCase_ )
self.assertIn('tensorflow_text' , lowerCAmelCase_ )
self.assertIn('sentencepiece_and_tokenizers' , lowerCAmelCase_ )
# Likewise, we can't assert on the exact content of a key
self.assertIn('BertModel' , objects['torch'] )
self.assertIn('TFBertModel' , objects['tf'] )
self.assertIn('FlaxBertModel' , objects['flax'] )
self.assertIn('BertModel' , objects['torch'] )
self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] )
self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] )
def A ( self ) -> Dict:
_SCREAMING_SNAKE_CASE : Union[str, Any] = create_dummy_object('CONSTANT' , '\'torch\'' )
self.assertEqual(lowerCAmelCase_ , '\nCONSTANT = None\n' )
_SCREAMING_SNAKE_CASE : Dict = create_dummy_object('function' , '\'torch\'' )
self.assertEqual(
lowerCAmelCase_ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' )
_SCREAMING_SNAKE_CASE : Optional[Any] = '''
class FakeClass(metaclass=DummyObject):
_backends = \'torch\'
def __init__(self, *args, **kwargs):
requires_backends(self, \'torch\')
'''
_SCREAMING_SNAKE_CASE : Dict = create_dummy_object('FakeClass' , '\'torch\'' )
self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ )
def A ( self ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE : Tuple = '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends
CONSTANT = None
def function(*args, **kwargs):
requires_backends(function, ["torch"])
class FakeClass(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
'''
_SCREAMING_SNAKE_CASE : Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} )
self.assertEqual(dummy_files['torch'] , lowerCAmelCase_ )
| 621 |
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 _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Tuple = np.array([[1, item, train_mtch[i]] for i, item in enumerate(UpperCAmelCase )] )
lowerCamelCase__ : str = np.array(UpperCAmelCase )
lowerCamelCase__ : Optional[Any] = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , UpperCAmelCase ) ) , x.transpose() ) , UpperCAmelCase )
return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] )
def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Optional[int] = (1, 2, 1)
lowerCamelCase__ : List[str] = (1, 1, 0, 7)
lowerCamelCase__ : Union[str, Any] = SARIMAX(
UpperCAmelCase , exog=UpperCAmelCase , order=UpperCAmelCase , seasonal_order=UpperCAmelCase )
lowerCamelCase__ : int = model.fit(disp=UpperCAmelCase , maxiter=600 , method='''nm''' )
lowerCamelCase__ : Optional[int] = model_fit.predict(1 , len(UpperCAmelCase ) , exog=[test_match] )
return result[0]
def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Dict = SVR(kernel='''rbf''' , C=1 , gamma=0.1 , epsilon=0.1 )
regressor.fit(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase__ : Tuple = regressor.predict(UpperCAmelCase )
return y_pred[0]
def _a ( UpperCAmelCase ) -> float:
"""simple docstring"""
train_user.sort()
lowerCamelCase__ : Any = np.percentile(UpperCAmelCase , 25 )
lowerCamelCase__ : Any = np.percentile(UpperCAmelCase , 75 )
lowerCamelCase__ : Optional[Any] = qa - qa
lowerCamelCase__ : Any = qa - (iqr * 0.1)
return low_lim
def _a ( UpperCAmelCase , UpperCAmelCase ) -> bool:
"""simple docstring"""
lowerCamelCase__ : List[str] = 0
lowerCamelCase__ : Any = 0
for i in list_vote:
if i > actual_result:
lowerCamelCase__ : List[str] = not_safe + 1
else:
if abs(abs(UpperCAmelCase ) - abs(UpperCAmelCase ) ) <= 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 : Dict = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]]
_A : Dict = pd.DataFrame(
data_input, columns=['total_user', 'total_even', 'days']
)
_A : Optional[int] = Normalizer().fit_transform(data_input_df.values)
# split data
_A : str = normalize_df[:, 2].tolist()
_A : Union[str, Any] = normalize_df[:, 0].tolist()
_A : Union[str, Any] = normalize_df[:, 1].tolist()
# for svr (input variable = total date and total match)
_A : int = normalize_df[:, [1, 2]].tolist()
_A : str = x[: len(x) - 1]
_A : Optional[Any] = x[len(x) - 1 :]
# for linear regression & sarimax
_A : Any = total_date[: len(total_date) - 1]
_A : List[str] = total_user[: len(total_user) - 1]
_A : List[str] = total_match[: len(total_match) - 1]
_A : Any = total_date[len(total_date) - 1 :]
_A : Optional[int] = total_user[len(total_user) - 1 :]
_A : str = total_match[len(total_match) - 1 :]
# voting system with forecasting
_A : Any = [
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 : Union[str, Any] = '' if data_safety_checker(res_vote, tst_user) else 'not '
print('Today\'s data is {not_str}safe.')
| 315 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
__UpperCAmelCase = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase = ["BartphoTokenizer"]
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_bartpho import BartphoTokenizer
else:
import sys
__UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 714 |
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__ ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase_ =["image_processor", "tokenizer"]
UpperCAmelCase_ ="Pix2StructImageProcessor"
UpperCAmelCase_ =("T5Tokenizer", "T5TokenizerFast")
def __init__( self , _A , _A ) -> Optional[int]:
SCREAMING_SNAKE_CASE_ = False
super().__init__(_A , _A )
def __call__( self , _A=None , _A = None , _A = True , _A = False , _A = None , _A = None , _A = 2048 , _A = 0 , _A = None , _A = None , _A = False , _A = False , _A = False , _A = False , _A = False , _A = True , _A = None , **_A , ) -> BatchEncoding:
if images is None and text is None:
raise ValueError('''You have to specify either images or text.''' )
# Get only text
if images is None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ = self.tokenizer
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
return text_encoding
if not self.image_processor.is_vqa:
# add pixel_values
SCREAMING_SNAKE_CASE_ = self.image_processor(
_A , return_tensors=_A , max_patches=_A , **_A )
else:
# add pixel_values and bbox
SCREAMING_SNAKE_CASE_ = self.image_processor(
_A , return_tensors=_A , max_patches=_A , header_text=_A , **_A )
if text is not None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
if "attention_mask" in text_encoding:
SCREAMING_SNAKE_CASE_ = text_encoding.pop('''attention_mask''' )
if "input_ids" in text_encoding:
SCREAMING_SNAKE_CASE_ = text_encoding.pop('''input_ids''' )
else:
SCREAMING_SNAKE_CASE_ = None
if text_encoding is not None:
encoding_image_processor.update(_A )
return encoding_image_processor
def _UpperCamelCase ( self , *_A , **_A ) -> int:
return self.tokenizer.batch_decode(*_A , **_A )
def _UpperCamelCase ( self , *_A , **_A ) -> List[str]:
return self.tokenizer.decode(*_A , **_A )
@property
def _UpperCamelCase ( self ) -> Tuple:
SCREAMING_SNAKE_CASE_ = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE_ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 597 | 0 |
from __future__ import annotations
import os
from collections.abc import Mapping
__lowerCamelCase : int = tuple[int, int]
class a__ :
def __init__( self : List[Any],_A : set[int],_A : Mapping[EdgeT, int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : set[int] = vertices
SCREAMING_SNAKE_CASE_ : dict[EdgeT, int] = {
(min(_A ), max(_A )): weight for edge, weight in edges.items()
}
def __UpperCamelCase ( self : Union[str, Any],_A : EdgeT,_A : int ):
"""simple docstring"""
self.vertices.add(edge[0] )
self.vertices.add(edge[1] )
SCREAMING_SNAKE_CASE_ : Optional[int] = weight
def __UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Graph = Graph({min(self.vertices )},{} )
SCREAMING_SNAKE_CASE_ : EdgeT
SCREAMING_SNAKE_CASE_ : int
SCREAMING_SNAKE_CASE_ : EdgeT
SCREAMING_SNAKE_CASE_ : int
while len(subgraph.vertices ) < len(self.vertices ):
SCREAMING_SNAKE_CASE_ : Any = max(self.edges.values() ) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
SCREAMING_SNAKE_CASE_ : List[Any] = edge
SCREAMING_SNAKE_CASE_ : Any = weight
subgraph.add_edge(_A,_A )
return subgraph
def _snake_case ( lowerCAmelCase : str = "p107_network.txt" ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = os.path.abspath(os.path.dirname(lowerCAmelCase ) )
SCREAMING_SNAKE_CASE_ : str = os.path.join(lowerCAmelCase , lowerCAmelCase )
SCREAMING_SNAKE_CASE_ : dict[EdgeT, int] = {}
SCREAMING_SNAKE_CASE_ : list[str]
SCREAMING_SNAKE_CASE_ : int
SCREAMING_SNAKE_CASE_ : int
with open(lowerCAmelCase ) as f:
SCREAMING_SNAKE_CASE_ : List[str] = f.read().strip().split("\n" )
SCREAMING_SNAKE_CASE_ : Any = [line.split("," ) for line in data]
for edgea in range(1 , len(lowerCAmelCase ) ):
for edgea in range(lowerCAmelCase ):
if adjaceny_matrix[edgea][edgea] != "-":
SCREAMING_SNAKE_CASE_ : Optional[Any] = int(adjaceny_matrix[edgea][edgea] )
SCREAMING_SNAKE_CASE_ : Graph = Graph(set(range(len(lowerCAmelCase ) ) ) , lowerCAmelCase )
SCREAMING_SNAKE_CASE_ : Graph = graph.prims_algorithm()
SCREAMING_SNAKE_CASE_ : int = sum(graph.edges.values() )
SCREAMING_SNAKE_CASE_ : int = sum(subgraph.edges.values() )
return initial_total - optimal_total
if __name__ == "__main__":
print(f'''{solution() = }''')
| 216 | class a__ :
def __init__( self : Any,_A : str = "",_A : bool = False ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : dict[str, RadixNode] = {}
# A node will be a leaf if the tree contains its word
SCREAMING_SNAKE_CASE_ : Tuple = is_leaf
SCREAMING_SNAKE_CASE_ : Tuple = prefix
def __UpperCamelCase ( self : Optional[Any],_A : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = 0
for q, w in zip(self.prefix,_A ):
if q != w:
break
x += 1
return self.prefix[:x], self.prefix[x:], word[x:]
def __UpperCamelCase ( self : Union[str, Any],_A : list[str] ):
"""simple docstring"""
for word in words:
self.insert(_A )
def __UpperCamelCase ( self : Tuple,_A : str ):
"""simple docstring"""
if self.prefix == word:
SCREAMING_SNAKE_CASE_ : Optional[int] = True
# Case 2: The node has no edges that have a prefix to the word
# Solution: We create an edge from the current node to a new one
# containing the word
elif word[0] not in self.nodes:
SCREAMING_SNAKE_CASE_ : Tuple = RadixNode(prefix=_A,is_leaf=_A )
else:
SCREAMING_SNAKE_CASE_ : Optional[int] = self.nodes[word[0]]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = incoming_node.match(
_A )
# Case 3: The node prefix is equal to the matching
# Solution: We insert remaining word on the next node
if remaining_prefix == "":
self.nodes[matching_string[0]].insert(_A )
# Case 4: The word is greater equal to the matching
# Solution: Create a node in between both nodes, change
# prefixes and add the new node for the remaining word
else:
SCREAMING_SNAKE_CASE_ : List[str] = remaining_prefix
SCREAMING_SNAKE_CASE_ : str = self.nodes[matching_string[0]]
SCREAMING_SNAKE_CASE_ : List[Any] = RadixNode(_A,_A )
SCREAMING_SNAKE_CASE_ : Tuple = aux_node
if remaining_word == "":
SCREAMING_SNAKE_CASE_ : int = True
else:
self.nodes[matching_string[0]].insert(_A )
def __UpperCamelCase ( self : Dict,_A : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.nodes.get(word[0],_A )
if not incoming_node:
return False
else:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = incoming_node.match(
_A )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# This applies when the word and the prefix are equal
elif remaining_word == "":
return incoming_node.is_leaf
# We have word remaining so we check the next node
else:
return incoming_node.find(_A )
def __UpperCamelCase ( self : Dict,_A : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.nodes.get(word[0],_A )
if not incoming_node:
return False
else:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = incoming_node.match(
_A )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# We have word remaining so we check the next node
elif remaining_word != "":
return incoming_node.delete(_A )
else:
# If it is not a leaf, we don't have to delete
if not incoming_node.is_leaf:
return False
else:
# We delete the nodes if no edges go from it
if len(incoming_node.nodes ) == 0:
del self.nodes[word[0]]
# We merge the current node with its only child
if len(self.nodes ) == 1 and not self.is_leaf:
SCREAMING_SNAKE_CASE_ : Dict = list(self.nodes.values() )[0]
SCREAMING_SNAKE_CASE_ : int = merging_node.is_leaf
self.prefix += merging_node.prefix
SCREAMING_SNAKE_CASE_ : str = merging_node.nodes
# If there is more than 1 edge, we just mark it as non-leaf
elif len(incoming_node.nodes ) > 1:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = False
# If there is 1 edge, we merge it with its child
else:
SCREAMING_SNAKE_CASE_ : int = list(incoming_node.nodes.values() )[0]
SCREAMING_SNAKE_CASE_ : Optional[int] = merging_node.is_leaf
incoming_node.prefix += merging_node.prefix
SCREAMING_SNAKE_CASE_ : Optional[Any] = merging_node.nodes
return True
def __UpperCamelCase ( self : Tuple,_A : int = 0 ):
"""simple docstring"""
if self.prefix != "":
print("-" * height,self.prefix," (leaf)" if self.is_leaf else "" )
for value in self.nodes.values():
value.print_tree(height + 1 )
def _snake_case ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = "banana bananas bandana band apple all beast".split()
SCREAMING_SNAKE_CASE_ : int = RadixNode()
root.insert_many(lowerCAmelCase )
assert all(root.find(lowerCAmelCase ) for word in words )
assert not root.find("bandanas" )
assert not root.find("apps" )
root.delete("all" )
assert not root.find("all" )
root.delete("banana" )
assert not root.find("banana" )
assert root.find("bananas" )
return True
def _snake_case ( ):
"""simple docstring"""
assert test_trie()
def _snake_case ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = RadixNode()
SCREAMING_SNAKE_CASE_ : Any = "banana bananas bandanas bandana band apple all beast".split()
root.insert_many(lowerCAmelCase )
print("Words:" , lowerCAmelCase )
print("Tree:" )
root.print_tree()
if __name__ == "__main__":
main()
| 216 | 1 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_fnet import FNetTokenizer
else:
__A : Optional[Any] = None
__A : Optional[int] = logging.get_logger(__name__)
__A : Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
__A : Any = {
"vocab_file": {
"google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
"google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
},
"tokenizer_file": {
"google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json",
"google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json",
},
}
__A : Tuple = {
"google/fnet-base": 5_1_2,
"google/fnet-large": 5_1_2,
}
__A : List[Any] = "▁"
class lowerCAmelCase__ ( _UpperCAmelCase ):
"""simple docstring"""
__UpperCAmelCase : Any = VOCAB_FILES_NAMES
__UpperCAmelCase : str = PRETRAINED_VOCAB_FILES_MAP
__UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__UpperCAmelCase : str = ["input_ids", "token_type_ids"]
__UpperCAmelCase : Optional[int] = FNetTokenizer
def __init__( self : List[str] , lowercase__ : str=None , lowercase__ : int=None , lowercase__ : int=False , lowercase__ : Dict=True , lowercase__ : Dict=True , lowercase__ : Optional[int]="<unk>" , lowercase__ : Dict="[SEP]" , lowercase__ : Union[str, Any]="<pad>" , lowercase__ : List[Any]="[CLS]" , lowercase__ : Any="[MASK]" , **lowercase__ : List[str] , ):
__lowercase : Union[str, Any] = (
AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ , normalized=lowerCamelCase_ )
if isinstance(lowerCamelCase_ , lowerCamelCase_ )
else mask_token
)
super().__init__(
lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , remove_space=lowerCamelCase_ , keep_accents=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , **lowerCamelCase_ , )
__lowercase : List[Any] = do_lower_case
__lowercase : int = remove_space
__lowercase : Dict = keep_accents
__lowercase : int = vocab_file
__lowercase : List[Any] = False if not self.vocab_file else True
def snake_case ( self : str , lowercase__ : List[int] , lowercase__ : Optional[List[int]] = None ):
__lowercase : Optional[Any] = [self.sep_token_id]
__lowercase : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def snake_case ( self : Any , lowercase__ : List[int] , lowercase__ : Optional[List[int]] = None ):
__lowercase : Tuple = [self.sep_token_id]
__lowercase : 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 ) * [0] + len(token_ids_a + sep ) * [1]
def snake_case ( self : Any , lowercase__ : str , lowercase__ : Optional[str] = None ):
if not os.path.isdir(lowerCamelCase_ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
__lowercase : Dict = os.path.join(
lowerCamelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ):
copyfile(self.vocab_file , lowerCamelCase_ )
return (out_vocab_file,)
| 718 |
"""simple docstring"""
from __future__ import annotations
def snake_case__ ( _lowerCamelCase, _lowerCamelCase = None ) ->list[list[str]]:
"""simple docstring"""
__lowercase : List[Any] = word_bank or []
# create a table
__lowercase : int = len(_lowerCamelCase ) + 1
__lowercase : list[list[list[str]]] = []
for _ in range(_lowerCamelCase ):
table.append([] )
# seed value
__lowercase : Any = [[]] # 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:
__lowercase : 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'],
)
)
| 281 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__lowercase : str =logging.get_logger(__name__)
__lowercase : List[str] ={
"""facebook/xmod-base""": """https://huggingface.co/facebook/xmod-base/resolve/main/config.json""",
"""facebook/xmod-large-prenorm""": """https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json""",
"""facebook/xmod-base-13-125k""": """https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json""",
"""facebook/xmod-base-30-125k""": """https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json""",
"""facebook/xmod-base-30-195k""": """https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json""",
"""facebook/xmod-base-60-125k""": """https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json""",
"""facebook/xmod-base-60-265k""": """https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json""",
"""facebook/xmod-base-75-125k""": """https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json""",
"""facebook/xmod-base-75-269k""": """https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json""",
}
class A ( __lowercase ):
_snake_case ='''xmod'''
def __init__( self: Union[str, Any] , _lowerCAmelCase: Optional[int]=3_0522 , _lowerCAmelCase: Union[str, Any]=768 , _lowerCAmelCase: Dict=12 , _lowerCAmelCase: Any=12 , _lowerCAmelCase: Dict=3072 , _lowerCAmelCase: List[Any]="gelu" , _lowerCAmelCase: int=0.1 , _lowerCAmelCase: Optional[Any]=0.1 , _lowerCAmelCase: Optional[int]=512 , _lowerCAmelCase: Union[str, Any]=2 , _lowerCAmelCase: Union[str, Any]=0.02 , _lowerCAmelCase: Any=1e-12 , _lowerCAmelCase: List[Any]=1 , _lowerCAmelCase: Union[str, Any]=0 , _lowerCAmelCase: Any=2 , _lowerCAmelCase: Any="absolute" , _lowerCAmelCase: List[str]=True , _lowerCAmelCase: Optional[Any]=None , _lowerCAmelCase: Any=False , _lowerCAmelCase: Union[str, Any]=2 , _lowerCAmelCase: str=False , _lowerCAmelCase: Any=True , _lowerCAmelCase: Optional[Any]=True , _lowerCAmelCase: List[Any]=("en_XX",) , _lowerCAmelCase: Tuple=None , **_lowerCAmelCase: Optional[int] , ) -> Tuple:
'''simple docstring'''
super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase )
UpperCAmelCase_ =vocab_size
UpperCAmelCase_ =hidden_size
UpperCAmelCase_ =num_hidden_layers
UpperCAmelCase_ =num_attention_heads
UpperCAmelCase_ =hidden_act
UpperCAmelCase_ =intermediate_size
UpperCAmelCase_ =hidden_dropout_prob
UpperCAmelCase_ =attention_probs_dropout_prob
UpperCAmelCase_ =max_position_embeddings
UpperCAmelCase_ =type_vocab_size
UpperCAmelCase_ =initializer_range
UpperCAmelCase_ =layer_norm_eps
UpperCAmelCase_ =position_embedding_type
UpperCAmelCase_ =use_cache
UpperCAmelCase_ =classifier_dropout
UpperCAmelCase_ =pre_norm
UpperCAmelCase_ =adapter_reduction_factor
UpperCAmelCase_ =adapter_layer_norm
UpperCAmelCase_ =adapter_reuse_layer_norm
UpperCAmelCase_ =ln_before_adapter
UpperCAmelCase_ =list(_lowerCAmelCase )
UpperCAmelCase_ =default_language
class A ( __lowercase ):
@property
def lowerCAmelCase__ ( self: Union[str, Any] ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
if self.task == "multiple-choice":
UpperCAmelCase_ ={0: "batch", 1: "choice", 2: "sequence"}
else:
UpperCAmelCase_ ={0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 54 |
"""simple docstring"""
from collections import deque
from math import floor
from random import random
from time import time
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self : Union[str, Any] ):
lowerCAmelCase__ : List[str] = {}
def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : Optional[Any] ,lowercase_ : str ,lowercase_ : List[str]=1 ):
if self.graph.get(lowercase_ ):
if self.graph[u].count([w, v] ) == 0:
self.graph[u].append([w, v] )
else:
lowerCAmelCase__ : Optional[int] = [[w, v]]
if not self.graph.get(lowercase_ ):
lowerCAmelCase__ : Union[str, Any] = []
def __lowerCAmelCase ( self : List[Any] ):
return list(self.graph )
def __lowerCAmelCase ( self : Dict ,lowercase_ : Tuple ,lowercase_ : Tuple ):
if self.graph.get(lowercase_ ):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(lowercase_ )
def __lowerCAmelCase ( self : int ,lowercase_ : Any=-2 ,lowercase_ : List[Any]=-1 ):
if s == d:
return []
lowerCAmelCase__ : int = []
lowerCAmelCase__ : List[Any] = []
if s == -2:
lowerCAmelCase__ : int = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : int = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : List[Any] = s
for node in self.graph[s]:
if visited.count(node[1] ) < 1:
if node[1] == d:
visited.append(lowercase_ )
return visited
else:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : Optional[int] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(lowercase_ ) != 0:
lowerCAmelCase__ : str = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : Union[str, Any] = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return visited
def __lowerCAmelCase ( self : Dict ,lowercase_ : Optional[Any]=-1 ):
if c == -1:
lowerCAmelCase__ : Any = floor(random() * 1_0_0_0_0 ) + 1_0
for i in range(lowercase_ ):
# every vertex has max 100 edges
for _ in range(floor(random() * 1_0_2 ) + 1 ):
lowerCAmelCase__ : Any = floor(random() * c ) + 1
if n != i:
self.add_pair(lowercase_ ,lowercase_ ,1 )
def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : Union[str, Any]=-2 ):
lowerCAmelCase__ : Tuple = deque()
lowerCAmelCase__ : Tuple = []
if s == -2:
lowerCAmelCase__ : Any = list(self.graph )[0]
d.append(lowercase_ )
visited.append(lowercase_ )
while d:
lowerCAmelCase__ : Dict = d.popleft()
if len(self.graph[s] ) != 0:
for node in self.graph[s]:
if visited.count(node[1] ) < 1:
d.append(node[1] )
visited.append(node[1] )
return visited
def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : Optional[Any] ):
lowerCAmelCase__ : Optional[Any] = 0
for x in self.graph:
for y in self.graph[x]:
if y[1] == u:
count += 1
return count
def __lowerCAmelCase ( self : str ,lowercase_ : Optional[int] ):
return len(self.graph[u] )
def __lowerCAmelCase ( self : List[str] ,lowercase_ : List[str]=-2 ):
lowerCAmelCase__ : Union[str, Any] = []
lowerCAmelCase__ : Any = []
if s == -2:
lowerCAmelCase__ : Any = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : Tuple = s
lowerCAmelCase__ : Optional[int] = []
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : Optional[Any] = s
for node in self.graph[s]:
if visited.count(node[1] ) < 1:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : Dict = node[1]
break
# check if all the children are visited
if s == ss:
sorted_nodes.append(stack.pop() )
if len(lowercase_ ) != 0:
lowerCAmelCase__ : Union[str, Any] = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : int = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return sorted_nodes
def __lowerCAmelCase ( self : List[Any] ):
lowerCAmelCase__ : str = []
lowerCAmelCase__ : List[str] = []
lowerCAmelCase__ : int = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : List[Any] = -2
lowerCAmelCase__ : str = []
lowerCAmelCase__ : Optional[Any] = s
lowerCAmelCase__ : Union[str, Any] = False
lowerCAmelCase__ : Optional[int] = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : List[str] = s
for node in self.graph[s]:
if (
visited.count(node[1] ) > 0
and node[1] != parent
and indirect_parents.count(node[1] ) > 0
and not on_the_way_back
):
lowerCAmelCase__ : List[Any] = len(lowercase_ ) - 1
while len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1] )
break
else:
anticipating_nodes.add(stack[len_stack] )
len_stack -= 1
if visited.count(node[1] ) < 1:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : Optional[int] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
lowerCAmelCase__ : str = True
if len(lowercase_ ) != 0:
lowerCAmelCase__ : Tuple = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : int = False
indirect_parents.append(lowercase_ )
lowerCAmelCase__ : str = s
lowerCAmelCase__ : Tuple = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return list(lowercase_ )
def __lowerCAmelCase ( self : int ):
lowerCAmelCase__ : Tuple = []
lowerCAmelCase__ : Tuple = []
lowerCAmelCase__ : Any = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : List[str] = -2
lowerCAmelCase__ : int = []
lowerCAmelCase__ : int = s
lowerCAmelCase__ : List[Any] = False
lowerCAmelCase__ : List[str] = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : Optional[int] = s
for node in self.graph[s]:
if (
visited.count(node[1] ) > 0
and node[1] != parent
and indirect_parents.count(node[1] ) > 0
and not on_the_way_back
):
lowerCAmelCase__ : List[Any] = len(lowercase_ ) - 1
while len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1] )
break
else:
return True
if visited.count(node[1] ) < 1:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : Optional[Any] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
lowerCAmelCase__ : List[str] = True
if len(lowercase_ ) != 0:
lowerCAmelCase__ : Dict = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : Union[str, Any] = False
indirect_parents.append(lowercase_ )
lowerCAmelCase__ : Tuple = s
lowerCAmelCase__ : Union[str, Any] = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return False
def __lowerCAmelCase ( self : Any ,lowercase_ : List[Any]=-2 ,lowercase_ : Union[str, Any]=-1 ):
lowerCAmelCase__ : Optional[int] = time()
self.dfs(lowercase_ ,lowercase_ )
lowerCAmelCase__ : Any = time()
return end - begin
def __lowerCAmelCase ( self : Any ,lowercase_ : Dict=-2 ):
lowerCAmelCase__ : List[str] = time()
self.bfs(lowercase_ )
lowerCAmelCase__ : List[Any] = time()
return end - begin
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self : Union[str, Any] ):
lowerCAmelCase__ : Tuple = {}
def __lowerCAmelCase ( self : List[Any] ,lowercase_ : Optional[int] ,lowercase_ : Dict ,lowercase_ : Any=1 ):
# check if the u exists
if self.graph.get(lowercase_ ):
# if there already is a edge
if self.graph[u].count([w, v] ) == 0:
self.graph[u].append([w, v] )
else:
# if u does not exist
lowerCAmelCase__ : List[Any] = [[w, v]]
# add the other way
if self.graph.get(lowercase_ ):
# if there already is a edge
if self.graph[v].count([w, u] ) == 0:
self.graph[v].append([w, u] )
else:
# if u does not exist
lowerCAmelCase__ : int = [[w, u]]
def __lowerCAmelCase ( self : Dict ,lowercase_ : Union[str, Any] ,lowercase_ : Dict ):
if self.graph.get(lowercase_ ):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(lowercase_ )
# the other way round
if self.graph.get(lowercase_ ):
for _ in self.graph[v]:
if _[1] == u:
self.graph[v].remove(lowercase_ )
def __lowerCAmelCase ( self : int ,lowercase_ : Optional[int]=-2 ,lowercase_ : str=-1 ):
if s == d:
return []
lowerCAmelCase__ : Optional[Any] = []
lowerCAmelCase__ : Any = []
if s == -2:
lowerCAmelCase__ : Tuple = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : int = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : Optional[int] = s
for node in self.graph[s]:
if visited.count(node[1] ) < 1:
if node[1] == d:
visited.append(lowercase_ )
return visited
else:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : List[str] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(lowercase_ ) != 0:
lowerCAmelCase__ : str = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : Dict = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return visited
def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : List[Any]=-1 ):
if c == -1:
lowerCAmelCase__ : str = floor(random() * 1_0_0_0_0 ) + 1_0
for i in range(lowercase_ ):
# every vertex has max 100 edges
for _ in range(floor(random() * 1_0_2 ) + 1 ):
lowerCAmelCase__ : List[str] = floor(random() * c ) + 1
if n != i:
self.add_pair(lowercase_ ,lowercase_ ,1 )
def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : List[Any]=-2 ):
lowerCAmelCase__ : Tuple = deque()
lowerCAmelCase__ : List[Any] = []
if s == -2:
lowerCAmelCase__ : Tuple = list(self.graph )[0]
d.append(lowercase_ )
visited.append(lowercase_ )
while d:
lowerCAmelCase__ : Any = d.popleft()
if len(self.graph[s] ) != 0:
for node in self.graph[s]:
if visited.count(node[1] ) < 1:
d.append(node[1] )
visited.append(node[1] )
return visited
def __lowerCAmelCase ( self : Any ,lowercase_ : Any ):
return len(self.graph[u] )
def __lowerCAmelCase ( self : Any ):
lowerCAmelCase__ : List[Any] = []
lowerCAmelCase__ : int = []
lowerCAmelCase__ : List[Any] = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : Optional[int] = -2
lowerCAmelCase__ : List[str] = []
lowerCAmelCase__ : Tuple = s
lowerCAmelCase__ : Tuple = False
lowerCAmelCase__ : Union[str, Any] = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : Union[str, Any] = s
for node in self.graph[s]:
if (
visited.count(node[1] ) > 0
and node[1] != parent
and indirect_parents.count(node[1] ) > 0
and not on_the_way_back
):
lowerCAmelCase__ : Tuple = len(lowercase_ ) - 1
while len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1] )
break
else:
anticipating_nodes.add(stack[len_stack] )
len_stack -= 1
if visited.count(node[1] ) < 1:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : Optional[int] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
lowerCAmelCase__ : Optional[int] = True
if len(lowercase_ ) != 0:
lowerCAmelCase__ : str = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : Tuple = False
indirect_parents.append(lowercase_ )
lowerCAmelCase__ : Optional[int] = s
lowerCAmelCase__ : Optional[int] = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return list(lowercase_ )
def __lowerCAmelCase ( self : Optional[Any] ):
lowerCAmelCase__ : Optional[Any] = []
lowerCAmelCase__ : Union[str, Any] = []
lowerCAmelCase__ : Tuple = list(self.graph )[0]
stack.append(lowercase_ )
visited.append(lowercase_ )
lowerCAmelCase__ : Dict = -2
lowerCAmelCase__ : Union[str, Any] = []
lowerCAmelCase__ : Optional[Any] = s
lowerCAmelCase__ : Any = False
lowerCAmelCase__ : Optional[int] = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s] ) != 0:
lowerCAmelCase__ : str = s
for node in self.graph[s]:
if (
visited.count(node[1] ) > 0
and node[1] != parent
and indirect_parents.count(node[1] ) > 0
and not on_the_way_back
):
lowerCAmelCase__ : str = len(lowercase_ ) - 1
while len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1] )
break
else:
return True
if visited.count(node[1] ) < 1:
stack.append(node[1] )
visited.append(node[1] )
lowerCAmelCase__ : List[str] = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
lowerCAmelCase__ : List[Any] = True
if len(lowercase_ ) != 0:
lowerCAmelCase__ : List[str] = stack[len(lowercase_ ) - 1]
else:
lowerCAmelCase__ : List[str] = False
indirect_parents.append(lowercase_ )
lowerCAmelCase__ : Optional[int] = s
lowerCAmelCase__ : List[Any] = ss
# check if se have reached the starting point
if len(lowercase_ ) == 0:
return False
def __lowerCAmelCase ( self : str ):
return list(self.graph )
def __lowerCAmelCase ( self : Any ,lowercase_ : Optional[int]=-2 ,lowercase_ : Any=-1 ):
lowerCAmelCase__ : Dict = time()
self.dfs(lowercase_ ,lowercase_ )
lowerCAmelCase__ : List[str] = time()
return end - begin
def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : int=-2 ):
lowerCAmelCase__ : Dict = time()
self.bfs(lowercase_ )
lowerCAmelCase__ : Any = time()
return end - begin
| 450 | 0 |
"""simple docstring"""
import argparse
import json
from typing import List
from ltp import LTP
from transformers import BertTokenizer
def lowercase ( _snake_case : Union[str, Any] ) ->int:
"""simple docstring"""
if (
(cp >= 0x4e00 and cp <= 0x9fff)
or (cp >= 0x3400 and cp <= 0x4dbf) #
or (cp >= 0x2_0000 and cp <= 0x2_a6df) #
or (cp >= 0x2_a700 and cp <= 0x2_b73f) #
or (cp >= 0x2_b740 and cp <= 0x2_b81f) #
or (cp >= 0x2_b820 and cp <= 0x2_ceaf) #
or (cp >= 0xf900 and cp <= 0xfaff)
or (cp >= 0x2_f800 and cp <= 0x2_fa1f) #
): #
return True
return False
def lowercase ( _snake_case : Union[str, Any] ) ->int:
"""simple docstring"""
for char in word:
__snake_case : Tuple = ord(__SCREAMING_SNAKE_CASE )
if not _is_chinese_char(__SCREAMING_SNAKE_CASE ):
return 0
return 1
def lowercase ( _snake_case : Dict ) ->Dict:
"""simple docstring"""
__snake_case : Optional[int] = set()
for token in tokens:
__snake_case : Dict = len(__SCREAMING_SNAKE_CASE ) > 1 and is_chinese(__SCREAMING_SNAKE_CASE )
if chinese_word:
word_set.add(__SCREAMING_SNAKE_CASE )
__snake_case : int = list(__SCREAMING_SNAKE_CASE )
return word_list
def lowercase ( _snake_case : Union[str, Any] , _snake_case : int ) ->List[Any]:
"""simple docstring"""
if not chinese_word_set:
return bert_tokens
__snake_case : Dict = max([len(__SCREAMING_SNAKE_CASE ) for w in chinese_word_set] )
__snake_case : Optional[int] = bert_tokens
__snake_case : List[str] = 0, len(__SCREAMING_SNAKE_CASE )
while start < end:
__snake_case : Dict = True
if is_chinese(bert_word[start] ):
__snake_case : List[Any] = min(end - start , __SCREAMING_SNAKE_CASE )
for i in range(__SCREAMING_SNAKE_CASE , 1 , -1 ):
__snake_case : Dict = "".join(bert_word[start : start + i] )
if whole_word in chinese_word_set:
for j in range(start + 1 , start + i ):
__snake_case : Optional[Any] = "##" + bert_word[j]
__snake_case : str = start + i
__snake_case : Dict = False
break
if single_word:
start += 1
return bert_word
def lowercase ( _snake_case : Tuple , _snake_case : Any , _snake_case : Union[str, Any] ) ->Dict:
"""simple docstring"""
__snake_case : Union[str, Any] = []
for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , 100 ):
__snake_case : Tuple = ltp_tokenizer.seg(lines[i : i + 100] )[0]
__snake_case : Optional[int] = [get_chinese_word(__SCREAMING_SNAKE_CASE ) for r in res]
ltp_res.extend(__SCREAMING_SNAKE_CASE )
assert len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE )
__snake_case : Optional[Any] = []
for i in range(0 , len(__SCREAMING_SNAKE_CASE ) , 100 ):
__snake_case : str = bert_tokenizer(lines[i : i + 100] , add_special_tokens=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=512 )
bert_res.extend(res['''input_ids'''] )
assert len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE )
__snake_case : int = []
for input_ids, chinese_word in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
__snake_case : List[str] = []
for id in input_ids:
__snake_case : List[str] = bert_tokenizer._convert_id_to_token(__SCREAMING_SNAKE_CASE )
input_tokens.append(__SCREAMING_SNAKE_CASE )
__snake_case : Optional[Any] = add_sub_symbol(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
__snake_case : Any = []
# We only save pos of chinese subwords start with ##, which mean is part of a whole word.
for i, token in enumerate(__SCREAMING_SNAKE_CASE ):
if token[:2] == "##":
__snake_case : List[str] = token[2:]
# save chinese tokens' pos
if len(__SCREAMING_SNAKE_CASE ) == 1 and _is_chinese_char(ord(__SCREAMING_SNAKE_CASE ) ):
ref_id.append(__SCREAMING_SNAKE_CASE )
ref_ids.append(__SCREAMING_SNAKE_CASE )
assert len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE )
return ref_ids
def lowercase ( _snake_case : List[Any] ) ->Tuple:
"""simple docstring"""
with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f:
__snake_case : List[Any] = f.readlines()
__snake_case : Dict = [line.strip() for line in data if len(__SCREAMING_SNAKE_CASE ) > 0 and not line.isspace()] # avoid delimiter like '\u2029'
__snake_case : int = LTP(args.ltp ) # faster in GPU device
__snake_case : Dict = BertTokenizer.from_pretrained(args.bert )
__snake_case : List[str] = prepare_ref(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f:
__snake_case : str = [json.dumps(__SCREAMING_SNAKE_CASE ) + "\n" for ref in ref_ids]
f.writelines(__SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser(description="""prepare_chinese_ref""")
parser.add_argument(
"""--file_name""",
type=str,
default="""./resources/chinese-demo.txt""",
help="""file need process, same as training data in lm""",
)
parser.add_argument(
"""--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path"""
)
parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""")
parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""")
SCREAMING_SNAKE_CASE : Tuple = parser.parse_args()
main(args)
| 704 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
SCREAMING_SNAKE_CASE : Optional[int] = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE : List[Any] = [
"""VAN_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""VanForImageClassification""",
"""VanModel""",
"""VanPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_van import (
VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
VanForImageClassification,
VanModel,
VanPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 229 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.