code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowercase : Optional[Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase ) class __snake_case ( lowerCAmelCase ): def __init__( self ,**snake_case ): '''simple docstring''' super().__init__(**snake_case ) if self.framework != "pt": raise ValueError(f"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self ,snake_case ,**snake_case ): '''simple docstring''' return super().__call__(snake_case ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' lowercase : Union[str, Any] = {} if "candidate_labels" in kwargs: lowercase : List[str] = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: lowercase : Dict = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=None ,snake_case="This is a sound of {}." ): '''simple docstring''' if isinstance(snake_case ,snake_case ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png lowercase : Optional[Any] = requests.get(snake_case ).content else: with open(snake_case ,"""rb""" ) as f: lowercase : Union[str, Any] = f.read() if isinstance(snake_case ,snake_case ): lowercase : int = ffmpeg_read(snake_case ,self.feature_extractor.sampling_rate ) if not isinstance(snake_case ,np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) lowercase : Dict = self.feature_extractor( [audio] ,sampling_rate=self.feature_extractor.sampling_rate ,return_tensors="""pt""" ) lowercase : Tuple = candidate_labels lowercase : Tuple = [hypothesis_template.format(snake_case ) for x in candidate_labels] lowercase : Optional[Any] = self.tokenizer(snake_case ,return_tensors=self.framework ,padding=snake_case ) lowercase : Optional[Any] = [text_inputs] return inputs def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : List[str] = model_inputs.pop("""candidate_labels""" ) lowercase : Dict = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] ,snake_case ): lowercase : List[Any] = text_inputs[0] else: # Batching case. lowercase : Dict = text_inputs[0][0] lowercase : Optional[Any] = self.model(**snake_case ,**snake_case ) lowercase : Any = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : List[Any] = model_outputs.pop("""candidate_labels""" ) lowercase : Any = model_outputs["""logits"""][0] if self.framework == "pt": lowercase : Any = logits.softmax(dim=0 ) lowercase : Tuple = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) lowercase : Tuple = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(snake_case ,snake_case ) ,key=lambda snake_case : -x[0] ) ] return result
20
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Any = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class _lowerCamelCase( _a ): lowercase_ : str = """ctrl""" lowercase_ : Dict = ["""past_key_values"""] lowercase_ : Any = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self, lowerCamelCase=24_65_34, lowerCamelCase=2_56, lowerCamelCase=12_80, lowerCamelCase=81_92, lowerCamelCase=48, lowerCamelCase=16, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=1E-6, lowerCamelCase=0.0_2, lowerCamelCase=True, **lowerCamelCase, ) -> List[str]: """simple docstring""" _lowercase : Tuple = vocab_size _lowercase : List[str] = n_positions _lowercase : int = n_embd _lowercase : Dict = n_layer _lowercase : List[Any] = n_head _lowercase : str = dff _lowercase : Optional[int] = resid_pdrop _lowercase : int = embd_pdrop _lowercase : Optional[Any] = layer_norm_epsilon _lowercase : Any = initializer_range _lowercase : List[str] = use_cache super().__init__(**lowerCamelCase)
21
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
0
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : int = 100 ) -> int: '''simple docstring''' _UpperCAmelCase = set() _UpperCAmelCase = 0 _UpperCAmelCase = n + 1 # maximum limit for a in range(2 , __lowercase ): for b in range(2 , __lowercase ): _UpperCAmelCase = a**b # calculates the current power collect_powers.add(__lowercase ) # adds the result to the set return len(__lowercase ) if __name__ == "__main__": print('''Number of terms ''', solution(int(str(input()).strip())))
22
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 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(lowerCAmelCase_ ): 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: a__ : List[str] = 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()
54
0
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE( A__ , unittest.TestCase ): """simple docstring""" lowerCamelCase__ = MobileBertTokenizer lowerCamelCase__ = MobileBertTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True lowerCamelCase__ = filter_non_english lowerCamelCase__ = """google/mobilebert-uncased""" def A ( self : Any ) -> int: super().setUp() UpperCAmelCase : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCAmelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) UpperCAmelCase : List[Any] = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def A ( self : Optional[Any] , __snake_case : Union[str, Any] ) -> Optional[Any]: UpperCAmelCase : Optional[Any] = '''UNwant\u00E9d,running''' UpperCAmelCase : int = '''unwanted, running''' return input_text, output_text def A ( self : Optional[Any] ) -> Dict: UpperCAmelCase : List[str] = self.tokenizer_class(self.vocab_file ) UpperCAmelCase : Dict = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__snake_case , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [9, 6, 7, 12, 10, 11] ) def A ( self : Any ) -> int: if not self.test_rust_tokenizer: return UpperCAmelCase : Optional[int] = self.get_tokenizer() UpperCAmelCase : Any = self.get_rust_tokenizer() UpperCAmelCase : int = '''UNwant\u00E9d,running''' UpperCAmelCase : Dict = tokenizer.tokenize(__snake_case ) UpperCAmelCase : Optional[int] = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Optional[int] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : int = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : int = self.get_rust_tokenizer() UpperCAmelCase : int = tokenizer.encode(__snake_case ) UpperCAmelCase : str = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) # With lower casing UpperCAmelCase : Dict = self.get_tokenizer(do_lower_case=__snake_case ) UpperCAmelCase : int = self.get_rust_tokenizer(do_lower_case=__snake_case ) UpperCAmelCase : Dict = '''UNwant\u00E9d,running''' UpperCAmelCase : int = tokenizer.tokenize(__snake_case ) UpperCAmelCase : List[Any] = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : int = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : List[Any] = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Optional[Any] = self.get_rust_tokenizer() UpperCAmelCase : Union[str, Any] = tokenizer.encode(__snake_case ) UpperCAmelCase : Union[str, Any] = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) def A ( self : List[str] ) -> List[str]: UpperCAmelCase : str = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def A ( self : Optional[int] ) -> Any: UpperCAmelCase : Tuple = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : Optional[int] ) -> int: UpperCAmelCase : Optional[Any] = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def A ( self : Union[str, Any] ) -> Optional[Any]: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : str ) -> Optional[int]: UpperCAmelCase : Any = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : Union[str, Any] ) -> Optional[int]: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Tuple ) -> Any: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Optional[int] ) -> Union[str, Any]: UpperCAmelCase : List[str] = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase : Tuple = BasicTokenizer(do_lower_case=__snake_case , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def A ( self : List[Any] ) -> Dict: UpperCAmelCase : List[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] UpperCAmelCase : Tuple = {} for i, token in enumerate(__snake_case ): UpperCAmelCase : List[str] = i UpperCAmelCase : str = WordpieceTokenizer(vocab=__snake_case , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def A ( self : Union[str, Any] ) -> Tuple: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def A ( self : Union[str, Any] ) -> Any: self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def A ( self : Optional[int] ) -> Tuple: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def A ( self : Union[str, Any] ) -> List[str]: UpperCAmelCase : Dict = self.get_tokenizer() UpperCAmelCase : int = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__snake_case ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__snake_case ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def A ( self : Union[str, Any] ) -> Optional[int]: UpperCAmelCase : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) UpperCAmelCase : Dict = tokenizer.encode('''sequence builders''' , add_special_tokens=__snake_case ) UpperCAmelCase : List[str] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__snake_case ) UpperCAmelCase : Any = tokenizer.build_inputs_with_special_tokens(__snake_case ) UpperCAmelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def A ( self : Optional[Any] ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase : Dict = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : str = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" UpperCAmelCase : Optional[int] = tokenizer_r.encode_plus( __snake_case , return_attention_mask=__snake_case , return_token_type_ids=__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case , ) UpperCAmelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__snake_case , '''do_lower_case''' ) else False UpperCAmelCase : str = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def A ( self : Optional[int] ) -> str: UpperCAmelCase : str = ['''的''', '''人''', '''有'''] UpperCAmelCase : List[Any] = ''''''.join(__snake_case ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase : Union[str, Any] = True UpperCAmelCase : List[str] = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : int = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : List[Any] = tokenizer_p.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Tuple = tokenizer_r.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Any = tokenizer_r.convert_ids_to_tokens(__snake_case ) UpperCAmelCase : Optional[int] = tokenizer_p.convert_ids_to_tokens(__snake_case ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__snake_case , __snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Union[str, Any] = False UpperCAmelCase : int = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : int = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : List[Any] = tokenizer_r.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Tuple = tokenizer_p.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : List[str] = tokenizer_r.convert_ids_to_tokens(__snake_case ) UpperCAmelCase : Optional[int] = tokenizer_p.convert_ids_to_tokens(__snake_case ) # it is expected that only the first Chinese character is not preceded by "##". UpperCAmelCase : Optional[Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(__snake_case ) ] self.assertListEqual(__snake_case , __snake_case ) self.assertListEqual(__snake_case , __snake_case )
23
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): A_ : Optional[Any] = 't5' A_ : str = ['past_key_values'] A_ : Optional[Any] = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__(self : Optional[int] , a__ : int=3_2128 , a__ : Dict=512 , a__ : Optional[Any]=64 , a__ : Dict=2048 , a__ : Optional[Any]=6 , a__ : int=None , a__ : List[Any]=8 , a__ : int=32 , a__ : Union[str, Any]=128 , a__ : str=0.1 , a__ : str=1E-6 , a__ : str=1.0 , a__ : Union[str, Any]="relu" , a__ : Any=True , a__ : Optional[int]=True , a__ : Any=0 , a__ : str=1 , **a__ : List[Any] , ): """simple docstring""" __snake_case = vocab_size __snake_case = d_model __snake_case = d_kv __snake_case = d_ff __snake_case = num_layers __snake_case = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case = num_heads __snake_case = relative_attention_num_buckets __snake_case = relative_attention_max_distance __snake_case = dropout_rate __snake_case = layer_norm_epsilon __snake_case = initializer_factor __snake_case = feed_forward_proj __snake_case = use_cache __snake_case = self.feed_forward_proj.split('''-''' ) __snake_case = act_info[-1] __snake_case = act_info[0] == '''gated''' if len(a__ ) > 1 and act_info[0] != "gated" or len(a__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case = '''gelu_new''' super().__init__( pad_token_id=a__ , eos_token_id=a__ , is_encoder_decoder=a__ , **a__ , ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def a (self : int ): """simple docstring""" __snake_case = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: __snake_case = '''past_encoder_sequence + sequence''' __snake_case = {0: '''batch'''} __snake_case = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: __snake_case = {0: '''batch''', 1: '''decoder_sequence'''} __snake_case = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(a__ , direction='''inputs''' ) return common_inputs @property def a (self : int ): """simple docstring""" return 13
24
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
"""simple docstring""" import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Dict = R"""\w+[.]\d+""" SCREAMING_SNAKE_CASE__ : Dict = re.findall(_snake_case ,_snake_case ) for pat in pats: SCREAMING_SNAKE_CASE__ : Dict = key.replace(_snake_case ,"""_""".join(pat.split(""".""" ) ) ) return key def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = pt_tuple_key[:-1] + ("""scale""",) if ( any("""norm""" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): SCREAMING_SNAKE_CASE__ : Tuple = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: SCREAMING_SNAKE_CASE__ : List[Any] = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: SCREAMING_SNAKE_CASE__ : Any = pt_tuple_key[:-1] + ("""embedding""",) return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE__ : str = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: SCREAMING_SNAKE_CASE__ : Tuple = pt_tensor.transpose(2 ,3 ,1 ,0 ) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE__ : Dict = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight": SCREAMING_SNAKE_CASE__ : str = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE__ : List[str] = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE__ : str = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowercase_ ( _snake_case ,_snake_case ,_snake_case=42 ): # Step 1: Convert pytorch tensor to numpy SCREAMING_SNAKE_CASE__ : str = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params SCREAMING_SNAKE_CASE__ : Optional[int] = flax_model.init_weights(PRNGKey(_snake_case ) ) SCREAMING_SNAKE_CASE__ : Any = flatten_dict(_snake_case ) SCREAMING_SNAKE_CASE__ : Dict = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE__ : Dict = rename_key(_snake_case ) SCREAMING_SNAKE_CASE__ : Dict = tuple(renamed_pt_key.split(""".""" ) ) # Correctly rename weight parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = rename_key_and_reshape_tensor(_snake_case ,_snake_case ,_snake_case ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE__ : List[str] = jnp.asarray(_snake_case ) return unflatten_dict(_snake_case )
25
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
def lowerCAmelCase_ ( snake_case_ ): if not isinstance(snake_case_,snake_case_ ): raise TypeError("""only integers accepted as input""" ) else: _A : int = str(abs(snake_case_ ) ) _A : Dict = [list(snake_case_ ) for char in range(len(snake_case_ ) )] for index in range(len(snake_case_ ) ): num_transpositions[index].pop(snake_case_ ) return max( int("""""".join(list(snake_case_ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
26
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
'''simple docstring''' import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): # Initialise PyTorch model __a : int = AlbertConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"""Building PyTorch model from configuration: {config}""" ) __a : Optional[Any] = AlbertForPreTraining(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_albert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--albert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained ALBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __lowercase : List[str] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
27
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __lowerCamelCase ( A__ ) -> bool: """simple docstring""" UpperCamelCase = int(number**0.5 ) return number == sq * sq def __lowerCamelCase ( A__ , A__ , A__ , A__ , A__ , A__ ) -> tuple[int, int]: """simple docstring""" UpperCamelCase = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase = x_den * y_den * z_den UpperCamelCase = gcd(A__ , A__ ) top //= hcf bottom //= hcf return top, bottom def __lowerCamelCase ( A__ = 35 ) -> int: """simple docstring""" UpperCamelCase = set() UpperCamelCase = 42 UpperCamelCase = Fraction(0 ) UpperCamelCase = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCamelCase = x_num * y_den + x_den * y_num UpperCamelCase = x_den * y_den UpperCamelCase = gcd(A__ , A__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase = add_three( A__ , A__ , A__ , A__ , A__ , A__ ) unique_s.add(A__ ) # n=2 UpperCamelCase = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase = x_den * x_den * y_den * y_den if is_sq(A__ ) and is_sq(A__ ): UpperCamelCase = int(sqrt(A__ ) ) UpperCamelCase = int(sqrt(A__ ) ) UpperCamelCase = gcd(A__ , A__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase = add_three( A__ , A__ , A__ , A__ , A__ , A__ ) unique_s.add(A__ ) # n=-1 UpperCamelCase = x_num * y_num UpperCamelCase = x_den * y_num + x_num * y_den UpperCamelCase = gcd(A__ , A__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase = add_three( A__ , A__ , A__ , A__ , A__ , A__ ) unique_s.add(A__ ) # n=2 UpperCamelCase = x_num * x_num * y_num * y_num UpperCamelCase = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(A__ ) and is_sq(A__ ): UpperCamelCase = int(sqrt(A__ ) ) UpperCamelCase = int(sqrt(A__ ) ) UpperCamelCase = gcd(A__ , A__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase = add_three( A__ , A__ , A__ , A__ , A__ , A__ ) unique_s.add(A__ ) for num, den in unique_s: total += Fraction(A__ , A__ ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
28
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
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 lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase=1_3 , _UpperCamelCase=7 , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=9_9 , _UpperCamelCase=6_4 , _UpperCamelCase=3_2 , _UpperCamelCase=5 , _UpperCamelCase=4 , _UpperCamelCase=3_7 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=5_1_2 , _UpperCamelCase=1_6 , _UpperCamelCase=2 , _UpperCamelCase=0.02 , _UpperCamelCase=3 , _UpperCamelCase=4 , _UpperCamelCase=None , ) -> Tuple: UpperCAmelCase_ : Union[str, Any] = parent UpperCAmelCase_ : Tuple = batch_size UpperCAmelCase_ : Dict = seq_length UpperCAmelCase_ : str = is_training UpperCAmelCase_ : str = use_input_mask UpperCAmelCase_ : Tuple = use_token_type_ids UpperCAmelCase_ : Optional[Any] = use_labels UpperCAmelCase_ : List[Any] = vocab_size UpperCAmelCase_ : Any = hidden_size UpperCAmelCase_ : Optional[int] = embedding_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : Optional[Any] = num_attention_heads UpperCAmelCase_ : Any = intermediate_size UpperCAmelCase_ : List[Any] = hidden_act UpperCAmelCase_ : Dict = hidden_dropout_prob UpperCAmelCase_ : Optional[int] = attention_probs_dropout_prob UpperCAmelCase_ : Tuple = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : Optional[int] = type_sequence_label_size UpperCAmelCase_ : Tuple = initializer_range UpperCAmelCase_ : List[Any] = num_labels UpperCAmelCase_ : str = num_choices UpperCAmelCase_ : Optional[Any] = scope def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Any = None if self.use_input_mask: UpperCAmelCase_ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : Tuple = None if self.use_token_type_ids: UpperCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Any = None UpperCAmelCase_ : Any = None UpperCAmelCase_ : Any = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ) -> Optional[Any]: 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=_UpperCamelCase , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: UpperCAmelCase_ : Dict = MegatronBertModel(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Dict = model(_UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase ) UpperCAmelCase_ : Optional[int] = model(_UpperCamelCase , token_type_ids=_UpperCamelCase ) UpperCAmelCase_ : Tuple = 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 __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: UpperCAmelCase_ : List[Any] = MegatronBertForMaskedLM(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Tuple = model(_UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: UpperCAmelCase_ : Any = MegatronBertForCausalLM(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : List[Any] = 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 __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> str: UpperCAmelCase_ : Optional[int] = MegatronBertForNextSentencePrediction(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Optional[Any] = model( _UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: UpperCAmelCase_ : Optional[int] = MegatronBertForPreTraining(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : List[str] = model( _UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase , next_sentence_label=_UpperCamelCase , ) 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 __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: UpperCAmelCase_ : Optional[int] = MegatronBertForQuestionAnswering(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Dict = 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 __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: UpperCAmelCase_ : Union[str, Any] = self.num_labels UpperCAmelCase_ : List[Any] = MegatronBertForSequenceClassification(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Any = model(_UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> str: UpperCAmelCase_ : Union[str, Any] = self.num_labels UpperCAmelCase_ : Optional[Any] = MegatronBertForTokenClassification(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Optional[int] = model(_UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: UpperCAmelCase_ : Optional[int] = self.num_choices UpperCAmelCase_ : str = MegatronBertForMultipleChoice(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() UpperCAmelCase_ : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : Tuple = model( _UpperCamelCase , attention_mask=_UpperCamelCase , token_type_ids=_UpperCamelCase , labels=_UpperCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase_ : Dict = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Optional[Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCamelCase (_snake_case , _snake_case , unittest.TestCase ): '''simple docstring''' _snake_case : Tuple = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) _snake_case : str = ( { '''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 {} ) _snake_case : Any = True # test_resize_embeddings = False _snake_case : List[str] = False def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=False ) -> Any: UpperCAmelCase_ : Dict = super()._prepare_for_class(_UpperCamelCase , _UpperCamelCase , return_labels=_UpperCamelCase ) if return_labels: if model_class in get_values(_UpperCamelCase ): UpperCAmelCase_ : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_UpperCamelCase ) UpperCAmelCase_ : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_UpperCamelCase ) return inputs_dict def __UpperCAmelCase ( self ) -> Tuple: UpperCAmelCase_ : int = MegatronBertModelTester(self ) UpperCAmelCase_ : Dict = ConfigTester(self , config_class=_UpperCamelCase , hidden_size=3_7 ) def __UpperCAmelCase ( self ) -> Optional[int]: self.config_tester.run_common_tests() def __UpperCAmelCase ( self ) -> Any: UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> str: UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> List[str]: UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> str: UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> int: UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*_UpperCamelCase ) def lowercase__ ( __snake_case : Optional[Any] ): '''simple docstring''' return torch.tensor( __snake_case , dtype=torch.long , device=__snake_case , ) __UpperCAmelCase = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase (unittest.TestCase ): '''simple docstring''' @slow @unittest.skip('Model is not available.' ) def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase_ : int = 'nvidia/megatron-bert-uncased-345m' if "MYDIR" in os.environ: UpperCAmelCase_ : List[str] = os.path.join(os.environ['MYDIR'] , _UpperCamelCase ) UpperCAmelCase_ : Tuple = MegatronBertModel.from_pretrained(_UpperCamelCase ) model.to(_UpperCamelCase ) model.half() UpperCAmelCase_ : Any = _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]] ) with torch.no_grad(): UpperCAmelCase_ : str = model(_UpperCamelCase )[0] UpperCAmelCase_ : List[Any] = torch.Size((1, 9, 1_0_2_4) ) self.assertEqual(output.shape , _UpperCamelCase ) UpperCAmelCase_ : Optional[int] = [-0.60_40, -0.25_17, -0.10_25, 0.34_20, -0.67_58, -0.00_17, -0.10_89, -0.19_90, 0.57_28] for ii in range(3 ): for jj in range(3 ): UpperCAmelCase_ : Optional[int] = output[0, ii, jj] UpperCAmelCase_ : Any = expected[3 * ii + jj] UpperCAmelCase_ : List[Any] = 'ii={} jj={} a={} b={}'.format(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) self.assertTrue(math.isclose(_UpperCamelCase , _UpperCamelCase , rel_tol=_UpperCamelCase , abs_tol=_UpperCamelCase ) , msg=_UpperCamelCase )
29
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
30
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
'''simple docstring''' __SCREAMING_SNAKE_CASE : int = """Alexander Joslin""" import operator as op from .stack import Stack def UpperCamelCase_ ( _UpperCAmelCase : str ) -> int: """simple docstring""" _UpperCAmelCase : Tuple = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} _UpperCAmelCase : Stack[int] = Stack() _UpperCAmelCase : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase ) ) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase ) elif i == ")": # RULE 4 _UpperCAmelCase : str = operator_stack.peek() operator_stack.pop() _UpperCAmelCase : List[str] = operand_stack.peek() operand_stack.pop() _UpperCAmelCase : List[str] = operand_stack.peek() operand_stack.pop() _UpperCAmelCase : List[Any] = operators[opr](_UpperCAmelCase , _UpperCAmelCase ) operand_stack.push(_UpperCAmelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'{equation} = {dijkstras_two_stack_algorithm(equation)}')
31
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : int = BertJapaneseTokenizer snake_case__ : Optional[int] = False snake_case__ : Union[str, Any] = True def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: super().setUp() a_ : Optional[Any] = [ '[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは', '世界', '##世界', '、', '##、', '。', '##。', ] a_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: a_ : Optional[int] = 'こんにちは、世界。 \nこんばんは、世界。' a_ : Optional[Any] = 'こんにちは 、 世界 。 こんばんは 、 世界 。' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> int: a_ , a_ : int = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: a_ : Union[str, Any] = self.tokenizer_class(self.vocab_file ) a_ : str = tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: a_ : str = self.tokenizer_class(self.vocab_file , word_tokenizer_type='mecab' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) a_ : str = 'こんにちは、世界。\nこんばんは、世界。' a_ : List[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] ) a_ : Optional[int] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as handle: pickle.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as handle: a_ : Union[str, Any] = pickle.load(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer_new.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: a_ : List[str] = MecabTokenizer(mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: try: a_ : List[str] = MecabTokenizer(mecab_dic='unidic_lite' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: try: a_ : Union[str, Any] = MecabTokenizer(mecab_dic='unidic' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def SCREAMING_SNAKE_CASE ( self : str ) -> Any: a_ : Optional[Any] = MecabTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: try: a_ : Any = MecabTokenizer( do_lower_case=SCREAMING_SNAKE_CASE__ , normalize_text=SCREAMING_SNAKE_CASE__ , mecab_option='-d /usr/local/lib/mecab/dic/jumandic' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '\u3000', '。'] , ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: a_ : int = MecabTokenizer(normalize_text=SCREAMING_SNAKE_CASE__ , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', ' ', '。'] , ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : List[str] = self.tokenizer_class(self.vocab_file , word_tokenizer_type='sudachi' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = 'こんにちは、世界。\nこんばんは、世界。' a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] ) a_ : int = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as handle: pickle.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as handle: a_ : Union[str, Any] = pickle.load(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer_new.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : List[str] = SudachiTokenizer(sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: a_ : List[Any] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='A' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国', '人', '参政', '権'] ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Tuple = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='B' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人', '参政権'] ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: a_ : Union[str, Any] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='C' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人参政権'] ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: a_ : Dict = SudachiTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: a_ : Any = SudachiTokenizer(normalize_text=SCREAMING_SNAKE_CASE__ , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' '] , ) @require_sudachi def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: a_ : int = SudachiTokenizer(trim_whitespace=SCREAMING_SNAKE_CASE__ , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: a_ : Tuple = self.tokenizer_class(self.vocab_file , word_tokenizer_type='jumanpp' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) a_ : Any = 'こんにちは、世界。\nこんばんは、世界。' a_ : List[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] ) a_ : Optional[int] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as handle: pickle.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as handle: a_ : Optional[Any] = pickle.load(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer_new.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: a_ : Optional[Any] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Union[str, Any] = JumanppTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: a_ : Optional[int] = JumanppTokenizer(normalize_text=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['ア', 'ッ', 'フ', '゚', 'ル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : Any ) -> int: a_ : Dict = JumanppTokenizer(trim_whitespace=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。'] , ) @require_jumanpp def SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: a_ : str = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('ありがとうございますm(_ _)m見つけるのが大変です。' ) , ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。'] , ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: a_ : Tuple = ['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは'] a_ : List[Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): a_ : List[str] = i a_ : Dict = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE__ , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こんにちは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは' ) , ['こん', '##ばんは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは' ) , ['こん', '##ばんは', '[UNK]', 'こんにちは'] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: a_ : List[str] = BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp' ) a_ : List[str] = tokenizer.subword_tokenizer a_ : Optional[int] = subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。'] ) a_ : Optional[int] = subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは'] ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: a_ : Optional[Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese' ) a_ : int = tokenizer.encode('ありがとう。' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.encode('どういたしまして。' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Optional[int] = BertJapaneseTokenizer snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : str ) -> Any: super().setUp() a_ : int = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] a_ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='character' , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: a_ : List[Any] = 'こんにちは、世界。 \nこんばんは、世界。' a_ : Optional[Any] = 'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: a_ : Optional[int] = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='character' ) a_ : Any = tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [3, 4, 5, 6, 7, 1_1, 9, 1_0, 1_2, 3, 4, 8, 4, 7, 1_1, 9, 1_0, 1_2] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Dict = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] a_ : Dict = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): a_ : str = i a_ : Optional[Any] = CharacterTokenizer(vocab=SCREAMING_SNAKE_CASE__ , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こ', 'ん', 'に', 'ち', 'は'] ) self.assertListEqual(tokenizer.tokenize('こんにちほ' ) , ['こ', 'ん', 'に', 'ち', '[UNK]'] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Union[str, Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char' ) a_ : Optional[Any] = tokenizer.encode('ありがとう。' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode('どういたしまして。' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: a_ : int = 'cl-tohoku/bert-base-japanese' a_ : Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : List[str] = 'cl-tohoku/bert-base-japanese' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) ) a_ : Tuple = 'bert-base-cased' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) )
32
"""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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
0
"""simple docstring""" def lowercase ( __snake_case : Union[str, Any] , __snake_case : Tuple ): lowercase_ : Tuple = [1] for i in range(2 , __snake_case ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" lowercase_ : str = [] lowercase_ : str = list(range(__snake_case ) ) # Find permutation while factorials: lowercase_ : int = factorials.pop() lowercase_ , lowercase_ : List[Any] = divmod(__snake_case , __snake_case ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
33
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
0
'''simple docstring''' from __future__ import annotations def snake_case_ (_a : float , _a : float , _a : float ): if (voltage, current, resistance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance < 0: raise ValueError('''Resistance cannot be negative''' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
34
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
0
'''simple docstring''' import re import string import numpy as np import datasets __a = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" __a = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" __a = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def lowerCamelCase ( self : 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""" ), } ) , reference_urls=[] , ) def lowerCamelCase ( self : Tuple , snake_case_ : int , snake_case_ : Tuple , snake_case_ : List[Any]=None , snake_case_ : Any=False , snake_case_ : Optional[int]=False , snake_case_ : str=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: snake_case__ : int = np.array([re.sub(snake_case_ , """""" , snake_case_ ) for x in predictions] ) snake_case__ : Any = np.array([re.sub(snake_case_ , """""" , snake_case_ ) for x in references] ) else: snake_case__ : int = np.asarray(snake_case_ ) snake_case__ : Optional[int] = np.asarray(snake_case_ ) if ignore_case: snake_case__ : Dict = np.char.lower(snake_case_ ) snake_case__ : Tuple = np.char.lower(snake_case_ ) if ignore_punctuation: snake_case__ : str = string.punctuation.maketrans("""""" , """""" , string.punctuation ) snake_case__ : Tuple = np.char.translate(snake_case_ , table=snake_case_ ) snake_case__ : Dict = np.char.translate(snake_case_ , table=snake_case_ ) if ignore_numbers: snake_case__ : Any = string.digits.maketrans("""""" , """""" , string.digits ) snake_case__ : Union[str, Any] = np.char.translate(snake_case_ , table=snake_case_ ) snake_case__ : Union[str, Any] = np.char.translate(snake_case_ , table=snake_case_ ) snake_case__ : Tuple = predictions == references return {"exact_match": np.mean(snake_case_ ) * 100}
35
"""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_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["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 __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # 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})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
0
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( 'The RoBERTa Model transformer with early exiting (DeeRoBERTa). ' , a , ) class UpperCAmelCase_ ( a): lowerCamelCase__ = RobertaConfig lowerCamelCase__ = 'roberta' def __init__( self, __a): '''simple docstring''' super().__init__(__a) _lowerCAmelCase : Optional[Any] = RobertaEmbeddings(__a) self.init_weights() @add_start_docstrings( 'RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. ' , a , ) class UpperCAmelCase_ ( a): lowerCamelCase__ = RobertaConfig lowerCamelCase__ = 'roberta' def __init__( self, __a): '''simple docstring''' super().__init__(__a) _lowerCAmelCase : Optional[int] = config.num_labels _lowerCAmelCase : Optional[int] = config.num_hidden_layers _lowerCAmelCase : Optional[int] = DeeRobertaModel(__a) _lowerCAmelCase : Union[str, Any] = nn.Dropout(config.hidden_dropout_prob) _lowerCAmelCase : List[str] = nn.Linear(config.hidden_size, self.config.num_labels) @add_start_docstrings_to_model_forward(__a) def snake_case__ ( self, __a=None, __a=None, __a=None, __a=None, __a=None, __a=None, __a=None, __a=-1, __a=False, ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.num_layers try: _lowerCAmelCase : List[Any] = self.roberta( __a, attention_mask=__a, token_type_ids=__a, position_ids=__a, head_mask=__a, inputs_embeds=__a, ) _lowerCAmelCase : List[Any] = outputs[1] _lowerCAmelCase : Dict = self.dropout(__a) _lowerCAmelCase : Dict = self.classifier(__a) _lowerCAmelCase : Optional[Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase : Tuple = e.message _lowerCAmelCase : Union[str, Any] = e.exit_layer _lowerCAmelCase : List[Any] = outputs[0] if not self.training: _lowerCAmelCase : int = entropy(__a) _lowerCAmelCase : List[Any] = [] _lowerCAmelCase : str = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase : Optional[Any] = MSELoss() _lowerCAmelCase : int = loss_fct(logits.view(-1), labels.view(-1)) else: _lowerCAmelCase : Optional[Any] = CrossEntropyLoss() _lowerCAmelCase : Optional[Any] = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) # work with highway exits _lowerCAmelCase : Optional[int] = [] for highway_exit in outputs[-1]: _lowerCAmelCase : Any = highway_exit[0] if not self.training: highway_logits_all.append(__a) highway_entropy.append(highway_exit[2]) if self.num_labels == 1: # We are doing regression _lowerCAmelCase : List[str] = MSELoss() _lowerCAmelCase : List[Any] = loss_fct(highway_logits.view(-1), labels.view(-1)) else: _lowerCAmelCase : Dict = CrossEntropyLoss() _lowerCAmelCase : Optional[Any] = loss_fct(highway_logits.view(-1, self.num_labels), labels.view(-1)) highway_losses.append(__a) if train_highway: _lowerCAmelCase : int = (sum(highway_losses[:-1]),) + outputs # exclude the final highway, of course else: _lowerCAmelCase : Any = (loss,) + outputs if not self.training: _lowerCAmelCase : Optional[Any] = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase : Optional[Any] = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
36
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
0
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _lowerCAmelCase = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias""")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", F"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", F"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias""")) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('''input_proj.weight''', '''input_projection.weight'''), ('''input_proj.bias''', '''input_projection.bias'''), ('''query_embed.weight''', '''query_position_embeddings.weight'''), ('''transformer.encoder.norm.weight''', '''encoder.layernorm.weight'''), ('''transformer.encoder.norm.bias''', '''encoder.layernorm.bias'''), ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''), ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''), ('''class_embed.weight''', '''class_labels_classifier.weight'''), ('''class_embed.bias''', '''class_labels_classifier.bias'''), ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''), ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''), ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''), ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''), ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''), ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''), ] ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[Any] = state_dict.pop(UpperCamelCase ) lowerCAmelCase__ : Tuple = val def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Optional[int] = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: lowerCAmelCase__ : List[str] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) lowerCAmelCase__ : List[Any] = value else: lowerCAmelCase__ : Optional[int] = value return new_state_dict def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Tuple = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) lowerCAmelCase__ : Union[str, Any] = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) lowerCAmelCase__ : Any = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ : Union[str, Any] = in_proj_weight[:256, :] lowerCAmelCase__ : List[Any] = in_proj_bias[:256] lowerCAmelCase__ : str = in_proj_weight[256:512, :] lowerCAmelCase__ : Optional[int] = in_proj_bias[256:512] lowerCAmelCase__ : Union[str, Any] = in_proj_weight[-256:, :] lowerCAmelCase__ : str = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention lowerCAmelCase__ : List[str] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) lowerCAmelCase__ : Optional[Any] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ : Optional[int] = in_proj_weight[:256, :] lowerCAmelCase__ : Dict = in_proj_bias[:256] lowerCAmelCase__ : Any = in_proj_weight[256:512, :] lowerCAmelCase__ : Dict = in_proj_bias[256:512] lowerCAmelCase__ : Tuple = in_proj_weight[-256:, :] lowerCAmelCase__ : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention lowerCAmelCase__ : List[Any] = state_dict.pop( f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) lowerCAmelCase__ : List[str] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict lowerCAmelCase__ : str = in_proj_weight_cross_attn[:256, :] lowerCAmelCase__ : List[Any] = in_proj_bias_cross_attn[:256] lowerCAmelCase__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] lowerCAmelCase__ : str = in_proj_bias_cross_attn[256:512] lowerCAmelCase__ : Dict = in_proj_weight_cross_attn[-256:, :] lowerCAmelCase__ : str = in_proj_bias_cross_attn[-256:] def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : str = image.size lowerCAmelCase__ : Tuple = max(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : str = 800 if """detection""" in checkpoint_url else 1000 lowerCAmelCase__ : Union[str, Any] = target_max_size / current_max_size lowerCAmelCase__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Tuple = F.to_tensor(UpperCamelCase ) lowerCAmelCase__ : Union[str, Any] = F.normalize(UpperCamelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" logger.info("""Converting model...""" ) # load original state dict lowerCAmelCase__ : str = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Tuple = rename_backbone_keys(UpperCamelCase ) # query, key and value matrices need special treatment read_in_q_k_v(UpperCamelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them lowerCAmelCase__ : List[str] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): lowerCAmelCase__ : Optional[Any] = state_dict.pop(UpperCamelCase ) lowerCAmelCase__ : int = val # create HuggingFace model and load state dict lowerCAmelCase__ : List[str] = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: lowerCAmelCase__ : int = 15 lowerCAmelCase__ : Tuple = 2 lowerCAmelCase__ : Optional[Any] = {0: """table""", 1: """table rotated"""} lowerCAmelCase__ : Union[str, Any] = idalabel lowerCAmelCase__ : Tuple = {v: k for k, v in idalabel.items()} else: lowerCAmelCase__ : Optional[Any] = 125 lowerCAmelCase__ : int = 6 lowerCAmelCase__ : Union[str, Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } lowerCAmelCase__ : Any = idalabel lowerCAmelCase__ : Any = {v: k for k, v in idalabel.items()} lowerCAmelCase__ : List[Any] = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) lowerCAmelCase__ : Optional[int] = TableTransformerForObjectDetection(UpperCamelCase ) model.load_state_dict(UpperCamelCase ) model.eval() # verify our conversion lowerCAmelCase__ : List[Any] = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" lowerCAmelCase__ : int = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=UpperCamelCase ) lowerCAmelCase__ : List[str] = Image.open(UpperCamelCase ).convert("""RGB""" ) lowerCAmelCase__ : Union[str, Any] = normalize(resize(UpperCamelCase , UpperCamelCase ) ).unsqueeze(0 ) lowerCAmelCase__ : Tuple = model(UpperCamelCase ) if "detection" in checkpoint_url: lowerCAmelCase__ : List[str] = (1, 15, 3) lowerCAmelCase__ : Optional[Any] = torch.tensor( [[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]] ) lowerCAmelCase__ : Optional[Any] = torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]] ) else: lowerCAmelCase__ : Any = (1, 125, 7) lowerCAmelCase__ : str = torch.tensor( [[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]] ) lowerCAmelCase__ : List[str] = torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , UpperCamelCase , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , UpperCamelCase , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) model.save_pretrained(UpperCamelCase ) image_processor.save_pretrained(UpperCamelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) lowerCAmelCase__ : Optional[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(UpperCamelCase ) image_processor.push_to_hub(UpperCamelCase ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''', type=str, choices=[ '''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''', '''https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth''', ], help='''URL of the Table Transformer checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _lowerCAmelCase = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
37
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" if n == 1 or not isinstance(__magic_name__ , __magic_name__ ): return 0 elif n == 2: return 1 else: UpperCamelCase :List[Any] = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> int: """simple docstring""" UpperCamelCase :Dict = 0 UpperCamelCase :int = 2 while digits < n: index += 1 UpperCamelCase :Optional[Any] = len(str(fibonacci(__magic_name__ ) ) ) return index def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 1000 ) -> int: """simple docstring""" return fibonacci_digits_index(__magic_name__ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
38
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
0
import functools def __A ( __lowerCAmelCase , __lowerCAmelCase )-> int: """simple docstring""" _UpperCAmelCase = len(__lowerCAmelCase ) _UpperCAmelCase = len(__lowerCAmelCase ) @functools.cache def min_distance(__lowerCAmelCase , __lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa _UpperCAmelCase = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , __lowerCAmelCase ) , 1 + min_distance(__lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
39
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
0
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class _A : """simple docstring""" def __init__( self : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Any=12 , __UpperCAmelCase : List[str]=7 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Dict=99 , __UpperCAmelCase : Union[str, Any]=32 , __UpperCAmelCase : Union[str, Any]=32 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : int=4 , __UpperCAmelCase : Dict=37 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : str=0.1 , __UpperCAmelCase : Tuple=512 , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : Dict=None , ): a : int = parent a : List[Any] = batch_size a : Any = seq_length a : List[str] = is_training a : int = use_input_mask a : List[str] = use_labels a : Optional[int] = vocab_size a : Union[str, Any] = hidden_size a : int = projection_dim a : int = num_hidden_layers a : Dict = num_attention_heads a : Any = intermediate_size a : str = dropout a : List[Any] = attention_dropout a : Optional[int] = max_position_embeddings a : Any = initializer_range a : List[Any] = scope a : Tuple = bos_token_id def __snake_case ( self : int): a : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a : Dict = None if self.use_input_mask: a : int = random_attention_mask([self.batch_size, self.seq_length]) if input_mask is not None: a : Any = input_mask.numpy() a , a : Tuple = input_mask.shape a : int = np.random.randint(1 , seq_length - 1 , size=(batch_size,)) for batch_idx, start_index in enumerate(__UpperCAmelCase): a : int = 1 a : List[Any] = 0 a : Optional[Any] = self.get_config() return config, input_ids, tf.convert_to_tensor(__UpperCAmelCase) def __snake_case ( self : Tuple): return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def __snake_case ( self : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any]): a : Optional[Any] = TFBlipTextModel(config=__UpperCAmelCase) a : Any = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , training=__UpperCAmelCase) a : Optional[Any] = model(__UpperCAmelCase , training=__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 __snake_case ( self : Optional[int]): a : Optional[int] = self.prepare_config_and_inputs() a , a , a : str = config_and_inputs a : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _A ( _a ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : int = (TFBlipTextModel,) if is_tf_available() else () UpperCAmelCase : str = False UpperCAmelCase : List[Any] = False UpperCAmelCase : Optional[Any] = False def __snake_case ( self : Dict): a : Any = BlipTextModelTester(self) a : Optional[Any] = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37) def __snake_case ( self : int): self.config_tester.run_common_tests() def __snake_case ( self : List[Any]): a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase) def __snake_case ( self : int): pass def __snake_case ( self : Dict): pass @unittest.skip(reason="Blip does not use inputs_embeds") def __snake_case ( self : List[str]): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING") def __snake_case ( self : List[Any]): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING") def __snake_case ( self : Dict): pass @slow def __snake_case ( self : str): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : str = TFBlipTextModel.from_pretrained(__UpperCAmelCase) self.assertIsNotNone(__UpperCAmelCase) def __snake_case ( self : Optional[Any] , __UpperCAmelCase : int=True): super().test_pt_tf_model_equivalence(allow_missing_keys=__UpperCAmelCase)
40
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
0
'''simple docstring''' 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 _lowercase ( _lowercase ): a = ["""image_processor""", """tokenizer"""] a = """Pix2StructImageProcessor""" a = ("""T5Tokenizer""", """T5TokenizerFast""") def __init__( self: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: Any ): lowerCamelCase__ : Optional[int] = False super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self: Union[str, Any] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase__: bool = True , UpperCamelCase__: Union[bool, str, PaddingStrategy] = False , UpperCamelCase__: Union[bool, str, TruncationStrategy] = None , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[int] = 2_048 , UpperCamelCase__: int = 0 , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[bool] = None , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = True , UpperCamelCase__: Optional[Union[str, TensorType]] = None , **UpperCamelCase__: Optional[Any] , ): 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: lowerCamelCase__ : Dict = self.tokenizer lowerCamelCase__ : Any = self.tokenizer( text=UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , stride=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , return_overflowing_tokens=UpperCamelCase__ , return_special_tokens_mask=UpperCamelCase__ , return_offsets_mapping=UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ , return_length=UpperCamelCase__ , verbose=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values lowerCamelCase__ : List[Any] = self.image_processor( UpperCamelCase__ , return_tensors=UpperCamelCase__ , max_patches=UpperCamelCase__ , **UpperCamelCase__ ) else: # add pixel_values and bbox lowerCamelCase__ : List[str] = self.image_processor( UpperCamelCase__ , return_tensors=UpperCamelCase__ , max_patches=UpperCamelCase__ , header_text=UpperCamelCase__ , **UpperCamelCase__ ) if text is not None and not self.image_processor.is_vqa: lowerCamelCase__ : Optional[Any] = self.tokenizer( text=UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , stride=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , return_overflowing_tokens=UpperCamelCase__ , return_special_tokens_mask=UpperCamelCase__ , return_offsets_mapping=UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ , return_length=UpperCamelCase__ , verbose=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ , ) if "attention_mask" in text_encoding: lowerCamelCase__ : Dict = text_encoding.pop("""attention_mask""" ) if "input_ids" in text_encoding: lowerCamelCase__ : int = text_encoding.pop("""input_ids""" ) else: lowerCamelCase__ : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(UpperCamelCase__ ) return encoding_image_processor def lowerCamelCase_ ( self: str , *UpperCamelCase__: Optional[Any] , **UpperCamelCase__: List[str] ): return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[Any] , *UpperCamelCase__: Any , **UpperCamelCase__: Optional[int] ): return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Union[str, Any] = self.tokenizer.model_input_names lowerCamelCase__ : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
41
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
0
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class __UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase ): @register_to_config def __init__( self , lowerCAmelCase_ = 7_68 , ): """simple docstring""" super().__init__() _snake_case = nn.Parameter(torch.zeros(1 , lowerCAmelCase_ ) ) _snake_case = nn.Parameter(torch.ones(1 , lowerCAmelCase_ ) ) def lowerCamelCase ( self , lowerCAmelCase_ = None , lowerCAmelCase_ = None , ): """simple docstring""" _snake_case = nn.Parameter(self.mean.to(lowerCAmelCase_ ).to(lowerCAmelCase_ ) ) _snake_case = nn.Parameter(self.std.to(lowerCAmelCase_ ).to(lowerCAmelCase_ ) ) return self def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = (embeds - self.mean) * 1.0 / self.std return embeds def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = (embeds * self.std) + self.mean return embeds
42
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowercase = logging.get_logger(__name__) __lowercase = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __lowercase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: __UpperCamelCase :Tuple = model_type_to_module_name(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Tuple = importlib.import_module(f""".{module_name}""" , '''transformers.models''' ) try: return getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(SCREAMING_SNAKE_CASE , '''__name__''' , SCREAMING_SNAKE_CASE ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __UpperCamelCase :List[str] = importlib.import_module('''transformers''' ) if hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return None def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , **SCREAMING_SNAKE_CASE , ): '''simple docstring''' __UpperCamelCase :Dict = get_file_from_repo( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , force_download=SCREAMING_SNAKE_CASE , resume_download=SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , use_auth_token=SCREAMING_SNAKE_CASE , revision=SCREAMING_SNAKE_CASE , local_files_only=SCREAMING_SNAKE_CASE , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as reader: return json.load(SCREAMING_SNAKE_CASE ) class lowerCamelCase_ : '''simple docstring''' def __init__( self) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''') @classmethod @replace_list_option_in_docstrings(__lowercase) def UpperCamelCase__ ( cls , __lowercase , **__lowercase) -> Union[str, Any]: __UpperCamelCase :Dict = kwargs.pop('''config''' , __lowercase) __UpperCamelCase :List[str] = kwargs.pop('''trust_remote_code''' , __lowercase) __UpperCamelCase :Optional[int] = True __UpperCamelCase , __UpperCamelCase :List[str] = ImageProcessingMixin.get_image_processor_dict(__lowercase , **__lowercase) __UpperCamelCase :Optional[int] = config_dict.get('''image_processor_type''' , __lowercase) __UpperCamelCase :Any = None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {}): __UpperCamelCase :int = config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: __UpperCamelCase :Dict = config_dict.pop('''feature_extractor_type''' , __lowercase) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''') __UpperCamelCase :str = feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''') if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {}): __UpperCamelCase :Optional[int] = config_dict['''auto_map''']['''AutoFeatureExtractor'''] __UpperCamelCase :Union[str, Any] = feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''') logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''') # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__lowercase , __lowercase): __UpperCamelCase :Union[str, Any] = AutoConfig.from_pretrained(__lowercase , **__lowercase) # It could be in `config.image_processor_type`` __UpperCamelCase :List[str] = getattr(__lowercase , '''image_processor_type''' , __lowercase) if hasattr(__lowercase , '''auto_map''') and "AutoImageProcessor" in config.auto_map: __UpperCamelCase :Union[str, Any] = config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: __UpperCamelCase :Tuple = image_processor_class_from_name(__lowercase) __UpperCamelCase :Union[str, Any] = image_processor_auto_map is not None __UpperCamelCase :str = image_processor_class is not None or type(__lowercase) in IMAGE_PROCESSOR_MAPPING __UpperCamelCase :Optional[Any] = resolve_trust_remote_code( __lowercase , __lowercase , __lowercase , __lowercase) if has_remote_code and trust_remote_code: __UpperCamelCase :int = get_class_from_dynamic_module( __lowercase , __lowercase , **__lowercase) __UpperCamelCase :Dict = kwargs.pop('''code_revision''' , __lowercase) if os.path.isdir(__lowercase): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__lowercase , **__lowercase) elif image_processor_class is not None: return image_processor_class.from_dict(__lowercase , **__lowercase) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__lowercase) in IMAGE_PROCESSOR_MAPPING: __UpperCamelCase :int = IMAGE_PROCESSOR_MAPPING[type(__lowercase)] return image_processor_class.from_dict(__lowercase , **__lowercase) raise ValueError( f"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ f"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ f"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}""") @staticmethod def UpperCamelCase__ ( __lowercase , __lowercase) -> Union[str, Any]: IMAGE_PROCESSOR_MAPPING.register(__lowercase , __lowercase)
43
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
0
"""simple docstring""" from math import asin, atan, cos, radians, sin, sqrt, tan _a : Any = 6_37_81_37.0 _a : List[str] = 6_35_67_52.31_42_45 _a : Tuple = 6_378_137 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : float ,_lowerCamelCase : float ,_lowerCamelCase : float ,_lowerCamelCase : float ) -> float: _lowerCAmelCase : Any = (AXIS_A - AXIS_B) / AXIS_A _lowerCAmelCase : List[str] = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) _lowerCAmelCase : Dict = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[Any] = radians(_lowerCamelCase ) _lowerCAmelCase : int = radians(_lowerCamelCase ) # Equation _lowerCAmelCase : Dict = sin((phi_a - phi_a) / 2 ) _lowerCAmelCase : Tuple = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda _lowerCAmelCase : int = sqrt(sin_sq_phi + (cos(_lowerCamelCase ) * cos(_lowerCamelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 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(lowerCAmelCase_ ): 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: a__ : List[str] = 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()
54
0
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Optional[Any]=None ): '''simple docstring''' lowerCAmelCase = argparse.ArgumentParser(add_help=SCREAMING_SNAKE_CASE , allow_abbrev=SCREAMING_SNAKE_CASE ) # The main config parser lowerCAmelCase = config_command_parser(SCREAMING_SNAKE_CASE ) # The subparser to add commands to lowerCAmelCase = config_parser.add_subparsers(title="""subcommands""" , dest="""subcommand""" ) # Then add other parsers with the parent parser default_command_parser(SCREAMING_SNAKE_CASE , parents=[parent_parser] ) update_command_parser(SCREAMING_SNAKE_CASE , parents=[parent_parser] ) return config_parser def UpperCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase = get_config_parser() lowerCAmelCase = config_parser.parse_args() if not hasattr(SCREAMING_SNAKE_CASE , """func""" ): config_parser.print_help() exit(1 ) # Run args.func(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
46
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") lowerCamelCase : Tuple = logging.getLogger(__name__) @dataclass class A__ : A__ = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A__ = field( default=A__ , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of prediction examples to this ' 'value if set.' ) } , ) @dataclass class A__ : A__ = field( default=A__ , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ = field( default=A__ , metadata={'help': 'Evaluation language. Also train language if `train_language` is set to None.'} ) A__ = field( default=A__ , metadata={'help': 'Train language if it is different from the evaluation language.'} ) A__ = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A__ = field( default=A__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A__ = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) A__ = field( default=A__ , metadata={'help': 'arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'} , ) A__ = field( default=A__ , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) A__ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A__ = field( default=A__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A__ = field( default=A__ , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , ) def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_xnli' , _UpperCamelCase ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) datasets.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: _SCREAMING_SNAKE_CASE =load_dataset( 'xnli' , model_args.language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: _SCREAMING_SNAKE_CASE =load_dataset( 'xnli' , model_args.train_language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE =train_dataset.features['label'].names if training_args.do_eval: _SCREAMING_SNAKE_CASE =load_dataset( 'xnli' , model_args.language , split='validation' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE =eval_dataset.features['label'].names if training_args.do_predict: _SCREAMING_SNAKE_CASE =load_dataset( 'xnli' , model_args.language , split='test' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE =predict_dataset.features['label'].names # Labels _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_UpperCamelCase , idalabel={str(_UpperCamelCase ): label for i, label in enumerate(_UpperCamelCase )} , labelaid={label: i for i, label in enumerate(_UpperCamelCase )} , finetuning_task='xnli' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: _SCREAMING_SNAKE_CASE ='max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch _SCREAMING_SNAKE_CASE =False def preprocess_function(_UpperCamelCase : str ): # Tokenize the texts return tokenizer( examples['premise'] , examples['hypothesis'] , padding=_UpperCamelCase , max_length=data_args.max_seq_length , truncation=_UpperCamelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE =min(len(_UpperCamelCase ) , data_args.max_train_samples ) _SCREAMING_SNAKE_CASE =train_dataset.select(range(_UpperCamelCase ) ) with training_args.main_process_first(desc='train dataset map pre-processing' ): _SCREAMING_SNAKE_CASE =train_dataset.map( _UpperCamelCase , batched=_UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on train dataset' , ) # Log a few random samples from the training set: for index in random.sample(range(len(_UpperCamelCase ) ) , 3 ): logger.info(f"Sample {index} of the training set: {train_dataset[index]}." ) if training_args.do_eval: if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE =min(len(_UpperCamelCase ) , data_args.max_eval_samples ) _SCREAMING_SNAKE_CASE =eval_dataset.select(range(_UpperCamelCase ) ) with training_args.main_process_first(desc='validation dataset map pre-processing' ): _SCREAMING_SNAKE_CASE =eval_dataset.map( _UpperCamelCase , batched=_UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on validation dataset' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: _SCREAMING_SNAKE_CASE =min(len(_UpperCamelCase ) , data_args.max_predict_samples ) _SCREAMING_SNAKE_CASE =predict_dataset.select(range(_UpperCamelCase ) ) with training_args.main_process_first(desc='prediction dataset map pre-processing' ): _SCREAMING_SNAKE_CASE =predict_dataset.map( _UpperCamelCase , batched=_UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on prediction dataset' , ) # Get the metric function _SCREAMING_SNAKE_CASE =evaluate.load('xnli' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(_UpperCamelCase : EvalPrediction ): _SCREAMING_SNAKE_CASE =p.predictions[0] if isinstance(p.predictions , _UpperCamelCase ) else p.predictions _SCREAMING_SNAKE_CASE =np.argmax(_UpperCamelCase , axis=1 ) return metric.compute(predictions=_UpperCamelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: _SCREAMING_SNAKE_CASE =default_data_collator elif training_args.fpaa: _SCREAMING_SNAKE_CASE =DataCollatorWithPadding(_UpperCamelCase , pad_to_multiple_of=8 ) else: _SCREAMING_SNAKE_CASE =None # Initialize our Trainer _SCREAMING_SNAKE_CASE =Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=_UpperCamelCase , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE =last_checkpoint _SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =train_result.metrics _SCREAMING_SNAKE_CASE =( data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =min(_UpperCamelCase , len(_UpperCamelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , _UpperCamelCase ) trainer.save_metrics('train' , _UpperCamelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) _SCREAMING_SNAKE_CASE =trainer.evaluate(eval_dataset=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =min(_UpperCamelCase , len(_UpperCamelCase ) ) trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Prediction if training_args.do_predict: logger.info('*** Predict ***' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =trainer.predict(_UpperCamelCase , metric_key_prefix='predict' ) _SCREAMING_SNAKE_CASE =( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =min(_UpperCamelCase , len(_UpperCamelCase ) ) trainer.log_metrics('predict' , _UpperCamelCase ) trainer.save_metrics('predict' , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.argmax(_UpperCamelCase , axis=1 ) _SCREAMING_SNAKE_CASE =os.path.join(training_args.output_dir , 'predictions.txt' ) if trainer.is_world_process_zero(): with open(_UpperCamelCase , 'w' ) as writer: writer.write('index\tprediction\n' ) for index, item in enumerate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =label_list[item] writer.write(f"{index}\t{item}\n" ) if __name__ == "__main__": main()
47
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Tuple = """codegen""" lowerCamelCase_ : Optional[int] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , UpperCamelCase__=5_0400 , UpperCamelCase__=2048 , UpperCamelCase__=2048 , UpperCamelCase__=4096 , UpperCamelCase__=28 , UpperCamelCase__=16 , UpperCamelCase__=64 , UpperCamelCase__=None , UpperCamelCase__="gelu_new" , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=1e-5 , UpperCamelCase__=0.02 , UpperCamelCase__=True , UpperCamelCase__=5_0256 , UpperCamelCase__=5_0256 , UpperCamelCase__=False , **UpperCamelCase__ , ) -> List[str]: lowerCamelCase : Union[str, Any] = vocab_size lowerCamelCase : Optional[Any] = n_ctx lowerCamelCase : Optional[int] = n_positions lowerCamelCase : int = n_embd lowerCamelCase : Optional[Any] = n_layer lowerCamelCase : List[Any] = n_head lowerCamelCase : Optional[int] = n_inner lowerCamelCase : Optional[int] = rotary_dim lowerCamelCase : int = activation_function lowerCamelCase : List[str] = resid_pdrop lowerCamelCase : Optional[int] = embd_pdrop lowerCamelCase : Tuple = attn_pdrop lowerCamelCase : int = layer_norm_epsilon lowerCamelCase : Optional[Any] = initializer_range lowerCamelCase : str = use_cache lowerCamelCase : List[Any] = bos_token_id lowerCamelCase : Tuple = eos_token_id super().__init__( bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , tie_word_embeddings=UpperCamelCase__ , **UpperCamelCase__ ) class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ = "default" , UpperCamelCase__ = None , UpperCamelCase__ = False , ) -> List[Any]: super().__init__(UpperCamelCase__ , task=UpperCamelCase__ , patching_specs=UpperCamelCase__ , use_past=UpperCamelCase__ ) if not getattr(self._config , "pad_token_id" , UpperCamelCase__ ): # TODO: how to do that better? lowerCamelCase : Union[str, Any] = 0 @property def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]: lowerCamelCase : List[Any] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase__ , direction="inputs" ) lowerCamelCase : Optional[Any] = {0: "batch", 1: "past_sequence + sequence"} else: lowerCamelCase : Dict = {0: "batch", 1: "sequence"} return common_inputs @property def _lowercase ( self ) -> int: return self._config.n_layer @property def _lowercase ( self ) -> int: return self._config.n_head def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = -1 , UpperCamelCase__ = -1 , UpperCamelCase__ = False , UpperCamelCase__ = None , ) -> Mapping[str, Any]: lowerCamelCase : int = super(UpperCamelCase__ , self ).generate_dummy_inputs( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) # We need to order the input in the way they appears in the forward() lowerCamelCase : int = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch lowerCamelCase , lowerCamelCase : Optional[int] = common_inputs["input_ids"].shape # Not using the same length for past_key_values lowerCamelCase : List[Any] = seqlen + 2 lowerCamelCase : Any = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCamelCase : Union[str, Any] = [ (torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(self.num_layers ) ] lowerCamelCase : str = common_inputs["attention_mask"] if self.use_past: lowerCamelCase : Optional[Any] = ordered_inputs["attention_mask"].dtype lowerCamelCase : Union[str, Any] = torch.cat( [ordered_inputs["attention_mask"], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 ) return ordered_inputs @property def _lowercase ( self ) -> int: return 13
48
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A ( __UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ : Any = LEDTokenizer UpperCamelCase__ : str = LEDTokenizerFast UpperCamelCase__ : List[Any] = True def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' super().setUp() __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 _lowerCamelCase ( self : str , **__SCREAMING_SNAKE_CASE : Dict): '''simple docstring''' kwargs.update(self.special_tokens_map) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : int , **__SCREAMING_SNAKE_CASE : int): '''simple docstring''' kwargs.update(self.special_tokens_map) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' return "lower newer", "lower newer" @cached_property def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' return LEDTokenizer.from_pretrained('''allenai/led-base-16384''') @cached_property def _lowerCamelCase ( self : Any): '''simple docstring''' return LEDTokenizerFast.from_pretrained('''allenai/led-base-16384''') @require_torch def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __a = [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , max_length=len(__SCREAMING_SNAKE_CASE) , padding=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual((2, 9) , batch.input_ids.shape) self.assertEqual((2, 9) , batch.attention_mask.shape) __a = batch.input_ids.tolist()[0] self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) @require_torch def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIn('''input_ids''' , __SCREAMING_SNAKE_CASE) self.assertIn('''attention_mask''' , __SCREAMING_SNAKE_CASE) self.assertNotIn('''labels''' , __SCREAMING_SNAKE_CASE) self.assertNotIn('''decoder_attention_mask''' , __SCREAMING_SNAKE_CASE) @require_torch def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = [ '''Summary of the text.''', '''Another summary.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(text_target=__SCREAMING_SNAKE_CASE , max_length=32 , padding='''max_length''' , return_tensors='''pt''') self.assertEqual(32 , targets['''input_ids'''].shape[1]) @require_torch def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer( ['''I am a small frog''' * 1_024, '''I am a small frog'''] , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(batch.input_ids.shape , (2, 5_122)) @require_torch def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = ['''A long paragraph for summarization.'''] __a = [ '''Summary of the text.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''pt''') __a = tokenizer(text_target=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') __a = inputs['''input_ids'''] __a = targets['''input_ids'''] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()) @require_torch def _lowerCamelCase ( self : Tuple): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = ['''Summary of the text.''', '''Another summary.'''] __a = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE) __a = [[0] * len(__SCREAMING_SNAKE_CASE) for x in encoded_output['''input_ids''']] __a = tokenizer.pad(__SCREAMING_SNAKE_CASE) self.assertSequenceEqual(outputs['''global_attention_mask'''] , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Dict): '''simple docstring''' pass def _lowerCamelCase ( self : Tuple): '''simple docstring''' 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) self.assertEqual(sum(tokens_r['''token_type_ids''']) , sum(tokens_p['''token_type_ids'''])) 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''']) self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>''']) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''])
49
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
_UpperCAmelCase : Dict = """ # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git """ _UpperCAmelCase : Optional[int] = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _UpperCAmelCase : List[Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
50
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar snake_case_ : Union[str, Any] = TypeVar("T") class __snake_case ( Generic[T] ): UpperCAmelCase__ : deque[T] # Cache store of keys UpperCAmelCase__ : set[T] # References of the keys in cache UpperCAmelCase__ : int = 1_0 # Maximum capacity of cache def __init__( self : Optional[int] , _snake_case : int): """simple docstring""" UpperCAmelCase_ = deque() UpperCAmelCase_ = set() if not n: UpperCAmelCase_ = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''') else: UpperCAmelCase_ = n def lowerCamelCase ( self : int , _snake_case : T): """simple docstring""" if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: UpperCAmelCase_ = self.dq_store.pop() self.key_reference.remove(_snake_case) else: self.dq_store.remove(_snake_case) self.dq_store.appendleft(_snake_case) self.key_reference.add(_snake_case) def lowerCamelCase ( self : Any): """simple docstring""" for k in self.dq_store: print(_snake_case) def __repr__( self : Optional[Any]): """simple docstring""" return F"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}""" if __name__ == "__main__": import doctest doctest.testmod() snake_case_ : LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
51
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class A__ ( __snake_case , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class A__ ( unittest.TestCase ): @property def __UpperCamelCase( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = ort.SessionOptions() UpperCamelCase : Any = False return options def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo.png" ) UpperCamelCase : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo_mask.png" ) UpperCamelCase : Optional[Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting" , revision="onnx" , safety_checker=A_ , feature_extractor=A_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = "A red cat sitting on a park bench" UpperCamelCase : List[Any] = np.random.RandomState(0 ) UpperCamelCase : Union[str, Any] = pipe( prompt=A_ , image=A_ , mask_image=A_ , guidance_scale=7.5 , num_inference_steps=10 , generator=A_ , output_type="np" , ) UpperCamelCase : Optional[int] = output.images UpperCamelCase : Any = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) UpperCamelCase : Dict = np.array([0.25_14, 0.30_07, 0.35_17, 0.17_90, 0.23_82, 0.31_67, 0.19_44, 0.22_73, 0.24_64] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo.png" ) UpperCamelCase : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo_mask.png" ) UpperCamelCase : Optional[Any] = LMSDiscreteScheduler.from_pretrained( "runwayml/stable-diffusion-inpainting" , subfolder="scheduler" , revision="onnx" ) UpperCamelCase : Optional[Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting" , revision="onnx" , scheduler=A_ , safety_checker=A_ , feature_extractor=A_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Optional[int] = "A red cat sitting on a park bench" UpperCamelCase : List[str] = np.random.RandomState(0 ) UpperCamelCase : Union[str, Any] = pipe( prompt=A_ , image=A_ , mask_image=A_ , guidance_scale=7.5 , num_inference_steps=20 , generator=A_ , output_type="np" , ) UpperCamelCase : Optional[Any] = output.images UpperCamelCase : List[str] = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) UpperCamelCase : List[Any] = np.array([0.00_86, 0.00_77, 0.00_83, 0.00_93, 0.01_07, 0.01_39, 0.00_94, 0.00_97, 0.01_25] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
52
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
'''simple docstring''' import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowercase__ ( __lowercase : int , __lowercase : int , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Any ) -> Optional[Any]: """simple docstring""" with open(__lowercase ) as metadata_file: __UpperCamelCase = json.load(__lowercase ) __UpperCamelCase = LukeConfig(use_entity_aware_attention=__lowercase , **metadata['model_config'] ) # Load in the weights from the checkpoint_path __UpperCamelCase = torch.load(__lowercase , map_location='cpu' ) # Load the entity vocab file __UpperCamelCase = load_entity_vocab(__lowercase ) __UpperCamelCase = RobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks __UpperCamelCase = AddedToken('<ent>' , lstrip=__lowercase , rstrip=__lowercase ) __UpperCamelCase = AddedToken('<ent2>' , lstrip=__lowercase , rstrip=__lowercase ) tokenizer.add_special_tokens({'additional_special_tokens': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__lowercase ) with open(os.path.join(__lowercase , LukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(__lowercase , __lowercase ) __UpperCamelCase = LukeTokenizer.from_pretrained(__lowercase ) # Initialize the embeddings of the special tokens __UpperCamelCase = state_dict['embeddings.word_embeddings.weight'] __UpperCamelCase = word_emb[tokenizer.convert_tokens_to_ids(['@'] )[0]].unsqueeze(0 ) __UpperCamelCase = word_emb[tokenizer.convert_tokens_to_ids(['#'] )[0]].unsqueeze(0 ) __UpperCamelCase = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: __UpperCamelCase = F'''encoder.layer.{layer_index}.attention.self.''' __UpperCamelCase = state_dict[prefix + matrix_name] __UpperCamelCase = state_dict[prefix + matrix_name] __UpperCamelCase = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __UpperCamelCase = state_dict['entity_embeddings.entity_embeddings.weight'] __UpperCamelCase = entity_emb[entity_vocab['[MASK]']] __UpperCamelCase = LukeModel(config=__lowercase ).eval() __UpperCamelCase , __UpperCamelCase = model.load_state_dict(__lowercase , strict=__lowercase ) if not (len(__lowercase ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F'''Missing keys {', '.join(__lowercase )}. Expected only missing embeddings.position_ids''' ) if not (all(key.startswith('entity_predictions' ) or key.startswith('lm_head' ) for key in unexpected_keys )): raise ValueError( 'Unexpected keys' F''' {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions' ) or key.startswith('lm_head' ))] )}''' ) # Check outputs __UpperCamelCase = LukeTokenizer.from_pretrained(__lowercase , task='entity_classification' ) __UpperCamelCase = ( 'Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the' ' new world number one avoid a humiliating second- round exit at Wimbledon .' ) __UpperCamelCase = (39, 42) __UpperCamelCase = tokenizer(__lowercase , entity_spans=[span] , add_prefix_space=__lowercase , return_tensors='pt' ) __UpperCamelCase = model(**__lowercase ) # Verify word hidden states if model_size == "large": __UpperCamelCase = torch.Size((1, 42, 1024) ) __UpperCamelCase = torch.tensor( [[0.0_1_3_3, 0.0_8_6_5, 0.0_0_9_5], [0.3_0_9_3, -0.2_5_7_6, -0.7_4_1_8], [-0.1_7_2_0, -0.2_1_1_7, -0.2_8_6_9]] ) else: # base __UpperCamelCase = torch.Size((1, 42, 768) ) __UpperCamelCase = torch.tensor([[0.0_0_3_7, 0.1_3_6_8, -0.0_0_9_1], [0.1_0_9_9, 0.3_3_2_9, -0.1_0_9_5], [0.0_7_6_5, 0.5_3_3_5, 0.1_1_7_9]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __lowercase , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": __UpperCamelCase = torch.Size((1, 1, 1024) ) __UpperCamelCase = torch.tensor([[0.0_4_6_6, -0.0_1_0_6, -0.0_1_7_9]] ) else: # base __UpperCamelCase = torch.Size((1, 1, 768) ) __UpperCamelCase = torch.tensor([[0.1_4_5_7, 0.1_0_4_4, 0.0_1_7_4]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __lowercase , atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(__lowercase ) ) model.save_pretrained(__lowercase ) def lowercase__ ( __lowercase : Dict ) -> List[str]: """simple docstring""" __UpperCamelCase = {} with open(__lowercase , 'r' , encoding='utf-8' ) as f: for index, line in enumerate(__lowercase ): __UpperCamelCase , __UpperCamelCase = line.rstrip().split('\t' ) __UpperCamelCase = index return entity_vocab if __name__ == "__main__": a__ : Any =argparse.ArgumentParser() # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Path to a pytorch_model.bin file.''') parser.add_argument( '''--metadata_path''', default=None, type=str, help='''Path to a metadata.json file, defining the configuration.''' ) parser.add_argument( '''--entity_vocab_path''', default=None, type=str, help='''Path to an entity_vocab.tsv file, containing the entity vocabulary.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to where to dump the output PyTorch model.''' ) parser.add_argument( '''--model_size''', default='''base''', type=str, choices=['''base''', '''large'''], help='''Size of the model to be converted.''' ) a__ : str =parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
53
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0
'''simple docstring''' import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig a_ : Union[str, Any] = { """facebook/maskformer-swin-base-ade""": ( """https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json""" ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } a_ : Tuple = logging.get_logger(__name__) class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "maskformer" _lowerCamelCase = {"hidden_size": "mask_feature_size"} _lowerCamelCase = ["resnet", "swin"] _lowerCamelCase = ["detr"] def __init__( self , UpperCamelCase = 256 , UpperCamelCase = 256 , UpperCamelCase = 0.1 , UpperCamelCase = False , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = 0.02 , UpperCamelCase = 1.0 , UpperCamelCase = 1.0 , UpperCamelCase = 1.0 , UpperCamelCase = 20.0 , UpperCamelCase = None , **UpperCamelCase , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k lowerCamelCase_ = SwinConfig( image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(UpperCamelCase , UpperCamelCase ): lowerCamelCase_ = backbone_config.pop("model_type" ) lowerCamelCase_ = CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ = config_class.from_dict(UpperCamelCase ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ''' f'''Supported model types: {",".join(self.backbones_supported )}''' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 lowerCamelCase_ = DetrConfig() else: # verify that the decoder is supported lowerCamelCase_ = ( decoder_config.pop("model_type" ) if isinstance(UpperCamelCase , UpperCamelCase ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'''Transformer Decoder {decoder_type} not supported, please use one of''' f''' {",".join(self.decoders_supported )}''' ) if isinstance(UpperCamelCase , UpperCamelCase ): lowerCamelCase_ = CONFIG_MAPPING[decoder_type] lowerCamelCase_ = config_class.from_dict(UpperCamelCase ) lowerCamelCase_ = backbone_config lowerCamelCase_ = decoder_config # main feature dimension for the model lowerCamelCase_ = fpn_feature_size lowerCamelCase_ = mask_feature_size # initializer lowerCamelCase_ = init_std lowerCamelCase_ = init_xavier_std # Hungarian matcher && loss lowerCamelCase_ = cross_entropy_weight lowerCamelCase_ = dice_weight lowerCamelCase_ = mask_weight lowerCamelCase_ = use_auxiliary_loss lowerCamelCase_ = no_object_weight lowerCamelCase_ = output_auxiliary_logits lowerCamelCase_ = self.decoder_config.encoder_attention_heads lowerCamelCase_ = self.decoder_config.num_hidden_layers super().__init__(**UpperCamelCase ) @classmethod def snake_case ( cls , UpperCamelCase , UpperCamelCase , **UpperCamelCase ): """simple docstring""" return cls( backbone_config=UpperCamelCase , decoder_config=UpperCamelCase , **UpperCamelCase , ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = copy.deepcopy(self.__dict__ ) lowerCamelCase_ = self.backbone_config.to_dict() lowerCamelCase_ = self.decoder_config.to_dict() lowerCamelCase_ = self.__class__.model_type return output
55
"""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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class a ( _lowerCamelCase ): snake_case_ = 42 class a ( nn.Module ): def __init__( self : int , lowercase_ : List[Any]=3 , lowercase_ : str=3 , lowercase_ : Union[str, Any]=("DownEncoderBlock2D",) , lowercase_ : str=(64,) , lowercase_ : Optional[Any]=2 , lowercase_ : Optional[Any]=32 , lowercase_ : Optional[int]="silu" , lowercase_ : Optional[int]=True , ): super().__init__() snake_case_ = layers_per_block snake_case_ = torch.nn.Convad( lowercase_ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) # down snake_case_ = block_out_channels[0] for i, down_block_type in enumerate(lowercase_ ): snake_case_ = output_channel snake_case_ = block_out_channels[i] snake_case_ = i == len(lowercase_ ) - 1 snake_case_ = get_down_block( lowercase_ , num_layers=self.layers_per_block , in_channels=lowercase_ , out_channels=lowercase_ , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=lowercase_ , resnet_groups=lowercase_ , attention_head_dim=lowercase_ , temb_channels=lowercase_ , ) self.down_blocks.append(lowercase_ ) # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=lowercase_ , output_scale_factor=1 , resnet_time_scale_shift='''default''' , attention_head_dim=block_out_channels[-1] , resnet_groups=lowercase_ , temb_channels=lowercase_ , ) # out snake_case_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=lowercase_ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = 2 * out_channels if double_z else out_channels snake_case_ = nn.Convad(block_out_channels[-1] , lowercase_ , 3 , padding=1 ) snake_case_ = False def A_ ( self : Union[str, Any] , lowercase_ : Tuple ): snake_case_ = x snake_case_ = self.conv_in(lowercase_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(lowercase_ : Tuple ): def custom_forward(*lowercase_ : Optional[int] ): return module(*lowercase_ ) return custom_forward # down if is_torch_version('''>=''' , '''1.11.0''' ): for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(lowercase_ ) , lowercase_ , use_reentrant=lowercase_ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowercase_ , use_reentrant=lowercase_ ) else: for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase_ ) , lowercase_ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , lowercase_ ) else: # down for down_block in self.down_blocks: snake_case_ = down_block(lowercase_ ) # middle snake_case_ = self.mid_block(lowercase_ ) # post-process snake_case_ = self.conv_norm_out(lowercase_ ) snake_case_ = self.conv_act(lowercase_ ) snake_case_ = self.conv_out(lowercase_ ) return sample class a ( nn.Module ): def __init__( self : Any , lowercase_ : Tuple=3 , lowercase_ : int=3 , lowercase_ : Dict=("UpDecoderBlock2D",) , lowercase_ : Tuple=(64,) , lowercase_ : Tuple=2 , lowercase_ : Union[str, Any]=32 , lowercase_ : str="silu" , lowercase_ : List[str]="group" , ): super().__init__() snake_case_ = layers_per_block snake_case_ = nn.Convad( lowercase_ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) snake_case_ = in_channels if norm_type == '''spatial''' else None # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=lowercase_ , output_scale_factor=1 , resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=lowercase_ , temb_channels=lowercase_ , ) # up snake_case_ = list(reversed(lowercase_ ) ) snake_case_ = reversed_block_out_channels[0] for i, up_block_type in enumerate(lowercase_ ): snake_case_ = output_channel snake_case_ = reversed_block_out_channels[i] snake_case_ = i == len(lowercase_ ) - 1 snake_case_ = get_up_block( lowercase_ , num_layers=self.layers_per_block + 1 , in_channels=lowercase_ , out_channels=lowercase_ , prev_output_channel=lowercase_ , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=lowercase_ , resnet_groups=lowercase_ , attention_head_dim=lowercase_ , temb_channels=lowercase_ , resnet_time_scale_shift=lowercase_ , ) self.up_blocks.append(lowercase_ ) snake_case_ = output_channel # out if norm_type == "spatial": snake_case_ = SpatialNorm(block_out_channels[0] , lowercase_ ) else: snake_case_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=lowercase_ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = nn.Convad(block_out_channels[0] , lowercase_ , 3 , padding=1 ) snake_case_ = False def A_ ( self : Union[str, Any] , lowercase_ : Optional[int] , lowercase_ : Optional[int]=None ): snake_case_ = z snake_case_ = self.conv_in(lowercase_ ) snake_case_ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(lowercase_ : int ): def custom_forward(*lowercase_ : Any ): return module(*lowercase_ ) return custom_forward if is_torch_version('''>=''' , '''1.11.0''' ): # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowercase_ , lowercase_ , use_reentrant=lowercase_ ) snake_case_ = sample.to(lowercase_ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(lowercase_ ) , lowercase_ , lowercase_ , use_reentrant=lowercase_ ) else: # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowercase_ , lowercase_ ) snake_case_ = sample.to(lowercase_ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase_ ) , lowercase_ , lowercase_ ) else: # middle snake_case_ = self.mid_block(lowercase_ , lowercase_ ) snake_case_ = sample.to(lowercase_ ) # up for up_block in self.up_blocks: snake_case_ = up_block(lowercase_ , lowercase_ ) # post-process if latent_embeds is None: snake_case_ = self.conv_norm_out(lowercase_ ) else: snake_case_ = self.conv_norm_out(lowercase_ , lowercase_ ) snake_case_ = self.conv_act(lowercase_ ) snake_case_ = self.conv_out(lowercase_ ) return sample class a ( nn.Module ): def __init__( self : Dict , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Any=None , lowercase_ : Optional[int]="random" , lowercase_ : Optional[int]=False , lowercase_ : int=True ): super().__init__() snake_case_ = n_e snake_case_ = vq_embed_dim snake_case_ = beta snake_case_ = legacy snake_case_ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case_ = remap if self.remap is not None: self.register_buffer('''used''' , torch.tensor(np.load(self.remap ) ) ) snake_case_ = self.used.shape[0] snake_case_ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case_ = self.re_embed snake_case_ = self.re_embed + 1 print( F"Remapping {self.n_e} indices to {self.re_embed} indices. " F"Using {self.unknown_index} for unknown indices." ) else: snake_case_ = n_e snake_case_ = sane_index_shape def A_ ( self : str , lowercase_ : List[str] ): snake_case_ = inds.shape assert len(lowercase_ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(lowercase_ ) snake_case_ = (inds[:, :, None] == used[None, None, ...]).long() snake_case_ = match.argmax(-1 ) snake_case_ = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case_ = self.unknown_index return new.reshape(lowercase_ ) def A_ ( self : int , lowercase_ : Tuple ): snake_case_ = inds.shape assert len(lowercase_ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(lowercase_ ) if self.re_embed > self.used.shape[0]: # extra token snake_case_ = 0 # simply set to zero snake_case_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , lowercase_ ) return back.reshape(lowercase_ ) def A_ ( self : str , lowercase_ : Any ): # reshape z -> (batch, height, width, channel) and flatten snake_case_ = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case_ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case_ = torch.argmin(torch.cdist(lowercase_ , self.embedding.weight ) , dim=1 ) snake_case_ = self.embedding(lowercase_ ).view(z.shape ) snake_case_ = None snake_case_ = None # compute loss for embedding if not self.legacy: snake_case_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case_ = z + (z_q - z).detach() # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case_ = self.remap_to_used(lowercase_ ) snake_case_ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def A_ ( self : Optional[int] , lowercase_ : Tuple , lowercase_ : Optional[Any] ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case_ = indices.reshape(shape[0] , -1 ) # add batch axis snake_case_ = self.unmap_to_all(lowercase_ ) snake_case_ = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case_ = self.embedding(lowercase_ ) if shape is not None: snake_case_ = z_q.view(lowercase_ ) # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class a ( _lowerCamelCase ): def __init__( self : Tuple , lowercase_ : List[str] , lowercase_ : Any=False ): snake_case_ = parameters snake_case_ ,snake_case_ = torch.chunk(lowercase_ , 2 , dim=1 ) snake_case_ = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case_ = deterministic snake_case_ = torch.exp(0.5 * self.logvar ) snake_case_ = torch.exp(self.logvar ) if self.deterministic: snake_case_ = snake_case_ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def A_ ( self : List[Any] , lowercase_ : Optional[torch.Generator] = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case_ = randn_tensor( self.mean.shape , generator=lowercase_ , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case_ = self.mean + self.std * sample return x def A_ ( self : Dict , lowercase_ : Any=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def A_ ( self : List[Any] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case_ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=lowercase_ ) def A_ ( self : Dict ): return self.mean
56
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , __a , __a=13 , __a=30 , __a=2 , __a=3 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.0_2 , ): __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 1 def snake_case ( self ): __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = ViTConfig( 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=__a , initializer_range=self.initializer_range , ) return config, pixel_values def snake_case ( self , __a , __a ): __lowerCAmelCase = FlaxViTModel(config=__a ) __lowerCAmelCase = model(__a ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = (self.image_size, self.image_size) __lowerCAmelCase = (self.patch_size, self.patch_size) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def snake_case ( self , __a , __a ): __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = FlaxViTForImageClassification(config=__a ) __lowerCAmelCase = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = FlaxViTForImageClassification(__a ) __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(__a ) def snake_case ( self ): __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class _UpperCamelCase ( lowerCAmelCase__ ,unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int =(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def snake_case ( self ): __lowerCAmelCase = FlaxViTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def snake_case ( self ): self.config_tester.run_common_tests() def snake_case ( self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def snake_case ( self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) def snake_case ( self ): __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(__a ) __lowerCAmelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def snake_case ( self ): __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCAmelCase = self._prepare_for_class(__a , __a ) __lowerCAmelCase = model_class(__a ) @jax.jit def model_jitted(__a , **__a ): return model(pixel_values=__a , **__a ) with self.subTest("JIT Enabled" ): __lowerCAmelCase = model_jitted(**__a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __lowerCAmelCase = model_jitted(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) ) for jitted_output, output in zip(__a , __a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def snake_case ( self ): for model_class_name in self.all_model_classes: __lowerCAmelCase = model_class_name.from_pretrained("google/vit-base-patch16-224" ) __lowerCAmelCase = model(np.ones((1, 3, 2_24, 2_24) ) ) self.assertIsNotNone(__a )
57
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->int: if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
58
"""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_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["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 __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # 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})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
0
import operator as op __lowerCamelCase = """scaler.pt""" __lowerCamelCase = """pytorch_model""" __lowerCamelCase = """random_states""" __lowerCamelCase = """optimizer""" __lowerCamelCase = """scheduler""" __lowerCamelCase = """pytorch_model.bin""" __lowerCamelCase = """pytorch_model.bin.index.json""" __lowerCamelCase = """model.safetensors""" __lowerCamelCase = """model.safetensors.index.json""" __lowerCamelCase = """1.10.2""" __lowerCamelCase = """py38""" __lowerCamelCase = """4.17.0""" __lowerCamelCase = ["""ml.p3.16xlarge""", """ml.p3dn.24xlarge""", """ml.p4dn.24xlarge"""] __lowerCamelCase = ["""FULL_SHARD""", """SHARD_GRAD_OP""", """NO_SHARD""", """HYBRID_SHARD""", """HYBRID_SHARD_ZERO2"""] __lowerCamelCase = ["""TRANSFORMER_BASED_WRAP""", """SIZE_BASED_WRAP""", """NO_WRAP"""] __lowerCamelCase = ["""BACKWARD_PRE""", """BACKWARD_POST""", """NO_PREFETCH"""] __lowerCamelCase = ["""FULL_STATE_DICT""", """LOCAL_STATE_DICT""", """SHARDED_STATE_DICT"""] __lowerCamelCase = """2.0.1""" __lowerCamelCase = ["""pdsh""", """standard""", """openmpi""", """mvapich"""] __lowerCamelCase = ["""default""", """reduce-overhead""", """max-autotune"""] __lowerCamelCase = {""">""": op.gt, """>=""": op.ge, """==""": op.eq, """!=""": op.ne, """<=""": op.le, """<""": op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 __lowerCamelCase = [ """nnodes""", """nproc_per_node""", """rdzv_backend""", """rdzv_endpoint""", """rdzv_id""", """rdzv_conf""", """standalone""", """max_restarts""", """monitor_interval""", """start_method""", """role""", """module""", """m""", """no_python""", """run_path""", """log_dir""", """r""", """redirects""", """t""", """tee""", """node_rank""", """master_addr""", """master_port""", ] __lowerCamelCase = ["""DEEPSPEED""", """MULTI_GPU""", """FSDP""", """MEGATRON_LM"""] __lowerCamelCase = ["""DEEPSPEED""", """MULTI_XPU""", """FSDP"""]
59
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
0
"""simple docstring""" from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case__ : List[str] = datasets.load_iris() snake_case__ : Union[str, Any] = np.array(data['''data''']) snake_case__ : Optional[Any] = np.array(data['''target''']) snake_case__ : Optional[Any] = data['''target_names'''] snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = train_test_split(X, y) def _snake_case ( _snake_case : Union[str, Any] , _snake_case : Dict ): return np.linalg.norm(np.array(_snake_case ) - np.array(_snake_case ) ) def _snake_case ( _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Dict=5 ): lowerCAmelCase : Optional[Any] = zip(_snake_case , _snake_case ) # List of distances of all points from the point to be classified lowerCAmelCase : Union[str, Any] = [] for data_point in data: lowerCAmelCase : Any = euclidean_distance(data_point[0] , _snake_case ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. lowerCAmelCase : str = [i[1] for i in sorted(_snake_case )[:k]] # Most commonly occurring class among them # is the class into which the point is classified lowerCAmelCase : Optional[Any] = Counter(_snake_case ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
60
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
0
"""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 = None _a = logging.get_logger(__name__) _a = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} _a = { '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 = { 'google/fnet-base': 512, 'google/fnet-large': 512, } _a = '▁' class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Tuple = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["""input_ids""", """token_type_ids"""] SCREAMING_SNAKE_CASE__ : Tuple = FNetTokenizer def __init__( self , lowercase_=None , lowercase_=None , lowercase_=False , lowercase_=True , lowercase_=True , lowercase_="<unk>" , lowercase_="[SEP]" , lowercase_="<pad>" , lowercase_="[CLS]" , lowercase_="[MASK]" , **lowercase_ , ): """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCAmelCase_ : int = ( AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_ , normalized=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else mask_token ) super().__init__( lowercase_ , tokenizer_file=lowercase_ , do_lower_case=lowercase_ , remove_space=lowercase_ , keep_accents=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , pad_token=lowercase_ , cls_token=lowercase_ , mask_token=lowercase_ , **lowercase_ , ) UpperCAmelCase_ : Any = do_lower_case UpperCAmelCase_ : Tuple = remove_space UpperCAmelCase_ : str = keep_accents UpperCAmelCase_ : Any = vocab_file UpperCAmelCase_ : List[Any] = False if not self.vocab_file else True def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" UpperCAmelCase_ : Tuple = [self.sep_token_id] UpperCAmelCase_ : 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 UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" UpperCAmelCase_ : Any = [self.sep_token_id] UpperCAmelCase_ : 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 ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" if not os.path.isdir(lowercase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : List[str] = os.path.join( lowercase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ): copyfile(self.vocab_file , lowercase_ ) return (out_vocab_file,)
61
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
0
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): while y: # --> when y=0 then loop will terminate and return x as final GCD. __UpperCamelCase , __UpperCamelCase =y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): try: __UpperCamelCase =input('Enter two integers separated by comma (,): ' ).split(',' ) __UpperCamelCase =int(nums[0] ) __UpperCamelCase =int(nums[1] ) print( F'greatest_common_divisor({num_a}, {num_a}) = ' F'{greatest_common_divisor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )}' ) print(F'By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )}' ) except (IndexError, UnboundLocalError, ValueError): print('Wrong input' ) if __name__ == "__main__": main()
62
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values 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 import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) __a =( { 'feature-extraction': TFMobileBertModel, 'fill-mask': TFMobileBertForMaskedLM, 'question-answering': TFMobileBertForQuestionAnswering, 'text-classification': TFMobileBertForSequenceClassification, 'token-classification': TFMobileBertForTokenClassification, 'zero-shot': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) __a =False __a =False def UpperCamelCase__ ( self : str , __a : Tuple , __a : Optional[Any] , __a : List[str]=False ): _a = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class in get_values(__a ): _a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] , __a : int , __a : Union[str, Any]=13 , __a : int=7 , __a : List[str]=True , __a : str=True , __a : Union[str, Any]=True , __a : Union[str, Any]=True , __a : Tuple=99 , __a : Any=32 , __a : Tuple=32 , __a : Any=2 , __a : int=4 , __a : Dict=37 , __a : Union[str, Any]="gelu" , __a : Optional[Any]=0.1 , __a : Union[str, Any]=0.1 , __a : Dict=5_12 , __a : int=16 , __a : str=2 , __a : Tuple=0.02 , __a : Any=3 , __a : Tuple=4 , __a : Any=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope _a = embedding_size def UpperCamelCase__ ( self : Any ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = 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 , 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self : Optional[int] , __a : Optional[Any] , __a : int , __a : Tuple , __a : str , __a : List[Any] , __a : List[Any] , __a : str ): _a = TFMobileBertModel(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) _a = [input_ids, input_mask] _a = model(__a ) _a = model(__a ) 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 UpperCamelCase__ ( self : List[str] , __a : List[str] , __a : Dict , __a : Tuple , __a : Union[str, Any] , __a : Dict , __a : List[Any] , __a : List[str] ): _a = TFMobileBertForMaskedLM(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Dict , __a : Dict , __a : Any , __a : Any , __a : str , __a : Tuple , __a : str ): _a = TFMobileBertForNextSentencePrediction(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple , __a : Optional[Any] , __a : List[Any] , __a : List[Any] , __a : List[str] , __a : Optional[Any] , __a : List[Any] ): _a = TFMobileBertForPreTraining(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) 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 UpperCamelCase__ ( self : List[str] , __a : List[Any] , __a : str , __a : str , __a : Union[str, Any] , __a : List[Any] , __a : List[Any] , __a : List[Any] ): _a = self.num_labels _a = TFMobileBertForSequenceClassification(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self : Any , __a : str , __a : Any , __a : Optional[int] , __a : int , __a : Optional[int] , __a : int , __a : List[Any] ): _a = self.num_choices _a = TFMobileBertForMultipleChoice(config=__a ) _a = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _a = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _a = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _a = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _a = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self : List[str] , __a : List[str] , __a : List[Any] , __a : Dict , __a : Dict , __a : int , __a : str , __a : List[str] ): _a = self.num_labels _a = TFMobileBertForTokenClassification(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self : Optional[Any] , __a : Tuple , __a : List[Any] , __a : str , __a : int , __a : Any , __a : int , __a : List[str] ): _a = TFMobileBertForQuestionAnswering(config=__a ) _a = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _a = model(__a ) 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 UpperCamelCase__ ( self : Any ): _a = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) = config_and_inputs _a = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict def UpperCamelCase__ ( self : str ): _a = TFMobileBertModelTest.TFMobileBertModelTester(self ) _a = ConfigTester(self , config_class=__a , hidden_size=37 ) def UpperCamelCase__ ( self : Tuple ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*__a ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*__a ) def UpperCamelCase__ ( self : List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*__a ) def UpperCamelCase__ ( self : Optional[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*__a ) @slow def UpperCamelCase__ ( self : List[str] ): # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: _a = TFMobileBertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_tf class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__ ( self : Optional[Any] ): _a = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased" ) _a = tf.constant([[0, 1, 2, 3, 4, 5]] ) _a = model(__a )[0] _a = [1, 6, 3_05_22] self.assertEqual(output.shape , __a ) _a = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-4 )
63
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
0
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": A_ = argparse.ArgumentParser( description=( '''Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''bert''', choices=['''bert''']) parser.add_argument('''--model_name''', default='''bert-base-uncased''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_bert-base-uncased_0247911.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') A_ = parser.parse_args() if args.model_type == "bert": A_ = BertForMaskedLM.from_pretrained(args.model_name) A_ = '''bert''' else: raise ValueError('''args.model_type should be "bert".''') A_ = model.state_dict() A_ = {} for w in ["word_embeddings", "position_embeddings"]: A_ = state_dict[F'''{prefix}.embeddings.{w}.weight'''] for w in ["weight", "bias"]: A_ = state_dict[F'''{prefix}.embeddings.LayerNorm.{w}'''] A_ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}''' ] A_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}''' ] std_idx += 1 A_ = state_dict['''cls.predictions.decoder.weight'''] A_ = state_dict['''cls.predictions.bias'''] if args.vocab_transform: for w in ["weight", "bias"]: A_ = state_dict[F'''cls.predictions.transform.dense.{w}'''] A_ = state_dict[F'''cls.predictions.transform.LayerNorm.{w}'''] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
64
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
0
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class A : __UpperCAmelCase : CommonSchedulerState # setable values __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : Optional[int] = None @classmethod def lowercase_ (cls : Any , __UpperCAmelCase : CommonSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray ) -> List[str]: """simple docstring""" return cls(common=__UpperCAmelCase , init_noise_sigma=__UpperCAmelCase , timesteps=__UpperCAmelCase ) @dataclass class A ( UpperCAmelCase_ ): __UpperCAmelCase : DDPMSchedulerState class A ( UpperCAmelCase_ , UpperCAmelCase_ ): __UpperCAmelCase : Any = [e.name for e in FlaxKarrasDiffusionSchedulers] __UpperCAmelCase : jnp.dtype @property def lowercase_ (self : Any ) -> Union[str, Any]: """simple docstring""" return True @register_to_config def __init__(self : Optional[Any] , __UpperCAmelCase : int = 1_0_0_0 , __UpperCAmelCase : float = 0.0001 , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : str = "linear" , __UpperCAmelCase : Optional[jnp.ndarray] = None , __UpperCAmelCase : str = "fixed_small" , __UpperCAmelCase : bool = True , __UpperCAmelCase : str = "epsilon" , __UpperCAmelCase : jnp.dtype = jnp.floataa , ) -> List[str]: """simple docstring""" UpperCAmelCase__ = dtype def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : Optional[CommonSchedulerState] = None ) -> DDPMSchedulerState: """simple docstring""" if common is None: UpperCAmelCase__ = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution UpperCAmelCase__ = jnp.array(1.0 , dtype=self.dtype ) UpperCAmelCase__ = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__UpperCAmelCase , init_noise_sigma=__UpperCAmelCase , timesteps=__UpperCAmelCase , ) def lowercase_ (self : Optional[int] , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : Optional[int] = None ) -> jnp.ndarray: """simple docstring""" return sample def lowercase_ (self : Any , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : int , __UpperCAmelCase : Tuple = () ) -> DDPMSchedulerState: """simple docstring""" UpperCAmelCase__ = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 UpperCAmelCase__ = (jnp.arange(0 , __UpperCAmelCase ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__UpperCAmelCase , timesteps=__UpperCAmelCase , ) def lowercase_ (self : str , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Optional[int]=None ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = state.common.alphas_cumprod[t] UpperCAmelCase__ = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCAmelCase__ = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: UpperCAmelCase__ = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": UpperCAmelCase__ = jnp.clip(__UpperCAmelCase , a_min=1E-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": UpperCAmelCase__ = jnp.log(jnp.clip(__UpperCAmelCase , a_min=1E-20 ) ) elif variance_type == "fixed_large": UpperCAmelCase__ = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log UpperCAmelCase__ = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": UpperCAmelCase__ = variance UpperCAmelCase__ = state.common.betas[t] UpperCAmelCase__ = (predicted_variance + 1) / 2 UpperCAmelCase__ = frac * max_log + (1 - frac) * min_log return variance def lowercase_ (self : int , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : int , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : Optional[jax.random.KeyArray] = None , __UpperCAmelCase : bool = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: """simple docstring""" UpperCAmelCase__ = timestep if key is None: UpperCAmelCase__ = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: UpperCAmelCase__ , UpperCAmelCase__ = jnp.split(__UpperCAmelCase , sample.shape[1] , axis=1 ) else: UpperCAmelCase__ = None # 1. compute alphas, betas UpperCAmelCase__ = state.common.alphas_cumprod[t] UpperCAmelCase__ = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) UpperCAmelCase__ = 1 - alpha_prod_t UpperCAmelCase__ = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCAmelCase__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCAmelCase__ = model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` """ " for the FlaxDDPMScheduler." ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCAmelCase__ = jnp.clip(__UpperCAmelCase , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase__ = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t UpperCAmelCase__ = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase__ = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): UpperCAmelCase__ = jax.random.split(__UpperCAmelCase , num=1 ) UpperCAmelCase__ = jax.random.normal(__UpperCAmelCase , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__UpperCAmelCase , __UpperCAmelCase , predicted_variance=__UpperCAmelCase ) ** 0.5) * noise UpperCAmelCase__ = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) UpperCAmelCase__ = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__UpperCAmelCase , state=__UpperCAmelCase ) def lowercase_ (self : int , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , ) -> jnp.ndarray: """simple docstring""" return add_noise_common(state.common , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def lowercase_ (self : Tuple , __UpperCAmelCase : DDPMSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , ) -> jnp.ndarray: """simple docstring""" return get_velocity_common(state.common , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __len__(self : int ) -> Union[str, Any]: """simple docstring""" return self.config.num_train_timesteps
65
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision 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 LevitImageProcessor class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self: int , snake_case: int , snake_case: Tuple=7 , snake_case: Optional[int]=3 , snake_case: List[Any]=18 , snake_case: Dict=30 , snake_case: Optional[int]=400 , snake_case: int=True , snake_case: Dict=None , snake_case: Dict=True , snake_case: Tuple=None , snake_case: Optional[Any]=True , snake_case: Dict=[0.5, 0.5, 0.5] , snake_case: Union[str, Any]=[0.5, 0.5, 0.5] , ) -> int: snake_case_ :Tuple = size if size is not None else {"""shortest_edge""": 18} snake_case_ :Dict = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} snake_case_ :str = parent snake_case_ :int = batch_size snake_case_ :Tuple = num_channels snake_case_ :Any = image_size snake_case_ :int = min_resolution snake_case_ :Dict = max_resolution snake_case_ :Any = do_resize snake_case_ :Optional[int] = size snake_case_ :Optional[int] = do_center_crop snake_case_ :Dict = crop_size snake_case_ :int = do_normalize snake_case_ :Optional[Any] = image_mean snake_case_ :Optional[Any] = image_std def lowerCAmelCase_ ( self: List[Any] ) -> str: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class lowerCamelCase ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : List[str] = LevitImageProcessor if is_vision_available() else None def lowerCAmelCase_ ( self: List[Any] ) -> str: snake_case_ :List[str] = LevitImageProcessingTester(self ) @property def lowerCAmelCase_ ( self: str ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self: List[Any] ) -> Any: snake_case_ :Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case , """image_mean""" ) ) self.assertTrue(hasattr(snake_case , """image_std""" ) ) self.assertTrue(hasattr(snake_case , """do_normalize""" ) ) self.assertTrue(hasattr(snake_case , """do_resize""" ) ) self.assertTrue(hasattr(snake_case , """do_center_crop""" ) ) self.assertTrue(hasattr(snake_case , """size""" ) ) def lowerCAmelCase_ ( self: Dict ) -> List[str]: snake_case_ :List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) snake_case_ :Tuple = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase_ ( self: Optional[int] ) -> List[str]: pass def lowerCAmelCase_ ( self: int ) -> Optional[Any]: # Initialize image_processing snake_case_ :str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , Image.Image ) # Test not batched input snake_case_ :int = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ :Optional[Any] = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase_ ( self: List[Any] ) -> List[Any]: # Initialize image_processing snake_case_ :List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ :Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , np.ndarray ) # Test not batched input snake_case_ :Union[str, Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ :List[str] = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase_ ( self: List[str] ) -> int: # Initialize image_processing snake_case_ :Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , torch.Tensor ) # Test not batched input snake_case_ :Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ :Optional[int] = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
66
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
0
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP __UpperCAmelCase =False try: __UpperCAmelCase =_is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class a__ : def __init__( self : Dict , a : str = None , a : list = [] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = choices __lowerCamelCase = prompt if sys.platform == "win32": __lowerCamelCase = '''*''' else: __lowerCamelCase = '''➔ ''' def SCREAMING_SNAKE_CASE__ ( self : str , a : int , a : str = "" ): """simple docstring""" if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : int ): """simple docstring""" if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def SCREAMING_SNAKE_CASE__ ( self : Any , a : Direction , a : int = 1 ): """simple docstring""" __lowerCamelCase = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['''up'''] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" self.move_direction(Direction.UP ) @input.mark(KEYMAP['''down'''] ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['''newline'''] ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" move_cursor(len(self.choices ) - self.position , '''DOWN''' ) return self.position @input.mark(KEYMAP['''interrupt'''] ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" move_cursor(len(self.choices ) - self.position , '''DOWN''' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = int(chr(self.current_selection ) ) __lowerCamelCase = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : int = 0 ): """simple docstring""" if self.prompt: linebreak() forceWrite(self.prompt , '''\n''' ) if in_colab: forceWrite('''Please input a choice index (starting from 0), and press enter''' , '''\n''' ) else: forceWrite('''Please select a choice using the arrow or number keys, and selecting with enter''' , '''\n''' ) __lowerCamelCase = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('''\n''' ) move_cursor(len(self.choices ) - self.position , '''UP''' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase = int(builtins.input() ) except ValueError: __lowerCamelCase = default_choice else: __lowerCamelCase = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , '''UP''' ) clear_line() self.write_choice(a , '''\n''' ) return choice
67
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 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(lowerCAmelCase_ ): 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: a__ : List[str] = 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()
54
0
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = None def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any]=0.999 , SCREAMING_SNAKE_CASE_: str="cosine" , ) -> Optional[int]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(SCREAMING_SNAKE_CASE_: Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(SCREAMING_SNAKE_CASE_: List[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A__ = [] for i in range(SCREAMING_SNAKE_CASE_ ): A__ = i / num_diffusion_timesteps A__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) / alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) return torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) class a__ ( snake_case , snake_case ): """simple docstring""" __lowerCamelCase = 1 @register_to_config def __init__( self , lowercase = 1000 , lowercase = 0.0001 , lowercase = 0.02 , lowercase = "linear" , lowercase = None , lowercase = True , lowercase = True , lowercase = 0 , lowercase = "epsilon" , lowercase = 1.0 , **lowercase , ) -> Union[str, Any]: '''simple docstring''' if kwargs.get("set_alpha_to_one" , lowercase ) is not None: A__ = ( "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead." ) deprecate("set_alpha_to_one" , "1.0.0" , lowercase , standard_warn=lowercase ) A__ = kwargs["set_alpha_to_one"] if trained_betas is not None: A__ = torch.tensor(lowercase , dtype=torch.floataa ) elif beta_schedule == "linear": A__ = torch.linspace(lowercase , lowercase , lowercase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowercase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A__ = betas_for_alpha_bar(lowercase ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A__ = 1.0 - self.betas A__ = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. A__ = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution A__ = 1.0 # setable values A__ = None A__ = torch.from_numpy(np.arange(0 , lowercase ).copy().astype(np.intaa ) ) def UpperCamelCase ( self , lowercase , lowercase = None ) -> torch.FloatTensor: '''simple docstring''' return sample def UpperCamelCase ( self , lowercase , lowercase = None ) -> Optional[int]: '''simple docstring''' if num_inference_steps > self.config.num_train_timesteps: raise ValueError( F'`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:' F' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle' F' maximal {self.config.num_train_timesteps} timesteps.' ) A__ = num_inference_steps A__ = self.config.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 A__ = (np.arange(0 , lowercase ) * step_ratio).round().copy().astype(np.intaa ) A__ = torch.from_numpy(lowercase ).to(lowercase ) self.timesteps += self.config.steps_offset def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = 0.0 , lowercase = False , lowercase = None , lowercase = True , ) -> Union[DDIMSchedulerOutput, Tuple]: '''simple docstring''' A__ = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process A__ = self.alphas_cumprod[timestep] A__ = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) A__ = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": A__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 A__ = model_output elif self.config.prediction_type == "sample": A__ = model_output A__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": A__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output A__ = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or' " `v_prediction`" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: A__ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=lowercase , pred_original_sample=lowercase ) def __len__( self ) -> Optional[Any]: '''simple docstring''' return self.config.num_train_timesteps
68
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def UpperCAmelCase ( ) -> Generator[int, None, None]: snake_case_ = {} snake_case_ = 2 while True: snake_case_ = factor_map.pop(UpperCAmelCase , UpperCAmelCase ) if factor: snake_case_ = factor + prime while x in factor_map: x += factor snake_case_ = factor else: snake_case_ = prime yield prime prime += 1 def UpperCAmelCase ( UpperCAmelCase = 1e10 ) -> int: snake_case_ = sieve() snake_case_ = 1 while True: snake_case_ = next(UpperCAmelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(UpperCAmelCase ) n += 2 if __name__ == "__main__": print(solution())
69
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES A__ : Any ='''tiny-wmt19-en-ru''' # Build # borrowed from a test A__ : Optional[Any] =[ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] A__ : Dict =dict(zip(vocab, range(len(vocab)))) A__ : Tuple =['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: A__ : str =Path(tmpdirname) A__ : Union[str, Any] =build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] A__ : Union[str, Any] =build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] A__ : str =build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, '''w''') as fp: fp.write('''\n'''.join(merges)) A__ : Any =FSMTTokenizer( langs=['''en''', '''ru'''], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) A__ : Optional[Any] =FSMTConfig( langs=['''ru''', '''en'''], src_vocab_size=10_00, tgt_vocab_size=10_00, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) A__ : List[Any] =FSMTForConditionalGeneration(config) print(F"""num of params {tiny_model.num_parameters()}""") # Test A__ : Union[str, Any] =tokenizer(['''Making tiny model'''], return_tensors='''pt''') A__ : List[str] =tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"""Generated {mname_tiny}""") # Upload # transformers-cli upload tiny-wmt19-en-ru
70
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
from bisect import bisect from itertools import accumulate def A ( a_ ,a_ ,a_ ,a_ ) -> Optional[Any]: __UpperCamelCase : str =sorted(zip(a_ ,a_ ) ,key=lambda a_ : x[0] / x[1] ,reverse=a_ ) __UpperCamelCase , __UpperCamelCase : int =[i[0] for i in r], [i[1] for i in r] __UpperCamelCase : List[str] =list(accumulate(a_ ) ) __UpperCamelCase : str =bisect(a_ ,a_ ) 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()
71
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
"""simple docstring""" import math from collections.abc import Callable def snake_case_ ( A_ : Callable[[float], float], A_ : float, A_ : float ): '''simple docstring''' _lowerCamelCase : float = xa _lowerCamelCase : float = xa while True: if x_n == x_na or function(A_ ) == function(A_ ): raise ZeroDivisionError('''float division by zero, could not find root''' ) _lowerCamelCase : float = x_na - ( function(A_ ) / ((function(A_ ) - function(A_ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na _lowerCamelCase : int = x_na _lowerCamelCase : List[Any] = x_na def snake_case_ ( A_ : float ): '''simple docstring''' return math.pow(A_, 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
72
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[Any] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : Optional[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : int = [file for file in files if n_ not in file] else: __lowerCamelCase : List[str] = [file for file in files if n_identifier not in file] __lowerCamelCase : Any = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Dict = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : List[Any] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : Union[str, Any] = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : List[Any] = 'modeling' __lowerCamelCase : int = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : int = Path('src/transformers') __lowerCamelCase : Any = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : Tuple = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Any = Path('src/transformers') __lowerCamelCase : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : List[str] = Path('docs/source') __lowerCamelCase : int = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
73
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
"""simple docstring""" import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def _snake_case ( snake_case__ : List[str] ): A = [] for line in lines: A = re.sub(r'#.*' , '' , snake_case__ ) # remove comments if line: filtered_lines.append(snake_case__ ) A = '\n'.join(snake_case__ ) # Make a hash from all this code A = full_str.encode('utf-8' ) return shaaaa(snake_case__ ).hexdigest() # get importable module names and hash for caching _lowercase = { '''csv''': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), '''json''': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), '''pandas''': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), '''parquet''': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), '''arrow''': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), '''text''': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), '''imagefolder''': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), '''audiofolder''': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions _lowercase = { '''.csv''': ('''csv''', {}), '''.tsv''': ('''csv''', {'''sep''': '''\t'''}), '''.json''': ('''json''', {}), '''.jsonl''': ('''json''', {}), '''.parquet''': ('''parquet''', {}), '''.arrow''': ('''arrow''', {}), '''.txt''': ('''text''', {}), } _EXTENSION_TO_MODULE.update({ext: ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _lowercase = {'''imagefolder''', '''audiofolder'''} # Used to filter data files based on extensions given a module name _lowercase = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('''.zip''') _MODULE_TO_EXTENSIONS["audiofolder"].append('''.zip''')
74
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging a_ : List[Any] = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) a_ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def a_ ( ) -> List[str]: """simple docstring""" lowerCamelCase_ ='''https://pypi.org/pypi/diffusers/json''' lowerCamelCase_ =json.loads(request.urlopen(__snake_case ).read() )['''releases'''].keys() return sorted(__snake_case , key=lambda __snake_case : version.Version(__snake_case ) ) def a_ ( ) -> str: """simple docstring""" # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return sys.path.append(__snake_case ) os.makedirs(__snake_case , exist_ok=__snake_case ) lowerCamelCase_ =Path(__snake_case ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def a_ ( __snake_case : Union[str, os.PathLike] ) -> List[str]: """simple docstring""" init_hf_modules() lowerCamelCase_ =Path(__snake_case ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__snake_case , exist_ok=__snake_case ) lowerCamelCase_ =dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def a_ ( __snake_case : Tuple ) -> List[str]: """simple docstring""" with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: lowerCamelCase_ =f.read() # Imports of the form `import .xxx` lowerCamelCase_ =re.findall('''^\s*import\s+\.(\S+)\s*$''' , __snake_case , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __snake_case , flags=re.MULTILINE ) # Unique-ify return list(set(__snake_case ) ) def a_ ( __snake_case : str ) -> str: """simple docstring""" lowerCamelCase_ =False lowerCamelCase_ =[module_file] lowerCamelCase_ =[] # Let's recurse through all relative imports while not no_change: lowerCamelCase_ =[] for f in files_to_check: new_imports.extend(get_relative_imports(__snake_case ) ) lowerCamelCase_ =Path(__snake_case ).parent lowerCamelCase_ =[str(module_path / m ) for m in new_imports] lowerCamelCase_ =[f for f in new_import_files if f not in all_relative_imports] lowerCamelCase_ =[F'''{f}.py''' for f in new_import_files] lowerCamelCase_ =len(__snake_case ) == 0 all_relative_imports.extend(__snake_case ) return all_relative_imports def a_ ( __snake_case : Union[str, Any] ) -> Optional[int]: """simple docstring""" with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: lowerCamelCase_ =f.read() # Imports of the form `import xxx` lowerCamelCase_ =re.findall('''^\s*import\s+(\S+)\s*$''' , __snake_case , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __snake_case , flags=re.MULTILINE ) # Only keep the top-level module lowerCamelCase_ =[imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowerCamelCase_ =list(set(__snake_case ) ) lowerCamelCase_ =[] for imp in imports: try: importlib.import_module(__snake_case ) except ImportError: missing_packages.append(__snake_case ) if len(__snake_case ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__snake_case )}. Run `pip install {' '.join(__snake_case )}`''' ) return get_relative_imports(__snake_case ) def a_ ( __snake_case : Tuple , __snake_case : Tuple ) -> List[Any]: """simple docstring""" lowerCamelCase_ =module_path.replace(os.path.sep , '''.''' ) lowerCamelCase_ =importlib.import_module(__snake_case ) if class_name is None: return find_pipeline_class(__snake_case ) return getattr(__snake_case , __snake_case ) def a_ ( __snake_case : Dict ) -> Any: """simple docstring""" from ..pipelines import DiffusionPipeline lowerCamelCase_ =dict(inspect.getmembers(__snake_case , inspect.isclass ) ) lowerCamelCase_ =None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __snake_case ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowerCamelCase_ =cls return pipeline_class def a_ ( __snake_case : Union[str, os.PathLike] , __snake_case : str , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ =str(__snake_case ) lowerCamelCase_ =os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ): lowerCamelCase_ =module_file_or_url lowerCamelCase_ ='''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowerCamelCase_ =get_diffusers_versions() # cut ".dev0" lowerCamelCase_ ='''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowerCamelCase_ =latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowerCamelCase_ =F'''v{revision}''' elif revision == "main": lowerCamelCase_ =revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowerCamelCase_ =COMMUNITY_PIPELINES_URL.format(revision=__snake_case , pipeline=__snake_case ) try: lowerCamelCase_ =cached_download( __snake_case , cache_dir=__snake_case , force_download=__snake_case , proxies=__snake_case , resume_download=__snake_case , local_files_only=__snake_case , use_auth_token=__snake_case , ) lowerCamelCase_ ='''git''' lowerCamelCase_ =pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowerCamelCase_ =hf_hub_download( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , proxies=__snake_case , resume_download=__snake_case , local_files_only=__snake_case , use_auth_token=__snake_case , ) lowerCamelCase_ =os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowerCamelCase_ =check_imports(__snake_case ) # Now we move the module inside our cached dynamic modules. lowerCamelCase_ =DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__snake_case ) lowerCamelCase_ =Path(__snake_case ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__snake_case , submodule_path / module_file ) for module_needed in modules_needed: lowerCamelCase_ =F'''{module_needed}.py''' shutil.copy(os.path.join(__snake_case , __snake_case ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__snake_case , __snake_case ): lowerCamelCase_ =use_auth_token elif use_auth_token is True: lowerCamelCase_ =HfFolder.get_token() else: lowerCamelCase_ =None lowerCamelCase_ =model_info(__snake_case , revision=__snake_case , token=__snake_case ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowerCamelCase_ =submodule_path / commit_hash lowerCamelCase_ =full_submodule + os.path.sep + commit_hash create_dynamic_module(__snake_case ) if not (submodule_path / module_file).exists(): shutil.copy(__snake_case , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __snake_case , F'''{module_needed}.py''' , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) return os.path.join(__snake_case , __snake_case ) def a_ ( __snake_case : Union[str, os.PathLike] , __snake_case : str , __snake_case : Optional[str] = None , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , **__snake_case : Optional[int] , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ =get_cached_module_file( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) return get_class_in_module(__snake_case , final_module.replace('''.py''' , '''''' ) )
75
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCamelCase__ ( _a , _a): # Load checkpoint SCREAMING_SNAKE_CASE : int = torch.load(_a , map_location="cpu") SCREAMING_SNAKE_CASE : Dict = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : List[str] = v else: SCREAMING_SNAKE_CASE : int = v SCREAMING_SNAKE_CASE : int = chkpt["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(_a , (torch.FloatTensor, numpy.ndarray))} SCREAMING_SNAKE_CASE : List[Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE : List[Any] = {s + "</w>" if s.find("@@") == -1 and i > 13 else s.replace("@@" , ""): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f"Save PyTorch model to {pytorch_weights_dump_path}") torch.save(_a , _a) print(f"Save configuration file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") print(f"Save vocab file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
76
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0
"""simple docstring""" def a_ ( _lowerCAmelCase : str , _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : Optional[Any] = len(_lowerCAmelCase ) lowercase__ : Any = len(_lowerCAmelCase ) lowercase__ : Optional[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] lowercase__ : Any = True for i in range(_lowerCAmelCase ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: lowercase__ : Tuple = True if a[i].islower(): lowercase__ : Optional[int] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
77
"""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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
0
"""simple docstring""" import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class A_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) UpperCAmelCase = Vector() def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(lowercase_ ) , '(0,0,0,0,0,1)' ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Vector([1, 2, 3, 4] ) self.assertEqual(len(lowercase_ ) , 4 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2] ) UpperCAmelCase = Vector([1, 2, 3, 4, 5] ) UpperCAmelCase = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) UpperCAmelCase = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCAmelCase__ ( self :Dict ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCAmelCase__ ( self :Tuple ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([2, -1, 4] ) # for test of dot product UpperCAmelCase = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , '(3.0,6.0,9.0)' ) self.assertEqual((a * b) , 0 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: self.assertEqual(str(zero_vector(10 ) ).count('0' ) , 10 ) def UpperCAmelCase__ ( self :List[Any] ) -> None: self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , '(0,1,0)' ) def UpperCAmelCase__ ( self :Dict ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , lowercase_ , lowercase_ ) ) , '(3,4,7)' ) def UpperCAmelCase__ ( self :Tuple ) -> None: UpperCAmelCase = Vector([1, 0, 0, 0, 0, 0] ) UpperCAmelCase = x.copy() self.assertEqual(str(lowercase_ ) , str(lowercase_ ) ) def UpperCAmelCase__ ( self :List[str] ) -> None: UpperCAmelCase = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(lowercase_ ) , '(0,1,0)' ) def UpperCAmelCase__ ( self :str ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual('|1,2,3|\n|2,4,5|\n|6,7,8|\n' , str(lowercase_ ) ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(lowercase_ , lowercase_ ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(lowercase_ , lowercase_ ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) UpperCAmelCase = Vector([1, 2, 3] ) self.assertEqual('(14,32,50)' , str(a * x ) ) self.assertEqual('|2,4,6|\n|8,10,12|\n|14,16,18|\n' , str(a * 2 ) ) def UpperCAmelCase__ ( self :List[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual('|1,2,5|\n|2,4,5|\n|6,7,8|\n' , str(lowercase_ ) ) def UpperCAmelCase__ ( self :int ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|2,4,10|\n|4,8,10|\n|12,14,18|\n' , str(a + b ) ) def UpperCAmelCase__ ( self :str ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|0,0,-4|\n|0,0,0|\n|0,0,-2|\n' , str(a - b ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: self.assertEqual( '|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n' , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
78
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
0
'''simple docstring''' # limitations under the License. # 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 .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( '''pipelines_utils''', '''0.22.0''', '''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''', standard_warn=False, stacklevel=3, )
79
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
0
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
"""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_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["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 __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # 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})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a ={ '''task_specific_params''': { '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4}, '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4}, '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6}, } } a ={ '''task_specific_params.summarization.length_penalty''': 1.0, '''task_specific_params.summarization.max_length''': 128, '''task_specific_params.summarization.min_length''': 12, '''task_specific_params.summarization.num_beams''': 4, '''task_specific_params.summarization_cnn.length_penalty''': 2.0, '''task_specific_params.summarization_cnn.max_length''': 142, '''task_specific_params.summarization_cnn.min_length''': 56, '''task_specific_params.summarization_cnn.num_beams''': 4, '''task_specific_params.summarization_xsum.length_penalty''': 1.0, '''task_specific_params.summarization_xsum.max_length''': 62, '''task_specific_params.summarization_xsum.min_length''': 11, '''task_specific_params.summarization_xsum.num_beams''': 6, } self.assertEqual(flatten_dict(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(__A ) , x.transpose() ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Any: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A ) , np.asarray(transpose(__A ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , np.asarray(transpose(__A , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.reshape(__A , (4, 3) ) ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.reshape(__A , (12, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.asarray(reshape(__A , (4, 3) ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.asarray(reshape(__A , (12, 5) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(__A ) , np.squeeze(__A ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.squeeze(__A , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(1 , 3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =np.random.randn(1 , 3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(1 , 3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A ) , np.asarray(squeeze(__A ) ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.asarray(squeeze(__A , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.expand_dims(__A , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.asarray(expand_dims(__A , axis=1 ) ) ) )
81
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
0
import math def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initial intensity if angle < 0 or angle > 3_60: raise ValueError("""In Malus Law, the angle is in the range 0-360 degrees""" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(snake_case ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="""malus_law""")
82
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase__ ( lowercase ): lowercase__ = 42 lowercase__ = 42 class lowercase__ ( nn.Module ): lowercase__ = 42 lowercase__ = (16, 32, 96, 2_56) lowercase__ = jnp.floataa def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _UpperCamelCase : List[str] = nn.Conv( self.block_out_channels[0] ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) _UpperCamelCase : List[Any] = [] for i in range(len(self.block_out_channels ) - 1 ): _UpperCamelCase : Optional[int] = self.block_out_channels[i] _UpperCamelCase : List[Any] = self.block_out_channels[i + 1] _UpperCamelCase : int = nn.Conv( lowerCamelCase__ ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) blocks.append(lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = nn.Conv( lowerCamelCase__ ,kernel_size=(3, 3) ,strides=(2, 2) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) blocks.append(lowerCamelCase__ ) _UpperCamelCase : Any = blocks _UpperCamelCase : List[str] = nn.Conv( self.conditioning_embedding_channels ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) def __call__( self : List[Any] ,lowerCamelCase__ : Tuple ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.conv_in(lowerCamelCase__ ) _UpperCamelCase : List[Any] = nn.silu(lowerCamelCase__ ) for block in self.blocks: _UpperCamelCase : List[str] = block(lowerCamelCase__ ) _UpperCamelCase : Dict = nn.silu(lowerCamelCase__ ) _UpperCamelCase : List[str] = self.conv_out(lowerCamelCase__ ) return embedding @flax_register_to_config class lowercase__ ( nn.Module , lowercase , lowercase ): lowercase__ = 32 lowercase__ = 4 lowercase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowercase__ = False lowercase__ = (3_20, 6_40, 12_80, 12_80) lowercase__ = 2 lowercase__ = 8 lowercase__ = None lowercase__ = 12_80 lowercase__ = 0.0 lowercase__ = False lowercase__ = jnp.floataa lowercase__ = True lowercase__ = 0 lowercase__ = "rgb" lowercase__ = (16, 32, 96, 2_56) def UpperCamelCase_ ( self : List[Any] ,lowerCamelCase__ : jax.random.KeyArray ): '''simple docstring''' # init input tensors _UpperCamelCase : Optional[Any] = (1, self.in_channels, self.sample_size, self.sample_size) _UpperCamelCase : Tuple = jnp.zeros(lowerCamelCase__ ,dtype=jnp.floataa ) _UpperCamelCase : Optional[int] = jnp.ones((1,) ,dtype=jnp.intaa ) _UpperCamelCase : Any = jnp.zeros((1, 1, self.cross_attention_dim) ,dtype=jnp.floataa ) _UpperCamelCase : Tuple = (1, 3, self.sample_size * 8, self.sample_size * 8) _UpperCamelCase : Union[str, Any] = jnp.zeros(lowerCamelCase__ ,dtype=jnp.floataa ) _UpperCamelCase , _UpperCamelCase : Optional[int] = jax.random.split(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )["params"] def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = self.block_out_channels _UpperCamelCase : Optional[int] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _UpperCamelCase : Dict = self.num_attention_heads or self.attention_head_dim # input _UpperCamelCase : Optional[int] = nn.Conv( block_out_channels[0] ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) # time _UpperCamelCase : Union[str, Any] = FlaxTimesteps( block_out_channels[0] ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.config.freq_shift ) _UpperCamelCase : List[Any] = FlaxTimestepEmbedding(lowerCamelCase__ ,dtype=self.dtype ) _UpperCamelCase : str = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] ,block_out_channels=self.conditioning_embedding_out_channels ,) _UpperCamelCase : Tuple = self.only_cross_attention if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase : int = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase : List[str] = (num_attention_heads,) * len(self.down_block_types ) # down _UpperCamelCase : List[Any] = [] _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : Dict = block_out_channels[0] _UpperCamelCase : int = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) for i, down_block_type in enumerate(self.down_block_types ): _UpperCamelCase : Dict = output_channel _UpperCamelCase : List[Any] = block_out_channels[i] _UpperCamelCase : Any = i == len(lowerCamelCase__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": _UpperCamelCase : Any = FlaxCrossAttnDownBlockaD( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,num_attention_heads=num_attention_heads[i] ,add_downsample=not is_final_block ,use_linear_projection=self.use_linear_projection ,only_cross_attention=only_cross_attention[i] ,dtype=self.dtype ,) else: _UpperCamelCase : Dict = FlaxDownBlockaD( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,add_downsample=not is_final_block ,dtype=self.dtype ,) down_blocks.append(lowerCamelCase__ ) for _ in range(self.layers_per_block ): _UpperCamelCase : Any = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) if not is_final_block: _UpperCamelCase : List[Any] = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = down_blocks _UpperCamelCase : List[str] = controlnet_down_blocks # mid _UpperCamelCase : Any = block_out_channels[-1] _UpperCamelCase : Tuple = FlaxUNetMidBlockaDCrossAttn( in_channels=lowerCamelCase__ ,dropout=self.dropout ,num_attention_heads=num_attention_heads[-1] ,use_linear_projection=self.use_linear_projection ,dtype=self.dtype ,) _UpperCamelCase : Any = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) def __call__( self : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ,lowerCamelCase__ : str ,lowerCamelCase__ : float = 1.0 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = False ,): '''simple docstring''' _UpperCamelCase : Any = self.controlnet_conditioning_channel_order if channel_order == "bgr": _UpperCamelCase : Optional[Any] = jnp.flip(lowerCamelCase__ ,axis=1 ) # 1. time if not isinstance(lowerCamelCase__ ,jnp.ndarray ): _UpperCamelCase : Tuple = jnp.array([timesteps] ,dtype=jnp.intaa ) elif isinstance(lowerCamelCase__ ,jnp.ndarray ) and len(timesteps.shape ) == 0: _UpperCamelCase : Optional[Any] = timesteps.astype(dtype=jnp.floataa ) _UpperCamelCase : List[str] = jnp.expand_dims(lowerCamelCase__ ,0 ) _UpperCamelCase : Any = self.time_proj(lowerCamelCase__ ) _UpperCamelCase : Dict = self.time_embedding(lowerCamelCase__ ) # 2. pre-process _UpperCamelCase : List[Any] = jnp.transpose(lowerCamelCase__ ,(0, 2, 3, 1) ) _UpperCamelCase : Optional[int] = self.conv_in(lowerCamelCase__ ) _UpperCamelCase : Optional[int] = jnp.transpose(lowerCamelCase__ ,(0, 2, 3, 1) ) _UpperCamelCase : Tuple = self.controlnet_cond_embedding(lowerCamelCase__ ) sample += controlnet_cond # 3. down _UpperCamelCase : Any = (sample,) for down_block in self.down_blocks: if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase , _UpperCamelCase : Union[str, Any] = down_block(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) else: _UpperCamelCase , _UpperCamelCase : str = down_block(lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) down_block_res_samples += res_samples # 4. mid _UpperCamelCase : Optional[int] = self.mid_block(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) # 5. contronet blocks _UpperCamelCase : Union[str, Any] = () for down_block_res_sample, controlnet_block in zip(lowerCamelCase__ ,self.controlnet_down_blocks ): _UpperCamelCase : List[str] = controlnet_block(lowerCamelCase__ ) controlnet_down_block_res_samples += (down_block_res_sample,) _UpperCamelCase : Optional[int] = controlnet_down_block_res_samples _UpperCamelCase : Tuple = self.controlnet_mid_block(lowerCamelCase__ ) # 6. scaling _UpperCamelCase : Dict = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=lowerCamelCase__ ,mid_block_res_sample=lowerCamelCase__ )
83
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
0
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, 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 import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _SCREAMING_SNAKE_CASE : def __init__( self , __A , __A=13 , __A=7 , __A=True , __A=True , __A=True , __A=True , __A=99 , __A=32 , __A=2 , __A=4 , __A=37 , __A="gelu" , __A=0.1 , __A=0.1 , __A=512 , __A=16 , __A=2 , __A=0.0_2 , __A=3 , __A=4 , __A=None , ) -> Union[str, Any]: lowerCAmelCase_ :str = parent lowerCAmelCase_ :str = 13 lowerCAmelCase_ :Tuple = 7 lowerCAmelCase_ :Tuple = True lowerCAmelCase_ :List[str] = True lowerCAmelCase_ :int = True lowerCAmelCase_ :str = True lowerCAmelCase_ :List[str] = 99 lowerCAmelCase_ :Tuple = 384 lowerCAmelCase_ :Any = 2 lowerCAmelCase_ :int = 4 lowerCAmelCase_ :Any = 37 lowerCAmelCase_ :Any = """gelu""" lowerCAmelCase_ :Tuple = 0.1 lowerCAmelCase_ :str = 0.1 lowerCAmelCase_ :Dict = 512 lowerCAmelCase_ :Dict = 16 lowerCAmelCase_ :Tuple = 2 lowerCAmelCase_ :List[Any] = 0.0_2 lowerCAmelCase_ :Optional[int] = 3 lowerCAmelCase_ :Tuple = 4 lowerCAmelCase_ :Tuple = 128 lowerCAmelCase_ :Any = 2 lowerCAmelCase_ :Optional[Any] = 9 lowerCAmelCase_ :List[str] = 1 lowerCAmelCase_ :List[str] = None def __lowerCAmelCase ( self ) -> Optional[Any]: lowerCAmelCase_ :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase_ :int = None if self.use_input_mask: lowerCAmelCase_ :str = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase_ :List[str] = None if self.use_token_type_ids: lowerCAmelCase_ :str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase_ :Union[str, Any] = None lowerCAmelCase_ :int = None lowerCAmelCase_ :Optional[Any] = None if self.use_labels: lowerCAmelCase_ :Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase_ :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase_ :str = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase_ :List[Any] = ConvBertConfig( 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 , return_dict=__A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> Union[str, Any]: lowerCAmelCase_ :Optional[int] = TFConvBertModel(config=__A ) lowerCAmelCase_ :Any = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCAmelCase_ :List[str] = [input_ids, input_mask] lowerCAmelCase_ :List[str] = model(__A ) lowerCAmelCase_ :str = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> str: lowerCAmelCase_ :List[Any] = TFConvBertForMaskedLM(config=__A ) lowerCAmelCase_ :Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCAmelCase_ :Optional[int] = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> int: lowerCAmelCase_ :Any = self.num_labels lowerCAmelCase_ :List[str] = TFConvBertForSequenceClassification(config=__A ) lowerCAmelCase_ :List[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCAmelCase_ :Dict = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> Dict: lowerCAmelCase_ :Any = self.num_choices lowerCAmelCase_ :int = TFConvBertForMultipleChoice(config=__A ) lowerCAmelCase_ :List[str] = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase_ :Tuple = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase_ :Dict = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase_ :Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCAmelCase_ :Any = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> Union[str, Any]: lowerCAmelCase_ :Optional[Any] = self.num_labels lowerCAmelCase_ :Tuple = TFConvBertForTokenClassification(config=__A ) lowerCAmelCase_ :Union[str, Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCAmelCase_ :Dict = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , __A , __A , __A , __A , __A , __A , __A ) -> Optional[int]: lowerCAmelCase_ :str = TFConvBertForQuestionAnswering(config=__A ) lowerCAmelCase_ :List[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCAmelCase_ :int = model(__A ) 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 ) -> str: lowerCAmelCase_ :Union[str, Any] = self.prepare_config_and_inputs() ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) :List[Any] = config_and_inputs lowerCAmelCase_ :Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( A__ , A__ , unittest.TestCase ): UpperCAmelCase_ :Union[str, Any] = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase_ :str = ( { "feature-extraction": TFConvBertModel, "fill-mask": TFConvBertForMaskedLM, "question-answering": TFConvBertForQuestionAnswering, "text-classification": TFConvBertForSequenceClassification, "token-classification": TFConvBertForTokenClassification, "zero-shot": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase_ :Union[str, Any] = False UpperCAmelCase_ :List[str] = False UpperCAmelCase_ :Union[str, Any] = False def __lowerCAmelCase ( self ) -> List[str]: lowerCAmelCase_ :List[str] = TFConvBertModelTester(self ) lowerCAmelCase_ :Optional[int] = ConfigTester(self , config_class=__A , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Dict: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Dict: lowerCAmelCase_ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def __lowerCAmelCase ( self ) -> Optional[Any]: lowerCAmelCase_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__A ) def __lowerCAmelCase ( self ) -> Tuple: lowerCAmelCase_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__A ) def __lowerCAmelCase ( self ) -> Tuple: lowerCAmelCase_ :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A ) def __lowerCAmelCase ( self ) -> str: lowerCAmelCase_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__A ) def __lowerCAmelCase ( self ) -> int: lowerCAmelCase_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) @slow def __lowerCAmelCase ( self ) -> Tuple: lowerCAmelCase_ , lowerCAmelCase_ :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_ :Optional[Any] = True lowerCAmelCase_ :Optional[Any] = True if hasattr(__A , """use_cache""" ): lowerCAmelCase_ :Dict = True lowerCAmelCase_ :Tuple = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCAmelCase_ :str = getattr(self.model_tester , """key_length""" , __A ) for model_class in self.all_model_classes: lowerCAmelCase_ :Tuple = self._prepare_for_class(__A , __A ) lowerCAmelCase_ :Optional[Any] = model_class(__A ) lowerCAmelCase_ :List[str] = len(model(__A ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__A , saved_model=__A ) lowerCAmelCase_ :Optional[int] = os.path.join(__A , """saved_model""" , """1""" ) lowerCAmelCase_ :int = tf.keras.models.load_model(__A ) lowerCAmelCase_ :Optional[int] = model(__A ) if self.is_encoder_decoder: lowerCAmelCase_ :Optional[int] = outputs["""encoder_hidden_states"""] lowerCAmelCase_ :int = outputs["""encoder_attentions"""] else: lowerCAmelCase_ :int = outputs["""hidden_states"""] lowerCAmelCase_ :Optional[int] = outputs["""attentions"""] self.assertEqual(len(__A ) , __A ) lowerCAmelCase_ :Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__A ) , __A ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __lowerCAmelCase ( self ) -> Tuple: lowerCAmelCase_ :Dict = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(__A ) def __lowerCAmelCase ( self ) -> Optional[Any]: lowerCAmelCase_ , lowerCAmelCase_ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_ :List[str] = True lowerCAmelCase_ :List[Any] = getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) lowerCAmelCase_ :Dict = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCAmelCase_ :Tuple = getattr(self.model_tester , """key_length""" , __A ) lowerCAmelCase_ :List[Any] = getattr(self.model_tester , """key_length""" , __A ) def check_decoder_attentions_output(__A ): lowerCAmelCase_ :List[str] = len(__A ) self.assertEqual(out_len % 2 , 0 ) lowerCAmelCase_ :Tuple = outputs.decoder_attentions self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__A ): lowerCAmelCase_ :List[str] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: lowerCAmelCase_ :Optional[int] = True lowerCAmelCase_ :Tuple = False lowerCAmelCase_ :Optional[int] = model_class(__A ) lowerCAmelCase_ :Union[str, Any] = model(self._prepare_for_class(__A , __A ) ) lowerCAmelCase_ :Any = len(__A ) self.assertEqual(config.output_hidden_states , __A ) check_encoder_attentions_output(__A ) if self.is_encoder_decoder: lowerCAmelCase_ :Any = model_class(__A ) lowerCAmelCase_ :Optional[Any] = model(self._prepare_for_class(__A , __A ) ) self.assertEqual(config.output_hidden_states , __A ) check_decoder_attentions_output(__A ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowerCAmelCase_ :List[str] = True lowerCAmelCase_ :Union[str, Any] = model_class(__A ) lowerCAmelCase_ :Tuple = model(self._prepare_for_class(__A , __A ) ) self.assertEqual(config.output_hidden_states , __A ) check_encoder_attentions_output(__A ) # Check attention is always last and order is fine lowerCAmelCase_ :Union[str, Any] = True lowerCAmelCase_ :Tuple = True lowerCAmelCase_ :List[Any] = model_class(__A ) lowerCAmelCase_ :Tuple = model(self._prepare_for_class(__A , __A ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__A ) ) self.assertEqual(model.config.output_hidden_states , __A ) check_encoder_attentions_output(__A ) @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> Dict: lowerCAmelCase_ :Optional[int] = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) lowerCAmelCase_ :List[str] = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCAmelCase_ :List[Any] = model(__A )[0] lowerCAmelCase_ :Tuple = [1, 6, 768] self.assertEqual(output.shape , __A ) lowerCAmelCase_ :List[Any] = tf.constant( [ [ [-0.0_3_4_7_5_4_9_3, -0.4_6_8_6_0_3_4, -0.3_0_6_3_8_8_3_2], [0.2_2_6_3_7_2_4_8, -0.2_6_9_8_8_6_4_6, -0.7_4_2_3_4_2_4], [0.1_0_3_2_4_8_6_8, -0.4_5_0_1_3_5_0_8, -0.5_8_2_8_0_7_8_4], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1E-4 )
84
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
0
'''simple docstring''' 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 _snake_case ( lowercase_ ): lowerCAmelCase_ : int = ["image_processor", "tokenizer"] lowerCAmelCase_ : Union[str, Any] = "BridgeTowerImageProcessor" lowerCAmelCase_ : Union[str, Any] = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' super().__init__(a__ , a__ ) def __call__( self , a__ , a__ = None , a__ = True , a__ = False , a__ = None , a__ = None , a__ = 0 , a__ = None , a__ = None , a__ = None , a__ = False , a__ = False , a__ = False , a__ = False , a__ = True , a__ = None , **a__ , ) -> BatchEncoding: '''simple docstring''' 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_token_type_ids=a__ , return_attention_mask=a__ , return_overflowing_tokens=a__ , return_special_tokens_mask=a__ , return_offsets_mapping=a__ , return_length=a__ , verbose=a__ , return_tensors=a__ , **a__ , ) # add pixel_values + pixel_mask snake_case_ = self.image_processor( a__ , return_tensors=a__ , do_normalize=a__ , do_center_crop=a__ , **a__ ) encoding.update(a__ ) return encoding def lowerCAmelCase__ ( self , *a__ , **a__ ) -> Optional[int]: '''simple docstring''' return self.tokenizer.batch_decode(*a__ , **a__ ) def lowerCAmelCase__ ( self , *a__ , **a__ ) -> int: '''simple docstring''' return self.tokenizer.decode(*a__ , **a__ ) @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tokenizer.model_input_names snake_case_ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase__ = { """configuration_mctct""": ["""MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MCTCTConfig"""], """feature_extraction_mctct""": ["""MCTCTFeatureExtractor"""], """processing_mctct""": ["""MCTCTProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ """MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MCTCTForCTC""", """MCTCTModel""", """MCTCTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
86
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
0
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class snake_case_ ( __A ): def __init__( self : Any , *lowercase_ : int , lowercase_ : Tuple=None , lowercase_ : Union[str, Any]=None , **lowercase_ : int ) -> List[str]: super().__init__(*lowercase_ , **lowercase_ ) lowercase__ : Optional[int] = eval_examples lowercase__ : Optional[Any] = post_process_function def __UpperCamelCase ( self : List[str] , lowercase_ : Union[str, Any]=None , lowercase_ : Union[str, Any]=None , lowercase_ : List[str]=None , lowercase_ : str = "eval" ) -> int: lowercase__ : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase__ : Optional[int] = self.get_eval_dataloader(lowercase_ ) lowercase__ : Optional[int] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase__ : str = self.compute_metrics lowercase__ : Optional[int] = None lowercase__ : str = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop lowercase__ : Optional[Any] = time.time() try: lowercase__ : Union[str, Any] = eval_loop( lowercase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=lowercase_ , metric_key_prefix=lowercase_ , ) finally: lowercase__ : Dict = compute_metrics lowercase__ : Union[str, Any] = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( lowercase_ , lowercase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase__ : Tuple = self.post_process_function(lowercase_ , lowercase_ , output.predictions ) lowercase__ : List[str] = self.compute_metrics(lowercase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase__ : Dict = metrics.pop(lowercase_ ) metrics.update(output.metrics ) else: lowercase__ : str = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(lowercase_ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase__ : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , lowercase_ ) return metrics def __UpperCamelCase ( self : List[Any] , lowercase_ : int , lowercase_ : Dict , lowercase_ : Optional[int]=None , lowercase_ : str = "test" ) -> Dict: lowercase__ : str = self.get_test_dataloader(lowercase_ ) # Temporarily disable metric computation, we will do it in the loop here. lowercase__ : int = self.compute_metrics lowercase__ : Optional[int] = None lowercase__ : Union[str, Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop lowercase__ : Dict = time.time() try: lowercase__ : Any = eval_loop( lowercase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=lowercase_ , metric_key_prefix=lowercase_ , ) finally: lowercase__ : Any = compute_metrics lowercase__ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( lowercase_ , lowercase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase__ : Union[str, Any] = self.post_process_function(lowercase_ , lowercase_ , output.predictions , "predict" ) lowercase__ : Tuple = self.compute_metrics(lowercase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase__ : int = metrics.pop(lowercase_ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=lowercase_ )
87
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = ["""image_processor""", """tokenizer"""] a__ = """LayoutLMv3ImageProcessor""" a__ = ("""LayoutLMv3Tokenizer""", """LayoutLMv3TokenizerFast""") def __init__( self : Dict , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , UpperCamelCase__ , ) __magic_name__ = kwargs.pop("""feature_extractor""" ) __magic_name__ = 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__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , UpperCamelCase__ : Union[List[List[int]], List[List[List[int]]]] = None , UpperCamelCase__ : Optional[Union[List[int], List[List[int]]]] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[bool, str, PaddingStrategy] = False , UpperCamelCase__ : Union[bool, str, TruncationStrategy] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : int = 0 , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : List[Any] , ) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.""" ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""" ) # first, apply the image processor __magic_name__ = self.image_processor(images=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): __magic_name__ = [text] # add batch dimension (as the image processor always adds a batch dimension) __magic_name__ = features["""words"""] __magic_name__ = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , stride=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , return_overflowing_tokens=UpperCamelCase__ , return_special_tokens_mask=UpperCamelCase__ , return_offsets_mapping=UpperCamelCase__ , return_length=UpperCamelCase__ , verbose=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ , ) # add pixel values __magic_name__ = features.pop("""pixel_values""" ) if return_overflowing_tokens is True: __magic_name__ = self.get_overflowing_images(UpperCamelCase__ , encoded_inputs["""overflow_to_sample_mapping"""] ) __magic_name__ = images return encoded_inputs def _lowercase ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Dict: """simple docstring""" __magic_name__ = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" F''' {len(UpperCamelCase__ )} and {len(UpperCamelCase__ )}''' ) return images_with_overflow def _lowercase ( self : Optional[Any] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Dict ) -> Tuple: """simple docstring""" return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Any ) -> List[str]: """simple docstring""" return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def _lowercase ( self : Any ) -> Union[str, Any]: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def _lowercase ( self : str ) -> Tuple: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , UpperCamelCase__ , ) return self.image_processor_class @property def _lowercase ( self : Dict ) -> Tuple: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , UpperCamelCase__ , ) return self.image_processor
88
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
0
'''simple docstring''' import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def __lowerCamelCase ( ) -> Any: _a : Dict = 10 _a : Union[str, Any] = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) _a : Optional[int] = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(lowerCAmelCase_ ) ), } , features=lowerCAmelCase_ , ) return dataset @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> int: _a : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=lowerCAmelCase_ ) return filename # FILE_CONTENT + files __lowerCAmelCase = '''\ Text data. Second line of data.''' @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : str = tmp_path_factory.mktemp('data' ) / 'file.txt' _a : Optional[Any] = FILE_CONTENT with open(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ ) return filename @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Union[str, Any]: import bza _a : Dict = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' _a : Any = bytes(lowerCAmelCase_ , 'utf-8' ) with bza.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: import gzip _a : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) _a : Union[str, Any] = bytes(lowerCAmelCase_ , 'utf-8' ) with gzip.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> str: if datasets.config.LZ4_AVAILABLE: import lza.frame _a : List[str] = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' _a : Optional[int] = bytes(lowerCAmelCase_ , 'utf-8' ) with lza.frame.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr _a : Tuple = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(lowerCAmelCase_ , 'w' ) as archive: archive.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: import tarfile _a : Tuple = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(lowerCAmelCase_ , 'w' ) as f: f.add(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Union[str, Any]: import lzma _a : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' _a : int = bytes(lowerCAmelCase_ , 'utf-8' ) with lzma.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: import zipfile _a : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _a : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' _a : Optional[Any] = bytes(lowerCAmelCase_ , 'utf-8' ) with zstd.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: _a : Any = tmp_path_factory.mktemp('data' ) / 'file.xml' _a : int = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ ) return filename __lowerCAmelCase = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] __lowerCAmelCase = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] __lowerCAmelCase = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } __lowerCAmelCase = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] __lowerCAmelCase = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope='session' ) def __lowerCamelCase ( ) -> List[str]: return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> int: _a : Dict = datasets.Dataset.from_dict(lowerCAmelCase_ ) _a : str = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> int: _a : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(lowerCAmelCase_ ) ) as con: _a : Tuple = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: _a : int = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(lowerCAmelCase_ , 'w' , newline='' ) as f: _a : Dict = csv.DictWriter(lowerCAmelCase_ , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Tuple: _a : int = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(lowerCAmelCase_ , 'w' , newline='' ) as f: _a : int = csv.DictWriter(lowerCAmelCase_ , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: import bza _a : str = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(lowerCAmelCase_ , 'rb' ) as f: _a : Optional[Any] = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowerCAmelCase_ , 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: _a : int = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Any: _a : str = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[int]: _a : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> str: _a : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) _a : Optional[int] = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(lowerCAmelCase_ , 'wb' ) as f: _a : Optional[int] = pq.ParquetWriter(lowerCAmelCase_ , schema=lowerCAmelCase_ ) _a : List[str] = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowerCAmelCase_ ) )] for k in DATA[0]} , schema=lowerCAmelCase_ ) writer.write_table(lowerCAmelCase_ ) writer.close() return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _a : Tuple = {'data': DATA} with open(lowerCAmelCase_ , 'w' ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> str: _a : Any = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _a : Optional[int] = {'data': DATA_DICT_OF_LISTS} with open(lowerCAmelCase_ , 'w' ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> int: _a : List[str] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in DATA: f.write(json.dumps(lowerCAmelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[int]: _a : int = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in DATA: f.write(json.dumps(lowerCAmelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Dict: _a : int = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in DATA_312: f.write(json.dumps(lowerCAmelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Dict: _a : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(lowerCAmelCase_ ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: import gzip _a : str = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(lowerCAmelCase_ , 'rb' ) as orig_file: with gzip.open(lowerCAmelCase_ , 'wb' ) as zipped_file: zipped_file.writelines(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: import gzip _a : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(lowerCAmelCase_ , 'rb' ) as orig_file: with gzip.open(lowerCAmelCase_ , 'wb' ) as zipped_file: zipped_file.writelines(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _a : int = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]: _a : List[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.join('nested' , os.path.basename(lowerCAmelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: _a : Tuple = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[int]: _a : int = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(lowerCAmelCase_ , 'w' ) as f: f.add(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) f.add(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[int]: _a : Any = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(lowerCAmelCase_ , 'w' ) as f: f.add(lowerCAmelCase_ , arcname=os.path.join('nested' , os.path.basename(lowerCAmelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: _a : Any = ['0', '1', '2', '3'] _a : int = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: _a : List[Any] = ['0', '1', '2', '3'] _a : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(lowerCAmelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> Tuple: _a : List[str] = ['0', '1', '2', '3'] _a : Any = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(lowerCAmelCase_ , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _a : Dict = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[int]: _a : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) f.write(lowerCAmelCase_ , arcname=os.path.join('main_dir' , os.path.basename(lowerCAmelCase_ ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: _a : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename('unsupported.ext' ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> int: _a : int = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) _a : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(lowerCAmelCase_ , 'w' , encoding='utf-8' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( ) -> List[str]: return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def __lowerCamelCase ( ) -> Union[str, Any]: return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _a : Dict = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(lowerCAmelCase_ , 'w' ) as f: f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ) ) f.write(lowerCAmelCase_ , arcname=os.path.basename(lowerCAmelCase_ ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def __lowerCamelCase ( lowerCAmelCase_ ) -> str: _a : Tuple = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) return data_dir
89
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 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(lowerCAmelCase_ ): 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: a__ : List[str] = 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()
54
0
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = ['''input_values''', '''padding_mask'''] def __init__( self , lowerCamelCase__ = 1 , lowerCamelCase__ = 24_000 , lowerCamelCase__ = 0.0 , lowerCamelCase__ = None , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(feature_size=lowerCamelCase__ , sampling_rate=lowerCamelCase__ , padding_value=lowerCamelCase__ , **lowerCamelCase__ ) __lowerCamelCase = chunk_length_s __lowerCamelCase = overlap @property def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) if padding and truncation: raise ValueError('Both padding and truncation were set. Make sure you only set one.' ) elif padding is None: # by default let's pad the inputs __lowerCamelCase = True __lowerCamelCase = bool( isinstance(lowerCamelCase__ , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: __lowerCamelCase = [np.asarray(lowerCamelCase__ , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(lowerCamelCase__ , np.ndarray ): __lowerCamelCase = np.asarray(lowerCamelCase__ , dtype=np.floataa ) elif isinstance(lowerCamelCase__ , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): __lowerCamelCase = raw_audio.astype(np.floataa ) # always return batch if not is_batched: __lowerCamelCase = [np.asarray(lowerCamelCase__ ).T] # verify inputs are valid for idx, example in enumerate(lowerCamelCase__ ): if example.ndim > 2: raise ValueError(f"""Expected input shape (channels, length) but got shape {example.shape}""" ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(f"""Expected mono audio but example has {example.shape[-1]} channels""" ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(f"""Expected stereo audio but example has {example.shape[-1]} channels""" ) __lowerCamelCase = None __lowerCamelCase = BatchFeature({'input_values': raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: __lowerCamelCase = min(array.shape[0] for array in raw_audio ) __lowerCamelCase = int(np.floor(max_length / self.chunk_stride ) ) __lowerCamelCase = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: __lowerCamelCase = max(array.shape[0] for array in raw_audio ) __lowerCamelCase = int(np.ceil(max_length / self.chunk_stride ) ) __lowerCamelCase = (nb_step - 1) * self.chunk_stride + self.chunk_length __lowerCamelCase = 'max_length' else: __lowerCamelCase = input_values # normal padding on batch if padded_inputs is None: __lowerCamelCase = self.pad( lowerCamelCase__ , max_length=lowerCamelCase__ , truncation=lowerCamelCase__ , padding=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , ) if padding: __lowerCamelCase = padded_inputs.pop('attention_mask' ) __lowerCamelCase = [] for example in padded_inputs.pop('input_values' ): if self.feature_size == 1: __lowerCamelCase = example[..., None] input_values.append(example.T ) __lowerCamelCase = input_values if return_tensors is not None: __lowerCamelCase = padded_inputs.convert_to_tensors(lowerCamelCase__ ) return padded_inputs
90
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "ViTImageProcessor" __UpperCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : str , lowercase_ : Any=None , lowercase_ : Optional[Any]=None , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''feature_extractor''') SCREAMING_SNAKE_CASE_ : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''') if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''') super().__init__(lowercase_ , lowercase_) def __call__( self : Optional[Any] , lowercase_ : str=None , lowercase_ : Optional[int]=None , lowercase_ : Dict=None , lowercase_ : List[Any]=None , **lowercase_ : int): '''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: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_) if visual_prompt is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_) if images is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_) if visual_prompt is not None and images is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''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: SCREAMING_SNAKE_CASE_ : int = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: SCREAMING_SNAKE_CASE_ : int = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowercase_) , tensor_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : str , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : Union[str, Any] , **lowercase_ : List[str]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowercase_ , ) return self.image_processor_class @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowercase_ , ) return self.image_processor
91
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
import os def _a ( ): __lowerCAmelCase = os.path.dirname(os.path.realpath(SCREAMING_SNAKE_CASE_ ) ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , "triangle.txt" ) with open(SCREAMING_SNAKE_CASE_ ) as f: __lowerCAmelCase = f.readlines() __lowerCAmelCase = [] for line in triangle: __lowerCAmelCase = [] for number in line.strip().split(" " ): numbers_from_line.append(int(SCREAMING_SNAKE_CASE_ ) ) a.append(SCREAMING_SNAKE_CASE_ ) for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): for j in range(len(a[i] ) ): __lowerCAmelCase = a[i - 1][j] if j != len(a[i - 1] ) else 0 __lowerCAmelCase = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
92
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
'''simple docstring''' import argparse import os import re _lowercase : int = "src/transformers" # Pattern that looks at the indentation in a line. _lowercase : int = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowercase : Tuple = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowercase : Dict = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowercase : Union[str, Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowercase : List[str] = re.compile(r"\[([^\]]+)\]") def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Any = _re_indent.search(__SCREAMING_SNAKE_CASE ) return "" if search is None else search.groups()[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Tuple="" , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[Any]=None ): """simple docstring""" lowercase_ : Union[str, Any] = 0 lowercase_ : Dict = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__SCREAMING_SNAKE_CASE ): index += 1 lowercase_ : int = ['''\n'''.join(lines[:index] )] else: lowercase_ : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowercase_ : Optional[Any] = [lines[index]] index += 1 while index < len(__SCREAMING_SNAKE_CASE ) and (end_prompt is None or not lines[index].startswith(__SCREAMING_SNAKE_CASE )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__SCREAMING_SNAKE_CASE ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) if index < len(__SCREAMING_SNAKE_CASE ) - 1: lowercase_ : Optional[Any] = [lines[index + 1]] index += 1 else: lowercase_ : Tuple = [] else: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__SCREAMING_SNAKE_CASE ) > 0: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__SCREAMING_SNAKE_CASE ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" def _inner(__SCREAMING_SNAKE_CASE : Union[str, Any] ): return key(__SCREAMING_SNAKE_CASE ).lower().replace('''_''' , '''''' ) return _inner def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" def noop(__SCREAMING_SNAKE_CASE : List[str] ): return x if key is None: lowercase_ : Optional[Any] = noop # Constants are all uppercase, they go first. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE )[0].isupper() and not key(__SCREAMING_SNAKE_CASE ).isupper()] # Functions begin with a lowercase, they go last. lowercase_ : List[str] = [obj for obj in objects if not key(__SCREAMING_SNAKE_CASE )[0].isupper()] lowercase_ : str = ignore_underscore(__SCREAMING_SNAKE_CASE ) return sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" def _replace(__SCREAMING_SNAKE_CASE : Dict ): lowercase_ : List[str] = match.groups()[0] if "," not in imports: return F'''[{imports}]''' lowercase_ : Union[str, Any] = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Dict = keys[:-1] return "[" + ", ".join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) + "]" lowercase_ : List[str] = import_statement.split('''\n''' ) if len(__SCREAMING_SNAKE_CASE ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowercase_ : int = 2 if lines[1].strip() == '''[''' else 1 lowercase_ : Optional[int] = [(i, _re_strip_line.search(__SCREAMING_SNAKE_CASE ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowercase_ : str = sort_objects(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] ) lowercase_ : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__SCREAMING_SNAKE_CASE ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowercase_ : int = _re_bracket_content.sub(_replace , lines[1] ) else: lowercase_ : str = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Optional[int] = keys[:-1] lowercase_ : str = get_indent(lines[1] ) + ''', '''.join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) return "\n".join(__SCREAMING_SNAKE_CASE ) else: # Finally we have to deal with imports fitting on one line lowercase_ : List[str] = _re_bracket_content.sub(_replace , __SCREAMING_SNAKE_CASE ) return import_statement def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as f: lowercase_ : Optional[int] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowercase_ : Dict = split_code_in_indented_blocks( __SCREAMING_SNAKE_CASE , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__SCREAMING_SNAKE_CASE ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowercase_ : Dict = main_blocks[block_idx] lowercase_ : str = block.split('''\n''' ) # Get to the start of the imports. lowercase_ : Any = 0 while line_idx < len(__SCREAMING_SNAKE_CASE ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowercase_ : Dict = len(__SCREAMING_SNAKE_CASE ) else: line_idx += 1 if line_idx >= len(__SCREAMING_SNAKE_CASE ): continue # Ignore beginning and last line: they don't contain anything. lowercase_ : Any = '''\n'''.join(block_lines[line_idx:-1] ) lowercase_ : Tuple = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowercase_ : Tuple = split_code_in_indented_blocks(__SCREAMING_SNAKE_CASE , indent_level=__SCREAMING_SNAKE_CASE ) # We have two categories of import key: list or _import_structure[key].append/extend lowercase_ : str = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowercase_ : Optional[int] = [(pattern.search(__SCREAMING_SNAKE_CASE ).groups()[0] if pattern.search(__SCREAMING_SNAKE_CASE ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowercase_ : List[str] = [(i, key) for i, key in enumerate(__SCREAMING_SNAKE_CASE ) if key is not None] lowercase_ : Optional[Any] = [x[0] for x in sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowercase_ : int = 0 lowercase_ : Union[str, Any] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowercase_ : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(__SCREAMING_SNAKE_CASE ) count += 1 # And we put our main block back together with its first and last line. lowercase_ : int = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(__SCREAMING_SNAKE_CASE ): if check_only: return True else: print(F'''Overwriting {file}.''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int]=True ): """simple docstring""" lowercase_ : str = [] for root, _, files in os.walk(__SCREAMING_SNAKE_CASE ): if "__init__.py" in files: lowercase_ : Optional[Any] = sort_imports(os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' ) , check_only=__SCREAMING_SNAKE_CASE ) if result: lowercase_ : List[str] = [os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' )] if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F'''Would overwrite {len(__SCREAMING_SNAKE_CASE )} files, run `make style`.''' ) if __name__ == "__main__": _lowercase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowercase : Any = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
93
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
from __future__ import annotations def __lowerCamelCase ( UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : float , ): """simple docstring""" if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative in a semiconductor''' ) elif hole_conc < 0: raise ValueError('''Hole concentration cannot be negative in a semiconductor''' ) elif intrinsic_conc < 0: raise ValueError( '''Intrinsic concentration cannot be negative in a semiconductor''' ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
94
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _snake_case ( lowercase__ ): _lowerCamelCase : Tuple = filter(lambda lowercase__ : p.requires_grad , model.parameters() ) _lowerCamelCase : int = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowercase__ = logging.getLogger(__name__) def _snake_case ( lowercase__ , lowercase__ ): if metric == "rouge2": _lowerCamelCase : str = '{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": _lowerCamelCase : List[str] = '{val_avg_bleu:.4f}-{step_count}' elif metric == "em": _lowerCamelCase : Union[str, Any] = '{val_avg_em:.4f}-{step_count}' elif metric == "loss": _lowerCamelCase : Dict = '{val_avg_loss:.4f}-{step_count}' else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' ' function.' ) _lowerCamelCase : List[Any] = ModelCheckpoint( dirpath=lowercase__ , filename=lowercase__ , monitor=f'''val_{metric}''' , mode='max' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _snake_case ( lowercase__ , lowercase__ ): return EarlyStopping( monitor=f'''val_{metric}''' , mode='min' if 'loss' in metric else 'max' , patience=lowercase__ , verbose=lowercase__ , ) class lowerCAmelCase__ ( pl.Callback ): '''simple docstring''' def A_ ( self , lowercase , lowercase ): _lowerCamelCase : int = {F'''lr_group_{i}''': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(lowercase ) @rank_zero_only def A_ ( self , lowercase , lowercase , lowercase , lowercase=True ): logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _lowerCamelCase : Dict = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} ) # Log results _lowerCamelCase : List[str] = Path(pl_module.hparams.output_dir ) if type_path == "test": _lowerCamelCase : Union[str, Any] = od / 'test_results.txt' _lowerCamelCase : Dict = od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _lowerCamelCase : int = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' _lowerCamelCase : str = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=lowercase ) generations_file.parent.mkdir(exist_ok=lowercase ) with open(lowercase , 'a+' ) as writer: for key in sorted(lowercase ): if key in ["log", "progress_bar", "preds"]: continue _lowerCamelCase : Tuple = metrics[key] if isinstance(lowercase , torch.Tensor ): _lowerCamelCase : str = val.item() _lowerCamelCase : Tuple = F'''{key}: {val:.6f}\n''' writer.write(lowercase ) if not save_generations: return if "preds" in metrics: _lowerCamelCase : Any = '\n'.join(metrics['preds'] ) generations_file.open('w+' ).write(lowercase ) @rank_zero_only def A_ ( self , lowercase , lowercase ): try: _lowerCamelCase : Union[str, Any] = pl_module.model.model.num_parameters() except AttributeError: _lowerCamelCase : str = pl_module.model.num_parameters() _lowerCamelCase : List[Any] = count_trainable_parameters(lowercase ) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6} ) @rank_zero_only def A_ ( self , lowercase , lowercase ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(lowercase , lowercase , 'test' ) @rank_zero_only def A_ ( self , lowercase , lowercase ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
96
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def a ( __a ) -> Any: '''simple docstring''' UpperCamelCase__ :str = torch.exp(__a ) UpperCamelCase__ :Tuple = torch.sum(__a , dim=1 ) # sum of exp(x_i) UpperCamelCase__ :Optional[Any] = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(__a ) - B / A class lowercase ( nn.Module ): """simple docstring""" def __init__( self , UpperCamelCase_ ): '''simple docstring''' super().__init__() UpperCamelCase__ :Dict = config.output_attentions UpperCamelCase__ :Union[str, Any] = config.output_hidden_states UpperCamelCase__ :List[str] = nn.ModuleList([BertLayer(UpperCamelCase_ ) for _ in range(config.num_hidden_layers )] ) UpperCamelCase__ :int = nn.ModuleList([BertHighway(UpperCamelCase_ ) for _ in range(config.num_hidden_layers )] ) UpperCamelCase__ :str = [-1 for _ in range(config.num_hidden_layers )] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if (type(UpperCamelCase_ ) is float) or (type(UpperCamelCase_ ) is int): for i in range(len(self.early_exit_entropy ) ): UpperCamelCase__ :Union[str, Any] = x else: UpperCamelCase__ :Optional[Any] = x def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[str] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , ): '''simple docstring''' UpperCamelCase__ :str = () UpperCamelCase__ :Optional[int] = () UpperCamelCase__ :Optional[int] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: UpperCamelCase__ :Optional[int] = all_hidden_states + (hidden_states,) UpperCamelCase__ :Dict = layer_module( UpperCamelCase_ , UpperCamelCase_ , head_mask[i] , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase__ :str = layer_outputs[0] if self.output_attentions: UpperCamelCase__ :int = all_attentions + (layer_outputs[1],) UpperCamelCase__ :List[Any] = (hidden_states,) if self.output_hidden_states: UpperCamelCase__ :Union[str, Any] = current_outputs + (all_hidden_states,) if self.output_attentions: UpperCamelCase__ :int = current_outputs + (all_attentions,) UpperCamelCase__ :Optional[int] = self.highway[i](UpperCamelCase_ ) # logits, pooled_output if not self.training: UpperCamelCase__ :List[str] = highway_exit[0] UpperCamelCase__ :List[Any] = entropy(UpperCamelCase_ ) UpperCamelCase__ :Tuple = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy UpperCamelCase__ :int = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: UpperCamelCase__ :str = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(UpperCamelCase_ , i + 1 ) else: UpperCamelCase__ :int = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: UpperCamelCase__ :int = all_hidden_states + (hidden_states,) UpperCamelCase__ :List[Any] = (hidden_states,) if self.output_hidden_states: UpperCamelCase__ :Union[str, Any] = outputs + (all_hidden_states,) if self.output_attentions: UpperCamelCase__ :int = outputs + (all_attentions,) UpperCamelCase__ :Optional[Any] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( 'The Bert Model transformer with early exiting (DeeBERT). ' , A__ , ) class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ ): '''simple docstring''' super().__init__(UpperCamelCase_ ) UpperCamelCase__ :Tuple = config UpperCamelCase__ :Dict = BertEmbeddings(UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = DeeBertEncoder(UpperCamelCase_ ) UpperCamelCase__ :str = BertPooler(UpperCamelCase_ ) self.init_weights() def lowerCAmelCase__ ( self ): '''simple docstring''' self.encoder.init_highway_pooler(self.pooler ) def lowerCAmelCase__ ( self ): '''simple docstring''' return self.embeddings.word_embeddings def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = value def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(UpperCamelCase_ ) @add_start_docstrings_to_model_forward(UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , ): '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''' ) elif input_ids is not None: UpperCamelCase__ :List[str] = input_ids.size() elif inputs_embeds is not None: UpperCamelCase__ :int = inputs_embeds.size()[:-1] else: raise ValueError('''You have to specify either input_ids or inputs_embeds''' ) UpperCamelCase__ :Optional[Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: UpperCamelCase__ :str = torch.ones(UpperCamelCase_ , device=UpperCamelCase_ ) if encoder_attention_mask is None: UpperCamelCase__ :str = torch.ones(UpperCamelCase_ , device=UpperCamelCase_ ) if token_type_ids is None: UpperCamelCase__ :Optional[int] = torch.zeros(UpperCamelCase_ , dtype=torch.long , device=UpperCamelCase_ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. UpperCamelCase__ :torch.Tensor = self.get_extended_attention_mask(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: UpperCamelCase__ :Tuple = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: UpperCamelCase__ :int = encoder_attention_mask[:, None, None, :] UpperCamelCase__ :int = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility UpperCamelCase__ :str = (1.0 - encoder_extended_attention_mask) * -10000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] UpperCamelCase__ :Dict = self.get_head_mask(UpperCamelCase_ , self.config.num_hidden_layers ) UpperCamelCase__ :List[str] = self.embeddings( input_ids=UpperCamelCase_ , position_ids=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , inputs_embeds=UpperCamelCase_ ) UpperCamelCase__ :Tuple = self.encoder( UpperCamelCase_ , attention_mask=UpperCamelCase_ , head_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , ) UpperCamelCase__ :Any = encoder_outputs[0] UpperCamelCase__ :Tuple = self.pooler(UpperCamelCase_ ) UpperCamelCase__ :List[str] = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :str = message UpperCamelCase__ :Union[str, Any] = exit_layer # start from 1! class lowercase ( nn.Module ): """simple docstring""" def __init__( self , UpperCamelCase_ ): '''simple docstring''' super().__init__() UpperCamelCase__ :Dict = BertPooler(UpperCamelCase_ ) UpperCamelCase__ :Tuple = nn.Dropout(config.hidden_dropout_prob ) UpperCamelCase__ :Optional[int] = nn.Linear(config.hidden_size , config.num_labels ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = encoder_outputs[0] UpperCamelCase__ :Optional[Any] = self.pooler(UpperCamelCase_ ) # "return" pooler_output # BertModel UpperCamelCase__ :Union[str, Any] = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification UpperCamelCase__ :Any = bmodel_output[1] UpperCamelCase__ :Union[str, Any] = self.dropout(UpperCamelCase_ ) UpperCamelCase__ :List[Any] = self.classifier(UpperCamelCase_ ) return logits, pooled_output @add_start_docstrings( 'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ' , A__ , ) class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ ): '''simple docstring''' super().__init__(UpperCamelCase_ ) UpperCamelCase__ :List[Any] = config.num_labels UpperCamelCase__ :Tuple = config.num_hidden_layers UpperCamelCase__ :Any = DeeBertModel(UpperCamelCase_ ) UpperCamelCase__ :Any = nn.Dropout(config.hidden_dropout_prob ) UpperCamelCase__ :Optional[Any] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=-1 , UpperCamelCase_=False , ): '''simple docstring''' UpperCamelCase__ :int = self.num_layers try: UpperCamelCase__ :Optional[int] = self.bert( UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , position_ids=UpperCamelCase_ , head_mask=UpperCamelCase_ , inputs_embeds=UpperCamelCase_ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits UpperCamelCase__ :List[str] = outputs[1] UpperCamelCase__ :int = self.dropout(UpperCamelCase_ ) UpperCamelCase__ :Any = self.classifier(UpperCamelCase_ ) UpperCamelCase__ :List[str] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: UpperCamelCase__ :Any = e.message UpperCamelCase__ :Union[str, Any] = e.exit_layer UpperCamelCase__ :str = outputs[0] if not self.training: UpperCamelCase__ :Optional[Any] = entropy(UpperCamelCase_ ) UpperCamelCase__ :Dict = [] UpperCamelCase__ :int = [] if labels is not None: if self.num_labels == 1: # We are doing regression UpperCamelCase__ :Union[str, Any] = MSELoss() UpperCamelCase__ :Dict = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ :Dict = CrossEntropyLoss() UpperCamelCase__ :Tuple = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits UpperCamelCase__ :Optional[Any] = [] for highway_exit in outputs[-1]: UpperCamelCase__ :Any = highway_exit[0] if not self.training: highway_logits_all.append(UpperCamelCase_ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression UpperCamelCase__ :int = MSELoss() UpperCamelCase__ :List[str] = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ :Union[str, Any] = CrossEntropyLoss() UpperCamelCase__ :Any = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(UpperCamelCase_ ) if train_highway: UpperCamelCase__ :Dict = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: UpperCamelCase__ :Union[str, Any] = (loss,) + outputs if not self.training: UpperCamelCase__ :Any = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: UpperCamelCase__ :Optional[Any] = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
97
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
"""simple docstring""" # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests lowerCAmelCase__ : List[str] = open # noqa: we just need to have a builtin inside this module to test it properly
98
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0
from collections.abc import Sequence from queue import Queue class A__ : """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , lowercase=None , lowercase=None) -> Dict: '''simple docstring''' a__ : Tuple = start a__ : Any = end a__ : Optional[Any] = val a__ : Optional[Any] = (start + end) // 2 a__ : Optional[Any] = left a__ : Any = right def __repr__( self) -> int: '''simple docstring''' return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class A__ : """simple docstring""" def __init__( self , lowercase , lowercase) -> Optional[Any]: '''simple docstring''' a__ : Tuple = collection a__ : Tuple = function if self.collection: a__ : str = self._build_tree(0 , len(lowercase) - 1) def __lowercase ( self , lowercase , lowercase) -> str: '''simple docstring''' self._update_tree(self.root , lowercase , lowercase) def __lowercase ( self , lowercase , lowercase) -> List[str]: '''simple docstring''' return self._query_range(self.root , lowercase , lowercase) def __lowercase ( self , lowercase , lowercase) -> Any: '''simple docstring''' if start == end: return SegmentTreeNode(lowercase , lowercase , self.collection[start]) a__ : Union[str, Any] = (start + end) // 2 a__ : Any = self._build_tree(lowercase , lowercase) a__ : str = self._build_tree(mid + 1 , lowercase) return SegmentTreeNode(lowercase , lowercase , self.fn(left.val , right.val) , lowercase , lowercase) def __lowercase ( self , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' if node.start == i and node.end == i: a__ : Tuple = val return if i <= node.mid: self._update_tree(node.left , lowercase , lowercase) else: self._update_tree(node.right , lowercase , lowercase) a__ : Union[str, Any] = self.fn(node.left.val , node.right.val) def __lowercase ( self , lowercase , lowercase , lowercase) -> Tuple: '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , lowercase , lowercase) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , lowercase , node.mid) , self._query_range(node.right , node.mid + 1 , lowercase) , ) else: # range in right child tree return self._query_range(node.right , lowercase , lowercase) def __lowercase ( self) -> str: '''simple docstring''' if self.root is not None: a__ : List[str] = Queue() queue.put(self.root) while not queue.empty(): a__ : int = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("""*""" * 5_0) lowercase : str = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
99
"""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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Any ) -> int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(UpperCAmelCase__ ): DisjunctiveConstraint(UpperCAmelCase__ ) # fails here def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
54
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json", "BridgeTower/bridgetower-base-itm-mlm": ( "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json" ), } class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : int = '''bridgetower_vision_model''' def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2_8_8 , lowerCAmelCase__=1 , lowerCAmelCase__=1E-05 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=False , **lowerCAmelCase__ , ): super().__init__(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = initializer_factor __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = stop_gradient __SCREAMING_SNAKE_CASE = share_layernorm __SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_ ( cls , lowerCAmelCase__ , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCAmelCase__ , **lowerCAmelCase__) if config_dict.get("""model_type""") == "bridgetower": __SCREAMING_SNAKE_CASE = config_dict["""text_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(lowerCAmelCase__ , **lowerCAmelCase__) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : int = '''bridgetower_text_model''' def __init__( self , lowerCAmelCase__=5_0_2_6_5 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_4 , lowerCAmelCase__=1 , lowerCAmelCase__=1E-05 , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__="absolute" , lowerCAmelCase__=True , **lowerCAmelCase__ , ): super().__init__(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_factor __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_ ( cls , lowerCAmelCase__ , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCAmelCase__ , **lowerCAmelCase__) if config_dict.get("""model_type""") == "bridgetower": __SCREAMING_SNAKE_CASE = config_dict["""text_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(lowerCAmelCase__ , **lowerCAmelCase__) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : List[str] = '''bridgetower''' def __init__( self , lowerCAmelCase__=True , lowerCAmelCase__="gelu" , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1 , lowerCAmelCase__=1E-05 , lowerCAmelCase__=False , lowerCAmelCase__="add" , lowerCAmelCase__=1_2 , lowerCAmelCase__=6 , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ , ): # TODO: remove this once the Hub files are updated. __SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , lowerCAmelCase__) super().__init__(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = initializer_factor __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = share_link_tower_layers __SCREAMING_SNAKE_CASE = link_tower_type __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = tie_word_embeddings __SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""") if vision_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""") __SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**lowerCAmelCase__) @classmethod def snake_case_ ( cls , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__) __SCREAMING_SNAKE_CASE = self.text_config.to_dict() __SCREAMING_SNAKE_CASE = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
100
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
0
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCamelCase ( lowerCAmelCase__ = "isbn/0140328726" ): '''simple docstring''' lowercase = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' ) != 1: lowercase = f'{olid} is not a valid Open Library olid' raise ValueError(lowerCAmelCase__ ) return requests.get(f'https://openlibrary.org/{new_olid}.json' ).json() def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = { '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } lowercase = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} lowercase = [ get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors'''] ] lowercase = data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = ''', '''.join(lowerCAmelCase__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: lowercase__ :List[Any] = input("\nEnter the ISBN code to search (or 'quit' to stop): ").strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F'Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.') continue print(F'\nSearching Open Library for ISBN: {isbn}...\n') try: lowercase__ :List[str] = summarize_book(get_openlibrary_data(F'isbn/{isbn}')) print("\n".join(F'{key}: {value}' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F'Sorry, there are no results for ISBN: {isbn}.')
101
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if number > 0: raise ValueError("input must be a negative integer" ) __SCREAMING_SNAKE_CASE = len(bin(lowerCAmelCase_ )[3:] ) __SCREAMING_SNAKE_CASE = bin(abs(lowerCAmelCase_ ) - (1 << binary_number_length) )[3:] __SCREAMING_SNAKE_CASE = ( ( "1" + "0" * (binary_number_length - len(lowerCAmelCase_ )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
54
0
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def lowercase ( _snake_case : int ) ->Dict: """simple docstring""" return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def lowercase ( _snake_case : str , _snake_case : Union[str, Any] ) ->Dict: """simple docstring""" __snake_case : int = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __snake_case : Union[str, Any] = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) __snake_case : List[Any] = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) __snake_case : str = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) __snake_case : Optional[Any] = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) __snake_case : str = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) __snake_case : List[str] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) __snake_case : Optional[Any] = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) __snake_case : str = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) __snake_case : str = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) __snake_case : Any = key.replace('''image_encoder.module''' , '''flava.image_model''' ) __snake_case : Tuple = key.replace('''text_encoder.module''' , '''flava.text_model''' ) __snake_case : Any = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) __snake_case : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) __snake_case : Any = key.replace('''text_projection''' , '''flava.text_projection''' ) __snake_case : Optional[Any] = key.replace('''image_projection''' , '''flava.image_projection''' ) __snake_case : Any = value.float() for key, value in codebook_state_dict.items(): __snake_case : Union[str, Any] = value return upgrade @torch.no_grad() def lowercase ( _snake_case : Optional[int] , _snake_case : Dict , _snake_case : Dict , _snake_case : Dict=None ) ->Union[str, Any]: """simple docstring""" if config_path is not None: __snake_case : Dict = FlavaConfig.from_pretrained(_snake_case ) else: __snake_case : Optional[Any] = FlavaConfig() __snake_case : List[Any] = FlavaForPreTraining(_snake_case ).eval() __snake_case : Union[str, Any] = convert_dalle_checkpoint(_snake_case , _snake_case , save_checkpoint=_snake_case ) if os.path.exists(_snake_case ): __snake_case : List[str] = torch.load(_snake_case , map_location='''cpu''' ) else: __snake_case : List[str] = torch.hub.load_state_dict_from_url(_snake_case , map_location='''cpu''' ) __snake_case : Any = upgrade_state_dict(_snake_case , _snake_case ) hf_model.load_state_dict(_snake_case ) __snake_case : int = hf_model.state_dict() __snake_case : Union[str, Any] = count_parameters(_snake_case ) __snake_case : List[Any] = count_parameters(_snake_case ) + count_parameters(_snake_case ) assert torch.allclose(_snake_case , _snake_case , atol=1e-3 ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Optional[Any] = 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 flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
102
"""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_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = CLIPTokenizer snake_case__ : Dict = CLIPTokenizerFast snake_case__ : List[Any] = True snake_case__ : Optional[Any] = {} snake_case__ : Dict = False def UpperCAmelCase_ ( self : Any ) -> Any: super().setUp() # fmt: off __SCREAMING_SNAKE_CASE = ["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 __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] __SCREAMING_SNAKE_CASE = {"unk_token": "<unk>"} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Tuple ) -> List[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = "lower newer" return input_text, output_text def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE = [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , UpperCAmelCase__ ) @require_ftfy def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __SCREAMING_SNAKE_CASE = "xa\u0303y" + " " + "x\xe3y" __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of space type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # Test that the tokenization is identical on unicode of line break type __SCREAMING_SNAKE_CASE = [ "\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: __SCREAMING_SNAKE_CASE = tokenizer_s.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: # 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})""" ): __SCREAMING_SNAKE_CASE = "hello" # `hello` is a token in the vocabulary of `pretrained_name` __SCREAMING_SNAKE_CASE = F"""{text_of_1_token} {text_of_1_token}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(UpperCAmelCase__ ) + 1, len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) __SCREAMING_SNAKE_CASE = F""" {text}""" __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( UpperCAmelCase__ , use_fast=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r(UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(UpperCAmelCase__ ) + 1, 1 + len(UpperCAmelCase__ ) + 1 + len(UpperCAmelCase__ )) , ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(UpperCAmelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def UpperCAmelCase_ ( self : Optional[int] ) -> int: super().test_tokenization_python_rust_equals() def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: # CLIP always lower cases letters pass
54
0
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __snake_case ( unittest.TestCase ): _a = JukeboxTokenizer _a = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def UpperCAmelCase__ ( self : str): import torch lowerCAmelCase_ : List[Any] = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') lowerCAmelCase_ : Any = tokenizer(**self.metas)['''input_ids'''] # fmt: off lowerCAmelCase_ : List[str] = [ torch.tensor([[ 0, 0, 0, 7_1_6_9, 5_0_7, 9, 7_6, 3_9, 3_1, 4_6, 7_6, 2_7, 7_6, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_6, 3_2, 4_4, 4_1, 3_9, 7_6, 2_7, 4_0, 7_6, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_6, 3_8, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 4_1, 7_6, 4_5, 2_7, 3_5, 3_0, 7_6, 7_1, 2_0, 4_9, 4_1, 7_6, 4_8, 2_7, 4_5, 4_6, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_6, 3_8, 3_1, 3_3, 4_5, 7_6, 4_1, 3_2, 7_6, 4_5, 4_6, 4_1, 4_0, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_9, 4_6, 2_7, 4_0, 3_0, 7_6, 3_5, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 1_4, 3_1, 2_7, 4_4, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_5, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 8, 2_7, 3_8, 3_2, 7_6, 4_5, 4_7, 4_0, 3_7, 7_6, 2_7, 7_6, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_6, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_6, 3_8, 3_5, 3_1, 4_5, 6_4, 7_6, 4_9, 3_4, 4_1, 4_5, 3_1, 7_6, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_6, 3_8, 3_5, 4_2, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_5, 4_0, 3_1, 3_1, 4_4, 7_6, 4_1, 3_2, 7_6, 2_9, 4_1, 3_8, 3_0, 7_6, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_5, 4_6, 4_5, 7_6, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_6, 4_9, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 4_1, 4_5, 3_1, 7_6, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_6, 4_4, 3_1, 2_7, 3_0, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 3_5, 2_9, 3_4, 7_6, 5_1, 3_1, 4_6, 7_6, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_6, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_6, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_4, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_4, 3_1, 2_7, 4_4, 4_6, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_2, 3_1, 3_0, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 4_9, 4_1, 4_4, 3_0, 4_5, 7_6, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_3, 5_1, 7_6, 4_0, 2_7, 3_9, 3_1, 7_6, 3_5, 4_5, 7_6, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_6, 1_1, 3_5, 4_0, 3_3, 7_6, 4_1, 3_2, 7_6, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_2, 4_1, 4_1, 3_7, 7_6, 4_1, 4_0, 7_6, 3_9, 5_1, 7_6, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_6, 5_1, 3_1, 7_6, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_6, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_6, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_6, 1_8, 4_1, 4_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 2_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_5, 3_2, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_6, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_6, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_6, 2_7, 4_0, 3_0, 7_6, 2_8, 2_7, 4_4, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_8, 4_1, 4_0, 3_1, 7_6, 2_7, 4_0, 3_0, 7_6, 3_8, 3_1, 4_8, 3_1, 3_8, 7_6, 4_5, 2_7, 4_0, 3_0, 4_5, 7_6, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_6, 3_2, 2_7, 4_4, 7_6, 2_7, 4_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6]]), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]]), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def UpperCAmelCase__ ( self : Any): import torch lowerCAmelCase_ : str = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') lowerCAmelCase_ : List[Any] = tokenizer(**self.metas)['''input_ids'''] # fmt: off lowerCAmelCase_ : Optional[int] = [ torch.tensor([[ 0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1, 9, 7_7, 3_9, 3_1, 4_6, 7_7, 2_7, 7_7, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_7, 3_2, 4_4, 4_1, 3_9, 7_7, 2_7, 4_0, 7_7, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_7, 3_8, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 4_1, 7_7, 4_5, 2_7, 3_5, 3_0, 7_7, 7_2, 2_0, 4_9, 4_1, 7_7, 4_8, 2_7, 4_5, 4_6, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_7, 3_8, 3_1, 3_3, 4_5, 7_7, 4_1, 3_2, 7_7, 4_5, 4_6, 4_1, 4_0, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_9, 4_6, 2_7, 4_0, 3_0, 7_7, 3_5, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 1_4, 3_1, 2_7, 4_4, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_5, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 8, 2_7, 3_8, 3_2, 7_7, 4_5, 4_7, 4_0, 3_7, 7_7, 2_7, 7_7, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_7, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_7, 3_8, 3_5, 3_1, 4_5, 6_4, 7_7, 4_9, 3_4, 4_1, 4_5, 3_1, 7_7, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_7, 3_8, 3_5, 4_2, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_5, 4_0, 3_1, 3_1, 4_4, 7_7, 4_1, 3_2, 7_7, 2_9, 4_1, 3_8, 3_0, 7_7, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_5, 4_6, 4_5, 7_7, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_7, 4_9, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 4_1, 4_5, 3_1, 7_7, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_7, 4_4, 3_1, 2_7, 3_0, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 3_5, 2_9, 3_4, 7_7, 5_1, 3_1, 4_6, 7_7, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_7, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_7, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_4, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_4, 3_1, 2_7, 4_4, 4_6, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_2, 3_1, 3_0, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 4_9, 4_1, 4_4, 3_0, 4_5, 7_7, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_3, 5_1, 7_7, 4_0, 2_7, 3_9, 3_1, 7_7, 3_5, 4_5, 7_7, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_7, 1_1, 3_5, 4_0, 3_3, 7_7, 4_1, 3_2, 7_7, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_2, 4_1, 4_1, 3_7, 7_7, 4_1, 4_0, 7_7, 3_9, 5_1, 7_7, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_7, 5_1, 3_1, 7_7, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_7, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_7, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_7, 1_8, 4_1, 4_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 2_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_5, 3_2, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_7, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_7, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_7, 2_7, 4_0, 3_0, 7_7, 2_8, 2_7, 4_4, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_8, 4_1, 4_0, 3_1, 7_7, 2_7, 4_0, 3_0, 7_7, 3_8, 3_1, 4_8, 3_1, 3_8, 7_7, 4_5, 2_7, 4_0, 3_0, 4_5, 7_7, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_7, 3_2, 2_7, 4_4, 7_7, 2_7, 4_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7]]), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
103
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_ , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _distribute_shards(**lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = _split_gen_kwargs(lowerCAmelCase_ , lowerCAmelCase_ ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if expected is RuntimeError: with pytest.raises(lowerCAmelCase_ ): _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ ) assert out == expected
54
0
'''simple docstring''' 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__ = { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 'convbert' def __init__( self : Optional[Any] ,lowercase__ : Dict=3_0_5_2_2 ,lowercase__ : Any=7_6_8 ,lowercase__ : Any=1_2 ,lowercase__ : Dict=1_2 ,lowercase__ : Union[str, Any]=3_0_7_2 ,lowercase__ : List[Any]="gelu" ,lowercase__ : Optional[int]=0.1 ,lowercase__ : Tuple=0.1 ,lowercase__ : Any=5_1_2 ,lowercase__ : Union[str, Any]=2 ,lowercase__ : Dict=0.0_2 ,lowercase__ : str=1e-1_2 ,lowercase__ : Tuple=1 ,lowercase__ : Optional[int]=0 ,lowercase__ : int=2 ,lowercase__ : Optional[int]=7_6_8 ,lowercase__ : List[Any]=2 ,lowercase__ : List[str]=9 ,lowercase__ : Any=1 ,lowercase__ : str=None ,**lowercase__ : List[Any] ,): super().__init__( pad_token_id=lowercase__ ,bos_token_id=lowercase__ ,eos_token_id=lowercase__ ,**lowercase__ ,) __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = embedding_size __lowercase = head_ratio __lowercase = conv_kernel_size __lowercase = num_groups __lowercase = classifier_dropout class lowercase_ (lowerCamelCase__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self : Any ): if self.task == "multiple-choice": __lowercase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowercase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
104
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) __SCREAMING_SNAKE_CASE = "x = y" __SCREAMING_SNAKE_CASE = {"y": 5} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 5, "y": 5} ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = "y = add_two(x)" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result is None assert "tried to execute add_two" in out.out def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "x = 3" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3} ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "x = 3\ny = 5" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 5} ) def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = "text = f'This is x: {x}.'" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "text": "This is x: 3."} ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "if x <= 3:\n y = 2\nelse:\n y = 5" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 2} ) __SCREAMING_SNAKE_CASE = {"x": 8} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 8, "y": 5} ) def UpperCAmelCase_ ( self : Tuple ) -> str: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3, 5] ) self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "y = x" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {} , state=UpperCAmelCase__ ) assert result == 3 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "y": 3} ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = "test_list = [x, add_two(x)]\ntest_list[1]" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_list": [3, 5]} ) __SCREAMING_SNAKE_CASE = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __SCREAMING_SNAKE_CASE = {"x": 3} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"add_two": add_two} , state=UpperCAmelCase__ ) assert result == 5 self.assertDictEqual(UpperCAmelCase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = "x = 0\nfor i in range(3):\n x = i" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = evaluate(UpperCAmelCase__ , {"range": range} , state=UpperCAmelCase__ ) assert result == 2 self.assertDictEqual(UpperCAmelCase__ , {"x": 2, "i": 2} )
54
0
"""simple docstring""" import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class __UpperCamelCase ( unittest.TestCase ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=99 , lowerCAmelCase__=32 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=512 , lowerCAmelCase__=16 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=4 , ) -> Optional[int]: a : Any = parent a : Any = batch_size a : List[Any] = seq_length a : Union[str, Any] = is_training a : Any = use_attention_mask a : Dict = use_token_type_ids a : Tuple = use_labels a : Tuple = vocab_size a : int = hidden_size a : str = num_hidden_layers a : List[Any] = num_attention_heads a : List[Any] = intermediate_size a : Optional[Any] = hidden_act a : List[Any] = hidden_dropout_prob a : int = attention_probs_dropout_prob a : Union[str, Any] = max_position_embeddings a : Optional[Any] = type_vocab_size a : List[str] = type_sequence_label_size a : Any = initializer_range a : Any = num_choices def __a ( self ) -> Dict: a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_attention_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : str = None if self.use_token_type_ids: a : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a : Union[str, Any] = 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 , is_decoder=lowerCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __a ( self ) -> Any: a : str = self.prepare_config_and_inputs() a, a, a, a : Optional[Any] = config_and_inputs a : int = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class __UpperCamelCase ( a__ , unittest.TestCase ): lowerCamelCase : int =( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def __a ( self ) -> Tuple: a : Optional[int] = FlaxAlbertModelTester(self ) @slow def __a ( self ) -> Any: for model_class_name in self.all_model_classes: a : Optional[int] = model_class_name.from_pretrained("albert-base-v2" ) a : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase__ ) @require_flax class __UpperCamelCase ( unittest.TestCase ): @slow def __a ( self ) -> Optional[int]: a : int = FlaxAlbertModel.from_pretrained("albert-base-v2" ) a : int = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) a : Union[str, Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) a : Optional[int] = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] a : str = (1, 11, 768) self.assertEqual(output.shape , lowerCAmelCase__ ) a : Any = np.array( [[[-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(jnp.allclose(output[:, 1:4, 1:4] , lowerCAmelCase__ , atol=1E-4 ) )
105
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
54
0
"""simple docstring""" __UpperCamelCase : Dict = ''' # 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 ''' __UpperCamelCase : Any = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] __UpperCamelCase : Dict = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
106
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a__ : Tuple = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("tpu-config" , description=_description ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __SCREAMING_SNAKE_CASE = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=lowerCAmelCase_ , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=lowerCAmelCase_ , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __SCREAMING_SNAKE_CASE = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=lowerCAmelCase_ , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __SCREAMING_SNAKE_CASE = defaults.command_file if not args.command and defaults.commands is not None: __SCREAMING_SNAKE_CASE = defaults.commands if not args.tpu_name: __SCREAMING_SNAKE_CASE = defaults.tpu_name if not args.tpu_zone: __SCREAMING_SNAKE_CASE = defaults.tpu_zone if args.accelerate_version == "dev": __SCREAMING_SNAKE_CASE = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __SCREAMING_SNAKE_CASE = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __SCREAMING_SNAKE_CASE = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __SCREAMING_SNAKE_CASE = ["cd /usr/share"] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command __SCREAMING_SNAKE_CASE = "; ".join(lowerCAmelCase_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __SCREAMING_SNAKE_CASE = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {' '.join(lowerCAmelCase_ )}""" ) return subprocess.run(lowerCAmelCase_ ) print("Successfully setup pod." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = tpu_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() tpu_command_launcher(lowerCAmelCase_ )
54
0
from __future__ import annotations from collections.abc import Iterator from typing import Any class snake_case__ : """simple docstring""" def __init__( self : List[str] , __lowerCamelCase : Any ) -> Union[str, Any]: a = data a = None class snake_case__ : """simple docstring""" def __init__( self : Tuple ) -> List[Any]: a = None a = None def __iter__( self : Any ) -> Iterator[Any]: a = self.head while self.head: yield node.data a = node.next if node == self.head: break def __len__( self : Optional[int] ) -> int: return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> Optional[int]: return "->".join(str(__lowerCamelCase ) for item in iter(self ) ) def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Any ) -> None: self.insert_nth(len(self ) , __lowerCamelCase ) def __UpperCAmelCase ( self : Dict , __lowerCamelCase : Any ) -> None: self.insert_nth(0 , __lowerCamelCase ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int , __lowerCamelCase : Any ) -> None: if index < 0 or index > len(self ): raise IndexError("list index out of range." ) a = Node(__lowerCamelCase ) if self.head is None: a = new_node # first node points itself a = a = new_node elif index == 0: # insert at head a = self.head a = a = new_node else: a = self.head for _ in range(index - 1 ): a = temp.next a = temp.next a = new_node if index == len(self ) - 1: # insert at tail a = new_node def __UpperCAmelCase ( self : List[Any] ) -> List[str]: return self.delete_nth(0 ) def __UpperCAmelCase ( self : Optional[int] ) -> Any: return self.delete_nth(len(self ) - 1 ) def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : int = 0 ) -> Any: if not 0 <= index < len(self ): raise IndexError("list index out of range." ) a = self.head if self.head == self.tail: # just one node a = a = None elif index == 0: # delete head node a = self.tail.next.next a = self.head.next else: a = self.head for _ in range(index - 1 ): a = temp.next a = temp.next a = temp.next.next if index == len(self ) - 1: # delete at tail a = temp return delete_node.data def __UpperCAmelCase ( self : str ) -> bool: return len(self ) == 0 def __magic_name__ ( ): '''simple docstring''' a = CircularLinkedList() assert len(A ) == 0 assert circular_linked_list.is_empty() is True assert str(A ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(A ) == i circular_linked_list.insert_nth(A, i + 1 ) assert str(A ) == "->".join(str(A ) for i in range(1, 6 ) ) circular_linked_list.insert_tail(6 ) assert str(A ) == "->".join(str(A ) for i in range(1, 7 ) ) circular_linked_list.insert_head(0 ) assert str(A ) == "->".join(str(A ) for i in range(0, 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(A ) == "->".join(str(A ) for i in range(1, 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2, 3 ) assert str(A ) == "->".join(str(A ) for i in range(1, 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
107
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> int: raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self : int ) -> Optional[int]: raise NotImplementedError()
54
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Swinv2ForImageClassification''', '''Swinv2ForMaskedImageModeling''', '''Swinv2Model''', '''Swinv2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
108
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
0
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' with open(_SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as input_file: UpperCAmelCase : List[str] = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) UpperCAmelCase : str = input_file.read() UpperCAmelCase : int = regexp.search(_SCREAMING_SNAKE_CASE ) return match def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' with open(_SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as input_file: UpperCAmelCase : Union[str, Any] = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) UpperCAmelCase : Optional[Any] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` UpperCAmelCase : int = regexp.finditer(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[int] = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' UpperCAmelCase : Dict = Path("""./datasets""" ) UpperCAmelCase : Optional[int] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_SCREAMING_SNAKE_CASE ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : Any = Path("""./datasets""" ) UpperCAmelCase : Optional[Any] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(_SCREAMING_SNAKE_CASE ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
109
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCamelCase_ : """simple docstring""" snake_case__ : Dict = PegasusConfig snake_case__ : Union[str, Any] = {} snake_case__ : Any = "gelu" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : List[Any]=2_0 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __SCREAMING_SNAKE_CASE = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = np.concatenate([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2_0 __SCREAMING_SNAKE_CASE = model_class_name(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase__ , decoder_position_ids=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ , UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) snake_case__ : Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () snake_case__ : Tuple = True snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : List[Any] = False def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) @jax.jit def encode_jitted(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : int ): return model.encode(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = encode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __SCREAMING_SNAKE_CASE = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , encoder_outputs=UpperCAmelCase__ , ) with self.subTest("JIT Enabled" ): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE = decode_jitted(**UpperCAmelCase__ ).to_tuple() self.assertEqual(len(UpperCAmelCase__ ) , len(UpperCAmelCase__ ) ) for jitted_output, output in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("google/pegasus-large" , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.ones((1, 1) ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) __SCREAMING_SNAKE_CASE = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] __SCREAMING_SNAKE_CASE = [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="np" , truncation=UpperCAmelCase__ , max_length=5_1_2 , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(**UpperCAmelCase__ , num_beams=2 ).sequences __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) assert tgt_text == decoded
54
0
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) lowerCAmelCase = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=3_0522, type=int) lowerCAmelCase = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, 'rb') as fp: lowerCAmelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') lowerCAmelCase = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
110
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set(range(3 , lowerCAmelCase_ , 2 ) ) primes.add(2 ) for p in range(3 , lowerCAmelCase_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , lowerCAmelCase_ , lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = [float(lowerCAmelCase_ ) for n in range(limit + 1 )] for p in primes: for n in range(lowerCAmelCase_ , limit + 1 , lowerCAmelCase_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
54
0
SCREAMING_SNAKE_CASE__ : Optional[int] = ''' # 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 ''' SCREAMING_SNAKE_CASE__ : Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] SCREAMING_SNAKE_CASE__ : List[str] = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
48
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 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(lowerCAmelCase_ ): 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: a__ : List[str] = 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()
54
0
"""simple docstring""" from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter lowercase__ : Tuple = '''Create a default config file for Accelerate with only a few flags set.''' def UpperCamelCase_ ( lowerCAmelCase__ : List[str]="no" , lowerCAmelCase__ : Optional[Any] = default_json_config_file , lowerCAmelCase__ : Optional[int] = False ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase_ : Optional[int] = Path(lowerCAmelCase_ ) path.parent.mkdir(parents=lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) if path.exists(): print( f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`." ) return False lowerCAmelCase_ : Union[str, Any] = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}" ) lowerCAmelCase_ : List[Any] = { 'compute_environment': 'LOCAL_MACHINE', 'mixed_precision': mixed_precision, } if torch.cuda.is_available(): lowerCAmelCase_ : int = torch.cuda.device_count() lowerCAmelCase_ : Any = num_gpus lowerCAmelCase_ : int = False if num_gpus > 1: lowerCAmelCase_ : Union[str, Any] = 'MULTI_GPU' else: lowerCAmelCase_ : List[Any] = 'NO' elif is_xpu_available() and use_xpu: lowerCAmelCase_ : str = torch.xpu.device_count() lowerCAmelCase_ : str = num_xpus lowerCAmelCase_ : int = False if num_xpus > 1: lowerCAmelCase_ : List[str] = 'MULTI_XPU' else: lowerCAmelCase_ : Optional[Any] = 'NO' elif is_npu_available(): lowerCAmelCase_ : int = torch.npu.device_count() lowerCAmelCase_ : Optional[Any] = num_npus lowerCAmelCase_ : List[Any] = False if num_npus > 1: lowerCAmelCase_ : List[str] = 'MULTI_NPU' else: lowerCAmelCase_ : int = 'NO' else: lowerCAmelCase_ : Dict = 0 lowerCAmelCase_ : Optional[Any] = True lowerCAmelCase_ : Any = 1 lowerCAmelCase_ : Tuple = 'NO' lowerCAmelCase_ : Dict = ClusterConfig(**lowerCAmelCase_ ) config.to_json_file(lowerCAmelCase_ ) return path def UpperCamelCase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict ) -> str: """simple docstring""" lowerCAmelCase_ : Optional[Any] = parser.add_parser('default' , parents=lowerCAmelCase_ , help=lowerCAmelCase_ , formatter_class=lowerCAmelCase_ ) parser.add_argument( '--config_file' , default=lowerCAmelCase_ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , dest='save_location' , ) parser.add_argument( '--mixed_precision' , choices=['no', 'fp16', 'bf16'] , type=lowerCAmelCase_ , help='Whether or not to use mixed precision training. ' 'Choose between FP16 and BF16 (bfloat16) training. ' 'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.' , default='no' , ) parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Tuple: """simple docstring""" lowerCAmelCase_ : int = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"accelerate configuration saved at {config_file}" )
224
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') a__ : Tuple = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "The input training data file (a text file)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: if self.train_file is not None: __SCREAMING_SNAKE_CASE = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __SCREAMING_SNAKE_CASE = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : PreTrainedTokenizerBase snake_case__ : Union[bool, str, PaddingStrategy] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : int , UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = "label" if "label" in features[0].keys() else "labels" __SCREAMING_SNAKE_CASE = [feature.pop(UpperCAmelCase__ ) for feature in features] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = len(features[0]["input_ids"] ) __SCREAMING_SNAKE_CASE = [ [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__ )] for feature in features ] __SCREAMING_SNAKE_CASE = list(chain(*UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.tokenizer.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) # Un-flatten __SCREAMING_SNAKE_CASE = {k: v.view(UpperCAmelCase__ , UpperCAmelCase__ , -1 ) for k, v in batch.items()} # Add back labels __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ , dtype=torch.intaa ) return batch def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , lowerCAmelCase_ , lowerCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) datasets.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: __SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: __SCREAMING_SNAKE_CASE = data_args.validation_file __SCREAMING_SNAKE_CASE = data_args.train_file.split("." )[-1] __SCREAMING_SNAKE_CASE = load_dataset( lowerCAmelCase_ , data_files=lowerCAmelCase_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __SCREAMING_SNAKE_CASE = [f"""ending{i}""" for i in range(4 )] __SCREAMING_SNAKE_CASE = "sent1" __SCREAMING_SNAKE_CASE = "sent2" if data_args.max_seq_length is None: __SCREAMING_SNAKE_CASE = tokenizer.model_max_length if max_seq_length > 1024: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __SCREAMING_SNAKE_CASE = 1024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __SCREAMING_SNAKE_CASE = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [[context] * 4 for context in examples[context_name]] __SCREAMING_SNAKE_CASE = examples[question_header_name] __SCREAMING_SNAKE_CASE = [ [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowerCAmelCase_ ) ] # Flatten out __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = list(chain(*lowerCAmelCase_ ) ) # Tokenize __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(lowerCAmelCase_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["train"] if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __SCREAMING_SNAKE_CASE = raw_datasets["validation"] if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_eval_samples ) __SCREAMING_SNAKE_CASE = eval_dataset.select(range(lowerCAmelCase_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __SCREAMING_SNAKE_CASE = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=lowerCAmelCase_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = eval_predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() # Saves the tokenizer too for easy upload __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' main() if __name__ == "__main__": main()
54
0
"""simple docstring""" import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = "facebook/bart-large-mnli" SCREAMING_SNAKE_CASE_ : str = ( "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." ) SCREAMING_SNAKE_CASE_ : Tuple = "text_classifier" SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoModelForSequenceClassification SCREAMING_SNAKE_CASE_ : Any = ["text", ["text"]] SCREAMING_SNAKE_CASE_ : Optional[int] = ["text"] def A ( self : Optional[int] ) -> List[Any]: super().setup() lowercase_ : Any = self.model.config lowercase_ : str = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): lowercase_ : Union[str, Any] = int(UpperCAmelCase__ ) if self.entailment_id == -1: raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' ) def A ( self : Optional[Any] , A : Union[str, Any] , A : Tuple ) -> Union[str, Any]: lowercase_ : List[Any] = labels return self.pre_processor( [text] * len(UpperCAmelCase__ ) , [F'''This example is {label}''' for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def A ( self : Any , A : List[str] ) -> Dict: lowercase_ : Optional[Any] = outputs.logits lowercase_ : Any = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
33
"""simple docstring""" from PIL import Image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = image.size __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = image.load() for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pixels[j, i] mean += pixel mean //= width * height for j in range(lowerCAmelCase_ ): for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
54
0
"""simple docstring""" class UpperCAmelCase_ : def __init__( self : Dict , __UpperCamelCase : int , __UpperCamelCase : Any , __UpperCamelCase : List[str] ) -> str: _UpperCamelCase = name _UpperCamelCase = value _UpperCamelCase = weight def __repr__( self : Tuple ) -> Union[str, Any]: return F'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _UpperCamelCase ( self : Dict ) -> Any: return self.value def _UpperCamelCase ( self : List[Any] ) -> str: return self.name def _UpperCamelCase ( self : Tuple ) -> int: return self.weight def _UpperCamelCase ( self : int ) -> int: return self.value / self.weight def lowercase ( a__ : str , a__ : List[Any] , a__ : List[str] ) -> Optional[Any]: _UpperCamelCase = [] for i in range(len(lowerCAmelCase_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def lowercase ( a__ : str , a__ : str , a__ : Any ) -> Dict: _UpperCamelCase = sorted(lowerCAmelCase_ , key=lowerCAmelCase_ , reverse=lowerCAmelCase_ ) _UpperCamelCase = [] _UpperCamelCase , _UpperCamelCase = 0.0, 0.0 for i in range(len(lowerCAmelCase_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def lowercase ( ) -> List[str]: pass if __name__ == "__main__": import doctest doctest.testmod()
256
"""simple docstring""" from jiwer import compute_measures import datasets a__ : Optional[int] = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' a__ : List[str] = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' a__ : Dict = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> str: 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=False ) -> Optional[int]: if concatenate_texts: return compute_measures(UpperCAmelCase__ , UpperCAmelCase__ )["wer"] else: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for prediction, reference in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = compute_measures(UpperCAmelCase__ , UpperCAmelCase__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
54
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __lowercase = logging.get_logger(__name__) __lowercase = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __lowercase = { '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } __lowercase = { '''gpt-neox-20b''': 2048, } class _A ( _a ): """simple docstring""" UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : Union[str, Any] = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , __UpperCAmelCase : int=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Union[str, Any]="<|endoftext|>" , __UpperCAmelCase : Optional[Any]="<|endoftext|>" , __UpperCAmelCase : List[str]="<|endoftext|>" , __UpperCAmelCase : List[Any]=False , **__UpperCAmelCase : Optional[int] , ): super().__init__( UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , **UpperCAmelCase__ , ) a : Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get("add_prefix_space" , UpperCAmelCase__) != add_prefix_space: a : List[str] = getattr(UpperCAmelCase__ , pre_tok_state.pop("type")) a : List[str] = add_prefix_space a : Optional[int] = pre_tok_class(**UpperCAmelCase__) a : List[Any] = add_prefix_space def __snake_case ( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None): a : Union[str, Any] = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__) return tuple(UpperCAmelCase__) def __snake_case ( self : Optional[int] , __UpperCAmelCase : "Conversation"): a : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__) + [self.eos_token_id]) if len(UpperCAmelCase__) > self.model_max_length: a : Tuple = input_ids[-self.model_max_length :] return input_ids
40
"""simple docstring""" from __future__ import annotations import pandas as pd def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes __SCREAMING_SNAKE_CASE = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 9_9999_9999 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowerCAmelCase_ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: __SCREAMING_SNAKE_CASE = remaining_time[j] __SCREAMING_SNAKE_CASE = j __SCREAMING_SNAKE_CASE = True if not check: increment_time += 1 continue remaining_time[short] -= 1 __SCREAMING_SNAKE_CASE = remaining_time[short] if minm == 0: __SCREAMING_SNAKE_CASE = 9_9999_9999 if remaining_time[short] == 0: complete += 1 __SCREAMING_SNAKE_CASE = False # Find finish time of current process __SCREAMING_SNAKE_CASE = increment_time + 1 # Calculate waiting time __SCREAMING_SNAKE_CASE = finish_time - arrival_time[short] __SCREAMING_SNAKE_CASE = finar - burst_time[short] if waiting_time[short] < 0: __SCREAMING_SNAKE_CASE = 0 # Increment time increment_time += 1 return waiting_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [0] * no_of_processes for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = burst_time[i] + waiting_time[i] return turn_around_time def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = total_waiting_time + waiting_time[i] __SCREAMING_SNAKE_CASE = total_turn_around_time + turn_around_time[i] print(f"""Average waiting time = {total_waiting_time / no_of_processes:.5f}""" ) print("Average turn around time =" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('''Enter how many process you want to analyze''') a__ : Optional[Any] = int(input()) a__ : Optional[int] = [0] * no_of_processes a__ : int = [0] * no_of_processes a__ : List[Any] = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('''Enter the arrival time and burst time for process:--''' + str(i + 1)) a__ , a__ : Tuple = map(int, input().split()) a__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a__ : Dict = burst_time a__ : Any = no_of_processes a__ : Optional[int] = waiting_time a__ : Union[str, Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a__ : str = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ '''Process''', '''BurstTime''', '''ArrivalTime''', '''WaitingTime''', '''TurnAroundTime''', ], ) # Printing the dataFrame pd.set_option('''display.max_rows''', fcfs.shape[0] + 1) print(fcfs)
54
0
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __snake_case = 4 __snake_case = 3 class lowercase ( A__ ): """simple docstring""" pass def a ( __a ) -> Optional[Any]: '''simple docstring''' for shard in shards: for i in range(lowerCAmelCase_ ): yield {"i": i, "shard": shard} def a ( ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ :Tuple = int(os.environ['''RANK'''] ) UpperCamelCase__ :str = int(os.environ['''WORLD_SIZE'''] ) UpperCamelCase__ :Dict = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase_ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase_ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase_ , default=0 ) UpperCamelCase__ :Union[str, Any] = parser.parse_args() UpperCamelCase__ :str = args.streaming UpperCamelCase__ :Union[str, Any] = args.num_workers UpperCamelCase__ :Union[str, Any] = {'''shards''': [f'''shard_{shard_idx}''' for shard_idx in range(lowerCAmelCase_ )]} UpperCamelCase__ :List[Any] = IterableDataset.from_generator(lowerCAmelCase_ , gen_kwargs=lowerCAmelCase_ ) if not streaming: UpperCamelCase__ :int = Dataset.from_list(list(lowerCAmelCase_ ) ) UpperCamelCase__ :Any = split_dataset_by_node(lowerCAmelCase_ , rank=lowerCAmelCase_ , world_size=lowerCAmelCase_ ) UpperCamelCase__ :Optional[Any] = torch.utils.data.DataLoader(lowerCAmelCase_ , num_workers=lowerCAmelCase_ ) UpperCamelCase__ :Union[str, Any] = NUM_SHARDS * NUM_ITEMS_PER_SHARD UpperCamelCase__ :List[str] = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) UpperCamelCase__ :str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
97
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
"""simple docstring""" from __future__ import annotations import math def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ) -> Tuple: if num <= 0: _lowerCAmelCase : Union[str, Any] = f"{num}: Invalid input, please enter a positive integer." raise ValueError(lowerCAmelCase_ ) _lowerCAmelCase : List[Any] = [True] * (num + 1) _lowerCAmelCase : Tuple = [] _lowerCAmelCase : Optional[Any] = 2 _lowerCAmelCase : str = int(math.sqrt(lowerCAmelCase_ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowerCAmelCase_ ) # Set multiples of start be False for i in range(start * start ,num + 1 ,lowerCAmelCase_ ): if sieve[i] is True: _lowerCAmelCase : int = False start += 1 for j in range(end + 1 ,num + 1 ): if sieve[j] is True: prime.append(lowerCAmelCase_ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
44
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a__ : Any = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) __SCREAMING_SNAKE_CASE = pearsonr(lowerCAmelCase_ , lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = spearmanr(lowerCAmelCase_ , lowerCAmelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' warnings.warn(lowerCAmelCase_ , lowerCAmelCase_ ) requires_backends(lowerCAmelCase_ , "sklearn" ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_ )} and {len(lowerCAmelCase_ )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError(lowerCAmelCase_ )
54
0
import warnings warnings.warn( '''memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ''' '''`from accelerate import find_executable_batch_size` to avoid this warning.''', FutureWarning, )
283
"""simple docstring""" import math import random def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value a__ : Tuple = 0.02 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCAmelCase_ ): # Forward propagation __SCREAMING_SNAKE_CASE = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? __SCREAMING_SNAKE_CASE = (expected / 100) - layer_a # Error delta __SCREAMING_SNAKE_CASE = layer_1_error * sigmoid_function(lowerCAmelCase_ , lowerCAmelCase_ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Expected value: ''')) a__ : str = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
54
0
'''simple docstring''' from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
229
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class a_ ( lowerCamelCase ): lowercase = "gpt_bigcode" lowercase = ["past_key_values"] lowercase = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , _SCREAMING_SNAKE_CASE=50257 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="gelu_pytorch_tanh" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=50256 , _SCREAMING_SNAKE_CASE=50256 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = n_positions UpperCamelCase = n_embd UpperCamelCase = n_layer UpperCamelCase = n_head UpperCamelCase = n_inner UpperCamelCase = activation_function UpperCamelCase = resid_pdrop UpperCamelCase = embd_pdrop UpperCamelCase = attn_pdrop UpperCamelCase = layer_norm_epsilon UpperCamelCase = initializer_range UpperCamelCase = scale_attn_weights UpperCamelCase = use_cache UpperCamelCase = attention_softmax_in_fpaa UpperCamelCase = scale_attention_softmax_in_fpaa UpperCamelCase = multi_query UpperCamelCase = bos_token_id UpperCamelCase = eos_token_id super().__init__(bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ )
321
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> Any: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : List[str] ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Dict ) -> Any: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Tuple ) -> int: return False
54
0